From ee562d1f6f53f37c6c872a04046eff95fe5e7c6a Mon Sep 17 00:00:00 2001 From: Michal Dziekonski Date: Sat, 15 Dec 2018 20:37:35 +0100 Subject: [PATCH] Remove indentation & file ending inconsistencies --- aboutpro.php | 166 +- action_logs/index.php | 2 +- activate.php | 106 +- admin/FleetControl.php | 656 +- admin/SFBSettings.php | 1400 ++--- admin/Telemetry.php | 620 +- admin/UserDevScanner.php | 4022 ++++++------- admin/action_logs/index.php | 2 +- admin/addMoon.php | 172 +- admin/alerts_filters.php | 1168 ++-- admin/alerts_list.php | 1888 +++--- admin/autogziplogs.php | 250 +- admin/autostatbuilder.php | 2034 +++---- admin/autostatbuilder_functions.php | 438 +- admin/banslist.php | 610 +- admin/banuser.php | 588 +- admin/bashDetector.php | 600 +- admin/browse_actionlogs.php | 2492 ++++---- admin/chatbrowser.php | 644 +- admin/cron_GarbageCollector.php | 573 +- admin/declare_list.php | 454 +- admin/errors.php | 122 +- admin/images/index.php | 10 +- admin/index.php | 10 +- admin/iplog.php | 1318 ++-- admin/iplog_addproxy.php | 138 +- admin/massmessage.php | 139 +- admin/messagelist.php | 1004 ++-- admin/overview.php | 44 +- admin/planets_resmanager.php | 548 +- admin/reduceban.php | 402 +- admin/report_list.php | 282 +- admin/scripts/index.php | 10 +- admin/scripts/script.createUserDevDump.php | 380 +- admin/settings.php | 444 +- admin/ship_calculations.php | 436 +- admin/unbanuser.php | 316 +- admin/updater.php | 114 +- admin/updates/index.php | 10 +- admin/updates/update1.php | 30 +- admin/user_info.php | 1444 ++--- admin/userlist.php | 1850 +++--- admin/users_techmanager.php | 384 +- ainfo.php | 20 +- ajax/chat.add.php | 141 +- ajax/chat.del.php | 116 +- ajax/chat.msg.php | 546 +- ajax/chat.settings.php | 136 +- ajax/checkSkin.php | 136 +- ajax/galaxy.php | 168 +- ajax/galaxyfleet.php | 1280 ++-- ajax/index.php | 2 +- ajax/messages.conversation.php | 412 +- ajax/sendmissiles.php | 728 +-- alliance.php | 5281 +++++++++-------- attackslist.php | 428 +- banned.php | 108 +- battlereport.php | 182 +- buddy.php | 814 +-- buildings.php | 218 +- cache/data/index.php | 10 +- cache/img/index.php | 10 +- cache/img/signatures/en/index.php | 10 +- cache/img/signatures/index.php | 10 +- cache/img/signatures/pl/index.php | 10 +- cache/img/signatures/static/index.php | 10 +- cache/index.php | 10 +- changelog.php | 90 +- chat.php | 166 +- chat_edit.php | 66 +- class/UniEngine_Cache.class.php | 124 +- class/index.php | 2 +- common.php | 975 +-- config.localhost.php | 2 +- config.php | 16 +- config.testserver.php | 2 +- contact.php | 84 +- converter.php | 116 +- css/admin/index.php | 4 +- css/index.php | 4 +- declaration.php | 604 +- destroy_rockets.php | 138 +- disassembler.php | 446 +- email_change.php | 346 +- empire.php | 526 +- fleet.php | 2318 ++++---- fleet1.php | 796 +-- fleet2.php | 1326 ++--- fleet3.php | 3218 +++++----- fleetretreat.php | 98 +- fleetshortcut.php | 486 +- galacticshop.php | 1224 ++-- galaxy.php | 444 +- generate_sig.php | 398 +- images/index.php | 2 +- images/jquery.farbtastic/index.php | 2 +- includes/CombatEngineAres.php | 2670 ++++----- includes/CombatEngineV2.php | 1224 ++-- includes/CombatEngineV3.php | 1108 ++-- includes/constants.php | 239 +- includes/db.php | 158 +- includes/debug.class.php | 142 +- includes/functions.php | 2634 ++++---- includes/functions/AddBuildingToQueue.php | 166 +- includes/functions/AlertSystemUtilities.php | 408 +- includes/functions/AlliancePageFunctions.php | 448 +- includes/functions/BBcodeFunction.php | 250 +- includes/functions/BatimentBuildingPage.php | 880 +-- includes/functions/BuildFleetEventTable.php | 508 +- .../functions/BuildingSavePlanetRecord.php | 26 +- includes/functions/Cache_Message.php | 92 +- .../functions/CalcInterplanetaryAttack.php | 314 +- .../functions/CancelBuildingFromQueue.php | 216 +- includes/functions/ChatUtilities.php | 132 +- includes/functions/CheckLabInQueue.php | 56 +- includes/functions/CheckPlanetUsedFields.php | 40 +- includes/functions/CheckUserSession.php | 208 +- includes/functions/CheckUserSessionCookie.php | 196 +- includes/functions/ConvertBattleReport.php | 554 +- includes/functions/CreateBattleReport.php | 128 +- includes/functions/CreateOneMoonRecord.php | 150 +- includes/functions/CreateOnePlanetRecord.php | 434 +- includes/functions/CreateSFBInfobox.php | 204 +- includes/functions/DefensesBuildingPage.php | 746 +-- .../functions/DeleteSelectedPlanetorMoon.php | 154 +- includes/functions/DeleteSelectedUser.php | 546 +- includes/functions/ElementBuildListBox.php | 74 +- includes/functions/FilterMessages.php | 56 +- includes/functions/Filters.php | 1086 ++-- includes/functions/FleetBuildingPage.php | 392 +- includes/functions/FleetControl_Retreat.php | 862 +-- includes/functions/FlyingFleetHandler.php | 2140 +++---- includes/functions/GalaxyLegendPopup.php | 66 +- includes/functions/GalaxyRowActions.php | 174 +- includes/functions/GalaxyRowAlly.php | 96 +- includes/functions/GalaxyRowDebris.php | 144 +- includes/functions/GalaxyRowMoon.php | 162 +- includes/functions/GalaxyRowPlanet.php | 252 +- includes/functions/GalaxyRowPlanetName.php | 206 +- includes/functions/GalaxyRowPos.php | 44 +- includes/functions/GalaxyRowUser.php | 440 +- includes/functions/GetBuildingPrice.php | 132 +- includes/functions/GetBuildingTime.php | 162 +- includes/functions/GetElementPrice.php | 124 +- includes/functions/GetElementRessources.php | 28 +- includes/functions/GetElementTechReq.php | 188 +- .../functions/GetMaxConstructibleElements.php | 110 +- includes/functions/GetMissileRange.php | 60 +- includes/functions/GetPhalanxRange.php | 16 +- includes/functions/GetRestPrice.php | 126 +- includes/functions/HandleFullUserUpdate.php | 132 +- includes/functions/HandlePlanetQueue.php | 220 +- .../HandlePlanetQueue_CreateQueueList.php | 120 +- .../HandlePlanetQueue_OnStructureBuildEnd.php | 472 +- .../HandlePlanetQueue_OnTechnologyEnd.php | 152 +- .../HandlePlanetQueue_StructuresSetNext.php | 560 +- .../HandlePlanetQueue_TechnologySetNext.php | 426 +- includes/functions/HandlePlanetUpdate.php | 132 +- .../HandlePlanetUpdate_MultiUpdate.php | 228 +- includes/functions/HandleShipyardQueue.php | 328 +- includes/functions/IPandUA_Logger.php | 172 +- includes/functions/InsertBuildListScript.php | 116 +- includes/functions/InsertGalaxyScripts.php | 38 +- .../InsertJavaScriptChronoApplet.php | 102 +- includes/functions/IsElementBuyable.php | 148 +- .../functions/IsTechnologieAccessible.php | 62 +- includes/functions/LaboratoryPage.php | 1240 ++-- includes/functions/MakeGraphs.php | 512 +- includes/functions/MissionCaseAttack.php | 3098 +++++----- .../functions/MissionCaseColonisation.php | 516 +- includes/functions/MissionCaseDestruction.php | 3616 +++++------ includes/functions/MissionCaseExpedition.php | 952 +-- includes/functions/MissionCaseGroupAttack.php | 3868 ++++++------ includes/functions/MissionCaseMIP.php | 738 +-- includes/functions/MissionCaseRecycling.php | 436 +- includes/functions/MissionCaseSpy.php | 816 +-- includes/functions/MissionCaseStay.php | 188 +- includes/functions/MissionCaseStayAlly.php | 238 +- includes/functions/MissionCaseTransport.php | 282 +- .../functions/MissionCheckCalculation.php | 136 +- includes/functions/Pagination.php | 390 +- includes/functions/PlanetResourceUpdate.php | 1006 ++-- .../functions/PostResearchSaveChanges.php | 48 +- includes/functions/ReadBattleReport.php | 846 +-- .../functions/RemoveBuildingFromQueue.php | 180 +- includes/functions/ResearchBuildingPage.php | 502 +- includes/functions/RestoreFleetToPlanet.php | 172 +- includes/functions/SendMail.php | 302 +- includes/functions/SendSimpleMassMessage.php | 42 +- includes/functions/SendSimpleMessage.php | 62 +- .../functions/SendSimpleMultipleMessages.php | 56 +- includes/functions/SetSelectedPlanet.php | 56 +- includes/functions/ShipyardPage.php | 1148 ++-- includes/functions/ShowBuildingQueue.php | 192 +- includes/functions/ShowGalaxyFooter.php | 72 +- includes/functions/ShowGalaxyMISelector.php | 74 +- includes/functions/ShowGalaxyRows.php | 350 +- includes/functions/ShowGalaxySelector.php | 72 +- includes/functions/ShowGalaxyTitles.php | 50 +- includes/functions/ShowTopNavigationBar.php | 850 +-- includes/functions/SortUserPlanets.php | 66 +- includes/functions/SpyTarget.php | 366 +- includes/functions/StoreGoodsToPlanet.php | 122 +- includes/functions/StructuresBuildingPage.php | 1550 ++--- includes/functions/TasksFunctions.php | 632 +- includes/functions/TechQueue_Add.php | 138 +- includes/functions/TechQueue_Remove.php | 148 +- includes/functions/index.php | 10 +- includes/index.php | 10 +- includes/ingamefunctions.php | 86 +- includes/phpBench.php | 476 +- includes/recaptchalib.php | 224 +- includes/strings.php | 126 +- includes/unlocalised.php | 924 +-- includes/vars.php | 152 +- includes/vars_combatdata.php | 2392 ++++---- includes/vars_elementcategories.php | 36 +- includes/vars_militaryupgrades.php | 134 +- includes/vars_prices.php | 1720 +++--- includes/vars_requirements.php | 698 +-- includes/vars_resources.php | 178 +- includes/vars_resproduction.php | 212 +- includes/vars_tasks.php | 3046 +++++----- index.php | 30 +- infos.php | 1370 ++--- install/index.php | 986 +-- install/install_body.tpl | 634 +- install/install_filetpl_config.tpl | 24 +- install/install_filetpl_constants.tpl | 468 +- install/install_functions.php | 80 +- js/admin/index.php | 4 +- js/index.php | 4 +- js/register.js | 2 +- jumpgate.php | 242 +- language/en/index.php | 2 +- language/index.php | 2 +- language/pl/admin/index.php | 10 +- language/pl/index.php | 10 +- login.php | 452 +- logout.php | 68 +- lostcode.php | 183 +- lostpassword.php | 248 +- merchant.php | 884 +-- messages.php | 2588 ++++---- modules/ally.changepact.php | 334 +- modules/ally.newpact.php | 296 +- modules/ally.pactslist.php | 1004 ++-- modules/index.php | 2 +- moon_sim.php | 162 +- morale_info.php | 168 +- notes.php | 604 +- officers.php | 248 +- other/index.php | 2 +- overview.php | 2302 +++---- phalanx.php | 478 +- phpcs.xml | 6 + polls.php | 642 +- profile.php | 562 +- records.php | 176 +- redirect.php | 56 +- ref_table.php | 106 +- reg_ajax.php | 952 +-- reg_mainpage.php | 184 +- report.php | 344 +- resources.php | 982 +-- rocket_simulator.php | 534 +- rules.php | 102 +- scripts/index.php | 10 +- search.php | 404 +- settings.php | 2728 ++++----- simulator.php | 1576 ++--- skins/epicblue/gebaeude/index.php | 2 +- skins/epicblue/gfx/index.php | 2 +- skins/epicblue/images/index.php | 2 +- skins/epicblue/img/index.php | 2 +- skins/epicblue/index.php | 10 +- skins/epicblue/officiers/index.php | 2 +- skins/epicblue/pic/index.php | 2 +- skins/epicblue/planeten/index.php | 2 +- skins/epicblue/planeten/small/index.php | 2 +- skins/epicblue_old/gebaeude/index.php | 2 +- skins/epicblue_old/gfx/index.php | 2 +- skins/epicblue_old/images/index.php | 2 +- skins/epicblue_old/img/index.php | 2 +- skins/epicblue_old/index.php | 10 +- skins/epicblue_old/officiers/index.php | 2 +- skins/epicblue_old/pic/index.php | 2 +- skins/epicblue_old/planeten/index.php | 2 +- skins/epicblue_old/planeten/small/index.php | 2 +- skins/index.php | 2 +- skins/xnova/gebaeude/index.php | 2 +- skins/xnova/gfx/index.php | 2 +- skins/xnova/images/index.php | 2 +- skins/xnova/img/index.php | 2 +- skins/xnova/index.php | 2 +- skins/xnova/officiers/index.php | 2 +- skins/xnova/pic/index.php | 2 +- skins/xnova/planeten/index.php | 2 +- skins/xnova/planeten/small/index.php | 2 +- stats.php | 610 +- tasks.php | 1022 ++-- techtree.php | 160 +- templates/default_template/admin/index.php | 10 +- templates/default_template/index.php | 10 +- templates/index.php | 2 +- texts.php | 80 +- 306 files changed, 70368 insertions(+), 70113 deletions(-) diff --git a/aboutpro.php b/aboutpro.php index 33c30fc7a..8f6d964a3 100644 --- a/aboutpro.php +++ b/aboutpro.php @@ -1,83 +1,83 @@ -', $_Lang['Benefits']); - - foreach($_Vars_ProAccountData as $Data) - { - $_Lang['ProArray'][$Data['shopID']]['time'] = $Data['time']; - if($Data['time'] == 1) - { - $_Lang['ProArray'][$Data['shopID']]['thistime'] = '_day'; - } - else - { - $_Lang['ProArray'][$Data['shopID']]['thistime'] = '_days'; - } - $_Lang['CostVal'.$Data['shopID']] = $Data['cost']; - $_Lang['ShopItemID'.$Data['shopID']] = $Data['shopID']; - } - - if($_User['pro_time'] > $Now) - { - $_Lang['ProState'] = $_Lang['ProTill']; - $_Lang['ProTime'] = prettyDate('d m Y H:i:s', $_User['pro_time'], 1); - $_Lang['ProTimeColor'] = 'lime'; - foreach($_Lang['ProArray'] as $ShopID => $Data) - { - $_Lang['BuyButton'.$ShopID] = sprintf($_Lang['RenewPro'], $Data['time'], $_Lang[$Data['thistime']]); - } - } - else if($_User['pro_time'] > 0) - { - $_Lang['ProState'] = $_Lang['ProEnded']; - $_Lang['ProTime'] = prettyDate('d m Y H:i:s', $_User['pro_time'], 1); - $_Lang['ProTimeColor'] = 'orange'; - foreach($_Lang['ProArray'] as $ShopID => $Data) - { - $_Lang['BuyButton'.$ShopID] = sprintf($_Lang['BuyAgain'], $Data['time'], $_Lang[$Data['thistime']]); - } - } - else - { - $_Lang['ProState'] = $_Lang['NeverHadPro']; - $_Lang['ProStateColor'] = 'red'; - foreach($_Lang['ProArray'] as $ShopID => $Data) - { - $_Lang['BuyButton'.$ShopID] = sprintf($_Lang['FirstBuy'], $Data['time'], $_Lang[$Data['thistime']]); - } - } - - $_Lang['DarkEnergy_Counter'] = $_User['darkEnergy']; - if($_User['darkEnergy'] >= 15) - { - $_Lang['DarkEnergy_Color'] = 'lime'; - } - else if($_User['darkEnergy'] > 0) - { - $_Lang['DarkEnergy_Color'] = 'orange'; - } - else - { - $_Lang['DarkEnergy_Color'] = 'red'; - } - - $page = parsetemplate(gettemplate('about_pro'), $_Lang); - display($page, $_Lang['aboutpro'], false); - -?> \ No newline at end of file +', $_Lang['Benefits']); + +foreach($_Vars_ProAccountData as $Data) +{ + $_Lang['ProArray'][$Data['shopID']]['time'] = $Data['time']; + if($Data['time'] == 1) + { + $_Lang['ProArray'][$Data['shopID']]['thistime'] = '_day'; + } + else + { + $_Lang['ProArray'][$Data['shopID']]['thistime'] = '_days'; + } + $_Lang['CostVal'.$Data['shopID']] = $Data['cost']; + $_Lang['ShopItemID'.$Data['shopID']] = $Data['shopID']; +} + +if($_User['pro_time'] > $Now) +{ + $_Lang['ProState'] = $_Lang['ProTill']; + $_Lang['ProTime'] = prettyDate('d m Y H:i:s', $_User['pro_time'], 1); + $_Lang['ProTimeColor'] = 'lime'; + foreach($_Lang['ProArray'] as $ShopID => $Data) + { + $_Lang['BuyButton'.$ShopID] = sprintf($_Lang['RenewPro'], $Data['time'], $_Lang[$Data['thistime']]); + } +} +else if($_User['pro_time'] > 0) +{ + $_Lang['ProState'] = $_Lang['ProEnded']; + $_Lang['ProTime'] = prettyDate('d m Y H:i:s', $_User['pro_time'], 1); + $_Lang['ProTimeColor'] = 'orange'; + foreach($_Lang['ProArray'] as $ShopID => $Data) + { + $_Lang['BuyButton'.$ShopID] = sprintf($_Lang['BuyAgain'], $Data['time'], $_Lang[$Data['thistime']]); + } +} +else +{ + $_Lang['ProState'] = $_Lang['NeverHadPro']; + $_Lang['ProStateColor'] = 'red'; + foreach($_Lang['ProArray'] as $ShopID => $Data) + { + $_Lang['BuyButton'.$ShopID] = sprintf($_Lang['FirstBuy'], $Data['time'], $_Lang[$Data['thistime']]); + } +} + +$_Lang['DarkEnergy_Counter'] = $_User['darkEnergy']; +if($_User['darkEnergy'] >= 15) +{ + $_Lang['DarkEnergy_Color'] = 'lime'; +} +else if($_User['darkEnergy'] > 0) +{ + $_Lang['DarkEnergy_Color'] = 'orange'; +} +else +{ + $_Lang['DarkEnergy_Color'] = 'red'; +} + +$page = parsetemplate(gettemplate('about_pro'), $_Lang); +display($page, $_Lang['aboutpro'], false); + +?> diff --git a/action_logs/index.php b/action_logs/index.php index 58f7bb163..8ea442135 100644 --- a/action_logs/index.php +++ b/action_logs/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/activate.php b/activate.php index eb648d904..642178b8e 100644 --- a/activate.php +++ b/activate.php @@ -1,53 +1,53 @@ - 0) - { - $Result = mysql_fetch_assoc($Result); - $Username = $Result['username']; - doquery("UPDATE {{table}} SET `activation_code` = '' WHERE `id` = '{$Result['id']}';", 'users'); - - $Msg = sprintf($_Lang['activation_completed'], $Username, 'overview.php', 3); - $Activated = true; - } - else - { - $Msg = $_Lang['no_code_in_db']; - } - } - else - { - $Msg = $_Lang['invalid_code_format']; - } - } - else - { - $Msg = $_Lang['empty_code']; - } - - if($Activated) - { - $Color = 'lime'; - } - else - { - $Color = 'red'; - } - - message("{$Msg}

{$_Lang['go_back']}", $_Lang['title']); - -?> \ No newline at end of file + 0) + { + $Result = mysql_fetch_assoc($Result); + $Username = $Result['username']; + doquery("UPDATE {{table}} SET `activation_code` = '' WHERE `id` = '{$Result['id']}';", 'users'); + + $Msg = sprintf($_Lang['activation_completed'], $Username, 'overview.php', 3); + $Activated = true; + } + else + { + $Msg = $_Lang['no_code_in_db']; + } + } + else + { + $Msg = $_Lang['invalid_code_format']; + } +} +else +{ + $Msg = $_Lang['empty_code']; +} + +if($Activated) +{ + $Color = 'lime'; +} +else +{ + $Color = 'red'; +} + +message("{$Msg}

{$_Lang['go_back']}", $_Lang['title']); + +?> diff --git a/admin/FleetControl.php b/admin/FleetControl.php index eef553ebe..93332c88e 100644 --- a/admin/FleetControl.php +++ b/admin/FleetControl.php @@ -1,328 +1,328 @@ - $IsOn) - { - if($IsOn == 'on') - { - $FleetID = floor(floatval($FleetID)); - if($FleetID > 0) - { - $ActionArray[] = $FleetID; - } - } - } - } - if(!empty($ActionArray)) - { - include($_EnginePath.'includes/functions/FleetControl_Retreat.php'); - $Result = FleetControl_Retreat("`fleet_id` IN (".implode(', ', $ActionArray).")", $UseFallback); - if(isset($Result['Updates']['Fleets']) && $Result['Updates']['Fleets'] > 0) - { - $MessageUse = ($UseFallback ? $_Lang['SysMsg_XFleetsFallenBack'] : $_Lang['SysMsg_XFleetsRetreated']); - $SysMessage[] = array('color' => 'lime', 'text' => sprintf($MessageUse, prettyNumber($Result['Updates']['Fleets']), prettyNumber($Result['Rows']))); - if((isset($Result['Updates']['ACS']) && $Result['Updates']['ACS'] > 0) || (isset($Result['Deletes']['ACS']) && $Result['Deletes']['ACS'] > 0)) - { - $MessageUse = ($UseFallback ? $_Lang['SysMsg_XACSChanged'] : $_Lang['SysMsg_XACSChanged']); - $SysMessage[] = array('color' => 'lime', 'text' => sprintf($MessageUse, prettyNumber($Result['Updates']['ACS']), prettyNumber($Result['Deletes']['ACS']))); - } - - if(isset($_POST['sendNotice']) && $_POST['sendNotice'] == 'on') - { - $GetOwnersIDs = implode(', ', array_keys($Result['Types'])); - $GetOwnersQuery = ''; - $GetOwnersQuery .= "SELECT `fleet_owner`, COUNT(`fleet_id`) AS `Count`, '1' AS `Type` "; - $GetOwnersQuery .= "FROM {{table}} "; - $GetOwnersQuery .= "WHERE `fleet_id` IN ({$GetOwnersIDs}) GROUP BY `fleet_owner` "; - $GetOwnersQuery .= "UNION "; - $GetOwnersQuery .= "SELECT `fleet_owner`, COUNT(`fleet_id`) AS `Count`, '2' AS `Type` "; - $GetOwnersQuery .= "FROM {{table}} GROUP BY `fleet_owner`;"; - - $GetOwners = doquery($GetOwnersQuery, 'fleets'); - if(mysql_num_rows($GetOwners) > 0) - { - while($FleetOwner = mysql_fetch_assoc($GetOwners)) - { - $OwnersArray[$FleetOwner['fleet_owner']][$FleetOwner['Type']] = $FleetOwner['Count']; - } - } - $ThisMsgID = ($UseFallback ? '094' : '093'); - foreach($OwnersArray as $UserID => $UserData) - { - if($UserData['1'] <= 0) - { - continue; - } - - Cache_Message($UserID, '0', $Now, 80, '002', '022', json_encode(array('msg_id' => $ThisMsgID, 'args' => array(prettyNumber($UserData['1']), prettyNumber($UserData['2']))))); - } - } - } - else - { - $MessageUse = ($UseFallback ? $_Lang['SysMsg_0FleetsFallenBack'] : $_Lang['SysMsg_0FleetsRetreated']); - $SysMessage[] = array('color' => 'orange', 'text' => sprintf($MessageUse, prettyNumber($Result['Rows']))); - } - } - else - { - $SysMessage[] = array('color' => 'red', 'text' => $_Lang['SysMsg_NoValidFleetsGiven']); - } - } - else - { - $SysMessage[] = array('color' => 'red', 'text' => $_Lang['SysMsg_AccessDenied']); - } - } - } - - if(!empty($SysMessage)) - { - foreach($SysMessage as $Message) - { - $Parse['MessageText'][] = "{$Message['text']}"; - } - $Parse['MessageText'] = implode('
', $Parse['MessageText']); - } - else - { - $Parse['Hide_Message'] = 'inv'; - } - - $HiddenOptions = 0; - if(!CheckAuth('supportadmin')) - { - $Parse['Hide_OptionRetreat'] = 'hide'; - $Parse['Hide_OptionFallback'] = 'hide'; - $HiddenOptions += 2; - } - - if($HiddenOptions >= 2) - { - $Parse['Hide_AllOptions'] = 'hide'; - } - - $Query = "SELECT * FROM {{table}} ORDER BY `fleet_start_time` ASC, `fleet_id` ASC;"; - $Result = doquery($Query, 'fleets'); - if(mysql_num_rows($Result) == 0) - { - $Parse['Rows'] = "{$_Lang['Error_NoFleetsFound']}"; - $Parse['Hide_AllOptions'] = 'hide'; - } - else - { - while($Fleets = mysql_fetch_assoc($Result)) - { - $GetACSData[] = $Fleets['fleet_id']; - $Data[$Fleets['fleet_id']] = $Fleets; - if(empty($GetUserNicks) OR !in_array($Fleets['fleet_owner'], $GetUserNicks)) - { - $GetUserNicks[] = $Fleets['fleet_owner']; - } - if(empty($GetUserNicks) OR !in_array($Fleets['fleet_target_owner'], $GetUserNicks) AND $Fleets['fleet_target_owner'] > 0) - { - $GetUserNicks[] = $Fleets['fleet_target_owner']; - } - } - if(!empty($GetUserNicks)) - { - $Query = "SELECT `id`, `username` FROM {{table}} WHERE `id` IN (".implode(', ', $GetUserNicks).");"; - $Result = doquery($Query, 'users'); - if(mysql_num_rows($Result) > 0) - { - while($UserData = mysql_fetch_assoc($Result)) - { - $UsersNicks[$UserData['id']] = $UserData['username']; - } - } - } - if(!empty($GetACSData)) - { - foreach($GetACSData as $ACSTempData) - { - $CheckJoinedFleets[] = "`fleets_id` LIKE '%|{$ACSTempData}|%'"; - } - $CheckJoinedFleets = implode(' OR ', $CheckJoinedFleets); - $Query = "SELECT `id`, `main_fleet_id`, `fleets_id` FROM {{table}} WHERE `main_fleet_id` IN (".implode(', ', $GetACSData).") OR {$CheckJoinedFleets};"; - $Result = doquery($Query, 'acs'); - if(mysql_num_rows($Result) > 0) - { - while($TempACSData = mysql_fetch_assoc($Result)) - { - $Temp1 = explode(',', str_replace('|', '', $TempACSData['fleets_id'])); - foreach($Temp1 as $TempData) - { - $ACSData[$TempData] = $TempACSData['id']; - } - $ACSData[$TempACSData['main_fleet_id']] = $TempACSData['id']; - } - } - } - - $Now = time(); - - include("{$_EnginePath}/includes/functions/InsertJavaScriptChronoApplet.php"); - - $AllFleetParse = ''; - foreach($Data as $FleetID => $FleetData) - { - $FleetParse = false; - $FleetArray = false; - $FleetShipsTemp = false; - $FleetCount = 0; - $FleetShipsParsed = false; - - $FleetParse['Fleet_ID'] = $FleetID; - $FleetParse['Fleet_Owner']= "{$UsersNicks[$FleetData['fleet_owner']]}
[{$FleetData['fleet_owner']}]
"; - - $FleetParse['Fleet_Mission'] = $_Lang['type_mission'][$FleetData['fleet_mission']]; - if(isset($ACSData[$FleetID]) && $ACSData[$FleetID] > 0) - { - if($FleetData['fleet_mission'] == 1) - { - $FleetParse['Fleet_Mission'] = $_Lang['type_mission'][2]; - } - $FleetParse['Fleet_Mission'] = "{$FleetParse['Fleet_Mission']}
[ACS: {$ACSData[$FleetID]}]"; - if($FleetData['fleet_mission'] == 1) - { - $FleetParse['Fleet_Mission'] = "{$FleetParse['Fleet_Mission']}"; - } - } - if(($FleetData['fleet_mess'] == 0 AND $FleetData['fleet_start_time'] <= $Now) OR ($FleetData['fleet_mess'] != 0 AND $FleetData['fleet_end_time'] <= $Now)) - { - $FleetParse['Fleet_Mission'] = "{$FleetParse['Fleet_Mission']}
[{$_Lang['Not_calculated']}]"; - } - if(($FleetData['fleet_start_time'] <= $Now AND $FleetData['fleet_mission'] != 5) OR ($FleetData['fleet_mission'] == 5 AND $FleetData['fleet_end_stay'] <= $Now)) - { - $FleetParse['Fleet_Mission'] .= "
[{$_Lang['Coming_back']}]"; - } - if($FleetData['fleet_mission'] == 5) - { - if($FleetData['fleet_start_time'] <= $Now AND $FleetData['fleet_end_stay'] > $Now) - { - $FleetParse['Fleet_Mission'] .= "
(".pretty_time($FleetData['fleet_end_stay'] - $Now, true, 'D').")"; - $Parse['ChronoApplets'] .= InsertJavaScriptChronoApplet('s', $FleetID, $FleetData['fleet_end_stay'] - $Now); - } - } - - $FleetArray = explode(';', $FleetData['fleet_array']); - foreach($FleetArray as $FleetShipsTemp) - { - if(!empty($FleetShipsTemp)) - { - $FleetShipsTemp = explode(',', $FleetShipsTemp); - $FleetCount += $FleetShipsTemp[1]; - $FleetShipsParsed[] = "{$_Lang['tech'][$FleetShipsTemp[0]]}".prettyNumber($FleetShipsTemp[1]).""; - } - } - $FleetCount = prettyNumber($FleetCount); - $FleetParse['Fleet_Ships'] = "".implode('', $FleetShipsParsed)."
"; - $FleetParse['Fleet_Array'] = "{$FleetCount}
(?)"; - if($FleetData['fleet_resource_metal'] == 0 AND $FleetData['fleet_resource_crystal'] == 0 AND $FleetData['fleet_resource_deuterium'] == 0) - { - $FleetParse['Fleet_Cargo'] = $_Lang['No_cargo']; - } - else - { - $FleetParse['Fleet_Cargo'] = $_Lang['See_cargo']; - $FleetParse['Fleet_Resources'] = "
{$_Lang['Metal']}".prettyNumber($FleetData['fleet_resource_metal'])."
{$_Lang['Crystal']}".prettyNumber($FleetData['fleet_resource_crystal'])."
{$_Lang['Deuterium']}".prettyNumber($FleetData['fleet_resource_deuterium'])."
"; - $FleetParse['Fleet_Cargo_class'] = ' fCar'; - } - $FleetParse['Fleet_Start_Title'] = ($FleetData['fleet_start_type'] == '1' ? $_Lang['Start_from_planet'] : $_Lang['Start_from_moon']); - $FleetParse['Fleet_Start'] = "[{$FleetData['fleet_start_galaxy']}:{$FleetData['fleet_start_system']}:{$FleetData['fleet_start_planet']}] ".($FleetData['fleet_start_type'] == '1' ? $_Lang['Planet_sign'] : $_Lang['Moon_sign']).""; - $FleetParse['Fleet_Start'] .= "
".date('d.m.Y', $FleetData['fleet_send_time'])."
".date('H:i:s', $FleetData['fleet_send_time'])."
(".pretty_time($Now - $FleetData['fleet_send_time'], true, 'D')." {$_Lang['_ago']})"; - $Parse['ChronoApplets'] .= InsertJavaScriptChronoApplet('a', $FleetID, $FleetData['fleet_send_time'], true, true); - - $FleetParse['Fleet_End_Title'] = ($FleetData['fleet_end_type'] == '1' ? $_Lang['Target_is_planet'] : ($FleetData['fleet_end_type'] == '2' ? $_Lang['Target_is_debris'] : $_Lang['Target_is_moon'])); - $FleetParse['Fleet_End'] = "[{$FleetData['fleet_end_galaxy']}:{$FleetData['fleet_end_system']}:{$FleetData['fleet_end_planet']}] ".($FleetData['fleet_end_type'] == '1' ? $_Lang['Planet_sign'] : ($FleetData['fleet_end_type'] == '2' ? $_Lang['Debris_sign'] : $_Lang['Moon_sign'])).""; - if($FleetData['fleet_start_time'] <= $Now) - { - $FleetParse['Fleet_end_time_set'] = "{$_Lang['TargetAchieved']}"; - } - else - { - $FleetParse['Fleet_end_time_set'] = pretty_time($FleetData['fleet_start_time'] - $Now, true, 'D'); - $Parse['ChronoApplets'] .= InsertJavaScriptChronoApplet('b', $FleetID, $FleetData['fleet_start_time'] - $Now); - } - $FleetParse['Fleet_End'] .= "
".date('d.m.Y', $FleetData['fleet_start_time'])."
".date('H:i:s', $FleetData['fleet_start_time'])."
({$FleetParse['Fleet_end_time_set']})"; - - if($FleetData['fleet_target_owner'] > 0) - { - $FleetParse['Fleet_End_owner'] = "{$UsersNicks[$FleetData['fleet_target_owner']]}
[{$FleetData['fleet_target_owner']}]"; - if($FleetData['fleet_target_owner'] == $FleetData['fleet_owner']) - { - $FleetParse['Fleet_End_owner_color'] = 'lime'; - } - else - { - if(in_array($FleetData['fleet_mission'], array(1, 2, 6, 9, 10, 11))) - { - $FleetParse['Fleet_End_owner_color'] = 'red'; - } - else - { - $FleetParse['Fleet_End_owner_color'] = 'blue'; - } - } - $FleetParse['Fleet_End_owner'] = "{$FleetParse['Fleet_End_owner']}"; - } - else - { - $FleetParse['Fleet_End_owner'] = $_Lang['None']; - } - - if($FleetData['fleet_end_time'] <= $Now) - { - $FleetParse['Fleet_back_time_set'] = "{$_Lang['FleetCameBack']}"; - } - else - { - $FleetParse['Fleet_back_time_set'] = pretty_time($FleetData['fleet_end_time'] - $Now, true, 'D'); - $Parse['ChronoApplets'] .= InsertJavaScriptChronoApplet('c', $FleetID, $FleetData['fleet_end_time'] - $Now); - } - $FleetParse['Fleet_Back_time'] = date('d.m.Y', $FleetData['fleet_end_time'])."
".date('H:i:s', $FleetData['fleet_end_time'])."
({$FleetParse['Fleet_back_time_set']})"; - - $AllFleetParse .= parsetemplate($RowTPL, $FleetParse); - } - - $Parse['Rows'] = $AllFleetParse; - } - - $Page = parsetemplate($PageTPL, $Parse); - - display($Page, $_Lang['PageTitle'], false, true); - } - else - { - AdminMessage($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); - } - -?> \ No newline at end of file + $IsOn) + { + if($IsOn == 'on') + { + $FleetID = floor(floatval($FleetID)); + if($FleetID > 0) + { + $ActionArray[] = $FleetID; + } + } + } + } + if(!empty($ActionArray)) + { + include($_EnginePath.'includes/functions/FleetControl_Retreat.php'); + $Result = FleetControl_Retreat("`fleet_id` IN (".implode(', ', $ActionArray).")", $UseFallback); + if(isset($Result['Updates']['Fleets']) && $Result['Updates']['Fleets'] > 0) + { + $MessageUse = ($UseFallback ? $_Lang['SysMsg_XFleetsFallenBack'] : $_Lang['SysMsg_XFleetsRetreated']); + $SysMessage[] = array('color' => 'lime', 'text' => sprintf($MessageUse, prettyNumber($Result['Updates']['Fleets']), prettyNumber($Result['Rows']))); + if((isset($Result['Updates']['ACS']) && $Result['Updates']['ACS'] > 0) || (isset($Result['Deletes']['ACS']) && $Result['Deletes']['ACS'] > 0)) + { + $MessageUse = ($UseFallback ? $_Lang['SysMsg_XACSChanged'] : $_Lang['SysMsg_XACSChanged']); + $SysMessage[] = array('color' => 'lime', 'text' => sprintf($MessageUse, prettyNumber($Result['Updates']['ACS']), prettyNumber($Result['Deletes']['ACS']))); + } + + if(isset($_POST['sendNotice']) && $_POST['sendNotice'] == 'on') + { + $GetOwnersIDs = implode(', ', array_keys($Result['Types'])); + $GetOwnersQuery = ''; + $GetOwnersQuery .= "SELECT `fleet_owner`, COUNT(`fleet_id`) AS `Count`, '1' AS `Type` "; + $GetOwnersQuery .= "FROM {{table}} "; + $GetOwnersQuery .= "WHERE `fleet_id` IN ({$GetOwnersIDs}) GROUP BY `fleet_owner` "; + $GetOwnersQuery .= "UNION "; + $GetOwnersQuery .= "SELECT `fleet_owner`, COUNT(`fleet_id`) AS `Count`, '2' AS `Type` "; + $GetOwnersQuery .= "FROM {{table}} GROUP BY `fleet_owner`;"; + + $GetOwners = doquery($GetOwnersQuery, 'fleets'); + if(mysql_num_rows($GetOwners) > 0) + { + while($FleetOwner = mysql_fetch_assoc($GetOwners)) + { + $OwnersArray[$FleetOwner['fleet_owner']][$FleetOwner['Type']] = $FleetOwner['Count']; + } + } + $ThisMsgID = ($UseFallback ? '094' : '093'); + foreach($OwnersArray as $UserID => $UserData) + { + if($UserData['1'] <= 0) + { + continue; + } + + Cache_Message($UserID, '0', $Now, 80, '002', '022', json_encode(array('msg_id' => $ThisMsgID, 'args' => array(prettyNumber($UserData['1']), prettyNumber($UserData['2']))))); + } + } + } + else + { + $MessageUse = ($UseFallback ? $_Lang['SysMsg_0FleetsFallenBack'] : $_Lang['SysMsg_0FleetsRetreated']); + $SysMessage[] = array('color' => 'orange', 'text' => sprintf($MessageUse, prettyNumber($Result['Rows']))); + } + } + else + { + $SysMessage[] = array('color' => 'red', 'text' => $_Lang['SysMsg_NoValidFleetsGiven']); + } + } + else + { + $SysMessage[] = array('color' => 'red', 'text' => $_Lang['SysMsg_AccessDenied']); + } + } + } + + if(!empty($SysMessage)) + { + foreach($SysMessage as $Message) + { + $Parse['MessageText'][] = "{$Message['text']}"; + } + $Parse['MessageText'] = implode('
', $Parse['MessageText']); + } + else + { + $Parse['Hide_Message'] = 'inv'; + } + + $HiddenOptions = 0; + if(!CheckAuth('supportadmin')) + { + $Parse['Hide_OptionRetreat'] = 'hide'; + $Parse['Hide_OptionFallback'] = 'hide'; + $HiddenOptions += 2; + } + + if($HiddenOptions >= 2) + { + $Parse['Hide_AllOptions'] = 'hide'; + } + + $Query = "SELECT * FROM {{table}} ORDER BY `fleet_start_time` ASC, `fleet_id` ASC;"; + $Result = doquery($Query, 'fleets'); + if(mysql_num_rows($Result) == 0) + { + $Parse['Rows'] = "{$_Lang['Error_NoFleetsFound']}"; + $Parse['Hide_AllOptions'] = 'hide'; + } + else + { + while($Fleets = mysql_fetch_assoc($Result)) + { + $GetACSData[] = $Fleets['fleet_id']; + $Data[$Fleets['fleet_id']] = $Fleets; + if(empty($GetUserNicks) OR !in_array($Fleets['fleet_owner'], $GetUserNicks)) + { + $GetUserNicks[] = $Fleets['fleet_owner']; + } + if(empty($GetUserNicks) OR !in_array($Fleets['fleet_target_owner'], $GetUserNicks) AND $Fleets['fleet_target_owner'] > 0) + { + $GetUserNicks[] = $Fleets['fleet_target_owner']; + } + } + if(!empty($GetUserNicks)) + { + $Query = "SELECT `id`, `username` FROM {{table}} WHERE `id` IN (".implode(', ', $GetUserNicks).");"; + $Result = doquery($Query, 'users'); + if(mysql_num_rows($Result) > 0) + { + while($UserData = mysql_fetch_assoc($Result)) + { + $UsersNicks[$UserData['id']] = $UserData['username']; + } + } + } + if(!empty($GetACSData)) + { + foreach($GetACSData as $ACSTempData) + { + $CheckJoinedFleets[] = "`fleets_id` LIKE '%|{$ACSTempData}|%'"; + } + $CheckJoinedFleets = implode(' OR ', $CheckJoinedFleets); + $Query = "SELECT `id`, `main_fleet_id`, `fleets_id` FROM {{table}} WHERE `main_fleet_id` IN (".implode(', ', $GetACSData).") OR {$CheckJoinedFleets};"; + $Result = doquery($Query, 'acs'); + if(mysql_num_rows($Result) > 0) + { + while($TempACSData = mysql_fetch_assoc($Result)) + { + $Temp1 = explode(',', str_replace('|', '', $TempACSData['fleets_id'])); + foreach($Temp1 as $TempData) + { + $ACSData[$TempData] = $TempACSData['id']; + } + $ACSData[$TempACSData['main_fleet_id']] = $TempACSData['id']; + } + } + } + + $Now = time(); + + include("{$_EnginePath}/includes/functions/InsertJavaScriptChronoApplet.php"); + + $AllFleetParse = ''; + foreach($Data as $FleetID => $FleetData) + { + $FleetParse = false; + $FleetArray = false; + $FleetShipsTemp = false; + $FleetCount = 0; + $FleetShipsParsed = false; + + $FleetParse['Fleet_ID'] = $FleetID; + $FleetParse['Fleet_Owner']= "{$UsersNicks[$FleetData['fleet_owner']]}
[{$FleetData['fleet_owner']}]
"; + + $FleetParse['Fleet_Mission'] = $_Lang['type_mission'][$FleetData['fleet_mission']]; + if(isset($ACSData[$FleetID]) && $ACSData[$FleetID] > 0) + { + if($FleetData['fleet_mission'] == 1) + { + $FleetParse['Fleet_Mission'] = $_Lang['type_mission'][2]; + } + $FleetParse['Fleet_Mission'] = "{$FleetParse['Fleet_Mission']}
[ACS: {$ACSData[$FleetID]}]"; + if($FleetData['fleet_mission'] == 1) + { + $FleetParse['Fleet_Mission'] = "{$FleetParse['Fleet_Mission']}"; + } + } + if(($FleetData['fleet_mess'] == 0 AND $FleetData['fleet_start_time'] <= $Now) OR ($FleetData['fleet_mess'] != 0 AND $FleetData['fleet_end_time'] <= $Now)) + { + $FleetParse['Fleet_Mission'] = "{$FleetParse['Fleet_Mission']}
[{$_Lang['Not_calculated']}]"; + } + if(($FleetData['fleet_start_time'] <= $Now AND $FleetData['fleet_mission'] != 5) OR ($FleetData['fleet_mission'] == 5 AND $FleetData['fleet_end_stay'] <= $Now)) + { + $FleetParse['Fleet_Mission'] .= "
[{$_Lang['Coming_back']}]"; + } + if($FleetData['fleet_mission'] == 5) + { + if($FleetData['fleet_start_time'] <= $Now AND $FleetData['fleet_end_stay'] > $Now) + { + $FleetParse['Fleet_Mission'] .= "
(".pretty_time($FleetData['fleet_end_stay'] - $Now, true, 'D').")"; + $Parse['ChronoApplets'] .= InsertJavaScriptChronoApplet('s', $FleetID, $FleetData['fleet_end_stay'] - $Now); + } + } + + $FleetArray = explode(';', $FleetData['fleet_array']); + foreach($FleetArray as $FleetShipsTemp) + { + if(!empty($FleetShipsTemp)) + { + $FleetShipsTemp = explode(',', $FleetShipsTemp); + $FleetCount += $FleetShipsTemp[1]; + $FleetShipsParsed[] = "{$_Lang['tech'][$FleetShipsTemp[0]]}".prettyNumber($FleetShipsTemp[1]).""; + } + } + $FleetCount = prettyNumber($FleetCount); + $FleetParse['Fleet_Ships'] = "".implode('', $FleetShipsParsed)."
"; + $FleetParse['Fleet_Array'] = "{$FleetCount}
(?)"; + if($FleetData['fleet_resource_metal'] == 0 AND $FleetData['fleet_resource_crystal'] == 0 AND $FleetData['fleet_resource_deuterium'] == 0) + { + $FleetParse['Fleet_Cargo'] = $_Lang['No_cargo']; + } + else + { + $FleetParse['Fleet_Cargo'] = $_Lang['See_cargo']; + $FleetParse['Fleet_Resources'] = "
{$_Lang['Metal']}".prettyNumber($FleetData['fleet_resource_metal'])."
{$_Lang['Crystal']}".prettyNumber($FleetData['fleet_resource_crystal'])."
{$_Lang['Deuterium']}".prettyNumber($FleetData['fleet_resource_deuterium'])."
"; + $FleetParse['Fleet_Cargo_class'] = ' fCar'; + } + $FleetParse['Fleet_Start_Title'] = ($FleetData['fleet_start_type'] == '1' ? $_Lang['Start_from_planet'] : $_Lang['Start_from_moon']); + $FleetParse['Fleet_Start'] = "[{$FleetData['fleet_start_galaxy']}:{$FleetData['fleet_start_system']}:{$FleetData['fleet_start_planet']}] ".($FleetData['fleet_start_type'] == '1' ? $_Lang['Planet_sign'] : $_Lang['Moon_sign']).""; + $FleetParse['Fleet_Start'] .= "
".date('d.m.Y', $FleetData['fleet_send_time'])."
".date('H:i:s', $FleetData['fleet_send_time'])."
(".pretty_time($Now - $FleetData['fleet_send_time'], true, 'D')." {$_Lang['_ago']})"; + $Parse['ChronoApplets'] .= InsertJavaScriptChronoApplet('a', $FleetID, $FleetData['fleet_send_time'], true, true); + + $FleetParse['Fleet_End_Title'] = ($FleetData['fleet_end_type'] == '1' ? $_Lang['Target_is_planet'] : ($FleetData['fleet_end_type'] == '2' ? $_Lang['Target_is_debris'] : $_Lang['Target_is_moon'])); + $FleetParse['Fleet_End'] = "[{$FleetData['fleet_end_galaxy']}:{$FleetData['fleet_end_system']}:{$FleetData['fleet_end_planet']}] ".($FleetData['fleet_end_type'] == '1' ? $_Lang['Planet_sign'] : ($FleetData['fleet_end_type'] == '2' ? $_Lang['Debris_sign'] : $_Lang['Moon_sign'])).""; + if($FleetData['fleet_start_time'] <= $Now) + { + $FleetParse['Fleet_end_time_set'] = "{$_Lang['TargetAchieved']}"; + } + else + { + $FleetParse['Fleet_end_time_set'] = pretty_time($FleetData['fleet_start_time'] - $Now, true, 'D'); + $Parse['ChronoApplets'] .= InsertJavaScriptChronoApplet('b', $FleetID, $FleetData['fleet_start_time'] - $Now); + } + $FleetParse['Fleet_End'] .= "
".date('d.m.Y', $FleetData['fleet_start_time'])."
".date('H:i:s', $FleetData['fleet_start_time'])."
({$FleetParse['Fleet_end_time_set']})"; + + if($FleetData['fleet_target_owner'] > 0) + { + $FleetParse['Fleet_End_owner'] = "{$UsersNicks[$FleetData['fleet_target_owner']]}
[{$FleetData['fleet_target_owner']}]"; + if($FleetData['fleet_target_owner'] == $FleetData['fleet_owner']) + { + $FleetParse['Fleet_End_owner_color'] = 'lime'; + } + else + { + if(in_array($FleetData['fleet_mission'], array(1, 2, 6, 9, 10, 11))) + { + $FleetParse['Fleet_End_owner_color'] = 'red'; + } + else + { + $FleetParse['Fleet_End_owner_color'] = 'blue'; + } + } + $FleetParse['Fleet_End_owner'] = "{$FleetParse['Fleet_End_owner']}"; + } + else + { + $FleetParse['Fleet_End_owner'] = $_Lang['None']; + } + + if($FleetData['fleet_end_time'] <= $Now) + { + $FleetParse['Fleet_back_time_set'] = "{$_Lang['FleetCameBack']}"; + } + else + { + $FleetParse['Fleet_back_time_set'] = pretty_time($FleetData['fleet_end_time'] - $Now, true, 'D'); + $Parse['ChronoApplets'] .= InsertJavaScriptChronoApplet('c', $FleetID, $FleetData['fleet_end_time'] - $Now); + } + $FleetParse['Fleet_Back_time'] = date('d.m.Y', $FleetData['fleet_end_time'])."
".date('H:i:s', $FleetData['fleet_end_time'])."
({$FleetParse['Fleet_back_time_set']})"; + + $AllFleetParse .= parsetemplate($RowTPL, $FleetParse); + } + + $Parse['Rows'] = $AllFleetParse; + } + + $Page = parsetemplate($PageTPL, $Parse); + + display($Page, $_Lang['PageTitle'], false, true); +} +else +{ + AdminMessage($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); +} + +?> diff --git a/admin/SFBSettings.php b/admin/SFBSettings.php index e79ed4f39..9dbe11efc 100644 --- a/admin/SFBSettings.php +++ b/admin/SFBSettings.php @@ -1,700 +1,700 @@ - 'users', 3 => 'planets'); - $_NeedElementIDTypes = array(2, 3); - - if(empty($_GET['cmd'])) - { - $_CMD = 1; - } - else - { - if($_GET['cmd'] == 'add') - { - $_CMD = 2; - if(isset($_POST['action']) && $_POST['action'] == 'save') - { - $_FormData_Type = intval($_POST['type']); - $_FormData_StartTime = strtotime($_POST['startTime_date']); - $_FormData_EndTime = strtotime($_POST['endTime_date']); - $_FormData_PostEndTime = strtotime($_POST['postEndTime_date']); - $_FormData_ElementID = round($_POST['elementID']); - $_FormData_DontBlockIfIdle = (isset($_POST['dontBlockIfIdle']) && $_POST['dontBlockIfIdle'] == 'on' ? 1 : 0); - $_FormData_Reason = $_POST['reason']; - if(!empty($_POST['mission']) AND (array)$_POST['mission'] === $_POST['mission']) - { - foreach($_POST['mission'] as $MissionID => $Data) - { - $MissionID = intval($MissionID); - if($Data == 'on' AND in_array($MissionID, $_Vars_FleetMissions['all'])) - { - $_FormData_Missions[] = $MissionID; - } - } - } - if($_FormData_StartTime <= $Now) - { - $_FormData_StartTime = $Now; - } - if($_FormData_PostEndTime <= $_FormData_EndTime) - { - $_FormData_PostEndTime = 0; - } - - if($_FormData_StartTime <= $_FormData_EndTime) - { - if(in_array($_FormData_Type, $_AllowedTypes)) - { - if($_FormData_Type == 1) - { - $_FormData_ElementID = 0; - } - elseif($_FormData_Type == 2 OR $_FormData_Type == 3) - { - $_FormData_DontBlockIfIdle = 0; - $_FormData_PostEndTime = 0; - } - - if(!empty($_FormData_Missions)) - { - if($_FormData_EndTime > $Now) - { - $AllowProceed = false; - if(in_array($_FormData_Type, $_NeedElementIDTypes)) - { - if($_FormData_ElementID > 0) - { - $CheckElementID = doquery("SELECT `ID` FROM {{table}} WHERE `id` = {$_FormData_ElementID} LIMIT 1;", $_BlockTypesTables[$_FormData_Type], true); - if($CheckElementID['ID'] == $_FormData_ElementID) - { - $AllowProceed = true; - } - else - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_AddElementIDNoExists']; - $_Lang['Insert_MsgBoxColor'] = 'red'; - } - } - else - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_AddBadElementID']; - $_Lang['Insert_MsgBoxColor'] = 'red'; - } - } - else - { - $AllowProceed = true; - } - - if($AllowProceed === true) - { - $_FormData_Reason = mysql_real_escape_string($_FormData_Reason); - if(count($_FormData_Missions) == count($_Vars_FleetMissions['all'])) - { - $_FormData_Missions = array('0'); - } - $_FormData_Missions = implode(',', $_FormData_Missions); - - $InsertSFB = "INSERT INTO {{table}} SET "; - $InsertSFB .= "`AdminID` = '{$_User['id']}', "; - $InsertSFB .= "`Type` = {$_FormData_Type},"; - $InsertSFB .= "`BlockMissions` = '{$_FormData_Missions}',"; - $InsertSFB .= "`Reason` = '{$_FormData_Reason}',"; - $InsertSFB .= "`StartTime` = '{$_FormData_StartTime}',"; - $InsertSFB .= "`EndTime` = '{$_FormData_EndTime}',"; - $InsertSFB .= "`PostEndTime` = '{$_FormData_PostEndTime}',"; - $InsertSFB .= "`ElementID` = '{$_FormData_ElementID}',"; - $InsertSFB .= "`DontBlockIfIdle` = '{$_FormData_DontBlockIfIdle}';"; - doquery($InsertSFB, 'smart_fleet_blockade'); - - header('Location: ?msg=addok'); - safeDie(); - } - } - else - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_AddEndTimeBad']; - $_Lang['Insert_MsgBoxColor'] = 'red'; - } - } - else - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_AddNoMissions']; - $_Lang['Insert_MsgBoxColor'] = 'red'; - } - } - else - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_AddBadType']; - $_Lang['Insert_MsgBoxColor'] = 'red'; - } - } - else - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_AddBadStart']; - $_Lang['Insert_MsgBoxColor'] = 'red'; - } - } - } - else if($_GET['cmd'] == 'edit') - { - $_CMD = 3; - $RowID = isset($_GET['id']) ? round($_GET['id']) : 0; - if($RowID > 0) - { - $GetEditRow = doquery("SELECT * FROM {{table}} WHERE `ID` = {$RowID} LIMIT 1;", 'smart_fleet_blockade', true); - if($GetEditRow['ID'] == $RowID) - { - if(($GetEditRow['EndTime'] > $Now) OR ($GetEditRow['PostEndTime'] > $Now AND $GetEditRow['Type'] == 1)) - { - $_FormData_Type = $GetEditRow['Type']; - $_FormData_StartTime = $GetEditRow['StartTime']; - $_FormData_EndTime = $GetEditRow['EndTime']; - $_FormData_PostEndTime = $GetEditRow['PostEndTime']; - $_FormData_ElementID = $GetEditRow['ElementID']; - $_FormData_DontBlockIfIdle = ($GetEditRow['DontBlockIfIdle'] == 1 ? 1 : 0); - $_FormData_Reason = $GetEditRow['Reason']; - if($GetEditRow['BlockMissions'] == '0') - { - $_FormData_Missions = $_Vars_FleetMissions['all']; - } - else - { - $_FormData_Missions = explode(',', $GetEditRow['BlockMissions']); - } - if($_FormData_StartTime > $Now) - { - $_Lang['Insert_Current_StartTime'] = date('(Y-m-d H:i:s)', $_FormData_StartTime); - } - else - { - $_Lang['Insert_Disable_StartTime'] = $_Disabled; - } - $_Lang['Insert_Current_EndTime'] = date('(Y-m-d H:i:s)', $_FormData_EndTime); - if($_FormData_PostEndTime > 0) - { - $_Lang['Insert_Current_PostEndTime'] = date('(Y-m-d H:i:s)', $_FormData_PostEndTime); - } - else - { - $HidePostEndTime = true; - } - if($_FormData_Type != 1) - { - $_Lang['Insert_Disable_PostEndTime'] = $_Disabled; - } - else - { - if($_FormData_EndTime <= $Now) - { - $_Lang['Insert_Disable_EndTime'] = $_Disabled; - } - } - - if(isset($_POST['action']) && $_POST['action'] == 'save') - { - $_FormData_StartTime = isset($_POST['startTime_date']) ? strtotime($_POST['startTime_date']) : 0; - $_FormData_EndTime = strtotime($_POST['endTime_date']); - $_FormData_PostEndTime = strtotime($_POST['postEndTime_date']); - $_FormData_DontBlockIfIdle = (isset($_POST['dontBlockIfIdle']) && $_POST['dontBlockIfIdle'] == 'on' ? 1 : 0); - $_FormData_Reason = $_POST['reason']; - $_FormData_Missions = array(); - if(!empty($_POST['mission']) AND (array)$_POST['mission'] === $_POST['mission']) - { - foreach($_POST['mission'] as $MissionID => $Data) - { - $MissionID = intval($MissionID); - if($Data == 'on' AND in_array($MissionID, $_Vars_FleetMissions['all'])) - { - $_FormData_Missions[] = $MissionID; - } - } - } - if($GetEditRow['StartTime'] <= $Now) - { - $_FormData_StartTime = $GetEditRow['StartTime']; - } - else - { - if($_FormData_StartTime <= $Now) - { - $_FormData_StartTime = $Now; - } - } - if($_FormData_PostEndTime <= $_FormData_EndTime) - { - $_FormData_PostEndTime = 0; - } - - if($_FormData_Type == 2 OR $_FormData_Type == 3) - { - $_FormData_DontBlockIfIdle = 0; - $_FormData_PostEndTime = 0; - } - else - { - if($GetEditRow['EndTime'] <= $Now) - { - $_FormData_EndTime = $GetEditRow['EndTime']; - } - } - - if(!empty($_FormData_Missions)) - { - if($GetEditRow['EndTime'] <= $_FormData_EndTime) - { - if(!($_FormData_Type == 1 AND $GetEditRow['EndTime'] <= $Now AND $_FormData_PostEndTime < $GetEditRow['PostEndTime'])) - { - $_FormData_Reason = mysql_real_escape_string($_FormData_Reason); - if(count($_FormData_Missions) == count($_Vars_FleetMissions['all'])) - { - $_FormData_Missions = array('0'); - } - $_FormData_Missions = implode(',', $_FormData_Missions); - - $UpdateSFB = "UPDATE {{table}} SET "; - $UpdateSFB .= "`BlockMissions` = '{$_FormData_Missions}',"; - $UpdateSFB .= "`Reason` = '{$_FormData_Reason}',"; - $UpdateSFB .= "`StartTime` = '{$_FormData_StartTime}', "; - $UpdateSFB .= "`EndTime` = '{$_FormData_EndTime}',"; - $UpdateSFB .= "`PostEndTime` = '{$_FormData_PostEndTime}',"; - $UpdateSFB .= "`DontBlockIfIdle` = '{$_FormData_DontBlockIfIdle}' "; - $UpdateSFB .= "WHERE `ID` = {$RowID};"; - doquery($UpdateSFB, 'smart_fleet_blockade'); - - header('Location: ?msg=editok'); - safeDie(); - } - else - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_EditPostEndTimeBad']; - $_Lang['Insert_MsgBoxColor'] = 'red'; - } - } - else - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_EditEndTimeBad']; - $_Lang['Insert_MsgBoxColor'] = 'red'; - } - } - else - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_EditNoMissions']; - $_Lang['Insert_MsgBoxColor'] = 'red'; - } - } - } - else - { - header('Location: ?msg=editold'); - safeDie(); - } - } - else - { - header('Location: ?msg=editnoid'); - safeDie(); - } - } - else - { - header('Location: ?msg=editbadid'); - safeDie(); - } - } - else if($_GET['cmd'] == 'cancel') - { - $_CMD = 1; // Use Overview & show there all messages from system - $CancelID = round($_GET['id']); - if($CancelID > 0) - { - $GetSFBRow = doquery("SELECT * FROM {{table}} WHERE `ID` = {$CancelID} LIMIT 1;", 'smart_fleet_blockade', true); - if($GetSFBRow['ID'] == $CancelID) - { - if($GetSFBRow['EndTime'] > $Now OR $GetSFBRow['PostEndTime'] > $Now) - { - if($GetSFBRow['EndTime'] > $Now) - { - $UpdateQueryArray[] = "`EndTime` = UNIX_TIMESTAMP()"; - } - if($GetSFBRow['PostEndTime'] > $Now) - { - $UpdateQueryArray[] = "`PostEndTime` = UNIX_TIMESTAMP()"; - } - $UpdateQuery = "UPDATE {{table}} SET ".implode(', ', $UpdateQueryArray)." WHERE `ID` = {$CancelID};"; - doquery($UpdateQuery, 'smart_fleet_blockade'); - - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_CancelOK']; - $_Lang['Insert_MsgBoxColor'] = 'lime'; - } - else - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_CancelInactive']; - $_Lang['Insert_MsgBoxColor'] = 'orange'; - } - } - else - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_CancelNoExist']; - $_Lang['Insert_MsgBoxColor'] = 'red'; - } - } - else - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_CancelBadID']; - $_Lang['Insert_MsgBoxColor'] = 'red'; - } - } - } - - if($_CMD == 1) - { - // Show Overview (Active Blockades & Short Log) - $TPL = gettemplate('admin/SFBSettings_body_overview'); - - $SelectActiveSFB = "SELECT * FROM {{table}} WHERE `EndTime` > UNIX_TIMESTAMP() OR `PostEndTime` > UNIX_TIMESTAMP() ORDER BY `EndTime` ASC;"; - $SelectInActiveSFB = "SELECT * FROM {{table}} WHERE `EndTime` <= UNIX_TIMESTAMP() AND (`PostEndTime` = 0 OR (`PostEndTime` <= UNIX_TIMESTAMP() AND `PostEndTime` > 0)) ORDER BY `EndTime` DESC LIMIT 10;"; - - $ActiveSFB = doquery($SelectActiveSFB, 'smart_fleet_blockade'); - $InActiveSFB = doquery($SelectInActiveSFB, 'smart_fleet_blockade'); - - $CombineData = array - ( - array('Result' => $ActiveSFB, 'Prefix' => 'ActiveList', 'RowType' => 1, 'NoRowsText' => $_Lang['SFB_ActiveList_NoElements']), - array('Result' => $InActiveSFB, 'Prefix' => 'InActiveList', 'RowType' => 2, 'NoRowsText' => $_Lang['SFB_InActiveList_NoElements']), - ); - } - else if($_CMD == 2 OR $_CMD == 3) - { - // Show Adding or Editing Form - $TPL = gettemplate('admin/SFBSettings_body_manage'); - $TPL_Manage_MissionSelector = gettemplate('admin/SFBSettings_body_manage_missionselector'); - - $_Lang['Insert_MissionSelectors'] = ''; - foreach($_Vars_FleetMissions['all'] as $MissionID) - { - $MissionSelector = array(); - $MissionSelector['MissionID'] = $MissionID; - if(in_array($MissionID, $_Vars_FleetMissions['civil'])) - { - $MissionSelector['MissionClass'] = 'civil'; - } - else - { - $MissionSelector['MissionClass'] = 'military'; - } - if(!empty($_FormData_Missions) AND in_array($MissionID, $_FormData_Missions)) - { - $MissionSelector['IsChecked'] = $_Checked; - } - $MissionSelector['MissionName'] = $_Lang['SFB_Mission__'.$MissionID]; - - $_Lang['Insert_MissionSelectors'] .= parsetemplate($TPL_Manage_MissionSelector, $MissionSelector); - } - - if(isset($_FormData_Type) && in_array($_FormData_Type, $_AllowedTypes)) - { - $_Lang['Insert_Form_Select_Type_'.$_FormData_Type] = $_Selected; - } - if(empty($_FormData_StartTime)) - { - $_Lang['Insert_startTime_date'] = date('Y-m-d H:i:s', $Now - ($Now % 60)); - } - else - { - $_Lang['Insert_startTime_date'] = date('Y-m-d H:i:s', $_FormData_StartTime); - } - if(empty($_FormData_EndTime)) - { - $_Lang['Insert_endTime_date'] = date('Y-m-d H:i:s', ($Now + TIME_DAY - ($Now % 60))); - } - else - { - $_Lang['Insert_endTime_date'] = date('Y-m-d H:i:s', $_FormData_EndTime); - } - if(!isset($HidePostEndTime)) - { - if(empty($_FormData_PostEndTime)) - { - $_Lang['Insert_postEndTime_date'] = date('Y-m-d H:i:s', ($Now + (2 * TIME_DAY) - ($Now % 60))); - } - else - { - $_Lang['Insert_postEndTime_date'] = date('Y-m-d H:i:s', $_FormData_PostEndTime); - } - } - if(!empty($_FormData_ElementID)) - { - $_Lang['Insert_Form_ElementID'] = $_FormData_ElementID; - } - if(isset($_FormData_DontBlockIfIdle) && $_FormData_DontBlockIfIdle == 1) - { - $_Lang['Insert_Form_Select_DontBlockIfIdle'] = $_Checked; - } - if(!empty($_FormData_Reason)) - { - $_Lang['Insert_Form_Reason'] = stripslashes($_FormData_Reason); - } - - if($_CMD == 2) - { - $_Lang['Insert_SubmitButton'] = $_Lang['SFB_Labels_SubmitAdd']; - } - else - { - $_Lang['Insert_SubmitButton'] = $_Lang['SFB_Labels_SubmitEdit']; - $_Lang['Insert_Disable_TypeSelect'] = $_Disabled; - $_Lang['Insert_Disable_ElementID'] = $_Disabled; - } - } - - if(empty($_Lang['Insert_MsgBoxText'])) - { - if(isset($_GET['msg']) && $_GET['msg'] == 'addok') - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_AddOK']; - $_Lang['Insert_MsgBoxColor'] = 'lime'; - } - else if(isset($_GET['msg']) && $_GET['msg'] == 'editok') - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_EditOK']; - $_Lang['Insert_MsgBoxColor'] = 'lime'; - } - else if(isset($_GET['msg']) && $_GET['msg'] == 'editold') - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_EditOldRow']; - $_Lang['Insert_MsgBoxColor'] = 'orange'; - } - else if(isset($_GET['msg']) && $_GET['msg'] == 'editnoid') - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_EditRowNoExists']; - $_Lang['Insert_MsgBoxColor'] = 'red'; - } - else if(isset($_GET['msg']) && $_GET['msg'] == 'editbadid') - { - $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_EditBadID']; - $_Lang['Insert_MsgBoxColor'] = 'red'; - } - else - { - $_Lang['Insert_HideMsgBox'] = 'inv'; - $_Lang['Insert_MsgBoxText'] = ' '; - } - } - - if(!empty($CombineData)) - { - foreach($CombineData as $Data) - { - if(mysql_num_rows($Data['Result']) > 0) - { - $_Lang['Insert_'.$Data['Prefix']] = $Parsed_List_Headers; - while($SFBData = mysql_fetch_assoc($Data['Result'])) - { - $SFBData['RowType'] = $Data['RowType']; - $SFBData['RowPrefix'] = $Data['Prefix']; - $SFBRows[] = $SFBData; - $GetUsernames[] = $SFBData['AdminID']; - if($SFBData['Type'] == 2) - { - $GetUsernames[] = $SFBData['ElementID']; - } - if($SFBData['Type'] == 3) - { - $GetPlanetsData[] = $SFBData['ElementID']; - } - } - } - else - { - $_Lang['Insert_'.$Data['Prefix']] = parsetemplate($TPL_List_NoElements, array('Text' => $Data['NoRowsText'])); - } - } - - if(!empty($SFBRows)) - { - include($_EnginePath.'includes/functions/InsertJavaScriptChronoApplet.php'); - - if(!empty($GetUsernames)) - { - $GetUsernames = doquery("SELECT `id`, `username` FROM {{table}} WHERE `id` IN (".implode(', ', $GetUsernames).");", 'users'); - if(mysql_num_rows($GetUsernames) > 0) - { - while($LoadData = mysql_fetch_assoc($GetUsernames)) - { - $Usernames[$LoadData['id']] = $LoadData['username']; - } - } - } - if(!empty($GetPlanetsData)) - { - $GetPlanetsData = doquery("SELECT `id`, `name`, `galaxy`, `system`, `planet`, `planet_type` FROM {{table}} WHERE `id` IN (".implode(', ', $GetPlanetsData).");", 'planets'); - if(mysql_num_rows($GetPlanetsData) > 0) - { - while($LoadData = mysql_fetch_assoc($GetPlanetsData)) - { - $Planets[$LoadData['id']] = $LoadData; - } - } - } - if($_GameConfig['enable_bbcode'] == 1) - { - include($_EnginePath.'includes/functions/BBcodeFunction.php'); - } - - foreach($SFBRows as $DataRow) - { - $DataRow['AdminParsed'] = "{$Usernames[$DataRow['AdminID']]} (#{$DataRow['AdminID']})"; - $DataRow['TypeParsed'] = $_Lang['SFB_Types_'.$DataRow['Type']]; - if($DataRow['Type'] == 2) - { - $DataRow['ElementParsed'] = (!empty($Usernames[$DataRow['ElementID']]) ? "{$Usernames[$DataRow['ElementID']]} (#{$DataRow['ElementID']})" : "{$_Lang['User_Deleted']} (#{$DataRow['ElementID']})"); - } - else if($DataRow['Type'] == 3) - { - $DataRow['ElementParsed'] = (!empty($Planets[$DataRow['ElementID']]) ? "{$Planets[$DataRow['ElementID']]['name']} (#{$DataRow['ElementID']})
[{$Planets[$DataRow['ElementID']]['galaxy']}:{$Planets[$DataRow['ElementID']]['system']}:{$Planets[$DataRow['ElementID']]['planet']}|".($Planets[$DataRow['ElementID']]['planet_type'] == 1 ? $_Lang['Symbols_Planet'] : $_Lang['Symbols_Moon'])."]
" : "".($Planets[$DataRow['ElementID']]['planet_type'] == 1 ? $_Lang['Planet_Deleted'] : $_Lang['Moon_Deleted'])." (#{$DataRow['ElementID']})"); - } - if($DataRow['BlockMissions'] == '0') - { - $DataRow['Missions'] = $_Lang['SFB_Mission_All']; - } - else - { - $ExplodeMissions = explode(',', $DataRow['BlockMissions']); - $CivilCount = 0; - $AggresiveCount = 0; - foreach($ExplodeMissions as $MissionID) - { - if(!in_array($MissionID, $_Vars_FleetMissions['all'])) - { - continue; - } - $DataRow['Missions'][] = $_Lang['SFB_Mission__'.$MissionID]; - if(in_array($MissionID, $_Vars_FleetMissions['civil'])) - { - $CivilCount += 1; - } - else - { - $AggresiveCount += 1; - } - } - if($CivilCount == count($_Vars_FleetMissions['civil']) AND $AggresiveCount == 0) - { - $DataRow['Missions'] = $_Lang['SFB_Mission_Civil']; - } - else if($AggresiveCount == count($_Vars_FleetMissions['military']) AND $CivilCount == 0) - { - $DataRow['Missions'] = $_Lang['SFB_Mission_Aggresive']; - } - else - { - $DataRow['Missions'] = implode(', ', $DataRow['Missions']); - } - } - if($DataRow['StartTime'] > $Now) - { - $_Lang['Insert_ChronoApplets'] .= InsertJavaScriptChronoApplet('Start', $DataRow['ID'], $DataRow['StartTime'], true); - $DataRow['StartTime'] = prettyDate('d m Y, H:i:s', $DataRow['StartTime'], 1)."
{$_Lang['SFB_EndIn']}: ".pretty_time($DataRow['StartTime'] - $Now, true, 'D').""; - } - else - { - $DataRow['StartTime'] = prettyDate('d m Y, H:i:s', $DataRow['StartTime'], 1); - } - if($DataRow['EndTime'] > $Now) - { - $_Lang['Insert_ChronoApplets'] .= InsertJavaScriptChronoApplet('End', $DataRow['ID'], $DataRow['EndTime'], true); - $DataRow['EndTime'] = prettyDate('d m Y, H:i:s', $DataRow['EndTime'], 1)."
{$_Lang['SFB_EndIn']}: ".pretty_time($DataRow['EndTime'] - $Now, true, 'D').""; - } - else - { - $DataRow['EndTime'] = prettyDate('d m Y, H:i:s', $DataRow['EndTime'], 1); - } - if($DataRow['Type'] == 1 AND $DataRow['PostEndTime'] > 0) - { - if($DataRow['PostEndTime'] > $Now) - { - $_Lang['Insert_ChronoApplets'] .= InsertJavaScriptChronoApplet('PostEnd', $DataRow['ID'], $DataRow['PostEndTime'], true); - $DataRow['PostEndTimeParse'] = prettyDate('d m Y, H:i:s', $DataRow['PostEndTime'], 1)."
{$_Lang['SFB_EndIn']}: ".pretty_time($DataRow['PostEndTime'] - $Now, true, 'D').""; - } - else - { - $DataRow['PostEndTimeParse'] = prettyDate('d m Y, H:i:s', $DataRow['PostEndTime'], 1); - } - $DataRow['PostEndTimeParse'] = "
{$DataRow['PostEndTimeParse']}
"; - } - if($DataRow['Type'] == 1 AND $DataRow['DontBlockIfIdle'] == 1) - { - $DataRow['AdditionalData'][] = $_Lang['SFB_Additional_DontBlockIfIdle']; - } - if(empty($DataRow['AdditionalData'])) - { - $DataRow['AdditionalData'] = ' '; - } - else - { - $DataRow['AdditionalData'] = implode('
', $DataRow['AdditionalData']); - } - - if(empty($DataRow['Reason'])) - { - $DataRow['Reason'] = '-'; - } - else - { - if($_GameConfig['enable_bbcode'] == 1){ - $DataRow['Reason'] = trim(nl2br(bbcode(image(strip_tags(str_replace("'", ''', $DataRow['Reason']), '

'))))); - } else { - $DataRow['Reason'] = trim(nl2br(strip_tags($DataRow['Reason'], '

'))); - } - } - - if($DataRow['RowType'] == 2) - { - $DataRow['ActionsParsed'] = ' '; - } - else - { - $DataRow['ActionsParsed'][] = "{$_Lang['SFB_Action_Edit']}"; - $DataRow['ActionsParsed'][] = "{$_Lang['SFB_Action_Cancel']}"; - $DataRow['ActionsParsed'] = implode('
', $DataRow['ActionsParsed']);$DataRow['ActionsParsed']; - } - - $_Lang['Insert_'.$DataRow['RowPrefix']] .= parsetemplate($TPL_List_Row, $DataRow); - } - } - } - - $Title = $_Lang['SFB_Title']; - $Page = parsetemplate($TPL, $_Lang); - - display($Page, $Title, false, true); - -?> \ No newline at end of file + 'users', 3 => 'planets'); +$_NeedElementIDTypes = array(2, 3); + +if(empty($_GET['cmd'])) +{ + $_CMD = 1; +} +else +{ + if($_GET['cmd'] == 'add') + { + $_CMD = 2; + if(isset($_POST['action']) && $_POST['action'] == 'save') + { + $_FormData_Type = intval($_POST['type']); + $_FormData_StartTime = strtotime($_POST['startTime_date']); + $_FormData_EndTime = strtotime($_POST['endTime_date']); + $_FormData_PostEndTime = strtotime($_POST['postEndTime_date']); + $_FormData_ElementID = round($_POST['elementID']); + $_FormData_DontBlockIfIdle = (isset($_POST['dontBlockIfIdle']) && $_POST['dontBlockIfIdle'] == 'on' ? 1 : 0); + $_FormData_Reason = $_POST['reason']; + if(!empty($_POST['mission']) AND (array)$_POST['mission'] === $_POST['mission']) + { + foreach($_POST['mission'] as $MissionID => $Data) + { + $MissionID = intval($MissionID); + if($Data == 'on' AND in_array($MissionID, $_Vars_FleetMissions['all'])) + { + $_FormData_Missions[] = $MissionID; + } + } + } + if($_FormData_StartTime <= $Now) + { + $_FormData_StartTime = $Now; + } + if($_FormData_PostEndTime <= $_FormData_EndTime) + { + $_FormData_PostEndTime = 0; + } + + if($_FormData_StartTime <= $_FormData_EndTime) + { + if(in_array($_FormData_Type, $_AllowedTypes)) + { + if($_FormData_Type == 1) + { + $_FormData_ElementID = 0; + } + elseif($_FormData_Type == 2 OR $_FormData_Type == 3) + { + $_FormData_DontBlockIfIdle = 0; + $_FormData_PostEndTime = 0; + } + + if(!empty($_FormData_Missions)) + { + if($_FormData_EndTime > $Now) + { + $AllowProceed = false; + if(in_array($_FormData_Type, $_NeedElementIDTypes)) + { + if($_FormData_ElementID > 0) + { + $CheckElementID = doquery("SELECT `ID` FROM {{table}} WHERE `id` = {$_FormData_ElementID} LIMIT 1;", $_BlockTypesTables[$_FormData_Type], true); + if($CheckElementID['ID'] == $_FormData_ElementID) + { + $AllowProceed = true; + } + else + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_AddElementIDNoExists']; + $_Lang['Insert_MsgBoxColor'] = 'red'; + } + } + else + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_AddBadElementID']; + $_Lang['Insert_MsgBoxColor'] = 'red'; + } + } + else + { + $AllowProceed = true; + } + + if($AllowProceed === true) + { + $_FormData_Reason = mysql_real_escape_string($_FormData_Reason); + if(count($_FormData_Missions) == count($_Vars_FleetMissions['all'])) + { + $_FormData_Missions = array('0'); + } + $_FormData_Missions = implode(',', $_FormData_Missions); + + $InsertSFB = "INSERT INTO {{table}} SET "; + $InsertSFB .= "`AdminID` = '{$_User['id']}', "; + $InsertSFB .= "`Type` = {$_FormData_Type},"; + $InsertSFB .= "`BlockMissions` = '{$_FormData_Missions}',"; + $InsertSFB .= "`Reason` = '{$_FormData_Reason}',"; + $InsertSFB .= "`StartTime` = '{$_FormData_StartTime}',"; + $InsertSFB .= "`EndTime` = '{$_FormData_EndTime}',"; + $InsertSFB .= "`PostEndTime` = '{$_FormData_PostEndTime}',"; + $InsertSFB .= "`ElementID` = '{$_FormData_ElementID}',"; + $InsertSFB .= "`DontBlockIfIdle` = '{$_FormData_DontBlockIfIdle}';"; + doquery($InsertSFB, 'smart_fleet_blockade'); + + header('Location: ?msg=addok'); + safeDie(); + } + } + else + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_AddEndTimeBad']; + $_Lang['Insert_MsgBoxColor'] = 'red'; + } + } + else + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_AddNoMissions']; + $_Lang['Insert_MsgBoxColor'] = 'red'; + } + } + else + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_AddBadType']; + $_Lang['Insert_MsgBoxColor'] = 'red'; + } + } + else + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_AddBadStart']; + $_Lang['Insert_MsgBoxColor'] = 'red'; + } + } + } + else if($_GET['cmd'] == 'edit') + { + $_CMD = 3; + $RowID = isset($_GET['id']) ? round($_GET['id']) : 0; + if($RowID > 0) + { + $GetEditRow = doquery("SELECT * FROM {{table}} WHERE `ID` = {$RowID} LIMIT 1;", 'smart_fleet_blockade', true); + if($GetEditRow['ID'] == $RowID) + { + if(($GetEditRow['EndTime'] > $Now) OR ($GetEditRow['PostEndTime'] > $Now AND $GetEditRow['Type'] == 1)) + { + $_FormData_Type = $GetEditRow['Type']; + $_FormData_StartTime = $GetEditRow['StartTime']; + $_FormData_EndTime = $GetEditRow['EndTime']; + $_FormData_PostEndTime = $GetEditRow['PostEndTime']; + $_FormData_ElementID = $GetEditRow['ElementID']; + $_FormData_DontBlockIfIdle = ($GetEditRow['DontBlockIfIdle'] == 1 ? 1 : 0); + $_FormData_Reason = $GetEditRow['Reason']; + if($GetEditRow['BlockMissions'] == '0') + { + $_FormData_Missions = $_Vars_FleetMissions['all']; + } + else + { + $_FormData_Missions = explode(',', $GetEditRow['BlockMissions']); + } + if($_FormData_StartTime > $Now) + { + $_Lang['Insert_Current_StartTime'] = date('(Y-m-d H:i:s)', $_FormData_StartTime); + } + else + { + $_Lang['Insert_Disable_StartTime'] = $_Disabled; + } + $_Lang['Insert_Current_EndTime'] = date('(Y-m-d H:i:s)', $_FormData_EndTime); + if($_FormData_PostEndTime > 0) + { + $_Lang['Insert_Current_PostEndTime'] = date('(Y-m-d H:i:s)', $_FormData_PostEndTime); + } + else + { + $HidePostEndTime = true; + } + if($_FormData_Type != 1) + { + $_Lang['Insert_Disable_PostEndTime'] = $_Disabled; + } + else + { + if($_FormData_EndTime <= $Now) + { + $_Lang['Insert_Disable_EndTime'] = $_Disabled; + } + } + + if(isset($_POST['action']) && $_POST['action'] == 'save') + { + $_FormData_StartTime = isset($_POST['startTime_date']) ? strtotime($_POST['startTime_date']) : 0; + $_FormData_EndTime = strtotime($_POST['endTime_date']); + $_FormData_PostEndTime = strtotime($_POST['postEndTime_date']); + $_FormData_DontBlockIfIdle = (isset($_POST['dontBlockIfIdle']) && $_POST['dontBlockIfIdle'] == 'on' ? 1 : 0); + $_FormData_Reason = $_POST['reason']; + $_FormData_Missions = array(); + if(!empty($_POST['mission']) AND (array)$_POST['mission'] === $_POST['mission']) + { + foreach($_POST['mission'] as $MissionID => $Data) + { + $MissionID = intval($MissionID); + if($Data == 'on' AND in_array($MissionID, $_Vars_FleetMissions['all'])) + { + $_FormData_Missions[] = $MissionID; + } + } + } + if($GetEditRow['StartTime'] <= $Now) + { + $_FormData_StartTime = $GetEditRow['StartTime']; + } + else + { + if($_FormData_StartTime <= $Now) + { + $_FormData_StartTime = $Now; + } + } + if($_FormData_PostEndTime <= $_FormData_EndTime) + { + $_FormData_PostEndTime = 0; + } + + if($_FormData_Type == 2 OR $_FormData_Type == 3) + { + $_FormData_DontBlockIfIdle = 0; + $_FormData_PostEndTime = 0; + } + else + { + if($GetEditRow['EndTime'] <= $Now) + { + $_FormData_EndTime = $GetEditRow['EndTime']; + } + } + + if(!empty($_FormData_Missions)) + { + if($GetEditRow['EndTime'] <= $_FormData_EndTime) + { + if(!($_FormData_Type == 1 AND $GetEditRow['EndTime'] <= $Now AND $_FormData_PostEndTime < $GetEditRow['PostEndTime'])) + { + $_FormData_Reason = mysql_real_escape_string($_FormData_Reason); + if(count($_FormData_Missions) == count($_Vars_FleetMissions['all'])) + { + $_FormData_Missions = array('0'); + } + $_FormData_Missions = implode(',', $_FormData_Missions); + + $UpdateSFB = "UPDATE {{table}} SET "; + $UpdateSFB .= "`BlockMissions` = '{$_FormData_Missions}',"; + $UpdateSFB .= "`Reason` = '{$_FormData_Reason}',"; + $UpdateSFB .= "`StartTime` = '{$_FormData_StartTime}', "; + $UpdateSFB .= "`EndTime` = '{$_FormData_EndTime}',"; + $UpdateSFB .= "`PostEndTime` = '{$_FormData_PostEndTime}',"; + $UpdateSFB .= "`DontBlockIfIdle` = '{$_FormData_DontBlockIfIdle}' "; + $UpdateSFB .= "WHERE `ID` = {$RowID};"; + doquery($UpdateSFB, 'smart_fleet_blockade'); + + header('Location: ?msg=editok'); + safeDie(); + } + else + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_EditPostEndTimeBad']; + $_Lang['Insert_MsgBoxColor'] = 'red'; + } + } + else + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_EditEndTimeBad']; + $_Lang['Insert_MsgBoxColor'] = 'red'; + } + } + else + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_EditNoMissions']; + $_Lang['Insert_MsgBoxColor'] = 'red'; + } + } + } + else + { + header('Location: ?msg=editold'); + safeDie(); + } + } + else + { + header('Location: ?msg=editnoid'); + safeDie(); + } + } + else + { + header('Location: ?msg=editbadid'); + safeDie(); + } + } + else if($_GET['cmd'] == 'cancel') + { + $_CMD = 1; // Use Overview & show there all messages from system + $CancelID = round($_GET['id']); + if($CancelID > 0) + { + $GetSFBRow = doquery("SELECT * FROM {{table}} WHERE `ID` = {$CancelID} LIMIT 1;", 'smart_fleet_blockade', true); + if($GetSFBRow['ID'] == $CancelID) + { + if($GetSFBRow['EndTime'] > $Now OR $GetSFBRow['PostEndTime'] > $Now) + { + if($GetSFBRow['EndTime'] > $Now) + { + $UpdateQueryArray[] = "`EndTime` = UNIX_TIMESTAMP()"; + } + if($GetSFBRow['PostEndTime'] > $Now) + { + $UpdateQueryArray[] = "`PostEndTime` = UNIX_TIMESTAMP()"; + } + $UpdateQuery = "UPDATE {{table}} SET ".implode(', ', $UpdateQueryArray)." WHERE `ID` = {$CancelID};"; + doquery($UpdateQuery, 'smart_fleet_blockade'); + + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_CancelOK']; + $_Lang['Insert_MsgBoxColor'] = 'lime'; + } + else + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_CancelInactive']; + $_Lang['Insert_MsgBoxColor'] = 'orange'; + } + } + else + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_CancelNoExist']; + $_Lang['Insert_MsgBoxColor'] = 'red'; + } + } + else + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_CancelBadID']; + $_Lang['Insert_MsgBoxColor'] = 'red'; + } + } +} + +if($_CMD == 1) +{ + // Show Overview (Active Blockades & Short Log) + $TPL = gettemplate('admin/SFBSettings_body_overview'); + + $SelectActiveSFB = "SELECT * FROM {{table}} WHERE `EndTime` > UNIX_TIMESTAMP() OR `PostEndTime` > UNIX_TIMESTAMP() ORDER BY `EndTime` ASC;"; + $SelectInActiveSFB = "SELECT * FROM {{table}} WHERE `EndTime` <= UNIX_TIMESTAMP() AND (`PostEndTime` = 0 OR (`PostEndTime` <= UNIX_TIMESTAMP() AND `PostEndTime` > 0)) ORDER BY `EndTime` DESC LIMIT 10;"; + + $ActiveSFB = doquery($SelectActiveSFB, 'smart_fleet_blockade'); + $InActiveSFB = doquery($SelectInActiveSFB, 'smart_fleet_blockade'); + + $CombineData = array + ( + array('Result' => $ActiveSFB, 'Prefix' => 'ActiveList', 'RowType' => 1, 'NoRowsText' => $_Lang['SFB_ActiveList_NoElements']), + array('Result' => $InActiveSFB, 'Prefix' => 'InActiveList', 'RowType' => 2, 'NoRowsText' => $_Lang['SFB_InActiveList_NoElements']), + ); +} +else if($_CMD == 2 OR $_CMD == 3) +{ + // Show Adding or Editing Form + $TPL = gettemplate('admin/SFBSettings_body_manage'); + $TPL_Manage_MissionSelector = gettemplate('admin/SFBSettings_body_manage_missionselector'); + + $_Lang['Insert_MissionSelectors'] = ''; + foreach($_Vars_FleetMissions['all'] as $MissionID) + { + $MissionSelector = array(); + $MissionSelector['MissionID'] = $MissionID; + if(in_array($MissionID, $_Vars_FleetMissions['civil'])) + { + $MissionSelector['MissionClass'] = 'civil'; + } + else + { + $MissionSelector['MissionClass'] = 'military'; + } + if(!empty($_FormData_Missions) AND in_array($MissionID, $_FormData_Missions)) + { + $MissionSelector['IsChecked'] = $_Checked; + } + $MissionSelector['MissionName'] = $_Lang['SFB_Mission__'.$MissionID]; + + $_Lang['Insert_MissionSelectors'] .= parsetemplate($TPL_Manage_MissionSelector, $MissionSelector); + } + + if(isset($_FormData_Type) && in_array($_FormData_Type, $_AllowedTypes)) + { + $_Lang['Insert_Form_Select_Type_'.$_FormData_Type] = $_Selected; + } + if(empty($_FormData_StartTime)) + { + $_Lang['Insert_startTime_date'] = date('Y-m-d H:i:s', $Now - ($Now % 60)); + } + else + { + $_Lang['Insert_startTime_date'] = date('Y-m-d H:i:s', $_FormData_StartTime); + } + if(empty($_FormData_EndTime)) + { + $_Lang['Insert_endTime_date'] = date('Y-m-d H:i:s', ($Now + TIME_DAY - ($Now % 60))); + } + else + { + $_Lang['Insert_endTime_date'] = date('Y-m-d H:i:s', $_FormData_EndTime); + } + if(!isset($HidePostEndTime)) + { + if(empty($_FormData_PostEndTime)) + { + $_Lang['Insert_postEndTime_date'] = date('Y-m-d H:i:s', ($Now + (2 * TIME_DAY) - ($Now % 60))); + } + else + { + $_Lang['Insert_postEndTime_date'] = date('Y-m-d H:i:s', $_FormData_PostEndTime); + } + } + if(!empty($_FormData_ElementID)) + { + $_Lang['Insert_Form_ElementID'] = $_FormData_ElementID; + } + if(isset($_FormData_DontBlockIfIdle) && $_FormData_DontBlockIfIdle == 1) + { + $_Lang['Insert_Form_Select_DontBlockIfIdle'] = $_Checked; + } + if(!empty($_FormData_Reason)) + { + $_Lang['Insert_Form_Reason'] = stripslashes($_FormData_Reason); + } + + if($_CMD == 2) + { + $_Lang['Insert_SubmitButton'] = $_Lang['SFB_Labels_SubmitAdd']; + } + else + { + $_Lang['Insert_SubmitButton'] = $_Lang['SFB_Labels_SubmitEdit']; + $_Lang['Insert_Disable_TypeSelect'] = $_Disabled; + $_Lang['Insert_Disable_ElementID'] = $_Disabled; + } +} + +if(empty($_Lang['Insert_MsgBoxText'])) +{ + if(isset($_GET['msg']) && $_GET['msg'] == 'addok') + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_AddOK']; + $_Lang['Insert_MsgBoxColor'] = 'lime'; + } + else if(isset($_GET['msg']) && $_GET['msg'] == 'editok') + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_EditOK']; + $_Lang['Insert_MsgBoxColor'] = 'lime'; + } + else if(isset($_GET['msg']) && $_GET['msg'] == 'editold') + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_EditOldRow']; + $_Lang['Insert_MsgBoxColor'] = 'orange'; + } + else if(isset($_GET['msg']) && $_GET['msg'] == 'editnoid') + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_EditRowNoExists']; + $_Lang['Insert_MsgBoxColor'] = 'red'; + } + else if(isset($_GET['msg']) && $_GET['msg'] == 'editbadid') + { + $_Lang['Insert_MsgBoxText'] = $_Lang['SFB_Response_EditBadID']; + $_Lang['Insert_MsgBoxColor'] = 'red'; + } + else + { + $_Lang['Insert_HideMsgBox'] = 'inv'; + $_Lang['Insert_MsgBoxText'] = ' '; + } +} + +if(!empty($CombineData)) +{ + foreach($CombineData as $Data) + { + if(mysql_num_rows($Data['Result']) > 0) + { + $_Lang['Insert_'.$Data['Prefix']] = $Parsed_List_Headers; + while($SFBData = mysql_fetch_assoc($Data['Result'])) + { + $SFBData['RowType'] = $Data['RowType']; + $SFBData['RowPrefix'] = $Data['Prefix']; + $SFBRows[] = $SFBData; + $GetUsernames[] = $SFBData['AdminID']; + if($SFBData['Type'] == 2) + { + $GetUsernames[] = $SFBData['ElementID']; + } + if($SFBData['Type'] == 3) + { + $GetPlanetsData[] = $SFBData['ElementID']; + } + } + } + else + { + $_Lang['Insert_'.$Data['Prefix']] = parsetemplate($TPL_List_NoElements, array('Text' => $Data['NoRowsText'])); + } + } + + if(!empty($SFBRows)) + { + include($_EnginePath.'includes/functions/InsertJavaScriptChronoApplet.php'); + + if(!empty($GetUsernames)) + { + $GetUsernames = doquery("SELECT `id`, `username` FROM {{table}} WHERE `id` IN (".implode(', ', $GetUsernames).");", 'users'); + if(mysql_num_rows($GetUsernames) > 0) + { + while($LoadData = mysql_fetch_assoc($GetUsernames)) + { + $Usernames[$LoadData['id']] = $LoadData['username']; + } + } + } + if(!empty($GetPlanetsData)) + { + $GetPlanetsData = doquery("SELECT `id`, `name`, `galaxy`, `system`, `planet`, `planet_type` FROM {{table}} WHERE `id` IN (".implode(', ', $GetPlanetsData).");", 'planets'); + if(mysql_num_rows($GetPlanetsData) > 0) + { + while($LoadData = mysql_fetch_assoc($GetPlanetsData)) + { + $Planets[$LoadData['id']] = $LoadData; + } + } + } + if($_GameConfig['enable_bbcode'] == 1) + { + include($_EnginePath.'includes/functions/BBcodeFunction.php'); + } + + foreach($SFBRows as $DataRow) + { + $DataRow['AdminParsed'] = "{$Usernames[$DataRow['AdminID']]} (#{$DataRow['AdminID']})"; + $DataRow['TypeParsed'] = $_Lang['SFB_Types_'.$DataRow['Type']]; + if($DataRow['Type'] == 2) + { + $DataRow['ElementParsed'] = (!empty($Usernames[$DataRow['ElementID']]) ? "{$Usernames[$DataRow['ElementID']]} (#{$DataRow['ElementID']})" : "{$_Lang['User_Deleted']} (#{$DataRow['ElementID']})"); + } + else if($DataRow['Type'] == 3) + { + $DataRow['ElementParsed'] = (!empty($Planets[$DataRow['ElementID']]) ? "{$Planets[$DataRow['ElementID']]['name']} (#{$DataRow['ElementID']})
[{$Planets[$DataRow['ElementID']]['galaxy']}:{$Planets[$DataRow['ElementID']]['system']}:{$Planets[$DataRow['ElementID']]['planet']}|".($Planets[$DataRow['ElementID']]['planet_type'] == 1 ? $_Lang['Symbols_Planet'] : $_Lang['Symbols_Moon'])."]
" : "".($Planets[$DataRow['ElementID']]['planet_type'] == 1 ? $_Lang['Planet_Deleted'] : $_Lang['Moon_Deleted'])." (#{$DataRow['ElementID']})"); + } + if($DataRow['BlockMissions'] == '0') + { + $DataRow['Missions'] = $_Lang['SFB_Mission_All']; + } + else + { + $ExplodeMissions = explode(',', $DataRow['BlockMissions']); + $CivilCount = 0; + $AggresiveCount = 0; + foreach($ExplodeMissions as $MissionID) + { + if(!in_array($MissionID, $_Vars_FleetMissions['all'])) + { + continue; + } + $DataRow['Missions'][] = $_Lang['SFB_Mission__'.$MissionID]; + if(in_array($MissionID, $_Vars_FleetMissions['civil'])) + { + $CivilCount += 1; + } + else + { + $AggresiveCount += 1; + } + } + if($CivilCount == count($_Vars_FleetMissions['civil']) AND $AggresiveCount == 0) + { + $DataRow['Missions'] = $_Lang['SFB_Mission_Civil']; + } + else if($AggresiveCount == count($_Vars_FleetMissions['military']) AND $CivilCount == 0) + { + $DataRow['Missions'] = $_Lang['SFB_Mission_Aggresive']; + } + else + { + $DataRow['Missions'] = implode(', ', $DataRow['Missions']); + } + } + if($DataRow['StartTime'] > $Now) + { + $_Lang['Insert_ChronoApplets'] .= InsertJavaScriptChronoApplet('Start', $DataRow['ID'], $DataRow['StartTime'], true); + $DataRow['StartTime'] = prettyDate('d m Y, H:i:s', $DataRow['StartTime'], 1)."
{$_Lang['SFB_EndIn']}: ".pretty_time($DataRow['StartTime'] - $Now, true, 'D').""; + } + else + { + $DataRow['StartTime'] = prettyDate('d m Y, H:i:s', $DataRow['StartTime'], 1); + } + if($DataRow['EndTime'] > $Now) + { + $_Lang['Insert_ChronoApplets'] .= InsertJavaScriptChronoApplet('End', $DataRow['ID'], $DataRow['EndTime'], true); + $DataRow['EndTime'] = prettyDate('d m Y, H:i:s', $DataRow['EndTime'], 1)."
{$_Lang['SFB_EndIn']}: ".pretty_time($DataRow['EndTime'] - $Now, true, 'D').""; + } + else + { + $DataRow['EndTime'] = prettyDate('d m Y, H:i:s', $DataRow['EndTime'], 1); + } + if($DataRow['Type'] == 1 AND $DataRow['PostEndTime'] > 0) + { + if($DataRow['PostEndTime'] > $Now) + { + $_Lang['Insert_ChronoApplets'] .= InsertJavaScriptChronoApplet('PostEnd', $DataRow['ID'], $DataRow['PostEndTime'], true); + $DataRow['PostEndTimeParse'] = prettyDate('d m Y, H:i:s', $DataRow['PostEndTime'], 1)."
{$_Lang['SFB_EndIn']}: ".pretty_time($DataRow['PostEndTime'] - $Now, true, 'D').""; + } + else + { + $DataRow['PostEndTimeParse'] = prettyDate('d m Y, H:i:s', $DataRow['PostEndTime'], 1); + } + $DataRow['PostEndTimeParse'] = "
{$DataRow['PostEndTimeParse']}
"; + } + if($DataRow['Type'] == 1 AND $DataRow['DontBlockIfIdle'] == 1) + { + $DataRow['AdditionalData'][] = $_Lang['SFB_Additional_DontBlockIfIdle']; + } + if(empty($DataRow['AdditionalData'])) + { + $DataRow['AdditionalData'] = ' '; + } + else + { + $DataRow['AdditionalData'] = implode('
', $DataRow['AdditionalData']); + } + + if(empty($DataRow['Reason'])) + { + $DataRow['Reason'] = '-'; + } + else + { + if($_GameConfig['enable_bbcode'] == 1){ + $DataRow['Reason'] = trim(nl2br(bbcode(image(strip_tags(str_replace("'", ''', $DataRow['Reason']), '

'))))); + } else { + $DataRow['Reason'] = trim(nl2br(strip_tags($DataRow['Reason'], '

'))); + } + } + + if($DataRow['RowType'] == 2) + { + $DataRow['ActionsParsed'] = ' '; + } + else + { + $DataRow['ActionsParsed'][] = "{$_Lang['SFB_Action_Edit']}"; + $DataRow['ActionsParsed'][] = "{$_Lang['SFB_Action_Cancel']}"; + $DataRow['ActionsParsed'] = implode('
', $DataRow['ActionsParsed']);$DataRow['ActionsParsed']; + } + + $_Lang['Insert_'.$DataRow['RowPrefix']] .= parsetemplate($TPL_List_Row, $DataRow); + } + } +} + +$Title = $_Lang['SFB_Title']; +$Page = parsetemplate($TPL, $_Lang); + +display($Page, $Title, false, true); + +?> diff --git a/admin/Telemetry.php b/admin/Telemetry.php index 3fa9460d7..0518d9b1a 100644 --- a/admin/Telemetry.php +++ b/admin/Telemetry.php @@ -1,310 +1,310 @@ - 0) - { - $Place = doquery("SELECT `places`.*, COUNT(`data`.`DataID`) AS `PointsCount` FROM {{table}} AS `places` LEFT JOIN {{prefix}}telemetry_data AS `data` ON `data`.`PlaceID` = `places`.`ID` WHERE `places`.`ID` = {$PID} GROUP BY `PlaceID` LIMIT 1;", 'telemetry_pages', true); - if($Place['ID'] == $PID) - { - $PlaceID = $PID; - } - } - } - - if($PlaceID > 0) - { - $BodyTPL = gettemplate('admin/telemetry_graph_body'); - $ModeColors = array('black', 'red', 'green', 'purple', 'blue'); - $ModeNameTranslation = array('_t', '_c', '_d', '_f0', '_f1'); - foreach($ModeNameTranslation as $Value) - { - $ModeNameTranslation[$Value] = $_Lang['Tele_NameTranslation_'.$Value]; - } - - $_Lang['ThisPID'] = $PlaceID; - - if(!empty($Place['Get'])) - { - $_Lang['CombinePlace'] = "{$Place['Page']}?{$Place['Get']}"; - } - else - { - $_Lang['CombinePlace'] = $Place['Page']; - } - - $_Lang['Insert_Filter_Where_Val'] = ''; - $_Lang['Insert_Filter_Order_Val'] = '`TimeStamp`'; - $_Lang['Insert_Filter_Limit_Val'] = '100'; - $_Lang['Insert_Filter_Jumps_On'] = ''; - $_Lang['Insert_Filter_JumpsMin_Val'] = '5'; - - if(!empty($_POST['filter_where'])) - { - $SelectDataWhere = mysql_real_escape_string($_POST['filter_where']); - } - if(!empty($_POST['filter_order'])) - { - $SelectDataOrder = mysql_real_escape_string($_POST['filter_order']); - } - if(!empty($_POST['filter_limit'])) - { - $SelectDataLimit = preg_replace('#[^0-9\ \,]#si', '', $_POST['filter_limit']); - } - if(isset($_POST['filter_jumps']) && $_POST['filter_jumps'] == 'on') - { - $_POST['filter_jumps_min'] = str_replace(',', '.', $_POST['filter_jumps_min']); - $MinimalDiff = floatval($_POST['filter_jumps_min']); - if($MinimalDiff > 1) - { - $DeleteScoreJumps = true; - $_Lang['Insert_Filter_Jumps_On'] = 'checked'; - $_Lang['Insert_Filter_JumpsMin_Val'] = $MinimalDiff; - } - } - - $InsertWhere = ''; - $InsertOrder = ''; - $InsertLimit = ''; - if(!empty($SelectDataWhere)) - { - $InsertWhere = " AND {$SelectDataWhere}"; - $_Lang['Insert_Filter_Where_Val'] = $SelectDataWhere; - } - if(!empty($SelectDataOrder)) - { - $SelectDataOrder = str_ireplace(array('asc', 'desc'), array('', ''), $SelectDataOrder); - $InsertOrder = "ORDER BY {$SelectDataOrder} DESC"; - $_Lang['Insert_Filter_Order_Val'] = $SelectDataOrder; - } - else - { - $InsertOrder = "ORDER BY `TimeStamp` DESC"; - } - if(!empty($SelectDataLimit)) - { - $InsertLimit = "LIMIT {$SelectDataLimit}"; - $_Lang['Insert_Filter_Limit_Val'] = $SelectDataLimit; - } - else - { - $InsertLimit = "LIMIT 100"; - } - $SelectData = doquery("SELECT `DataID`, `UserID`, `TimeStamp`, `Data` FROM {{table}} WHERE `PlaceID` = {$PlaceID} {$InsertWhere} {$InsertOrder} {$InsertLimit};", 'telemetry_data'); - if(mysql_num_rows($SelectData) > 0) - { - $ModesI = 0; - $ModesAdded = array(); - while($DataPoint = mysql_fetch_assoc($SelectData)) - { - $DataPoint['Data'] = json_decode($DataPoint['Data'], true); - foreach($DataPoint['Data'] as $DataKey => $DataValue) - { - if(!in_array($DataKey, $ModesAdded)) - { - if(empty($ModeNameTranslation[$DataKey])) - { - $ModeName = $DataKey; - } - else - { - $ModeName = $ModeNameTranslation[$DataKey]; - } - $Modes[$ModesI] = array - ( - 'id' => $ModesI, - 'vendor_id' => 1, - 'mode' => '', - 'name' => $ModeName, - 'color' => $ModeColors[$ModesI] - ); - $ModesAdded[] = $DataKey; - $ModesMap[$DataKey] = $ModesI; - $ModesI += 1; - } - $TimeValue = $DataValue * 1000; - - $CreateStamp = $DataPoint['TimeStamp'].str_pad($DataPoint['DataID'], 20, '0', STR_PAD_LEFT).str_pad($ModesMap[$DataKey], 5, '0', STR_PAD_LEFT); - $Scores[] = array - ( - 'run_id' => $DataPoint['DataID'], - 'user_id' => $DataPoint['UserID'], - 'mode_id' => $ModesMap[$DataKey], - 'score' => $TimeValue, - 'orgstamp' => $DataPoint['TimeStamp'], - 'stamp' => $CreateStamp - ); - $GetUsernames[$DataPoint['UserID']] = $DataPoint['UserID']; - - if(!isset($AvgScores[$ModesMap[$DataKey]])) - { - $AvgScores[$ModesMap[$DataKey]] = 0; - } - if(!isset($AvgCounts[$ModesMap[$DataKey]])) - { - $AvgCounts[$ModesMap[$DataKey]] = 0; - } - $AvgScores[$ModesMap[$DataKey]] += $TimeValue; - $AvgCounts[$ModesMap[$DataKey]] += 1; - } - } - - foreach($Scores as $ScoreKey => $ScoreData) - { - $ScoreStamps[$ScoreKey][] = $ScoreData['stamp']; - } - array_multisort($Scores, $ScoreStamps, SORT_ASC); - $ScoreIndexes = 0; - $ScoreLastDataID = $Scores[0]['run_id']; - foreach($Scores as $ScoreData) - { - if($ScoreData['run_id'] != $ScoreLastDataID) - { - $ScoreIndexes += 1; - $ScoreLastDataID = $ScoreData['run_id']; - } - $UserLinking[$ScoreData['mode_id']][$ScoreIndexes] = array - ( - 'user_id' => $ScoreData['user_id'], - 'stamp' => $ScoreData['orgstamp'] - ); - } - - foreach($AvgScores as $ModeID => &$Value) - { - $Value = $Value/$AvgCounts[$ModeID]; - $Modes[$ModeID]['avg'] = sprintf($_Lang['Tele_Legend_Avg'], sprintf('%0.3f', $Value)); - } - - if(isset($DeleteScoreJumps)) - { - foreach($Scores as &$ScoreData) - { - if($ScoreData['score'] > ($AvgScores[$ScoreData['mode_id']] * $MinimalDiff)) - { - $ScoreData['score'] = 'null'; - } - } - } - - if(!empty($GetUsernames)) - { - $GetUsernames = doquery("SELECT `id`, `username` FROM {{table}} WHERE `id` IN (".implode(', ', $GetUsernames).");", 'users'); - while($Username = mysql_fetch_assoc($GetUsernames)) - { - $Usernames[$Username['id']] = $Username['username']; - } - } - - foreach($UserLinking as $ModeID => $Linkings) - { - foreach($Linkings as $ThisIndex => $ThisData) - { - $ThisIndex = (string)($ThisIndex + 0); - if(empty($Usernames[$ThisData['user_id']])) - { - $Usernames[$ThisData['user_id']] = $_Lang['Tele_UsernameEmpty']; - } - $LinkUsers[$ModeID][$ThisIndex] = array('id' => $ThisData['user_id'], 'name' => $Usernames[$ThisData['user_id']]); - } - } - $LinkUsers = json_encode($LinkUsers); - - include($_EnginePath.'includes/functions/MakeGraphs.php'); - $Scores['data'] = array - ( - 'fullstamp' => '%d.%m.%Y, %H:%M:%S', - 'shortstamp' => '%d.%m
%H:%M:%S', - 'otherdate' => '%Y_%m_%d', - 'units' => $_Lang['Tele_TimeUnits'], - 'tooltiptext' => $_Lang['Tele_ToolTipText'] - ); - $Result = MakeGraphs - ( - $Modes, - array(0 => $Scores), - array('x' => 700, 'y' => 400), - 'if(UserLinking[modeNo][x] !== undefined){ var UserID = UserLinking[modeNo][x][\'id\']; var Username = UserLinking[modeNo][x][\'name\']; } else { var UserID = 0; var Username = \'none\'; } var OtherDate = graph.runs[x].otherDate;' - ); - - $_Lang['InsertUserLinkings'] = $LinkUsers; - $_Lang['InsertScripts'] = $Result['includes']; - $_Lang['InsertGraph'] = $Result['graphs'][0]; - $_Lang['InsertLegend'] = $Result['legend']; - } - else - { - $_Lang['MessageBox_Text'] = $_Lang['Tele_Msg_NoDataPoints']; - } - } - else - { - $BodyTPL = gettemplate('admin/telemetry_select_body'); - - $SelectPlaces = doquery("SELECT `places`.*, COUNT(*) AS `PointsCount` FROM {{table}} AS `places` JOIN {{prefix}}telemetry_data AS `data` ON `data`.`PlaceID` = `places`.`ID` GROUP BY `PlaceID` ORDER BY `places`.`Page` ASC;", 'telemetry_pages'); - if(mysql_num_rows($SelectPlaces) > 0) - { - $_Lang['Hide_Headers'] = ''; - $PlacesTPL = gettemplate('admin/telemetry_select_row'); - while($Place = mysql_fetch_assoc($SelectPlaces)) - { - if(!empty($Place['Get'])) - { - $Place['CombinePlace'] = "{$Place['Page']}?{$Place['Get']}"; - } - else - { - $Place['CombinePlace'] = $Place['Page']; - } - $Place['HasPost'] = $_Lang['Tele_HasPost'][(string)($Place['HasPost'] + 0)]; - $Place['HasPostColor'] = $Place['HasPost']['color']; - $Place['HasPost'] = $Place['HasPost']['txt']; - $Place['PointsCount'] = prettyNumber($Place['PointsCount']); - - $_Lang['Places'] .= parsetemplate($PlacesTPL, $Place); - } - } - else - { - $_Lang['MessageBox_Text'] = $_Lang['Tele_Msg_NoPlaces']; - } - } - - if(!empty($_Lang['MessageBox_Text'])) - { - $_Lang['Hide_MessageBox'] = ''; - } - - $Page = parsetemplate($BodyTPL, $_Lang); - display($Page, $Title, false, true); - -?> \ No newline at end of file + 0) + { + $Place = doquery("SELECT `places`.*, COUNT(`data`.`DataID`) AS `PointsCount` FROM {{table}} AS `places` LEFT JOIN {{prefix}}telemetry_data AS `data` ON `data`.`PlaceID` = `places`.`ID` WHERE `places`.`ID` = {$PID} GROUP BY `PlaceID` LIMIT 1;", 'telemetry_pages', true); + if($Place['ID'] == $PID) + { + $PlaceID = $PID; + } + } +} + +if($PlaceID > 0) +{ + $BodyTPL = gettemplate('admin/telemetry_graph_body'); + $ModeColors = array('black', 'red', 'green', 'purple', 'blue'); + $ModeNameTranslation = array('_t', '_c', '_d', '_f0', '_f1'); + foreach($ModeNameTranslation as $Value) + { + $ModeNameTranslation[$Value] = $_Lang['Tele_NameTranslation_'.$Value]; + } + + $_Lang['ThisPID'] = $PlaceID; + + if(!empty($Place['Get'])) + { + $_Lang['CombinePlace'] = "{$Place['Page']}?{$Place['Get']}"; + } + else + { + $_Lang['CombinePlace'] = $Place['Page']; + } + + $_Lang['Insert_Filter_Where_Val'] = ''; + $_Lang['Insert_Filter_Order_Val'] = '`TimeStamp`'; + $_Lang['Insert_Filter_Limit_Val'] = '100'; + $_Lang['Insert_Filter_Jumps_On'] = ''; + $_Lang['Insert_Filter_JumpsMin_Val'] = '5'; + + if(!empty($_POST['filter_where'])) + { + $SelectDataWhere = mysql_real_escape_string($_POST['filter_where']); + } + if(!empty($_POST['filter_order'])) + { + $SelectDataOrder = mysql_real_escape_string($_POST['filter_order']); + } + if(!empty($_POST['filter_limit'])) + { + $SelectDataLimit = preg_replace('#[^0-9\ \,]#si', '', $_POST['filter_limit']); + } + if(isset($_POST['filter_jumps']) && $_POST['filter_jumps'] == 'on') + { + $_POST['filter_jumps_min'] = str_replace(',', '.', $_POST['filter_jumps_min']); + $MinimalDiff = floatval($_POST['filter_jumps_min']); + if($MinimalDiff > 1) + { + $DeleteScoreJumps = true; + $_Lang['Insert_Filter_Jumps_On'] = 'checked'; + $_Lang['Insert_Filter_JumpsMin_Val'] = $MinimalDiff; + } + } + + $InsertWhere = ''; + $InsertOrder = ''; + $InsertLimit = ''; + if(!empty($SelectDataWhere)) + { + $InsertWhere = " AND {$SelectDataWhere}"; + $_Lang['Insert_Filter_Where_Val'] = $SelectDataWhere; + } + if(!empty($SelectDataOrder)) + { + $SelectDataOrder = str_ireplace(array('asc', 'desc'), array('', ''), $SelectDataOrder); + $InsertOrder = "ORDER BY {$SelectDataOrder} DESC"; + $_Lang['Insert_Filter_Order_Val'] = $SelectDataOrder; + } + else + { + $InsertOrder = "ORDER BY `TimeStamp` DESC"; + } + if(!empty($SelectDataLimit)) + { + $InsertLimit = "LIMIT {$SelectDataLimit}"; + $_Lang['Insert_Filter_Limit_Val'] = $SelectDataLimit; + } + else + { + $InsertLimit = "LIMIT 100"; + } + $SelectData = doquery("SELECT `DataID`, `UserID`, `TimeStamp`, `Data` FROM {{table}} WHERE `PlaceID` = {$PlaceID} {$InsertWhere} {$InsertOrder} {$InsertLimit};", 'telemetry_data'); + if(mysql_num_rows($SelectData) > 0) + { + $ModesI = 0; + $ModesAdded = array(); + while($DataPoint = mysql_fetch_assoc($SelectData)) + { + $DataPoint['Data'] = json_decode($DataPoint['Data'], true); + foreach($DataPoint['Data'] as $DataKey => $DataValue) + { + if(!in_array($DataKey, $ModesAdded)) + { + if(empty($ModeNameTranslation[$DataKey])) + { + $ModeName = $DataKey; + } + else + { + $ModeName = $ModeNameTranslation[$DataKey]; + } + $Modes[$ModesI] = array + ( + 'id' => $ModesI, + 'vendor_id' => 1, + 'mode' => '', + 'name' => $ModeName, + 'color' => $ModeColors[$ModesI] + ); + $ModesAdded[] = $DataKey; + $ModesMap[$DataKey] = $ModesI; + $ModesI += 1; + } + $TimeValue = $DataValue * 1000; + + $CreateStamp = $DataPoint['TimeStamp'].str_pad($DataPoint['DataID'], 20, '0', STR_PAD_LEFT).str_pad($ModesMap[$DataKey], 5, '0', STR_PAD_LEFT); + $Scores[] = array + ( + 'run_id' => $DataPoint['DataID'], + 'user_id' => $DataPoint['UserID'], + 'mode_id' => $ModesMap[$DataKey], + 'score' => $TimeValue, + 'orgstamp' => $DataPoint['TimeStamp'], + 'stamp' => $CreateStamp + ); + $GetUsernames[$DataPoint['UserID']] = $DataPoint['UserID']; + + if(!isset($AvgScores[$ModesMap[$DataKey]])) + { + $AvgScores[$ModesMap[$DataKey]] = 0; + } + if(!isset($AvgCounts[$ModesMap[$DataKey]])) + { + $AvgCounts[$ModesMap[$DataKey]] = 0; + } + $AvgScores[$ModesMap[$DataKey]] += $TimeValue; + $AvgCounts[$ModesMap[$DataKey]] += 1; + } + } + + foreach($Scores as $ScoreKey => $ScoreData) + { + $ScoreStamps[$ScoreKey][] = $ScoreData['stamp']; + } + array_multisort($Scores, $ScoreStamps, SORT_ASC); + $ScoreIndexes = 0; + $ScoreLastDataID = $Scores[0]['run_id']; + foreach($Scores as $ScoreData) + { + if($ScoreData['run_id'] != $ScoreLastDataID) + { + $ScoreIndexes += 1; + $ScoreLastDataID = $ScoreData['run_id']; + } + $UserLinking[$ScoreData['mode_id']][$ScoreIndexes] = array + ( + 'user_id' => $ScoreData['user_id'], + 'stamp' => $ScoreData['orgstamp'] + ); + } + + foreach($AvgScores as $ModeID => &$Value) + { + $Value = $Value/$AvgCounts[$ModeID]; + $Modes[$ModeID]['avg'] = sprintf($_Lang['Tele_Legend_Avg'], sprintf('%0.3f', $Value)); + } + + if(isset($DeleteScoreJumps)) + { + foreach($Scores as &$ScoreData) + { + if($ScoreData['score'] > ($AvgScores[$ScoreData['mode_id']] * $MinimalDiff)) + { + $ScoreData['score'] = 'null'; + } + } + } + + if(!empty($GetUsernames)) + { + $GetUsernames = doquery("SELECT `id`, `username` FROM {{table}} WHERE `id` IN (".implode(', ', $GetUsernames).");", 'users'); + while($Username = mysql_fetch_assoc($GetUsernames)) + { + $Usernames[$Username['id']] = $Username['username']; + } + } + + foreach($UserLinking as $ModeID => $Linkings) + { + foreach($Linkings as $ThisIndex => $ThisData) + { + $ThisIndex = (string)($ThisIndex + 0); + if(empty($Usernames[$ThisData['user_id']])) + { + $Usernames[$ThisData['user_id']] = $_Lang['Tele_UsernameEmpty']; + } + $LinkUsers[$ModeID][$ThisIndex] = array('id' => $ThisData['user_id'], 'name' => $Usernames[$ThisData['user_id']]); + } + } + $LinkUsers = json_encode($LinkUsers); + + include($_EnginePath.'includes/functions/MakeGraphs.php'); + $Scores['data'] = array + ( + 'fullstamp' => '%d.%m.%Y, %H:%M:%S', + 'shortstamp' => '%d.%m
%H:%M:%S', + 'otherdate' => '%Y_%m_%d', + 'units' => $_Lang['Tele_TimeUnits'], + 'tooltiptext' => $_Lang['Tele_ToolTipText'] + ); + $Result = MakeGraphs + ( + $Modes, + array(0 => $Scores), + array('x' => 700, 'y' => 400), + 'if(UserLinking[modeNo][x] !== undefined){ var UserID = UserLinking[modeNo][x][\'id\']; var Username = UserLinking[modeNo][x][\'name\']; } else { var UserID = 0; var Username = \'none\'; } var OtherDate = graph.runs[x].otherDate;' + ); + + $_Lang['InsertUserLinkings'] = $LinkUsers; + $_Lang['InsertScripts'] = $Result['includes']; + $_Lang['InsertGraph'] = $Result['graphs'][0]; + $_Lang['InsertLegend'] = $Result['legend']; + } + else + { + $_Lang['MessageBox_Text'] = $_Lang['Tele_Msg_NoDataPoints']; + } +} +else +{ + $BodyTPL = gettemplate('admin/telemetry_select_body'); + + $SelectPlaces = doquery("SELECT `places`.*, COUNT(*) AS `PointsCount` FROM {{table}} AS `places` JOIN {{prefix}}telemetry_data AS `data` ON `data`.`PlaceID` = `places`.`ID` GROUP BY `PlaceID` ORDER BY `places`.`Page` ASC;", 'telemetry_pages'); + if(mysql_num_rows($SelectPlaces) > 0) + { + $_Lang['Hide_Headers'] = ''; + $PlacesTPL = gettemplate('admin/telemetry_select_row'); + while($Place = mysql_fetch_assoc($SelectPlaces)) + { + if(!empty($Place['Get'])) + { + $Place['CombinePlace'] = "{$Place['Page']}?{$Place['Get']}"; + } + else + { + $Place['CombinePlace'] = $Place['Page']; + } + $Place['HasPost'] = $_Lang['Tele_HasPost'][(string)($Place['HasPost'] + 0)]; + $Place['HasPostColor'] = $Place['HasPost']['color']; + $Place['HasPost'] = $Place['HasPost']['txt']; + $Place['PointsCount'] = prettyNumber($Place['PointsCount']); + + $_Lang['Places'] .= parsetemplate($PlacesTPL, $Place); + } + } + else + { + $_Lang['MessageBox_Text'] = $_Lang['Tele_Msg_NoPlaces']; + } +} + +if(!empty($_Lang['MessageBox_Text'])) +{ + $_Lang['Hide_MessageBox'] = ''; +} + +$Page = parsetemplate($BodyTPL, $_Lang); +display($Page, $Title, false, true); + +?> diff --git a/admin/UserDevScanner.php b/admin/UserDevScanner.php index 5d06b622b..9ab3c1340 100644 --- a/admin/UserDevScanner.php +++ b/admin/UserDevScanner.php @@ -1,2011 +1,2011 @@ - $Data) - { - if($Data['start'] <= $StartTime) - { - if($Data['end'] >= $EndTime) - { - $Add_Multiplier_Resources = $ProductionTime; - break; - } - else - { - $Add_Multiplier_Resources += ($Data['end'] - $StartTime); - } - } - else - { - if($Data['start'] >= $EndTime) - { - break; - } - else - { - if($Data['end'] >= $EndTime) - { - $Add_Multiplier_Resources += ($EndTime - $Data['start']); - break; - } - else - { - $Add_Multiplier_Resources += ($Data['end'] - $Data['start']); - } - } - } - } - - if($Add_Multiplier_Resources > 0) - { - $Multiplier_Resources += (0.15 * ($Add_Multiplier_Resources / $ProductionTime)); - } - } - - $Multiplier_Energy = 1; - $Add_Multiplier_Energy = 0; - if(!empty($PremiumItemsArchive[6])) - { - foreach($PremiumItemsArchive[6] as $Index => $Data) - { - if($Data['start'] <= $StartTime) - { - if($Data['end'] >= $EndTime) - { - $Add_Multiplier_Energy = $ProductionTime; - break; - } - else - { - $Add_Multiplier_Energy += ($Data['end'] - $StartTime); - } - } - else - { - if($Data['start'] >= $EndTime) - { - break; - } - else - { - if($Data['end'] >= $EndTime) - { - $Add_Multiplier_Energy += ($EndTime - $Data['start']); - break; - } - else - { - $Add_Multiplier_Energy += ($Data['end'] - $Data['start']); - } - } - } - } - - if($Add_Multiplier_Energy > 0) - { - $Multiplier_Energy += (0.1 * ($Add_Multiplier_Energy / $ProductionTime)); - } - } - // Calculate Place in Storages - if(empty($CurrentPlanet['metal_max'])) - { - $CurrentPlanet['metal_max'] = (floor (BASE_STORAGE_SIZE * pow (1.7, $CurrentPlanet[$_Vars_GameElements[22]]))) * MAX_OVERFLOW; - $CurrentPlanet['crystal_max'] = (floor (BASE_STORAGE_SIZE * pow (1.7, $CurrentPlanet[$_Vars_GameElements[23]]))) * MAX_OVERFLOW; - $CurrentPlanet['deuterium_max'] = (floor (BASE_STORAGE_SIZE * pow (1.7, $CurrentPlanet[$_Vars_GameElements[24]]))) * MAX_OVERFLOW; - } - - // Calculate additional income - $Caps = array - ( - 'metal_perhour' => 0, - 'crystal_perhour' => 0, - 'deuterium_perhour' => 0, - 'energy_used' => 0, - 'energy_max' => 0 - ); - $BuildTemp = $CurrentPlanet['temp_max']; - $TextIfEmpty = 'return "0";'; - foreach($_Vars_ElementCategories['prod'] as $ElementID) - { - $BuildLevelFactor = $CurrentPlanet[$_Vars_GameElements[$ElementID].'_workpercent']; - $BuildLevel = $CurrentPlanet[$_Vars_GameElements[$ElementID]]; - - if($BuildLevel <= 0) - { - continue; - } - - if($_Vars_ResProduction[$ElementID]['formule']['metal'] != $TextIfEmpty) - { - $Caps['metal_perhour'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['metal']) * ($_GameConfig['resource_multiplier']) * $Multiplier_Resources); - } - if($_Vars_ResProduction[$ElementID]['formule']['crystal'] != $TextIfEmpty) - { - $Caps['crystal_perhour'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['crystal']) * ($_GameConfig['resource_multiplier']) * $Multiplier_Resources); - } - if($ElementID != 12) - { - if($_Vars_ResProduction[$ElementID]['formule']['deuterium'] != $TextIfEmpty) - { - $Caps['deuterium_perhour'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * ($_GameConfig['resource_multiplier']) * $Multiplier_Resources); - } - } - else - { - $Caps['deuterium_perhour'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * ($_GameConfig['resource_multiplier'])); - } - - if($ElementID < 4) - { - $Caps['energy_used'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy'])); - } - else - { - if($ElementID != 12) - { - $Caps['energy_max'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $Multiplier_Energy); - } - else - { - $MineDeuteriumUse = floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * ($_GameConfig['resource_multiplier'])) * (-1); - if($MineDeuteriumUse > 0) - { - if($CurrentPlanet['deuterium'] <= 0) - { - if($Caps['deuterium_perhour'] == ($MineDeuteriumUse * (-1))) - { - // If no enough + production of deuterium - } - else - { - // If there is still some deuterium in + production to use - $FusionReactorMulti = ($Caps['deuterium_perhour'] + $MineDeuteriumUse) / $MineDeuteriumUse; - if($FusionReactorMulti > 1) - { - $FusionReactorMulti = 1; - } - $Caps['energy_max'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $FusionReactorMulti * $Multiplier_Energy); - } - } - else - { - if($Caps['deuterium_perhour'] >= 0) - { - $Caps['energy_max'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $Multiplier_Energy); - } - else - { - $FusionReactorMulti = $CurrentPlanet['deuterium'] / ($MineDeuteriumUse / 3600); - if($FusionReactorMulti > 1) - { - $FusionReactorMulti = 1; - } - $Caps['energy_max'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $FusionReactorMulti * $Multiplier_Energy); - } - } - } - } - } - } - - if($Caps['energy_max'] == 0 AND abs($Caps['energy_used']) > 0) - { - $production_level = 0; - } - else if($Caps['energy_max'] > 0 AND abs($Caps['energy_used']) > $Caps['energy_max']) - { - $production_level = floor(($Caps['energy_max'] * 100) / abs($Caps['energy_used'])); - } - else - { - $production_level = 100; - } - if($production_level > 100) - { - $production_level = 100; - } - - if($CurrentPlanet['metal'] <= $CurrentPlanet['metal_max']) - { - $MetalProduction = ($ProductionTime * ($Caps['metal_perhour'] / 3600)) * (0.01 * $production_level); - $MetalBaseProduc = $ProductionTime * (($_GameConfig['metal_basic_income'] * $_GameConfig['resource_multiplier']) / 3600); - $MetalT = $MetalProduction + $MetalBaseProduc; - $MetalTheorical = $CurrentPlanet['metal'] + $MetalT; - - $Return['MetalProduction'] = $MetalT; - - if($MetalTheorical < 0) - { - $MetalTheorical = 0; - } - - if($MetalTheorical < $CurrentPlanet['metal_max']) - { - $CurrentPlanet['metal'] = $MetalTheorical; - } - else - { - $CurrentPlanet['metal'] = $CurrentPlanet['metal_max']; - $Return['MetalProduction'] -= ($MetalTheorical - $CurrentPlanet['metal']); - } - } - - if($CurrentPlanet['crystal'] <= $CurrentPlanet['crystal_max']) - { - $CrystalProduction = ($ProductionTime * ($Caps['crystal_perhour'] / 3600)) * (0.01 * $production_level); - $CrystalBaseProduc = $ProductionTime * (($_GameConfig['crystal_basic_income'] * $_GameConfig['resource_multiplier']) / 3600); - $CrystalT = $CrystalProduction + $CrystalBaseProduc; - $CrystalTheorical = $CurrentPlanet['crystal'] + $CrystalT; - - $Return['CrystalProduction'] = $CrystalT; - - if($CrystalTheorical < 0) - { - $CrystalTheorical = 0; - } - - if($CrystalTheorical < $CurrentPlanet['crystal_max']) - { - $CurrentPlanet['crystal'] = $CrystalTheorical; - } - else - { - $CurrentPlanet['crystal'] = $CurrentPlanet['crystal_max']; - $Return['CrystalProduction'] -= ($CrystalTheorical - $CurrentPlanet['crystal']); - } - } - - if($CurrentPlanet['deuterium'] <= $CurrentPlanet['deuterium_max']) - { - $DeuteriumProduction = ($ProductionTime * ($Caps['deuterium_perhour'] / 3600)) * (0.01 * $production_level); - $DeuteriumBaseProduc = $ProductionTime * (($_GameConfig['deuterium_basic_income'] * $_GameConfig['resource_multiplier']) / 3600); - $DeuteriumT = $DeuteriumProduction + $DeuteriumBaseProduc; - $DeuteriumTheorical = $CurrentPlanet['deuterium'] + $DeuteriumT; - - $Return['DeuteriumProduction'] = $DeuteriumT; - - if($DeuteriumTheorical < 0) - { - $DeuteriumTheorical = 0; - $Return['DeuteriumProduction'] = $CurrentPlanet['deuterium']; - } - - if($DeuteriumTheorical < $CurrentPlanet['deuterium_max']) - { - $CurrentPlanet['deuterium'] = $DeuteriumTheorical; - } - else - { - $CurrentPlanet['deuterium'] = $CurrentPlanet['deuterium_max']; - $Return['DeuteriumProduction'] -= ($DeuteriumTheorical - $CurrentPlanet['deuterium']); - } - } - - $CurrentPlanet['last_update'] = $EndTime; - - return isset($Return) ? $Return : null; - } - - $UID = isset($_POST['uid']) ? $_POST['uid'] : 0; - $Username = isset($_POST['username']) ? $_POST['username'] : null; - if(!empty($UID) OR !empty($Username)) - { - $Search = true; - if(!empty($UID)) - { - $UID = intval($UID); - if($UID > 0) - { - $WhereClausure = "`id` = {$UID}"; - } - } - if(!empty($Username) AND empty($WhereClausure)) - { - if(preg_match(REGEXP_USERNAME_ABSOLUTE, $Username)) - { - $WhereClausure = "`username` = '{$Username}'"; - } - } - } - - if($Search AND !empty($WhereClausure)) - { - $GetUser = doquery("SELECT * FROM {{table}} WHERE {$WhereClausure} LIMIT 1;", 'users', true); - if($GetUser['id'] > 0) - { - $AllowScan = true; - } - else - { - $_Lang['Error_Found'] = $_Lang['Error_UserNoExist']; - } - } - else - { - if($Search) - { - $_Lang['Error_Found'] = $_Lang['Error_BadPost']; - } - } - - if($AllowScan) - { - $BreakScan = false; - - $UserNewData = &$GetUser; - $LoadLastDump = doquery("SELECT * FROM {{table}} WHERE `UserID` = {$GetUser['id']} LIMIT 1;", 'user_developmentdumps', true); - if($LoadLastDump['UserID'] != $GetUser['id']) - { - $_Lang['Error_Found'] = $_Lang['Critical_NoDump']; - $BreakScan = true; - } - if(!$BreakScan) - { - $LastDumpTimestamp = $LoadLastDump['Date'] - SERVER_MAINOPEN_TSTAMP; - $GetLogs = doquery("SELECT * FROM {{table}} WHERE `UserID` = {$GetUser['id']} ORDER BY `ID` ASC;", 'user_developmentlog'); - if(mysql_num_rows($GetLogs) == 0) - { - $_Lang['Notice_Found'] = $_Lang['Notice_NoLogs']; - $BreakScan = true; - } - if(!$BreakScan) - { - $ScanStartTime = microtime(true); - - $PlanetsNewData = doquery("SELECT * FROM {{table}} WHERE `id_owner` = {$GetUser['id']};", 'planets'); - $FleetsNewData = doquery("SELECT * FROM {{table}} WHERE `fleet_owner` = {$GetUser['id']};", 'fleets'); - $UserPremiumItems = doquery("SELECT * FROM {{table}} WHERE `UserID` = {$GetUser['id']} AND `Item` IN (5,6);", 'premiumpayments'); - - if(mysql_num_rows($UserPremiumItems) > 0) - { - while($PremiumItem = mysql_fetch_assoc($UserPremiumItems)) - { - $Length = 14 * TIME_DAY; - $PremiumItemsArchive[$PremiumItem['Item']][] = array - ( - 'start' => $PremiumItem['Date'], - 'end' => $PremiumItem['Date'] + $Length - ); - } - } - - $PlanetsDumpData = json_decode($LoadLastDump['Planets'], true); - foreach($PlanetsDumpData as $PlanetID => $PlanetData) - { - $PlanetsDumpData[$PlanetID]['id'] = $PlanetID; - foreach($_Vars_ElementCategories as $reskey => $resvals) - { - if(in_array($reskey, array('tech', 'buildOn', 'units'))) - { - continue; - } - foreach($resvals as $resID) - { - if($reskey != 'prod') - { - $PlanetsDumpData[$PlanetID][$_Vars_GameElements[$resID]] = 0; - } - else - { - $PlanetsDumpData[$PlanetID][$_Vars_GameElements[$resID].'_workpercent'] = 0; - } - } - } - - $Resources = explode(',', $PlanetData['res']); - $PlanetData['b'] = isset($PlanetData['b']) ? explode(';', $PlanetData['b']) : array(); - $PlanetData['p'] = isset($PlanetData['p']) ? explode(';', $PlanetData['p']) : array(); - $PlanetData['f'] = isset($PlanetData['f']) ? explode(';', $PlanetData['f']) : array(); - - foreach($PlanetData['b'] as $ElementData) - { - $ElementData = explode(',', $ElementData); - $PlanetsDumpData[$PlanetID][$_Vars_GameElements[$ElementData[0]]] = $ElementData[1]; - } - foreach($PlanetData['f'] as $ElementData) - { - $ElementData = explode(',', $ElementData); - $PlanetsDumpData[$PlanetID][$_Vars_GameElements[$ElementData[0]]] = $ElementData[1]; - } - foreach($PlanetData['p'] as $ElementData) - { - $ElementData = explode(',', $ElementData); - $PlanetsDumpData[$PlanetID][$_Vars_GameElements[$ElementData[0]].'_workpercent'] = $ElementData[1]; - } - - if($Resources[0] > 0) - { - $PlanetsDumpData[$PlanetID]['metal'] = $Resources[0]; - } - else - { - $PlanetsDumpData[$PlanetID]['metal'] = 0; - } - if($Resources[1] > 0) - { - $PlanetsDumpData[$PlanetID]['crystal'] = $Resources[1]; - } - else - { - $PlanetsDumpData[$PlanetID]['crystal'] = 0; - } - if($Resources[2] > 0) - { - $PlanetsDumpData[$PlanetID]['deuterium'] = $Resources[2]; - } - else - { - $PlanetsDumpData[$PlanetID]['deuterium'] = 0; - } - - $PlanetsDumpData[$PlanetID]['last_update'] = $PlanetData['lu']; - $PlanetsDumpData[$PlanetID]['planet_type'] = $PlanetData['pt']; - $PlanetsDumpData[$PlanetID]['temp_max'] = $PlanetData['t']; - $PlanetsDumpData[$PlanetID]['metal_max'] = (floor(BASE_STORAGE_SIZE * pow (1.7, $PlanetsDumpData[$PlanetID][$_Vars_GameElements[22]]))) * MAX_OVERFLOW; - $PlanetsDumpData[$PlanetID]['crystal_max'] = (floor(BASE_STORAGE_SIZE * pow (1.7, $PlanetsDumpData[$PlanetID][$_Vars_GameElements[23]]))) * MAX_OVERFLOW; - $PlanetsDumpData[$PlanetID]['deuterium_max'] = (floor(BASE_STORAGE_SIZE * pow (1.7, $PlanetsDumpData[$PlanetID][$_Vars_GameElements[24]]))) * MAX_OVERFLOW; - } - $UserData = $GetUser; - foreach($_Vars_ElementCategories['tech'] as $TechID) - { - $UserData[$_Vars_GameElements[$TechID]] = 0; - } - $UserTechsDump = !empty($LoadLastDump['Techs']) ? explode(';', $LoadLastDump['Techs']) : array(); - foreach($UserTechsDump as $Exploded) - { - $Exploded = explode(',', $Exploded); - $UserData[$_Vars_GameElements[$Exploded[0]]] = $Exploded[1]; - } - - $ScaningNo = 0; - $ScanLog['LogScanned'] = 0; - $ScanLog['ResUpdates'] = 0; - - $UsedResources = array - ( - 'metal' => 0, - 'crystal' => 0, - 'deuterium' => 0, - ); - - while($Log = mysql_fetch_assoc($GetLogs)) - { - $Log['Date'] += SERVER_MAINOPEN_TSTAMP; - - $ScaningNo += 1; - - $PreventResourceUpdate = false; - $ResourcesChanged = false; - $ResUpdateReturn = false; - $ShipsChanged = false; - $ChangedShipsTypes = array(); - $Needed = array - ( - 'metal' => 0, - 'crystal' => 0, - 'deuterium' => 0, - ); - - // Main Checking Part - $Place = &$Log['Place']; - if($Place == 1) - { - // HandlePlanetQueue_StructuresSetNext [Remove Resources, Move Element in Structures Queue to first position] - $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); - if($ResUpdateReturn !== false) - { - $ScanLog['ResUpdates'] += 1; - } - - $Needed = GetBuildingPrice($UserData, $PlanetsDumpData[$Log['PlanetID']], $Log['ElementID'], true, ($Log['Code'] == 1 ? false : true)); - - $UsedResources['metal'] += $Needed['metal']; - $UsedResources['crystal'] += $Needed['crystal']; - $UsedResources['deuterium'] += $Needed['deuterium']; - $PlanetsDumpData[$Log['PlanetID']]['metal'] -= $Needed['metal']; - $PlanetsDumpData[$Log['PlanetID']]['crystal'] -= $Needed['crystal']; - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $Needed['deuterium']; - - $ResourcesChanged = $Log['PlanetID']; - } - else if($Place == 2) - { - // CancelBuildingFromQueue [Restore Resources] - $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); - if($ResUpdateReturn !== false) - { - $ScanLog['ResUpdates'] += 1; - } - $Needed = GetBuildingPrice($UserData, $PlanetsDumpData[$Log['PlanetID']], $Log['ElementID'], true, ($Log['Code'] == 1 ? false : true)); - - $UsedResources['metal'] -= $Needed['metal']; - $UsedResources['crystal'] -= $Needed['crystal']; - $UsedResources['deuterium'] -= $Needed['deuterium']; - $PlanetsDumpData[$Log['PlanetID']]['metal'] += $Needed['metal']; - $PlanetsDumpData[$Log['PlanetID']]['crystal'] += $Needed['crystal']; - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] += $Needed['deuterium']; - - $ResourcesChanged = $Log['PlanetID']; - } - else if($Place == 3) - { - // HandlePlanetQueue_OnStructureBuildEnd [Building has ended] - $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$Log['ElementID']]] += ($Log['Code'] == 1 ? 1 : -1); - - if($Log['ElementID'] == 22) - { - $PlanetsDumpData[$Log['PlanetID']]['metal_max'] = (floor(BASE_STORAGE_SIZE * pow (1.7, $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[22]]))) * MAX_OVERFLOW; - } - else if($Log['ElementID'] == 23) - { - $PlanetsDumpData[$Log['PlanetID']]['crystal_max'] = (floor(BASE_STORAGE_SIZE * pow (1.7, $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[23]]))) * MAX_OVERFLOW; - } - else if($Log['ElementID'] == 24) - { - $PlanetsDumpData[$Log['PlanetID']]['deuterium_max'] = (floor(BASE_STORAGE_SIZE * pow (1.7, $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[24]]))) * MAX_OVERFLOW; - } - } - else if($Place == 4) - { - // On Code 1 - HandlePlanetQueue_TechnologySetNext [Remove Resources, Move Element in Technology Queue to first position] - // On Code 2 - TechQueue_Remove [Fall Back Resource Removal] - $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); - if($ResUpdateReturn !== false) - { - $ScanLog['ResUpdates'] += 1; - } - - $Needed = GetBuildingPrice($UserData, $PlanetsDumpData[$Log['PlanetID']], $Log['ElementID']); - if($Log['Code'] == 2) - { - foreach($Needed as $Key => $Value) - { - $Needed[$Key] *= -1; - } - } - - $UsedResources['metal'] += $Needed['metal']; - $UsedResources['crystal'] += $Needed['crystal']; - $UsedResources['deuterium'] += $Needed['deuterium']; - $PlanetsDumpData[$Log['PlanetID']]['metal'] -= $Needed['metal']; - $PlanetsDumpData[$Log['PlanetID']]['crystal'] -= $Needed['crystal']; - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $Needed['deuterium']; - - $ResourcesChanged = $Log['PlanetID']; - } - else if($Place == 5) - { - // HandlePlanetQueue_OnTechnologyEnd [Research has ended] - $UserData[$_Vars_GameElements[$Log['ElementID']]] += 1; - - $PreventResourceUpdate = true; - } - else if($Place == 6) - { - // FleetBuildingPage / ShipyardPage (Ships) [Remove Resources] - $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); - if($ResUpdateReturn !== false) - { - $ScanLog['ResUpdates'] += 1; - } - - $Fleets = explode(';', $Log['AdditionalData']); - foreach($Fleets as $Ship) - { - $Ship = explode(',', $Ship); - - $Temp = GetElementRessources($Ship[0], $Ship[1]); - $Needed['metal'] += $Temp['metal']; - $Needed['crystal'] += $Temp['crystal']; - $Needed['deuterium'] += $Temp['deuterium']; - } - - $UsedResources['metal'] += $Needed['metal']; - $UsedResources['crystal'] += $Needed['crystal']; - $UsedResources['deuterium'] += $Needed['deuterium']; - $PlanetsDumpData[$Log['PlanetID']]['metal'] -= $Needed['metal']; - $PlanetsDumpData[$Log['PlanetID']]['crystal'] -= $Needed['crystal']; - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $Needed['deuterium']; - - $ResourcesChanged = $Log['PlanetID']; - } - else if($Place == 7) - { - // DefensesBuildingPage / ShipyardPage (Defense) [Remove Resources] - $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); - if($ResUpdateReturn !== false) - { - $ScanLog['ResUpdates'] += 1; - } - - $Defs = explode(';', $Log['AdditionalData']); - foreach($Defs as $Def) - { - $Def = explode(',', $Def); - - $Temp = GetElementRessources($Def[0], $Def[1]); - $Needed['metal'] += $Temp['metal']; - $Needed['crystal'] += $Temp['crystal']; - $Needed['deuterium'] += $Temp['deuterium']; - } - - $UsedResources['metal'] += $Needed['metal']; - $UsedResources['crystal'] += $Needed['crystal']; - $UsedResources['deuterium'] += $Needed['deuterium']; - $PlanetsDumpData[$Log['PlanetID']]['metal'] -= $Needed['metal']; - $PlanetsDumpData[$Log['PlanetID']]['crystal'] -= $Needed['crystal']; - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $Needed['deuterium']; - - $ResourcesChanged = $Log['PlanetID']; - } - else if($Place == 8) - { - // HandlePlanetQueue / HandlePlanetUpdate / PlanetResourceUpdate (Shipyard Queue Change) [Insert Fleets & Defenses to PlanetRow] - $Builded = explode(';', $Log['AdditionalData']); - - foreach($Builded as $Item) - { - $Item = explode(',', $Item); - - $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$Item[0]]] += $Item[1]; - } - } - else if($Place == 9) - { - // galaxyfleet.php [Remove Deuterium, Remove Ships] - $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); - if($ResUpdateReturn !== false) - { - $ScanLog['ResUpdates'] += 1; - } - - $Fleet = explode(';', $Log['AdditionalData']); - foreach($Fleet as $Ship) - { - $Ship = explode(',', $Ship); - - if($Ship[0] == 'F') - { - $UsedResources['deuterium'] += $Ship[1]; - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $Ship[1]; - - $ResourcesChanged = $Log['PlanetID']; - } - else - { - $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$Ship[0]]] -= $Ship[1]; - $ChangedShipsTypes[] = $Ship[0]; - } - } - - $ShipsChanged = array('Where' => $Log['PlanetID'], 'Types' => $ChangedShipsTypes); - } - else if($Place == 10) - { - // fleet3.php [Remove Resources, Remove Ships] - - $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); - if($ResUpdateReturn !== false) - { - $ScanLog['ResUpdates'] += 1; - } - - $Fleet = explode(';', $Log['AdditionalData']); - $Removed = array - ( - 'metal' => 0, - 'crystal' => 0, - 'deuterium' => 0, - ); - - foreach($Fleet as $Ship) - { - $Ship = explode(',', $Ship); - - if($Ship[0] == 'F' OR $Ship[0] == 'D') - { - $UsedResources['deuterium'] += $Ship[1]; - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $Ship[1]; - $Removed['deuterium'] += $Ship[1]; - - $ResourcesChanged = $Log['PlanetID']; - } - else if($Ship[0] == 'M') - { - $UsedResources['metal'] += $Ship[1]; - $PlanetsDumpData[$Log['PlanetID']]['metal'] -= $Ship[1]; - $Removed['metal'] += $Ship[1]; - - $ResourcesChanged = $Log['PlanetID']; - } - else if($Ship[0] == 'C') - { - $UsedResources['crystal'] += $Ship[1]; - $PlanetsDumpData[$Log['PlanetID']]['crystal'] -= $Ship[1]; - $Removed['crystal'] += $Ship[1]; - - $ResourcesChanged = $Log['PlanetID']; - } - else - { - $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$Ship[0]]] -= $Ship[1]; - $ChangedShipsTypes[] = $Ship[0]; - } - } - - $ShipsChanged = array('Where' => $Log['PlanetID'], 'Types' => $ChangedShipsTypes); - } - else if($Place == 11) - { - // sendmissiles.php - $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); - if($ResUpdateReturn !== false) - { - $ScanLog['ResUpdates'] += 1; - } - - $Missiles = explode(',', $Log['AdditionalData']); - $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[503]] -= $Missiles[1]; - $ChangedShipsTypes[] = 503; - - $ShipsChanged = array('Where' => $Log['PlanetID'], 'Types' => $ChangedShipsTypes); - } - else if($Place == 12 OR $Place == 13 OR $Place == 15) - { - // MissionCaseAttack.php (12) & MissionCaseGroupAttack.php (13) & MissionCaseDestruction.php (15) - if($Log['Code'] == 1) - { - // User is PlanetDefender - $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); - if($ResUpdateReturn !== false) - { - $ScanLog['ResUpdates'] += 1; - } - - $Lost = explode(';', $Log['AdditionalData']); - foreach($Lost as $LostData) - { - $LostData = explode(',', $LostData); - if($LostData[0] == 'M') - { - $PlanetsDumpData[$Log['PlanetID']]['metal'] -= $LostData[1]; - - $ResourcesChanged = $Log['PlanetID']; - } - else if($LostData[0] == 'C') - { - $PlanetsDumpData[$Log['PlanetID']]['crystal'] -= $LostData[1]; - - $ResourcesChanged = $Log['PlanetID']; - } - else if($LostData[0] == 'D') - { - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $LostData[1]; - - $ResourcesChanged = $Log['PlanetID']; - } - else if($LostData[0] == 'L') - { - $PlanetsDumpData[$LostData[1]]['id'] = $LostData[1]; - $PlanetsDumpData[$LostData[1]]['metal'] = 0; - $PlanetsDumpData[$LostData[1]]['crystal'] = 0; - $PlanetsDumpData[$LostData[1]]['deuterium'] = 0; - $PlanetsDumpData[$LostData[1]]['last_update'] = $Log['Date']; - $PlanetsDumpData[$LostData[1]]['planet_type'] = 3; - } - else - { - $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$LostData[0]]] -= $LostData[1]; - $ChangedShipsTypes[] = $LostData[0]; - - $ShipsChanged = true; - } - } - - if($ShipsChanged) - { - $ShipsChanged = array('Where' => $Log['PlanetID'], 'Types' => $ChangedShipsTypes); - } - - if($Place == 15 AND $Log['ElementID'] == 1) - { - $ShipsChanged = false; - $PreventResourceUpdate = true; - unset($PlanetsDumpData[$Log['PlanetID']]); - } - } - else if($Log['Code'] == 2) - { - // User is Attacker (Regular Attacker or ACS Leader) - - $PreventResourceUpdate = true; - } - else if($Log['Code'] == 3) - { - // User is FriendlyDefender - - $PreventResourceUpdate = true; - } - else if($Log['Code'] == 4) - { - // User is Additional Attacker (ACS Member) [only in 13!] - - $PreventResourceUpdate = true; - } - } - else if($Place == 14) - { - // MissionCaseColonisation.php - $ExplodeRes = explode(';', $Log['AdditionalData']); - foreach($ExplodeRes as $ExpRes) - { - $ExpRes = explode(',', $ExpRes); - if($ExpRes[0] == 'M') - { - $PlanetsDumpData[$Log['PlanetID']]['metal'] = $ExpRes[1]; - } - else if($ExpRes[0] == 'C') - { - $PlanetsDumpData[$Log['PlanetID']]['crystal'] = $ExpRes[1]; - } - else if($ExpRes[0] == 'D') - { - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] = $ExpRes[1]; - } - else if($ExpRes[0] == 'T') - { - $PlanetsDumpData[$Log['PlanetID']]['temp_max'] = $ExpRes[1]; - } - } - - foreach($_Vars_ElementCategories['prod'] as $ProdID) - { - $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$ProdID].'_workpercent'] = 10; - } - - $PlanetsDumpData[$Log['PlanetID']]['last_update'] = $Log['Date']; - $PlanetsDumpData[$Log['PlanetID']]['planet_type'] = 1; - $PlanetsDumpData[$Log['PlanetID']]['id'] = $Log['PlanetID']; - - $PreventResourceUpdate = true; - } - else if($Place == 16) - { - // MissionCaseMIP.php - $Lost = explode(';', $Log['AdditionalData']); - foreach($Lost as $LostData) - { - $LostData = explode(',', $LostData); - $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$LostData[0]]] -= $LostData[1]; - $ChangedShipsTypes[] = $LostData[0]; - } - - $ShipsChanged = array('Where' => $Log['PlanetID'], 'Types' => $ChangedShipsTypes); - } - else if($Place == 17) - { - // MissionCaseRecycling.php - - $PreventResourceUpdate = true; - } - else if($Place == 18) - { - // MissionCaseSpy.php - - $PreventResourceUpdate = true; - } - else if($Place == 19) - { - // MissionCaseTransport.php - - if(($Log['Code'] == 1 AND isset($PlanetsDumpData[$Log['PlanetID']])) OR $Log['Code'] == 2) - { - // Planet belongs to that user - $ExplodeRes = explode(';', $Log['AdditionalData']); - foreach($ExplodeRes as $ExpRes) - { - $ExpRes = explode(',', $ExpRes); - if($ExpRes[0] == 'M') - { - $PlanetsDumpData[$Log['PlanetID']]['metal'] += $ExpRes[1]; - } - else if($ExpRes[0] == 'C') - { - $PlanetsDumpData[$Log['PlanetID']]['crystal'] += $ExpRes[1]; - } - else if($ExpRes[0] == 'D') - { - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] += $ExpRes[1]; - } - } - - $PreventResourceUpdate = true; - } - else - { - // Friendly Transport - - $PreventResourceUpdate = true; - } - } - else if($Place == 20) - { - // Place Holder for Expeditions (maybe) - } - else if($Place == 21) - { - // RestoreFleetToPlanet.php - $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); - if($ResUpdateReturn !== false) - { - $ScanLog['ResUpdates'] += 1; - } - - $Restore = explode(';', $Log['AdditionalData']); - foreach($Restore as $Restored) - { - $Restored = explode(',', $Restored); - if($Restored[0] == 'M') - { - $PlanetsDumpData[$Log['PlanetID']]['metal'] += $Restored[1]; - $ResourcesChanged = $Log['PlanetID']; - } - else if($Restored[0] == 'C') - { - $PlanetsDumpData[$Log['PlanetID']]['crystal'] += $Restored[1]; - $ResourcesChanged = $Log['PlanetID']; - } - else if($Restored[0] == 'D') - { - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] += $Restored[1]; - $ResourcesChanged = $Log['PlanetID']; - } - else - { - $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$Restored[0]]] += $Restored[1]; - $ChangedShipsTypes[] = $Restored[0]; - - $ShipsChanged = true; - } - } - - if($ShipsChanged) - { - $ShipsChanged = array('Where' => $Log['PlanetID'], 'Types' => $ChangedShipsTypes); - } - } - else if($Place == 22) - { - // resources.php - $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); - if($ResUpdateReturn !== false) - { - $ScanLog['ResUpdates'] += 1; - } - - $Explode = explode(';', $Log['AdditionalData']); - foreach($Explode as $Exploded) - { - $Exploded = explode(',', $Exploded); - if($Log['Code'] == 1) - { - $PlanetsDumpData[$Log['PlanetID']][$Exploded[0].'_workpercent'] = $Exploded[1]; - } - else if($Log['Code'] == 2) - { - foreach($PlanetsDumpData as $ThisPlanetID => $ThisData) - { - if($ThisData['planet_type'] == 1) - { - $PlanetsDumpData[$ThisPlanetID][$Exploded[0].'_workpercent'] = $Exploded[1]; - } - } - } - } - - $PreventResourceUpdate = true; - } - else if($Place == 23) - { - // merchant.php - $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); - if($ResUpdateReturn !== false) - { - $ScanLog['ResUpdates'] += 1; - } - - $Traded = explode(';', $Log['AdditionalData']); - foreach($Traded as $TradeData) - { - $TradeData = explode(',', $TradeData); - if($Log['ElementID'] == 1) - { - // If Selling Resources - if($TradeData[0] == 'R') - { - if($Log['Code'] == 1) - { - $PlanetsDumpData[$Log['PlanetID']]['metal'] -= $TradeData[1]; - } - else if($Log['Code'] == 2) - { - $PlanetsDumpData[$Log['PlanetID']]['crystal'] -= $TradeData[1]; - } - else if($Log['Code'] == 3) - { - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $TradeData[1]; - } - } - else if($TradeData[0] == 'M') - { - $PlanetsDumpData[$Log['PlanetID']]['metal'] += $TradeData[1]; - } - else if($TradeData[0] == 'C') - { - $PlanetsDumpData[$Log['PlanetID']]['crystal'] += $TradeData[1]; - } - else if($TradeData[0] == 'D') - { - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] += $TradeData[1]; - } - } - else - { - // If Buying Resources - if($TradeData[0] == 'R') - { - if($Log['Code'] == 1) - { - $PlanetsDumpData[$Log['PlanetID']]['metal'] += $TradeData[1]; - } - else if($Log['Code'] == 2) - { - $PlanetsDumpData[$Log['PlanetID']]['crystal'] += $TradeData[1]; - } - else if($Log['Code'] == 3) - { - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] += $TradeData[1]; - } - } - else if($TradeData[0] == 'M') - { - $PlanetsDumpData[$Log['PlanetID']]['metal'] -= $TradeData[1]; - } - else if($TradeData[0] == 'C') - { - $PlanetsDumpData[$Log['PlanetID']]['crystal'] -= $TradeData[1]; - } - else if($TradeData[0] == 'D') - { - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $TradeData[1]; - } - } - } - - $ResourcesChanged = $Log['PlanetID']; - } - else if($Place == 24) - { - // disassembler.php - $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); - if($ResUpdateReturn !== false) - { - $ScanLog['ResUpdates'] += 1; - } - - $Disassembled = explode(';', $Log['AdditionalData']); - foreach($Disassembled as $Item) - { - $Item = explode(',', $Item); - if($Item[0] == 'P') - { - $Log['Disassebler_Percent'] = $Item[1] / 100; - } - else - { - $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$Item[0]]] -= $Item[1]; - $PlanetsDumpData[$Log['PlanetID']]['metal'] += $_Vars_Prices[$Item[0]]['metal'] * $Item[1] * $Log['Disassebler_Percent']; - $PlanetsDumpData[$Log['PlanetID']]['crystal'] += $_Vars_Prices[$Item[0]]['crystal'] * $Item[1] * $Log['Disassebler_Percent']; - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] += $_Vars_Prices[$Item[0]]['deuterium'] * $Item[1] * $Log['Disassebler_Percent']; - $ChangedShipsTypes[] = $Item[0]; - } - } - - $ShipsChanged = array('Where' => $Log['PlanetID'], 'Types' => $ChangedShipsTypes); - $ResourcesChanged = $Log['PlanetID']; - } - else if($Place == 25) - { - // overview.php [Deleting Planet/Moon] - unset($PlanetsDumpData[$Log['PlanetID']]); - - $PreventResourceUpdate = true; - } - else if($Place == 26) - { - // Settings.php [Go to/Leave VacationMode] - - if($Log['Code'] == 2) - { - foreach($PlanetsDumpData as $PlanetID => $PlanetData) - { - $PlanetsDumpData[$PlanetID]['last_update'] = $Log['Date']; - } - } - - $PreventResourceUpdate = true; - } - else if($Place == 27) - { - // JumpGate.php [Move Fleet] - - $Move = explode(';', $Log['AdditionalData']); - foreach($Move as $MoveShip) - { - $MoveShip = explode(',', $MoveShip); - $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$MoveShip[0]]] -= $MoveShip[1]; - $PlanetsDumpData[$Log['ElementID']][$_Vars_GameElements[$MoveShip[0]]] += $MoveShip[1]; - } - - $PreventResourceUpdate = true; - } - else if($Place == 28) - { - // Destroy_rockets.php [Delete Rockets] - - $Delete = explode(';', $Log['AdditionalData']); - foreach($Delete as $RocketData) - { - $RocketData = explode(',', $RocketData); - $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$RocketData[0]]] -= $RocketData[1]; - } - - $PreventResourceUpdate = true; - } - else if($Place == 29) - { - // Phalanx.php [Remove Deuterium from Scan] - - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= PHALANX_DEUTERIUMCOST; - $PreventResourceUpdate = true; - } - else if($Place == 30) - { - // common.php [Task System] - - $Added = explode(';', $Log['AdditionalData']); - foreach($Added as $ElementData) - { - $ElementData = explode(',', $ElementData); - if($ElementData[0] == 'M') - { - $PlanetsDumpData[$Log['PlanetID']]['metal'] += $ElementData[1]; - } - else if($ElementData[0] == 'C') - { - $PlanetsDumpData[$Log['PlanetID']]['crystal'] += $ElementData[1]; - } - else if($ElementData[0] == 'D') - { - $PlanetsDumpData[$Log['PlanetID']]['deuterium'] += $ElementData[1]; - } - else - { - $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$ElementData[0]]] += $ElementData[1]; - } - } - - $PreventResourceUpdate = true; - } - else - { - $ScanLog['Fatal'][] = array('ID' => '001', 'LogNo' => $ScaningNo, 'LogID' => $Log['ID'], 'Data' => array($Place)); - $PreventResourceUpdate = true; - } - // --- END of Main Checking Part - - - if($ResourcesChanged > 0) - { - if($PlanetsDumpData[$ResourcesChanged]['metal'] < 0 OR $PlanetsDumpData[$ResourcesChanged]['crystal'] < 0 OR $PlanetsDumpData[$ResourcesChanged]['deuterium'] < 0) - { - $ScanLog['Warning'][] = array - ( - 'ID' => '001', - 'LogNo' => $ScaningNo, - 'LogID' => $Log['ID'], - 'Date' => $Log['Date'], - 'PlanetID' => $ResourcesChanged, - 'Place' => $Place, - 'Code' => $Log['Code'], - 'ElementID' => $Log['ElementID'], - 'Data' => array - ( - $PlanetsDumpData[$ResourcesChanged]['metal'], - $PlanetsDumpData[$ResourcesChanged]['crystal'], - $PlanetsDumpData[$ResourcesChanged]['deuterium'] - ) - ); - } - } - - if($ShipsChanged !== false) - { - $CreateWarning = false; - foreach($ShipsChanged['Types'] as $ShipID) - { - if($PlanetsDumpData[$ShipsChanged['Where']][$_Vars_GameElements[$ShipID]] < 0) - { - $CreateWarning[$ShipID] = $PlanetsDumpData[$ShipsChanged['Where']][$_Vars_GameElements[$ShipID]]; - } - } - if(!empty($CreateWarning)) - { - $ScanLog['Warning'][] = array - ( - 'ID' => '003', - 'LogNo' => $ScaningNo, - 'LogID' => $Log['ID'], - 'Date' => $Log['Date'], - 'PlanetID' => $ShipsChanged['Where'], - 'Place' => $Place, - 'Code' => $Log['Code'], - 'ElementID' => $Log['ElementID'], - 'Data' => $CreateWarning - ); - } - } - - if(!$PreventResourceUpdate) - { - if($Log['PlanetID'] > 0) - { - $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); - if($ResUpdateReturn !== false) - { - $ScanLog['ResUpdates'] += 1; - } - } - else - { - $ScanLog['Warning'][] = array - ( - 'ID' => '002', - 'LogNo' => $ScaningNo, - 'LogID' => $Log['ID'], - 'Place' => $Place - ); - } - } - - $ScanLog['LogScanned'] += 1; - if(!isset($ScanLog['ScannedPlaces'][$Place])) - { - $ScanLog['ScannedPlaces'][$Place] = 0; - } - $ScanLog['ScannedPlaces'][$Place] += 1; - } - - $SummaryElements = array(); - $SummaryNew['metal'] = 0; - $SummaryNew['crystal'] = 0; - $SummaryNew['deuterium'] = 0; - $SummaryLog['metal'] = 0; - $SummaryLog['crystal'] = 0; - $SummaryLog['deuterium'] = 0; - - while($PlanetNew = mysql_fetch_assoc($PlanetsNewData)) - { - $PlanetNew['metal'] += 0; - $PlanetNew['crystal'] += 0; - $PlanetNew['deuterium'] += 0; - - $SummaryNew['metal'] += $PlanetNew['metal']; - $SummaryNew['crystal'] += $PlanetNew['crystal']; - $SummaryNew['deuterium'] += $PlanetNew['deuterium']; - - foreach($_Vars_ElementCategories as $Key => $Values) - { - if(in_array($Key, array('build', 'tech', 'prod', 'buildOn', 'units'))) - { - continue; - } - foreach($Values as $ItemID) - { - $PlanetNew[$_Vars_GameElements[$ItemID]] += 0; - if(!isset($SummaryNew[$ItemID])) - { - $SummaryNew[$ItemID] = 0; - } - $SummaryNew[$ItemID] += $PlanetNew[$_Vars_GameElements[$ItemID]]; - if(!in_array($ItemID, $SummaryElements)) - { - $SummaryElements[] = $ItemID; - } - } - } - - $CurrentPlanets[$PlanetNew['id']] = $PlanetNew; - } - - foreach($PlanetsDumpData as $PlanetID => $PlanetData) - { - if($PlanetData['last_update'] < $CurrentPlanets[$PlanetID]['last_update']) - { - ResourceUpdate($PlanetsDumpData[$PlanetID], $UserData, 'LA', $CurrentPlanets[$PlanetID]['last_update']); - $PlanetData = $PlanetsDumpData[$PlanetID]; - } - - $PlanetData['metal'] += 0; - $PlanetData['crystal'] += 0; - $PlanetData['deuterium'] += 0; - - $SummaryLog['metal'] += $PlanetData['metal']; - $SummaryLog['crystal'] += $PlanetData['crystal']; - $SummaryLog['deuterium'] += $PlanetData['deuterium']; - - if($PlanetData['metal'] != $CurrentPlanets[$PlanetID]['metal']) - { - if(!isset($AcceptableDifferences)) - { - $AcceptableDifferences = 0; - } - $AcceptableDifferences += 1; - $Difference = $CurrentPlanets[$PlanetID]['metal'] - $PlanetData['metal']; - if(($Difference > 0 AND $Difference > 1) OR ($Difference < 0 AND $Difference < -1)) - { - if($PlanetData['metal'] > $CurrentPlanets[$PlanetID]['metal'] * $PermDiff) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '003', - 'PlanetID' => $PlanetID, - 'ElementID' => $_Lang['Metal'], - 'Data' => array - ( - $PlanetData['metal'], - $CurrentPlanets[$PlanetID]['metal'], - ($PlanetData['metal'] != 0 ? $CurrentPlanets[$PlanetID]['metal'] / $PlanetData['metal'] : 'x') - ) - ); - } - else if($PlanetData['metal'] * $PermDiff < $CurrentPlanets[$PlanetID]['metal']) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '004', - 'PlanetID' => $PlanetID, - 'ElementID' => $_Lang['Metal'], - 'Data' => array - ( - $PlanetData['metal'], - $CurrentPlanets[$PlanetID]['metal'], - ($PlanetData['metal'] != 0 ? $CurrentPlanets[$PlanetID]['metal'] / $PlanetData['metal'] : 'x') - ) - ); - } - else - { - $ScanLog['Notice'][] = array - ( - 'ID' => '001', - 'PlanetID' => $PlanetID, - 'Data' => array - ( - ($PlanetData['metal'] != 0 ? $CurrentPlanets[$PlanetID]['metal'] / $PlanetData['metal'] : 'x'), - $Difference - ) - ); - } - } - } - if($PlanetData['crystal'] != $CurrentPlanets[$PlanetID]['crystal']) - { - if(!isset($AcceptableDifferences)) - { - $AcceptableDifferences = 0; - } - $AcceptableDifferences += 1; - $Difference = $CurrentPlanets[$PlanetID]['crystal'] - $PlanetData['crystal']; - if(($Difference > 0 AND $Difference > 1) OR ($Difference < 0 AND $Difference < -1)) - { - if($PlanetData['crystal'] > $CurrentPlanets[$PlanetID]['crystal'] * $PermDiff) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '003', - 'PlanetID' => $PlanetID, - 'ElementID' => $_Lang['Crystal'], - 'Data' => array - ( - $PlanetData['crystal'], - $CurrentPlanets[$PlanetID]['crystal'], - ($PlanetData['crystal'] != 0 ? $CurrentPlanets[$PlanetID]['crystal'] / $PlanetData['crystal'] : 'x') - ) - ); - } - else if($PlanetData['crystal'] * $PermDiff < $CurrentPlanets[$PlanetID]['crystal']) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '004', - 'PlanetID' => $PlanetID, - 'ElementID' => $_Lang['Crystal'], - 'Data' => array - ( - $PlanetData['crystal'], - $CurrentPlanets[$PlanetID]['crystal'], - ($PlanetData['crystal'] != 0 ? $CurrentPlanets[$PlanetID]['crystal'] / $PlanetData['crystal'] : 'x') - ) - ); - } - else - { - $ScanLog['Notice'][] = array - ( - 'ID' => '002', - 'PlanetID' => $PlanetID, - 'Data' => array - ( - ($PlanetData['crystal'] != 0 ? $CurrentPlanets[$PlanetID]['crystal'] / $PlanetData['crystal'] : 'x'), - $Difference - ) - ); - } - } - } - if($PlanetData['deuterium'] != $CurrentPlanets[$PlanetID]['deuterium']) - { - if(!isset($AcceptableDifferences)) - { - $AcceptableDifferences = 0; - } - $AcceptableDifferences += 1; - $Difference = $CurrentPlanets[$PlanetID]['deuterium'] - $PlanetData['deuterium']; - if(($Difference > 0 AND $Difference > 1) OR ($Difference < 0 AND $Difference < -1)) - { - if($PlanetData['deuterium'] > $CurrentPlanets[$PlanetID]['deuterium'] * $PermDiff) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '003', - 'PlanetID' => $PlanetID, - 'ElementID' => $_Lang['Deuterium'], - 'Data' => array - ( - $PlanetData['deuterium'], - $CurrentPlanets[$PlanetID]['deuterium'], - ($PlanetData['deuterium'] != 0 ? $CurrentPlanets[$PlanetID]['deuterium'] / $PlanetData['deuterium'] : 'x') - ) - ); - } - else if($PlanetData['deuterium'] * $PermDiff < $CurrentPlanets[$PlanetID]['deuterium']) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '004', - 'PlanetID' => $PlanetID, - 'ElementID' => $_Lang['Deuterium'], - 'Data' => array - ( - $PlanetData['deuterium'], - $CurrentPlanets[$PlanetID]['deuterium'], - ($PlanetData['deuterium'] != 0 ? $CurrentPlanets[$PlanetID]['deuterium'] / $PlanetData['deuterium'] : 'x') - ) - ); - } - else - { - $ScanLog['Notice'][] = array - ( - 'ID' => '003', - 'PlanetID' => $PlanetID, - 'Data' => array - ( - ($PlanetData['deuterium'] != 0 ? $CurrentPlanets[$PlanetID]['deuterium'] / $PlanetData['deuterium'] : 'x'), - $Difference - ) - ); - } - } - } - - foreach($_Vars_ElementCategories as $Key => $Values) - { - if(in_array($Key, array('tech', 'prod', 'buildOn', 'units'))) - { - continue; - } - foreach($Values as $ItemID) - { - if($Key != 'build') - { - if(!isset($SummaryLog[$ItemID])) - { - $SummaryLog[$ItemID] = 0; - } - $SummaryLog[$ItemID] += $PlanetData[$_Vars_GameElements[$ItemID]]; - if(!in_array($ItemID, $SummaryElements)) - { - $SummaryElements[] = $ItemID; - } - } - if(empty($PlanetData[$_Vars_GameElements[$ItemID]])) - { - $PlanetData[$_Vars_GameElements[$ItemID]] = 0; - } - if(empty($CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]])) - { - $CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]] = 0; - } - - if($PlanetData[$_Vars_GameElements[$ItemID]] > $CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]]) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '001', - 'PlanetID' => $PlanetID, - 'ElementID' => $ItemID, - 'Data' => array - ( - $PlanetData[$_Vars_GameElements[$ItemID]], - $CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]], - ($PlanetData[$_Vars_GameElements[$ItemID]] != 0 ? $CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]] / $PlanetData[$_Vars_GameElements[$ItemID]] : 'x') - ) - ); - } - else if($PlanetData[$_Vars_GameElements[$ItemID]] < $CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]]) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '002', - 'PlanetID' => $PlanetID, - 'ElementID' => $ItemID, - 'Data' => array - ( - $PlanetData[$_Vars_GameElements[$ItemID]], - $CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]], - ($PlanetData[$_Vars_GameElements[$ItemID]] != 0 ? $CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]] / $PlanetData[$_Vars_GameElements[$ItemID]] : 'x') - ) - ); - } - } - } - } - - if($SummaryLog['metal'] != $SummaryNew['metal']) - { - $Difference = $SummaryLog['metal'] - $SummaryNew['metal']; - if(($Difference > 0 AND $Difference > (1 * $AcceptableDifferences)) OR ($Difference < 0 AND $Difference < (-1 * $AcceptableDifferences))) - { - if($SummaryLog['metal'] > $SummaryNew['metal'] * $PermDiff) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '005', - 'ElementID' => $_Lang['Metal'], - 'Data' => array - ( - $SummaryLog['metal'], - $SummaryNew['metal'], - ($SummaryLog['metal'] != 0 ? $SummaryNew['metal'] / $SummaryLog['metal'] : 'x') - ) - ); - } - else if($SummaryLog['metal'] * $PermDiff < $SummaryNew['metal']) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '006', - 'ElementID' => $_Lang['Metal'], - 'Data' => array - ( - $SummaryLog['metal'], - $SummaryNew['metal'], - ($SummaryLog['metal'] != 0 ? $SummaryNew['metal'] / $SummaryLog['metal'] : 'x') - ) - ); - } - else - { - $ScanLog['Notice'][] = array - ( - 'ID' => '004' - ); - } - } - } - if($SummaryLog['crystal'] != $SummaryNew['crystal']) - { - $Difference = $SummaryLog['crystal'] - $SummaryNew['crystal']; - if(($Difference > 0 AND $Difference > (1 * $AcceptableDifferences)) OR ($Difference < 0 AND $Difference < (-1 * $AcceptableDifferences))) - { - if($SummaryLog['crystal'] > $SummaryNew['crystal'] * $PermDiff) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '005', - 'ElementID' => $_Lang['Crystal'], - 'Data' => array - ( - $SummaryLog['crystal'], - $SummaryNew['crystal'], - ($SummaryLog['crystal'] != 0 ? $SummaryNew['crystal'] / $SummaryLog['crystal'] : 'x') - ) - ); - } - else if($SummaryLog['crystal'] * $PermDiff < $SummaryNew['crystal']) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '006', - 'ElementID' => $_Lang['Crystal'], - 'Data' => array - ( - $SummaryLog['crystal'], - $SummaryNew['crystal'], - ($SummaryLog['crystal'] != 0 ? $SummaryNew['crystal'] / $SummaryLog['crystal'] : 'x') - ) - ); - } - else - { - $ScanLog['Notice'][] = array - ( - 'ID' => '005' - ); - } - } - } - if($SummaryLog['deuterium'] != $SummaryNew['deuterium']) - { - $Difference = $SummaryLog['deuterium'] - $SummaryNew['deuterium']; - if(($Difference > 0 AND $Difference > (1 * $AcceptableDifferences)) OR ($Difference < 0 AND $Difference < (-1 * $AcceptableDifferences))) - { - if($SummaryLog['deuterium'] > $SummaryNew['deuterium'] * $PermDiff) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '005', - 'ElementID' => $_Lang['Deuterium'], - 'Data' => array - ( - $SummaryLog['deuterium'], - $SummaryNew['deuterium'], - ($SummaryLog['deuterium'] != 0 ? $SummaryNew['deuterium'] / $SummaryLog['deuterium'] : 'x') - ) - ); - } - else if($SummaryLog['deuterium'] * $PermDiff < $SummaryNew['deuterium']) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '006', - 'ElementID' => $_Lang['Deuterium'], - 'Data' => array - ( - $SummaryLog['deuterium'], - $SummaryNew['deuterium'], - ($SummaryLog['deuterium'] != 0 ? $SummaryNew['deuterium'] / $SummaryLog['deuterium'] : 'x') - ) - ); - } - else - { - $ScanLog['Notice'][] = array - ( - 'ID' => '006' - ); - } - } - } - - if(!empty($SummaryElements)) - { - if(empty($SummaryLog[$ItemID])) - { - $SummaryLog[$ItemID] = 0; - } - if(empty($SummaryNew[$ItemID])) - { - $SummaryNew[$ItemID] = 0; - } - - foreach($SummaryElements as $ItemID) - { - if($SummaryLog[$ItemID] > $SummaryNew[$ItemID]) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '007', - 'ElementID' => $ItemID, - 'Data' => array - ( - $SummaryLog[$ItemID], - $SummaryNew[$ItemID], - ($SummaryLog[$ItemID] != 0 ? $SummaryNew[$ItemID] / $SummaryLog[$ItemID] : 'x') - ) - ); - } - else if($PlanetData[$_Vars_GameElements[$ItemID]] < $CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]]) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '008', - 'ElementID' => $ItemID, - 'Data' => array - ( - $SummaryLog[$ItemID], - $SummaryNew[$ItemID], - ($SummaryLog[$ItemID] != 0 ? $SummaryNew[$ItemID] / $SummaryLog[$ItemID] : 'x') - ) - ); - } - } - } - - foreach($_Vars_ElementCategories['tech'] as $TechID) - { - if(empty($UserData[$_Vars_GameElements[$TechID]])) - { - $UserData[$_Vars_GameElements[$TechID]] = 0; - } - if(empty($UserNewData[$_Vars_GameElements[$TechID]])) - { - $UserNewData[$_Vars_GameElements[$TechID]] = 0; - } - - if($UserData[$_Vars_GameElements[$TechID]] > $UserNewData[$_Vars_GameElements[$TechID]]) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '009', - 'ElementID' => $TechID, - 'Data' => array - ( - $UserData[$_Vars_GameElements[$TechID]], - $UserNewData[$_Vars_GameElements[$TechID]] - ) - ); - } - else if($UserData[$_Vars_GameElements[$TechID]] < $UserNewData[$_Vars_GameElements[$TechID]]) - { - $ScanLog['Summary'][] = array - ( - 'ID' => '010', - 'ElementID' => $TechID, - 'Data' => array - ( - $UserData[$_Vars_GameElements[$TechID]], - $UserNewData[$_Vars_GameElements[$TechID]] - ) - ); - } - } - - $ScanEndTime = microtime(true); - } - } - - $_Lang['PHP_Username'] = $GetUser['username']; - $_Lang['PHP_UID'] = $GetUser['id']; - - if($BreakScan OR empty($ScanLog)) - { - $_Lang['PHP_HideScanResult'] = $Hide; - - if(!empty($_Lang['Error_Found'])) - { - $_Lang['PHP_BreakErrorColor'] = 'red'; - $_Lang['PHP_BreakErrorText'] = $_Lang['Error_Found']; - } - else if(!empty($_Lang['Notice_Found'])) - { - $_Lang['PHP_BreakErrorColor'] = 'orange'; - $_Lang['PHP_BreakErrorText'] = $_Lang['Notice_Found']; - } - else - { - if(empty($ScanLog)) - { - $_Lang['PHP_BreakErrorColor'] = 'red'; - $_Lang['PHP_BreakErrorText'] = $_Lang['Critical_EmptyScanLog']; - } - else - { - $_Lang['PHP_BreakErrorColor'] = 'red'; - $_Lang['PHP_BreakErrorText'] = $_Lang['Critical_EmptyBreakErrorVar']; - } - } - } - else - { - $_Lang['PHP_HideBreakError'] = $Hide; - - $_Lang['PHP_ScanedLogs'] = $ScanLog['LogScanned']; - $_Lang['PHP_ScanTime'] = sprintf('%0.10f', ($ScanEndTime - $ScanStartTime)); - $_Lang['PHP_DumpDate'] = prettyDate('d m Y - H:i:s', $LoadLastDump['Date'], 1).'
('.$LoadLastDump['Date'].')'; - $_Lang['PHP_DateDifference'] = pretty_time(time() - $LoadLastDump['Date']); - - $ResultRowTPL = gettemplate('admin/userdevscanner_result_row'); - - // Found "Fatal"/"Warning"/"Notice" Exceptions & Handle Summary - if(empty($ScanLog['Fatal'])) - { - $ScanLog['Fatal'] = array(); - } - if(empty($ScanLog['Warning'])) - { - $ScanLog['Warning'] = array(); - } - if(empty($ScanLog['Notice'])) - { - $ScanLog['Notice'] = array(); - } - if(empty($ScanLog['Summary'])) - { - $ScanLog['Summary'] = array(); - } - - foreach($ScanLog as $ScanKey => $ScanData) - { - if($ScanKey != 'Fatal' AND $ScanKey != 'Warning' AND $ScanKey != 'Notice' AND $ScanKey != 'Summary') - { - continue; - } - if(!empty($ScanData)) - { - if($ScanKey == 'Fatal') - { - $ParseRowPattern = array('ModuleNumber' => '01', 'TextColor' => 'red', 'Table2_LogID' => $_Lang['Table2_LogID']); - } - else if($ScanKey == 'Warning') - { - $ParseRowPattern = array('ModuleNumber' => '02', 'TextColor' => 'orange', 'Table2_LogID' => $_Lang['Table2_LogID']); - } - else if($ScanKey == 'Notice') - { - $ParseRowPattern = array('ModuleNumber' => '03', 'TextColor' => 'yellow', 'Table2_LogID' => $_Lang['Table2_LogID']); - } - else if($ScanKey == 'Summary') - { - $ParseRowPattern = array('ModuleNumber' => '04', 'TextColor' => 'orange', 'Table2_LogID' => $_Lang['Table2_LogID']); - } - $LastLogIDLen = end($ScanData); - $LastLogIDLen = isset($LastLogIDLen['LogID']) ? strlen($LastLogIDLen['LogID']) : 0; - reset($ScanData); - $_Lang['Table2_Final'.$ScanKey.'Count'] = count($ScanData); - foreach($ScanData as $Index => $Data) - { - $ParseRow = $ParseRowPattern; - $Point = &$_Lang['Found'.$ScanKey.'s'][$Data['ID']]; - $ParseRow['Index'] = str_pad($Index + 1, 4, '0', STR_PAD_LEFT); - $ParseRow['RowTitle'] = $Point['Txt']; - if($ScanKey == 'Summary' OR $Data['LogID'] <= 0) - { - $ParseRow['HideLogID'] = $Hide; - } - else - { - $ParseRow['RowLogID'] = str_pad($Data['LogID'], $LastLogIDLen, '0', STR_PAD_LEFT); - if($Data['LogNo'] > 0) - { - $ParseRow['RowLogID'] .= '
LogNo: '.$Data['LogNo']; - } - } - if($Point['GenerateDataList'] === true) - { - if(!empty($Data['Data'])) - { - foreach($Data['Data'] as $DataID => $DataVal) - { - $Data['GeneratedDataList'][] = eval('return "'.$Point['DataListEvalCode'].'";'); - } - $Data['GeneratedDataList'] = implode($Point['DataListGlue'], $Data['GeneratedDataList']); - } - } - if(!empty($Point['Eval'])) - { - $ParseRow['RowData'] = eval('return "'.$Point['Eval'].'";'); - } - else - { - $ParseRow['RowData'] = '-'; - } - - if($ScanKey == 'Notice') - { - $ParseRow['IsCollapsed'] = 'collapsed'; - } - - if(!isset($_Lang['PHP_AllFound'.$ScanKey.'s'])) - { - $_Lang['PHP_AllFound'.$ScanKey.'s'] = ''; - } - $_Lang['PHP_AllFound'.$ScanKey.'s'] .= parsetemplate($ResultRowTPL, $ParseRow); - } - } - else - { - $_Lang['PHP_HideFound'.$ScanKey.'s'] = $Hide; - $_Lang['PHP_HideFound'.$ScanKey.'s2'] = 'hide'; - } - } - - if(empty($ScanLog['Summary'])) - { - $_Lang['PHP_OverallResultColor'] = 'lime'; - $_Lang['PHP_OverallResultText'] = $_Lang['FoundSummarys']['000']['Txt1']; - } - else - { - $_Lang['PHP_OverallResultColor'] = 'red'; - $_Lang['PHP_OverallResultText'] = $_Lang['FoundSummarys']['000']['Txt2']; - } - } - - $Page = parsetemplate(gettemplate('admin/userdevscanner_result'), $_Lang); - } - else - { - if(empty($_Lang['Error_Found'])) - { - $_Lang['PHP_ShowError'] = $Hide; - } - - $Page = parsetemplate(gettemplate('admin/userdevscanner_form'), $_Lang); - } - - display($Page, $_Lang['UserDevScanner_Title'], false, true); - -?> \ No newline at end of file + $Data) + { + if($Data['start'] <= $StartTime) + { + if($Data['end'] >= $EndTime) + { + $Add_Multiplier_Resources = $ProductionTime; + break; + } + else + { + $Add_Multiplier_Resources += ($Data['end'] - $StartTime); + } + } + else + { + if($Data['start'] >= $EndTime) + { + break; + } + else + { + if($Data['end'] >= $EndTime) + { + $Add_Multiplier_Resources += ($EndTime - $Data['start']); + break; + } + else + { + $Add_Multiplier_Resources += ($Data['end'] - $Data['start']); + } + } + } + } + + if($Add_Multiplier_Resources > 0) + { + $Multiplier_Resources += (0.15 * ($Add_Multiplier_Resources / $ProductionTime)); + } + } + + $Multiplier_Energy = 1; + $Add_Multiplier_Energy = 0; + if(!empty($PremiumItemsArchive[6])) + { + foreach($PremiumItemsArchive[6] as $Index => $Data) + { + if($Data['start'] <= $StartTime) + { + if($Data['end'] >= $EndTime) + { + $Add_Multiplier_Energy = $ProductionTime; + break; + } + else + { + $Add_Multiplier_Energy += ($Data['end'] - $StartTime); + } + } + else + { + if($Data['start'] >= $EndTime) + { + break; + } + else + { + if($Data['end'] >= $EndTime) + { + $Add_Multiplier_Energy += ($EndTime - $Data['start']); + break; + } + else + { + $Add_Multiplier_Energy += ($Data['end'] - $Data['start']); + } + } + } + } + + if($Add_Multiplier_Energy > 0) + { + $Multiplier_Energy += (0.1 * ($Add_Multiplier_Energy / $ProductionTime)); + } + } + // Calculate Place in Storages + if(empty($CurrentPlanet['metal_max'])) + { + $CurrentPlanet['metal_max'] = (floor (BASE_STORAGE_SIZE * pow (1.7, $CurrentPlanet[$_Vars_GameElements[22]]))) * MAX_OVERFLOW; + $CurrentPlanet['crystal_max'] = (floor (BASE_STORAGE_SIZE * pow (1.7, $CurrentPlanet[$_Vars_GameElements[23]]))) * MAX_OVERFLOW; + $CurrentPlanet['deuterium_max'] = (floor (BASE_STORAGE_SIZE * pow (1.7, $CurrentPlanet[$_Vars_GameElements[24]]))) * MAX_OVERFLOW; + } + + // Calculate additional income + $Caps = array + ( + 'metal_perhour' => 0, + 'crystal_perhour' => 0, + 'deuterium_perhour' => 0, + 'energy_used' => 0, + 'energy_max' => 0 + ); + $BuildTemp = $CurrentPlanet['temp_max']; + $TextIfEmpty = 'return "0";'; + foreach($_Vars_ElementCategories['prod'] as $ElementID) + { + $BuildLevelFactor = $CurrentPlanet[$_Vars_GameElements[$ElementID].'_workpercent']; + $BuildLevel = $CurrentPlanet[$_Vars_GameElements[$ElementID]]; + + if($BuildLevel <= 0) + { + continue; + } + + if($_Vars_ResProduction[$ElementID]['formule']['metal'] != $TextIfEmpty) + { + $Caps['metal_perhour'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['metal']) * ($_GameConfig['resource_multiplier']) * $Multiplier_Resources); + } + if($_Vars_ResProduction[$ElementID]['formule']['crystal'] != $TextIfEmpty) + { + $Caps['crystal_perhour'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['crystal']) * ($_GameConfig['resource_multiplier']) * $Multiplier_Resources); + } + if($ElementID != 12) + { + if($_Vars_ResProduction[$ElementID]['formule']['deuterium'] != $TextIfEmpty) + { + $Caps['deuterium_perhour'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * ($_GameConfig['resource_multiplier']) * $Multiplier_Resources); + } + } + else + { + $Caps['deuterium_perhour'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * ($_GameConfig['resource_multiplier'])); + } + + if($ElementID < 4) + { + $Caps['energy_used'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy'])); + } + else + { + if($ElementID != 12) + { + $Caps['energy_max'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $Multiplier_Energy); + } + else + { + $MineDeuteriumUse = floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * ($_GameConfig['resource_multiplier'])) * (-1); + if($MineDeuteriumUse > 0) + { + if($CurrentPlanet['deuterium'] <= 0) + { + if($Caps['deuterium_perhour'] == ($MineDeuteriumUse * (-1))) + { + // If no enough + production of deuterium + } + else + { + // If there is still some deuterium in + production to use + $FusionReactorMulti = ($Caps['deuterium_perhour'] + $MineDeuteriumUse) / $MineDeuteriumUse; + if($FusionReactorMulti > 1) + { + $FusionReactorMulti = 1; + } + $Caps['energy_max'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $FusionReactorMulti * $Multiplier_Energy); + } + } + else + { + if($Caps['deuterium_perhour'] >= 0) + { + $Caps['energy_max'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $Multiplier_Energy); + } + else + { + $FusionReactorMulti = $CurrentPlanet['deuterium'] / ($MineDeuteriumUse / 3600); + if($FusionReactorMulti > 1) + { + $FusionReactorMulti = 1; + } + $Caps['energy_max'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $FusionReactorMulti * $Multiplier_Energy); + } + } + } + } + } + } + + if($Caps['energy_max'] == 0 AND abs($Caps['energy_used']) > 0) + { + $production_level = 0; + } + else if($Caps['energy_max'] > 0 AND abs($Caps['energy_used']) > $Caps['energy_max']) + { + $production_level = floor(($Caps['energy_max'] * 100) / abs($Caps['energy_used'])); + } + else + { + $production_level = 100; + } + if($production_level > 100) + { + $production_level = 100; + } + + if($CurrentPlanet['metal'] <= $CurrentPlanet['metal_max']) + { + $MetalProduction = ($ProductionTime * ($Caps['metal_perhour'] / 3600)) * (0.01 * $production_level); + $MetalBaseProduc = $ProductionTime * (($_GameConfig['metal_basic_income'] * $_GameConfig['resource_multiplier']) / 3600); + $MetalT = $MetalProduction + $MetalBaseProduc; + $MetalTheorical = $CurrentPlanet['metal'] + $MetalT; + + $Return['MetalProduction'] = $MetalT; + + if($MetalTheorical < 0) + { + $MetalTheorical = 0; + } + + if($MetalTheorical < $CurrentPlanet['metal_max']) + { + $CurrentPlanet['metal'] = $MetalTheorical; + } + else + { + $CurrentPlanet['metal'] = $CurrentPlanet['metal_max']; + $Return['MetalProduction'] -= ($MetalTheorical - $CurrentPlanet['metal']); + } + } + + if($CurrentPlanet['crystal'] <= $CurrentPlanet['crystal_max']) + { + $CrystalProduction = ($ProductionTime * ($Caps['crystal_perhour'] / 3600)) * (0.01 * $production_level); + $CrystalBaseProduc = $ProductionTime * (($_GameConfig['crystal_basic_income'] * $_GameConfig['resource_multiplier']) / 3600); + $CrystalT = $CrystalProduction + $CrystalBaseProduc; + $CrystalTheorical = $CurrentPlanet['crystal'] + $CrystalT; + + $Return['CrystalProduction'] = $CrystalT; + + if($CrystalTheorical < 0) + { + $CrystalTheorical = 0; + } + + if($CrystalTheorical < $CurrentPlanet['crystal_max']) + { + $CurrentPlanet['crystal'] = $CrystalTheorical; + } + else + { + $CurrentPlanet['crystal'] = $CurrentPlanet['crystal_max']; + $Return['CrystalProduction'] -= ($CrystalTheorical - $CurrentPlanet['crystal']); + } + } + + if($CurrentPlanet['deuterium'] <= $CurrentPlanet['deuterium_max']) + { + $DeuteriumProduction = ($ProductionTime * ($Caps['deuterium_perhour'] / 3600)) * (0.01 * $production_level); + $DeuteriumBaseProduc = $ProductionTime * (($_GameConfig['deuterium_basic_income'] * $_GameConfig['resource_multiplier']) / 3600); + $DeuteriumT = $DeuteriumProduction + $DeuteriumBaseProduc; + $DeuteriumTheorical = $CurrentPlanet['deuterium'] + $DeuteriumT; + + $Return['DeuteriumProduction'] = $DeuteriumT; + + if($DeuteriumTheorical < 0) + { + $DeuteriumTheorical = 0; + $Return['DeuteriumProduction'] = $CurrentPlanet['deuterium']; + } + + if($DeuteriumTheorical < $CurrentPlanet['deuterium_max']) + { + $CurrentPlanet['deuterium'] = $DeuteriumTheorical; + } + else + { + $CurrentPlanet['deuterium'] = $CurrentPlanet['deuterium_max']; + $Return['DeuteriumProduction'] -= ($DeuteriumTheorical - $CurrentPlanet['deuterium']); + } + } + + $CurrentPlanet['last_update'] = $EndTime; + + return isset($Return) ? $Return : null; +} + +$UID = isset($_POST['uid']) ? $_POST['uid'] : 0; +$Username = isset($_POST['username']) ? $_POST['username'] : null; +if(!empty($UID) OR !empty($Username)) +{ + $Search = true; + if(!empty($UID)) + { + $UID = intval($UID); + if($UID > 0) + { + $WhereClausure = "`id` = {$UID}"; + } + } + if(!empty($Username) AND empty($WhereClausure)) + { + if(preg_match(REGEXP_USERNAME_ABSOLUTE, $Username)) + { + $WhereClausure = "`username` = '{$Username}'"; + } + } +} + +if($Search AND !empty($WhereClausure)) +{ + $GetUser = doquery("SELECT * FROM {{table}} WHERE {$WhereClausure} LIMIT 1;", 'users', true); + if($GetUser['id'] > 0) + { + $AllowScan = true; + } + else + { + $_Lang['Error_Found'] = $_Lang['Error_UserNoExist']; + } +} +else +{ + if($Search) + { + $_Lang['Error_Found'] = $_Lang['Error_BadPost']; + } +} + +if($AllowScan) +{ + $BreakScan = false; + + $UserNewData = &$GetUser; + $LoadLastDump = doquery("SELECT * FROM {{table}} WHERE `UserID` = {$GetUser['id']} LIMIT 1;", 'user_developmentdumps', true); + if($LoadLastDump['UserID'] != $GetUser['id']) + { + $_Lang['Error_Found'] = $_Lang['Critical_NoDump']; + $BreakScan = true; + } + if(!$BreakScan) + { + $LastDumpTimestamp = $LoadLastDump['Date'] - SERVER_MAINOPEN_TSTAMP; + $GetLogs = doquery("SELECT * FROM {{table}} WHERE `UserID` = {$GetUser['id']} ORDER BY `ID` ASC;", 'user_developmentlog'); + if(mysql_num_rows($GetLogs) == 0) + { + $_Lang['Notice_Found'] = $_Lang['Notice_NoLogs']; + $BreakScan = true; + } + if(!$BreakScan) + { + $ScanStartTime = microtime(true); + + $PlanetsNewData = doquery("SELECT * FROM {{table}} WHERE `id_owner` = {$GetUser['id']};", 'planets'); + $FleetsNewData = doquery("SELECT * FROM {{table}} WHERE `fleet_owner` = {$GetUser['id']};", 'fleets'); + $UserPremiumItems = doquery("SELECT * FROM {{table}} WHERE `UserID` = {$GetUser['id']} AND `Item` IN (5,6);", 'premiumpayments'); + + if(mysql_num_rows($UserPremiumItems) > 0) + { + while($PremiumItem = mysql_fetch_assoc($UserPremiumItems)) + { + $Length = 14 * TIME_DAY; + $PremiumItemsArchive[$PremiumItem['Item']][] = array + ( + 'start' => $PremiumItem['Date'], + 'end' => $PremiumItem['Date'] + $Length + ); + } + } + + $PlanetsDumpData = json_decode($LoadLastDump['Planets'], true); + foreach($PlanetsDumpData as $PlanetID => $PlanetData) + { + $PlanetsDumpData[$PlanetID]['id'] = $PlanetID; + foreach($_Vars_ElementCategories as $reskey => $resvals) + { + if(in_array($reskey, array('tech', 'buildOn', 'units'))) + { + continue; + } + foreach($resvals as $resID) + { + if($reskey != 'prod') + { + $PlanetsDumpData[$PlanetID][$_Vars_GameElements[$resID]] = 0; + } + else + { + $PlanetsDumpData[$PlanetID][$_Vars_GameElements[$resID].'_workpercent'] = 0; + } + } + } + + $Resources = explode(',', $PlanetData['res']); + $PlanetData['b'] = isset($PlanetData['b']) ? explode(';', $PlanetData['b']) : array(); + $PlanetData['p'] = isset($PlanetData['p']) ? explode(';', $PlanetData['p']) : array(); + $PlanetData['f'] = isset($PlanetData['f']) ? explode(';', $PlanetData['f']) : array(); + + foreach($PlanetData['b'] as $ElementData) + { + $ElementData = explode(',', $ElementData); + $PlanetsDumpData[$PlanetID][$_Vars_GameElements[$ElementData[0]]] = $ElementData[1]; + } + foreach($PlanetData['f'] as $ElementData) + { + $ElementData = explode(',', $ElementData); + $PlanetsDumpData[$PlanetID][$_Vars_GameElements[$ElementData[0]]] = $ElementData[1]; + } + foreach($PlanetData['p'] as $ElementData) + { + $ElementData = explode(',', $ElementData); + $PlanetsDumpData[$PlanetID][$_Vars_GameElements[$ElementData[0]].'_workpercent'] = $ElementData[1]; + } + + if($Resources[0] > 0) + { + $PlanetsDumpData[$PlanetID]['metal'] = $Resources[0]; + } + else + { + $PlanetsDumpData[$PlanetID]['metal'] = 0; + } + if($Resources[1] > 0) + { + $PlanetsDumpData[$PlanetID]['crystal'] = $Resources[1]; + } + else + { + $PlanetsDumpData[$PlanetID]['crystal'] = 0; + } + if($Resources[2] > 0) + { + $PlanetsDumpData[$PlanetID]['deuterium'] = $Resources[2]; + } + else + { + $PlanetsDumpData[$PlanetID]['deuterium'] = 0; + } + + $PlanetsDumpData[$PlanetID]['last_update'] = $PlanetData['lu']; + $PlanetsDumpData[$PlanetID]['planet_type'] = $PlanetData['pt']; + $PlanetsDumpData[$PlanetID]['temp_max'] = $PlanetData['t']; + $PlanetsDumpData[$PlanetID]['metal_max'] = (floor(BASE_STORAGE_SIZE * pow (1.7, $PlanetsDumpData[$PlanetID][$_Vars_GameElements[22]]))) * MAX_OVERFLOW; + $PlanetsDumpData[$PlanetID]['crystal_max'] = (floor(BASE_STORAGE_SIZE * pow (1.7, $PlanetsDumpData[$PlanetID][$_Vars_GameElements[23]]))) * MAX_OVERFLOW; + $PlanetsDumpData[$PlanetID]['deuterium_max'] = (floor(BASE_STORAGE_SIZE * pow (1.7, $PlanetsDumpData[$PlanetID][$_Vars_GameElements[24]]))) * MAX_OVERFLOW; + } + $UserData = $GetUser; + foreach($_Vars_ElementCategories['tech'] as $TechID) + { + $UserData[$_Vars_GameElements[$TechID]] = 0; + } + $UserTechsDump = !empty($LoadLastDump['Techs']) ? explode(';', $LoadLastDump['Techs']) : array(); + foreach($UserTechsDump as $Exploded) + { + $Exploded = explode(',', $Exploded); + $UserData[$_Vars_GameElements[$Exploded[0]]] = $Exploded[1]; + } + + $ScaningNo = 0; + $ScanLog['LogScanned'] = 0; + $ScanLog['ResUpdates'] = 0; + + $UsedResources = array + ( + 'metal' => 0, + 'crystal' => 0, + 'deuterium' => 0, + ); + + while($Log = mysql_fetch_assoc($GetLogs)) + { + $Log['Date'] += SERVER_MAINOPEN_TSTAMP; + + $ScaningNo += 1; + + $PreventResourceUpdate = false; + $ResourcesChanged = false; + $ResUpdateReturn = false; + $ShipsChanged = false; + $ChangedShipsTypes = array(); + $Needed = array + ( + 'metal' => 0, + 'crystal' => 0, + 'deuterium' => 0, + ); + + // Main Checking Part + $Place = &$Log['Place']; + if($Place == 1) + { + // HandlePlanetQueue_StructuresSetNext [Remove Resources, Move Element in Structures Queue to first position] + $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); + if($ResUpdateReturn !== false) + { + $ScanLog['ResUpdates'] += 1; + } + + $Needed = GetBuildingPrice($UserData, $PlanetsDumpData[$Log['PlanetID']], $Log['ElementID'], true, ($Log['Code'] == 1 ? false : true)); + + $UsedResources['metal'] += $Needed['metal']; + $UsedResources['crystal'] += $Needed['crystal']; + $UsedResources['deuterium'] += $Needed['deuterium']; + $PlanetsDumpData[$Log['PlanetID']]['metal'] -= $Needed['metal']; + $PlanetsDumpData[$Log['PlanetID']]['crystal'] -= $Needed['crystal']; + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $Needed['deuterium']; + + $ResourcesChanged = $Log['PlanetID']; + } + else if($Place == 2) + { + // CancelBuildingFromQueue [Restore Resources] + $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); + if($ResUpdateReturn !== false) + { + $ScanLog['ResUpdates'] += 1; + } + $Needed = GetBuildingPrice($UserData, $PlanetsDumpData[$Log['PlanetID']], $Log['ElementID'], true, ($Log['Code'] == 1 ? false : true)); + + $UsedResources['metal'] -= $Needed['metal']; + $UsedResources['crystal'] -= $Needed['crystal']; + $UsedResources['deuterium'] -= $Needed['deuterium']; + $PlanetsDumpData[$Log['PlanetID']]['metal'] += $Needed['metal']; + $PlanetsDumpData[$Log['PlanetID']]['crystal'] += $Needed['crystal']; + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] += $Needed['deuterium']; + + $ResourcesChanged = $Log['PlanetID']; + } + else if($Place == 3) + { + // HandlePlanetQueue_OnStructureBuildEnd [Building has ended] + $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$Log['ElementID']]] += ($Log['Code'] == 1 ? 1 : -1); + + if($Log['ElementID'] == 22) + { + $PlanetsDumpData[$Log['PlanetID']]['metal_max'] = (floor(BASE_STORAGE_SIZE * pow (1.7, $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[22]]))) * MAX_OVERFLOW; + } + else if($Log['ElementID'] == 23) + { + $PlanetsDumpData[$Log['PlanetID']]['crystal_max'] = (floor(BASE_STORAGE_SIZE * pow (1.7, $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[23]]))) * MAX_OVERFLOW; + } + else if($Log['ElementID'] == 24) + { + $PlanetsDumpData[$Log['PlanetID']]['deuterium_max'] = (floor(BASE_STORAGE_SIZE * pow (1.7, $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[24]]))) * MAX_OVERFLOW; + } + } + else if($Place == 4) + { + // On Code 1 - HandlePlanetQueue_TechnologySetNext [Remove Resources, Move Element in Technology Queue to first position] + // On Code 2 - TechQueue_Remove [Fall Back Resource Removal] + $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); + if($ResUpdateReturn !== false) + { + $ScanLog['ResUpdates'] += 1; + } + + $Needed = GetBuildingPrice($UserData, $PlanetsDumpData[$Log['PlanetID']], $Log['ElementID']); + if($Log['Code'] == 2) + { + foreach($Needed as $Key => $Value) + { + $Needed[$Key] *= -1; + } + } + + $UsedResources['metal'] += $Needed['metal']; + $UsedResources['crystal'] += $Needed['crystal']; + $UsedResources['deuterium'] += $Needed['deuterium']; + $PlanetsDumpData[$Log['PlanetID']]['metal'] -= $Needed['metal']; + $PlanetsDumpData[$Log['PlanetID']]['crystal'] -= $Needed['crystal']; + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $Needed['deuterium']; + + $ResourcesChanged = $Log['PlanetID']; + } + else if($Place == 5) + { + // HandlePlanetQueue_OnTechnologyEnd [Research has ended] + $UserData[$_Vars_GameElements[$Log['ElementID']]] += 1; + + $PreventResourceUpdate = true; + } + else if($Place == 6) + { + // FleetBuildingPage / ShipyardPage (Ships) [Remove Resources] + $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); + if($ResUpdateReturn !== false) + { + $ScanLog['ResUpdates'] += 1; + } + + $Fleets = explode(';', $Log['AdditionalData']); + foreach($Fleets as $Ship) + { + $Ship = explode(',', $Ship); + + $Temp = GetElementRessources($Ship[0], $Ship[1]); + $Needed['metal'] += $Temp['metal']; + $Needed['crystal'] += $Temp['crystal']; + $Needed['deuterium'] += $Temp['deuterium']; + } + + $UsedResources['metal'] += $Needed['metal']; + $UsedResources['crystal'] += $Needed['crystal']; + $UsedResources['deuterium'] += $Needed['deuterium']; + $PlanetsDumpData[$Log['PlanetID']]['metal'] -= $Needed['metal']; + $PlanetsDumpData[$Log['PlanetID']]['crystal'] -= $Needed['crystal']; + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $Needed['deuterium']; + + $ResourcesChanged = $Log['PlanetID']; + } + else if($Place == 7) + { + // DefensesBuildingPage / ShipyardPage (Defense) [Remove Resources] + $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); + if($ResUpdateReturn !== false) + { + $ScanLog['ResUpdates'] += 1; + } + + $Defs = explode(';', $Log['AdditionalData']); + foreach($Defs as $Def) + { + $Def = explode(',', $Def); + + $Temp = GetElementRessources($Def[0], $Def[1]); + $Needed['metal'] += $Temp['metal']; + $Needed['crystal'] += $Temp['crystal']; + $Needed['deuterium'] += $Temp['deuterium']; + } + + $UsedResources['metal'] += $Needed['metal']; + $UsedResources['crystal'] += $Needed['crystal']; + $UsedResources['deuterium'] += $Needed['deuterium']; + $PlanetsDumpData[$Log['PlanetID']]['metal'] -= $Needed['metal']; + $PlanetsDumpData[$Log['PlanetID']]['crystal'] -= $Needed['crystal']; + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $Needed['deuterium']; + + $ResourcesChanged = $Log['PlanetID']; + } + else if($Place == 8) + { + // HandlePlanetQueue / HandlePlanetUpdate / PlanetResourceUpdate (Shipyard Queue Change) [Insert Fleets & Defenses to PlanetRow] + $Builded = explode(';', $Log['AdditionalData']); + + foreach($Builded as $Item) + { + $Item = explode(',', $Item); + + $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$Item[0]]] += $Item[1]; + } + } + else if($Place == 9) + { + // galaxyfleet.php [Remove Deuterium, Remove Ships] + $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); + if($ResUpdateReturn !== false) + { + $ScanLog['ResUpdates'] += 1; + } + + $Fleet = explode(';', $Log['AdditionalData']); + foreach($Fleet as $Ship) + { + $Ship = explode(',', $Ship); + + if($Ship[0] == 'F') + { + $UsedResources['deuterium'] += $Ship[1]; + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $Ship[1]; + + $ResourcesChanged = $Log['PlanetID']; + } + else + { + $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$Ship[0]]] -= $Ship[1]; + $ChangedShipsTypes[] = $Ship[0]; + } + } + + $ShipsChanged = array('Where' => $Log['PlanetID'], 'Types' => $ChangedShipsTypes); + } + else if($Place == 10) + { + // fleet3.php [Remove Resources, Remove Ships] + + $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); + if($ResUpdateReturn !== false) + { + $ScanLog['ResUpdates'] += 1; + } + + $Fleet = explode(';', $Log['AdditionalData']); + $Removed = array + ( + 'metal' => 0, + 'crystal' => 0, + 'deuterium' => 0, + ); + + foreach($Fleet as $Ship) + { + $Ship = explode(',', $Ship); + + if($Ship[0] == 'F' OR $Ship[0] == 'D') + { + $UsedResources['deuterium'] += $Ship[1]; + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $Ship[1]; + $Removed['deuterium'] += $Ship[1]; + + $ResourcesChanged = $Log['PlanetID']; + } + else if($Ship[0] == 'M') + { + $UsedResources['metal'] += $Ship[1]; + $PlanetsDumpData[$Log['PlanetID']]['metal'] -= $Ship[1]; + $Removed['metal'] += $Ship[1]; + + $ResourcesChanged = $Log['PlanetID']; + } + else if($Ship[0] == 'C') + { + $UsedResources['crystal'] += $Ship[1]; + $PlanetsDumpData[$Log['PlanetID']]['crystal'] -= $Ship[1]; + $Removed['crystal'] += $Ship[1]; + + $ResourcesChanged = $Log['PlanetID']; + } + else + { + $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$Ship[0]]] -= $Ship[1]; + $ChangedShipsTypes[] = $Ship[0]; + } + } + + $ShipsChanged = array('Where' => $Log['PlanetID'], 'Types' => $ChangedShipsTypes); + } + else if($Place == 11) + { + // sendmissiles.php + $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); + if($ResUpdateReturn !== false) + { + $ScanLog['ResUpdates'] += 1; + } + + $Missiles = explode(',', $Log['AdditionalData']); + $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[503]] -= $Missiles[1]; + $ChangedShipsTypes[] = 503; + + $ShipsChanged = array('Where' => $Log['PlanetID'], 'Types' => $ChangedShipsTypes); + } + else if($Place == 12 OR $Place == 13 OR $Place == 15) + { + // MissionCaseAttack.php (12) & MissionCaseGroupAttack.php (13) & MissionCaseDestruction.php (15) + if($Log['Code'] == 1) + { + // User is PlanetDefender + $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); + if($ResUpdateReturn !== false) + { + $ScanLog['ResUpdates'] += 1; + } + + $Lost = explode(';', $Log['AdditionalData']); + foreach($Lost as $LostData) + { + $LostData = explode(',', $LostData); + if($LostData[0] == 'M') + { + $PlanetsDumpData[$Log['PlanetID']]['metal'] -= $LostData[1]; + + $ResourcesChanged = $Log['PlanetID']; + } + else if($LostData[0] == 'C') + { + $PlanetsDumpData[$Log['PlanetID']]['crystal'] -= $LostData[1]; + + $ResourcesChanged = $Log['PlanetID']; + } + else if($LostData[0] == 'D') + { + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $LostData[1]; + + $ResourcesChanged = $Log['PlanetID']; + } + else if($LostData[0] == 'L') + { + $PlanetsDumpData[$LostData[1]]['id'] = $LostData[1]; + $PlanetsDumpData[$LostData[1]]['metal'] = 0; + $PlanetsDumpData[$LostData[1]]['crystal'] = 0; + $PlanetsDumpData[$LostData[1]]['deuterium'] = 0; + $PlanetsDumpData[$LostData[1]]['last_update'] = $Log['Date']; + $PlanetsDumpData[$LostData[1]]['planet_type'] = 3; + } + else + { + $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$LostData[0]]] -= $LostData[1]; + $ChangedShipsTypes[] = $LostData[0]; + + $ShipsChanged = true; + } + } + + if($ShipsChanged) + { + $ShipsChanged = array('Where' => $Log['PlanetID'], 'Types' => $ChangedShipsTypes); + } + + if($Place == 15 AND $Log['ElementID'] == 1) + { + $ShipsChanged = false; + $PreventResourceUpdate = true; + unset($PlanetsDumpData[$Log['PlanetID']]); + } + } + else if($Log['Code'] == 2) + { + // User is Attacker (Regular Attacker or ACS Leader) + + $PreventResourceUpdate = true; + } + else if($Log['Code'] == 3) + { + // User is FriendlyDefender + + $PreventResourceUpdate = true; + } + else if($Log['Code'] == 4) + { + // User is Additional Attacker (ACS Member) [only in 13!] + + $PreventResourceUpdate = true; + } + } + else if($Place == 14) + { + // MissionCaseColonisation.php + $ExplodeRes = explode(';', $Log['AdditionalData']); + foreach($ExplodeRes as $ExpRes) + { + $ExpRes = explode(',', $ExpRes); + if($ExpRes[0] == 'M') + { + $PlanetsDumpData[$Log['PlanetID']]['metal'] = $ExpRes[1]; + } + else if($ExpRes[0] == 'C') + { + $PlanetsDumpData[$Log['PlanetID']]['crystal'] = $ExpRes[1]; + } + else if($ExpRes[0] == 'D') + { + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] = $ExpRes[1]; + } + else if($ExpRes[0] == 'T') + { + $PlanetsDumpData[$Log['PlanetID']]['temp_max'] = $ExpRes[1]; + } + } + + foreach($_Vars_ElementCategories['prod'] as $ProdID) + { + $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$ProdID].'_workpercent'] = 10; + } + + $PlanetsDumpData[$Log['PlanetID']]['last_update'] = $Log['Date']; + $PlanetsDumpData[$Log['PlanetID']]['planet_type'] = 1; + $PlanetsDumpData[$Log['PlanetID']]['id'] = $Log['PlanetID']; + + $PreventResourceUpdate = true; + } + else if($Place == 16) + { + // MissionCaseMIP.php + $Lost = explode(';', $Log['AdditionalData']); + foreach($Lost as $LostData) + { + $LostData = explode(',', $LostData); + $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$LostData[0]]] -= $LostData[1]; + $ChangedShipsTypes[] = $LostData[0]; + } + + $ShipsChanged = array('Where' => $Log['PlanetID'], 'Types' => $ChangedShipsTypes); + } + else if($Place == 17) + { + // MissionCaseRecycling.php + + $PreventResourceUpdate = true; + } + else if($Place == 18) + { + // MissionCaseSpy.php + + $PreventResourceUpdate = true; + } + else if($Place == 19) + { + // MissionCaseTransport.php + + if(($Log['Code'] == 1 AND isset($PlanetsDumpData[$Log['PlanetID']])) OR $Log['Code'] == 2) + { + // Planet belongs to that user + $ExplodeRes = explode(';', $Log['AdditionalData']); + foreach($ExplodeRes as $ExpRes) + { + $ExpRes = explode(',', $ExpRes); + if($ExpRes[0] == 'M') + { + $PlanetsDumpData[$Log['PlanetID']]['metal'] += $ExpRes[1]; + } + else if($ExpRes[0] == 'C') + { + $PlanetsDumpData[$Log['PlanetID']]['crystal'] += $ExpRes[1]; + } + else if($ExpRes[0] == 'D') + { + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] += $ExpRes[1]; + } + } + + $PreventResourceUpdate = true; + } + else + { + // Friendly Transport + + $PreventResourceUpdate = true; + } + } + else if($Place == 20) + { + // Place Holder for Expeditions (maybe) + } + else if($Place == 21) + { + // RestoreFleetToPlanet.php + $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); + if($ResUpdateReturn !== false) + { + $ScanLog['ResUpdates'] += 1; + } + + $Restore = explode(';', $Log['AdditionalData']); + foreach($Restore as $Restored) + { + $Restored = explode(',', $Restored); + if($Restored[0] == 'M') + { + $PlanetsDumpData[$Log['PlanetID']]['metal'] += $Restored[1]; + $ResourcesChanged = $Log['PlanetID']; + } + else if($Restored[0] == 'C') + { + $PlanetsDumpData[$Log['PlanetID']]['crystal'] += $Restored[1]; + $ResourcesChanged = $Log['PlanetID']; + } + else if($Restored[0] == 'D') + { + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] += $Restored[1]; + $ResourcesChanged = $Log['PlanetID']; + } + else + { + $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$Restored[0]]] += $Restored[1]; + $ChangedShipsTypes[] = $Restored[0]; + + $ShipsChanged = true; + } + } + + if($ShipsChanged) + { + $ShipsChanged = array('Where' => $Log['PlanetID'], 'Types' => $ChangedShipsTypes); + } + } + else if($Place == 22) + { + // resources.php + $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); + if($ResUpdateReturn !== false) + { + $ScanLog['ResUpdates'] += 1; + } + + $Explode = explode(';', $Log['AdditionalData']); + foreach($Explode as $Exploded) + { + $Exploded = explode(',', $Exploded); + if($Log['Code'] == 1) + { + $PlanetsDumpData[$Log['PlanetID']][$Exploded[0].'_workpercent'] = $Exploded[1]; + } + else if($Log['Code'] == 2) + { + foreach($PlanetsDumpData as $ThisPlanetID => $ThisData) + { + if($ThisData['planet_type'] == 1) + { + $PlanetsDumpData[$ThisPlanetID][$Exploded[0].'_workpercent'] = $Exploded[1]; + } + } + } + } + + $PreventResourceUpdate = true; + } + else if($Place == 23) + { + // merchant.php + $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); + if($ResUpdateReturn !== false) + { + $ScanLog['ResUpdates'] += 1; + } + + $Traded = explode(';', $Log['AdditionalData']); + foreach($Traded as $TradeData) + { + $TradeData = explode(',', $TradeData); + if($Log['ElementID'] == 1) + { + // If Selling Resources + if($TradeData[0] == 'R') + { + if($Log['Code'] == 1) + { + $PlanetsDumpData[$Log['PlanetID']]['metal'] -= $TradeData[1]; + } + else if($Log['Code'] == 2) + { + $PlanetsDumpData[$Log['PlanetID']]['crystal'] -= $TradeData[1]; + } + else if($Log['Code'] == 3) + { + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $TradeData[1]; + } + } + else if($TradeData[0] == 'M') + { + $PlanetsDumpData[$Log['PlanetID']]['metal'] += $TradeData[1]; + } + else if($TradeData[0] == 'C') + { + $PlanetsDumpData[$Log['PlanetID']]['crystal'] += $TradeData[1]; + } + else if($TradeData[0] == 'D') + { + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] += $TradeData[1]; + } + } + else + { + // If Buying Resources + if($TradeData[0] == 'R') + { + if($Log['Code'] == 1) + { + $PlanetsDumpData[$Log['PlanetID']]['metal'] += $TradeData[1]; + } + else if($Log['Code'] == 2) + { + $PlanetsDumpData[$Log['PlanetID']]['crystal'] += $TradeData[1]; + } + else if($Log['Code'] == 3) + { + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] += $TradeData[1]; + } + } + else if($TradeData[0] == 'M') + { + $PlanetsDumpData[$Log['PlanetID']]['metal'] -= $TradeData[1]; + } + else if($TradeData[0] == 'C') + { + $PlanetsDumpData[$Log['PlanetID']]['crystal'] -= $TradeData[1]; + } + else if($TradeData[0] == 'D') + { + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= $TradeData[1]; + } + } + } + + $ResourcesChanged = $Log['PlanetID']; + } + else if($Place == 24) + { + // disassembler.php + $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); + if($ResUpdateReturn !== false) + { + $ScanLog['ResUpdates'] += 1; + } + + $Disassembled = explode(';', $Log['AdditionalData']); + foreach($Disassembled as $Item) + { + $Item = explode(',', $Item); + if($Item[0] == 'P') + { + $Log['Disassebler_Percent'] = $Item[1] / 100; + } + else + { + $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$Item[0]]] -= $Item[1]; + $PlanetsDumpData[$Log['PlanetID']]['metal'] += $_Vars_Prices[$Item[0]]['metal'] * $Item[1] * $Log['Disassebler_Percent']; + $PlanetsDumpData[$Log['PlanetID']]['crystal'] += $_Vars_Prices[$Item[0]]['crystal'] * $Item[1] * $Log['Disassebler_Percent']; + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] += $_Vars_Prices[$Item[0]]['deuterium'] * $Item[1] * $Log['Disassebler_Percent']; + $ChangedShipsTypes[] = $Item[0]; + } + } + + $ShipsChanged = array('Where' => $Log['PlanetID'], 'Types' => $ChangedShipsTypes); + $ResourcesChanged = $Log['PlanetID']; + } + else if($Place == 25) + { + // overview.php [Deleting Planet/Moon] + unset($PlanetsDumpData[$Log['PlanetID']]); + + $PreventResourceUpdate = true; + } + else if($Place == 26) + { + // Settings.php [Go to/Leave VacationMode] + + if($Log['Code'] == 2) + { + foreach($PlanetsDumpData as $PlanetID => $PlanetData) + { + $PlanetsDumpData[$PlanetID]['last_update'] = $Log['Date']; + } + } + + $PreventResourceUpdate = true; + } + else if($Place == 27) + { + // JumpGate.php [Move Fleet] + + $Move = explode(';', $Log['AdditionalData']); + foreach($Move as $MoveShip) + { + $MoveShip = explode(',', $MoveShip); + $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$MoveShip[0]]] -= $MoveShip[1]; + $PlanetsDumpData[$Log['ElementID']][$_Vars_GameElements[$MoveShip[0]]] += $MoveShip[1]; + } + + $PreventResourceUpdate = true; + } + else if($Place == 28) + { + // Destroy_rockets.php [Delete Rockets] + + $Delete = explode(';', $Log['AdditionalData']); + foreach($Delete as $RocketData) + { + $RocketData = explode(',', $RocketData); + $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$RocketData[0]]] -= $RocketData[1]; + } + + $PreventResourceUpdate = true; + } + else if($Place == 29) + { + // Phalanx.php [Remove Deuterium from Scan] + + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] -= PHALANX_DEUTERIUMCOST; + $PreventResourceUpdate = true; + } + else if($Place == 30) + { + // common.php [Task System] + + $Added = explode(';', $Log['AdditionalData']); + foreach($Added as $ElementData) + { + $ElementData = explode(',', $ElementData); + if($ElementData[0] == 'M') + { + $PlanetsDumpData[$Log['PlanetID']]['metal'] += $ElementData[1]; + } + else if($ElementData[0] == 'C') + { + $PlanetsDumpData[$Log['PlanetID']]['crystal'] += $ElementData[1]; + } + else if($ElementData[0] == 'D') + { + $PlanetsDumpData[$Log['PlanetID']]['deuterium'] += $ElementData[1]; + } + else + { + $PlanetsDumpData[$Log['PlanetID']][$_Vars_GameElements[$ElementData[0]]] += $ElementData[1]; + } + } + + $PreventResourceUpdate = true; + } + else + { + $ScanLog['Fatal'][] = array('ID' => '001', 'LogNo' => $ScaningNo, 'LogID' => $Log['ID'], 'Data' => array($Place)); + $PreventResourceUpdate = true; + } + // --- END of Main Checking Part + + + if($ResourcesChanged > 0) + { + if($PlanetsDumpData[$ResourcesChanged]['metal'] < 0 OR $PlanetsDumpData[$ResourcesChanged]['crystal'] < 0 OR $PlanetsDumpData[$ResourcesChanged]['deuterium'] < 0) + { + $ScanLog['Warning'][] = array + ( + 'ID' => '001', + 'LogNo' => $ScaningNo, + 'LogID' => $Log['ID'], + 'Date' => $Log['Date'], + 'PlanetID' => $ResourcesChanged, + 'Place' => $Place, + 'Code' => $Log['Code'], + 'ElementID' => $Log['ElementID'], + 'Data' => array + ( + $PlanetsDumpData[$ResourcesChanged]['metal'], + $PlanetsDumpData[$ResourcesChanged]['crystal'], + $PlanetsDumpData[$ResourcesChanged]['deuterium'] + ) + ); + } + } + + if($ShipsChanged !== false) + { + $CreateWarning = false; + foreach($ShipsChanged['Types'] as $ShipID) + { + if($PlanetsDumpData[$ShipsChanged['Where']][$_Vars_GameElements[$ShipID]] < 0) + { + $CreateWarning[$ShipID] = $PlanetsDumpData[$ShipsChanged['Where']][$_Vars_GameElements[$ShipID]]; + } + } + if(!empty($CreateWarning)) + { + $ScanLog['Warning'][] = array + ( + 'ID' => '003', + 'LogNo' => $ScaningNo, + 'LogID' => $Log['ID'], + 'Date' => $Log['Date'], + 'PlanetID' => $ShipsChanged['Where'], + 'Place' => $Place, + 'Code' => $Log['Code'], + 'ElementID' => $Log['ElementID'], + 'Data' => $CreateWarning + ); + } + } + + if(!$PreventResourceUpdate) + { + if($Log['PlanetID'] > 0) + { + $ResUpdateReturn = ResourceUpdate($PlanetsDumpData[$Log['PlanetID']], $UserData, 'LA', $Log['Date']); + if($ResUpdateReturn !== false) + { + $ScanLog['ResUpdates'] += 1; + } + } + else + { + $ScanLog['Warning'][] = array + ( + 'ID' => '002', + 'LogNo' => $ScaningNo, + 'LogID' => $Log['ID'], + 'Place' => $Place + ); + } + } + + $ScanLog['LogScanned'] += 1; + if(!isset($ScanLog['ScannedPlaces'][$Place])) + { + $ScanLog['ScannedPlaces'][$Place] = 0; + } + $ScanLog['ScannedPlaces'][$Place] += 1; + } + + $SummaryElements = array(); + $SummaryNew['metal'] = 0; + $SummaryNew['crystal'] = 0; + $SummaryNew['deuterium'] = 0; + $SummaryLog['metal'] = 0; + $SummaryLog['crystal'] = 0; + $SummaryLog['deuterium'] = 0; + + while($PlanetNew = mysql_fetch_assoc($PlanetsNewData)) + { + $PlanetNew['metal'] += 0; + $PlanetNew['crystal'] += 0; + $PlanetNew['deuterium'] += 0; + + $SummaryNew['metal'] += $PlanetNew['metal']; + $SummaryNew['crystal'] += $PlanetNew['crystal']; + $SummaryNew['deuterium'] += $PlanetNew['deuterium']; + + foreach($_Vars_ElementCategories as $Key => $Values) + { + if(in_array($Key, array('build', 'tech', 'prod', 'buildOn', 'units'))) + { + continue; + } + foreach($Values as $ItemID) + { + $PlanetNew[$_Vars_GameElements[$ItemID]] += 0; + if(!isset($SummaryNew[$ItemID])) + { + $SummaryNew[$ItemID] = 0; + } + $SummaryNew[$ItemID] += $PlanetNew[$_Vars_GameElements[$ItemID]]; + if(!in_array($ItemID, $SummaryElements)) + { + $SummaryElements[] = $ItemID; + } + } + } + + $CurrentPlanets[$PlanetNew['id']] = $PlanetNew; + } + + foreach($PlanetsDumpData as $PlanetID => $PlanetData) + { + if($PlanetData['last_update'] < $CurrentPlanets[$PlanetID]['last_update']) + { + ResourceUpdate($PlanetsDumpData[$PlanetID], $UserData, 'LA', $CurrentPlanets[$PlanetID]['last_update']); + $PlanetData = $PlanetsDumpData[$PlanetID]; + } + + $PlanetData['metal'] += 0; + $PlanetData['crystal'] += 0; + $PlanetData['deuterium'] += 0; + + $SummaryLog['metal'] += $PlanetData['metal']; + $SummaryLog['crystal'] += $PlanetData['crystal']; + $SummaryLog['deuterium'] += $PlanetData['deuterium']; + + if($PlanetData['metal'] != $CurrentPlanets[$PlanetID]['metal']) + { + if(!isset($AcceptableDifferences)) + { + $AcceptableDifferences = 0; + } + $AcceptableDifferences += 1; + $Difference = $CurrentPlanets[$PlanetID]['metal'] - $PlanetData['metal']; + if(($Difference > 0 AND $Difference > 1) OR ($Difference < 0 AND $Difference < -1)) + { + if($PlanetData['metal'] > $CurrentPlanets[$PlanetID]['metal'] * $PermDiff) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '003', + 'PlanetID' => $PlanetID, + 'ElementID' => $_Lang['Metal'], + 'Data' => array + ( + $PlanetData['metal'], + $CurrentPlanets[$PlanetID]['metal'], + ($PlanetData['metal'] != 0 ? $CurrentPlanets[$PlanetID]['metal'] / $PlanetData['metal'] : 'x') + ) + ); + } + else if($PlanetData['metal'] * $PermDiff < $CurrentPlanets[$PlanetID]['metal']) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '004', + 'PlanetID' => $PlanetID, + 'ElementID' => $_Lang['Metal'], + 'Data' => array + ( + $PlanetData['metal'], + $CurrentPlanets[$PlanetID]['metal'], + ($PlanetData['metal'] != 0 ? $CurrentPlanets[$PlanetID]['metal'] / $PlanetData['metal'] : 'x') + ) + ); + } + else + { + $ScanLog['Notice'][] = array + ( + 'ID' => '001', + 'PlanetID' => $PlanetID, + 'Data' => array + ( + ($PlanetData['metal'] != 0 ? $CurrentPlanets[$PlanetID]['metal'] / $PlanetData['metal'] : 'x'), + $Difference + ) + ); + } + } + } + if($PlanetData['crystal'] != $CurrentPlanets[$PlanetID]['crystal']) + { + if(!isset($AcceptableDifferences)) + { + $AcceptableDifferences = 0; + } + $AcceptableDifferences += 1; + $Difference = $CurrentPlanets[$PlanetID]['crystal'] - $PlanetData['crystal']; + if(($Difference > 0 AND $Difference > 1) OR ($Difference < 0 AND $Difference < -1)) + { + if($PlanetData['crystal'] > $CurrentPlanets[$PlanetID]['crystal'] * $PermDiff) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '003', + 'PlanetID' => $PlanetID, + 'ElementID' => $_Lang['Crystal'], + 'Data' => array + ( + $PlanetData['crystal'], + $CurrentPlanets[$PlanetID]['crystal'], + ($PlanetData['crystal'] != 0 ? $CurrentPlanets[$PlanetID]['crystal'] / $PlanetData['crystal'] : 'x') + ) + ); + } + else if($PlanetData['crystal'] * $PermDiff < $CurrentPlanets[$PlanetID]['crystal']) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '004', + 'PlanetID' => $PlanetID, + 'ElementID' => $_Lang['Crystal'], + 'Data' => array + ( + $PlanetData['crystal'], + $CurrentPlanets[$PlanetID]['crystal'], + ($PlanetData['crystal'] != 0 ? $CurrentPlanets[$PlanetID]['crystal'] / $PlanetData['crystal'] : 'x') + ) + ); + } + else + { + $ScanLog['Notice'][] = array + ( + 'ID' => '002', + 'PlanetID' => $PlanetID, + 'Data' => array + ( + ($PlanetData['crystal'] != 0 ? $CurrentPlanets[$PlanetID]['crystal'] / $PlanetData['crystal'] : 'x'), + $Difference + ) + ); + } + } + } + if($PlanetData['deuterium'] != $CurrentPlanets[$PlanetID]['deuterium']) + { + if(!isset($AcceptableDifferences)) + { + $AcceptableDifferences = 0; + } + $AcceptableDifferences += 1; + $Difference = $CurrentPlanets[$PlanetID]['deuterium'] - $PlanetData['deuterium']; + if(($Difference > 0 AND $Difference > 1) OR ($Difference < 0 AND $Difference < -1)) + { + if($PlanetData['deuterium'] > $CurrentPlanets[$PlanetID]['deuterium'] * $PermDiff) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '003', + 'PlanetID' => $PlanetID, + 'ElementID' => $_Lang['Deuterium'], + 'Data' => array + ( + $PlanetData['deuterium'], + $CurrentPlanets[$PlanetID]['deuterium'], + ($PlanetData['deuterium'] != 0 ? $CurrentPlanets[$PlanetID]['deuterium'] / $PlanetData['deuterium'] : 'x') + ) + ); + } + else if($PlanetData['deuterium'] * $PermDiff < $CurrentPlanets[$PlanetID]['deuterium']) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '004', + 'PlanetID' => $PlanetID, + 'ElementID' => $_Lang['Deuterium'], + 'Data' => array + ( + $PlanetData['deuterium'], + $CurrentPlanets[$PlanetID]['deuterium'], + ($PlanetData['deuterium'] != 0 ? $CurrentPlanets[$PlanetID]['deuterium'] / $PlanetData['deuterium'] : 'x') + ) + ); + } + else + { + $ScanLog['Notice'][] = array + ( + 'ID' => '003', + 'PlanetID' => $PlanetID, + 'Data' => array + ( + ($PlanetData['deuterium'] != 0 ? $CurrentPlanets[$PlanetID]['deuterium'] / $PlanetData['deuterium'] : 'x'), + $Difference + ) + ); + } + } + } + + foreach($_Vars_ElementCategories as $Key => $Values) + { + if(in_array($Key, array('tech', 'prod', 'buildOn', 'units'))) + { + continue; + } + foreach($Values as $ItemID) + { + if($Key != 'build') + { + if(!isset($SummaryLog[$ItemID])) + { + $SummaryLog[$ItemID] = 0; + } + $SummaryLog[$ItemID] += $PlanetData[$_Vars_GameElements[$ItemID]]; + if(!in_array($ItemID, $SummaryElements)) + { + $SummaryElements[] = $ItemID; + } + } + if(empty($PlanetData[$_Vars_GameElements[$ItemID]])) + { + $PlanetData[$_Vars_GameElements[$ItemID]] = 0; + } + if(empty($CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]])) + { + $CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]] = 0; + } + + if($PlanetData[$_Vars_GameElements[$ItemID]] > $CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]]) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '001', + 'PlanetID' => $PlanetID, + 'ElementID' => $ItemID, + 'Data' => array + ( + $PlanetData[$_Vars_GameElements[$ItemID]], + $CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]], + ($PlanetData[$_Vars_GameElements[$ItemID]] != 0 ? $CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]] / $PlanetData[$_Vars_GameElements[$ItemID]] : 'x') + ) + ); + } + else if($PlanetData[$_Vars_GameElements[$ItemID]] < $CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]]) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '002', + 'PlanetID' => $PlanetID, + 'ElementID' => $ItemID, + 'Data' => array + ( + $PlanetData[$_Vars_GameElements[$ItemID]], + $CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]], + ($PlanetData[$_Vars_GameElements[$ItemID]] != 0 ? $CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]] / $PlanetData[$_Vars_GameElements[$ItemID]] : 'x') + ) + ); + } + } + } + } + + if($SummaryLog['metal'] != $SummaryNew['metal']) + { + $Difference = $SummaryLog['metal'] - $SummaryNew['metal']; + if(($Difference > 0 AND $Difference > (1 * $AcceptableDifferences)) OR ($Difference < 0 AND $Difference < (-1 * $AcceptableDifferences))) + { + if($SummaryLog['metal'] > $SummaryNew['metal'] * $PermDiff) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '005', + 'ElementID' => $_Lang['Metal'], + 'Data' => array + ( + $SummaryLog['metal'], + $SummaryNew['metal'], + ($SummaryLog['metal'] != 0 ? $SummaryNew['metal'] / $SummaryLog['metal'] : 'x') + ) + ); + } + else if($SummaryLog['metal'] * $PermDiff < $SummaryNew['metal']) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '006', + 'ElementID' => $_Lang['Metal'], + 'Data' => array + ( + $SummaryLog['metal'], + $SummaryNew['metal'], + ($SummaryLog['metal'] != 0 ? $SummaryNew['metal'] / $SummaryLog['metal'] : 'x') + ) + ); + } + else + { + $ScanLog['Notice'][] = array + ( + 'ID' => '004' + ); + } + } + } + if($SummaryLog['crystal'] != $SummaryNew['crystal']) + { + $Difference = $SummaryLog['crystal'] - $SummaryNew['crystal']; + if(($Difference > 0 AND $Difference > (1 * $AcceptableDifferences)) OR ($Difference < 0 AND $Difference < (-1 * $AcceptableDifferences))) + { + if($SummaryLog['crystal'] > $SummaryNew['crystal'] * $PermDiff) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '005', + 'ElementID' => $_Lang['Crystal'], + 'Data' => array + ( + $SummaryLog['crystal'], + $SummaryNew['crystal'], + ($SummaryLog['crystal'] != 0 ? $SummaryNew['crystal'] / $SummaryLog['crystal'] : 'x') + ) + ); + } + else if($SummaryLog['crystal'] * $PermDiff < $SummaryNew['crystal']) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '006', + 'ElementID' => $_Lang['Crystal'], + 'Data' => array + ( + $SummaryLog['crystal'], + $SummaryNew['crystal'], + ($SummaryLog['crystal'] != 0 ? $SummaryNew['crystal'] / $SummaryLog['crystal'] : 'x') + ) + ); + } + else + { + $ScanLog['Notice'][] = array + ( + 'ID' => '005' + ); + } + } + } + if($SummaryLog['deuterium'] != $SummaryNew['deuterium']) + { + $Difference = $SummaryLog['deuterium'] - $SummaryNew['deuterium']; + if(($Difference > 0 AND $Difference > (1 * $AcceptableDifferences)) OR ($Difference < 0 AND $Difference < (-1 * $AcceptableDifferences))) + { + if($SummaryLog['deuterium'] > $SummaryNew['deuterium'] * $PermDiff) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '005', + 'ElementID' => $_Lang['Deuterium'], + 'Data' => array + ( + $SummaryLog['deuterium'], + $SummaryNew['deuterium'], + ($SummaryLog['deuterium'] != 0 ? $SummaryNew['deuterium'] / $SummaryLog['deuterium'] : 'x') + ) + ); + } + else if($SummaryLog['deuterium'] * $PermDiff < $SummaryNew['deuterium']) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '006', + 'ElementID' => $_Lang['Deuterium'], + 'Data' => array + ( + $SummaryLog['deuterium'], + $SummaryNew['deuterium'], + ($SummaryLog['deuterium'] != 0 ? $SummaryNew['deuterium'] / $SummaryLog['deuterium'] : 'x') + ) + ); + } + else + { + $ScanLog['Notice'][] = array + ( + 'ID' => '006' + ); + } + } + } + + if(!empty($SummaryElements)) + { + if(empty($SummaryLog[$ItemID])) + { + $SummaryLog[$ItemID] = 0; + } + if(empty($SummaryNew[$ItemID])) + { + $SummaryNew[$ItemID] = 0; + } + + foreach($SummaryElements as $ItemID) + { + if($SummaryLog[$ItemID] > $SummaryNew[$ItemID]) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '007', + 'ElementID' => $ItemID, + 'Data' => array + ( + $SummaryLog[$ItemID], + $SummaryNew[$ItemID], + ($SummaryLog[$ItemID] != 0 ? $SummaryNew[$ItemID] / $SummaryLog[$ItemID] : 'x') + ) + ); + } + else if($PlanetData[$_Vars_GameElements[$ItemID]] < $CurrentPlanets[$PlanetID][$_Vars_GameElements[$ItemID]]) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '008', + 'ElementID' => $ItemID, + 'Data' => array + ( + $SummaryLog[$ItemID], + $SummaryNew[$ItemID], + ($SummaryLog[$ItemID] != 0 ? $SummaryNew[$ItemID] / $SummaryLog[$ItemID] : 'x') + ) + ); + } + } + } + + foreach($_Vars_ElementCategories['tech'] as $TechID) + { + if(empty($UserData[$_Vars_GameElements[$TechID]])) + { + $UserData[$_Vars_GameElements[$TechID]] = 0; + } + if(empty($UserNewData[$_Vars_GameElements[$TechID]])) + { + $UserNewData[$_Vars_GameElements[$TechID]] = 0; + } + + if($UserData[$_Vars_GameElements[$TechID]] > $UserNewData[$_Vars_GameElements[$TechID]]) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '009', + 'ElementID' => $TechID, + 'Data' => array + ( + $UserData[$_Vars_GameElements[$TechID]], + $UserNewData[$_Vars_GameElements[$TechID]] + ) + ); + } + else if($UserData[$_Vars_GameElements[$TechID]] < $UserNewData[$_Vars_GameElements[$TechID]]) + { + $ScanLog['Summary'][] = array + ( + 'ID' => '010', + 'ElementID' => $TechID, + 'Data' => array + ( + $UserData[$_Vars_GameElements[$TechID]], + $UserNewData[$_Vars_GameElements[$TechID]] + ) + ); + } + } + + $ScanEndTime = microtime(true); + } + } + + $_Lang['PHP_Username'] = $GetUser['username']; + $_Lang['PHP_UID'] = $GetUser['id']; + + if($BreakScan OR empty($ScanLog)) + { + $_Lang['PHP_HideScanResult'] = $Hide; + + if(!empty($_Lang['Error_Found'])) + { + $_Lang['PHP_BreakErrorColor'] = 'red'; + $_Lang['PHP_BreakErrorText'] = $_Lang['Error_Found']; + } + else if(!empty($_Lang['Notice_Found'])) + { + $_Lang['PHP_BreakErrorColor'] = 'orange'; + $_Lang['PHP_BreakErrorText'] = $_Lang['Notice_Found']; + } + else + { + if(empty($ScanLog)) + { + $_Lang['PHP_BreakErrorColor'] = 'red'; + $_Lang['PHP_BreakErrorText'] = $_Lang['Critical_EmptyScanLog']; + } + else + { + $_Lang['PHP_BreakErrorColor'] = 'red'; + $_Lang['PHP_BreakErrorText'] = $_Lang['Critical_EmptyBreakErrorVar']; + } + } + } + else + { + $_Lang['PHP_HideBreakError'] = $Hide; + + $_Lang['PHP_ScanedLogs'] = $ScanLog['LogScanned']; + $_Lang['PHP_ScanTime'] = sprintf('%0.10f', ($ScanEndTime - $ScanStartTime)); + $_Lang['PHP_DumpDate'] = prettyDate('d m Y - H:i:s', $LoadLastDump['Date'], 1).'
('.$LoadLastDump['Date'].')'; + $_Lang['PHP_DateDifference'] = pretty_time(time() - $LoadLastDump['Date']); + + $ResultRowTPL = gettemplate('admin/userdevscanner_result_row'); + + // Found "Fatal"/"Warning"/"Notice" Exceptions & Handle Summary + if(empty($ScanLog['Fatal'])) + { + $ScanLog['Fatal'] = array(); + } + if(empty($ScanLog['Warning'])) + { + $ScanLog['Warning'] = array(); + } + if(empty($ScanLog['Notice'])) + { + $ScanLog['Notice'] = array(); + } + if(empty($ScanLog['Summary'])) + { + $ScanLog['Summary'] = array(); + } + + foreach($ScanLog as $ScanKey => $ScanData) + { + if($ScanKey != 'Fatal' AND $ScanKey != 'Warning' AND $ScanKey != 'Notice' AND $ScanKey != 'Summary') + { + continue; + } + if(!empty($ScanData)) + { + if($ScanKey == 'Fatal') + { + $ParseRowPattern = array('ModuleNumber' => '01', 'TextColor' => 'red', 'Table2_LogID' => $_Lang['Table2_LogID']); + } + else if($ScanKey == 'Warning') + { + $ParseRowPattern = array('ModuleNumber' => '02', 'TextColor' => 'orange', 'Table2_LogID' => $_Lang['Table2_LogID']); + } + else if($ScanKey == 'Notice') + { + $ParseRowPattern = array('ModuleNumber' => '03', 'TextColor' => 'yellow', 'Table2_LogID' => $_Lang['Table2_LogID']); + } + else if($ScanKey == 'Summary') + { + $ParseRowPattern = array('ModuleNumber' => '04', 'TextColor' => 'orange', 'Table2_LogID' => $_Lang['Table2_LogID']); + } + $LastLogIDLen = end($ScanData); + $LastLogIDLen = isset($LastLogIDLen['LogID']) ? strlen($LastLogIDLen['LogID']) : 0; + reset($ScanData); + $_Lang['Table2_Final'.$ScanKey.'Count'] = count($ScanData); + foreach($ScanData as $Index => $Data) + { + $ParseRow = $ParseRowPattern; + $Point = &$_Lang['Found'.$ScanKey.'s'][$Data['ID']]; + $ParseRow['Index'] = str_pad($Index + 1, 4, '0', STR_PAD_LEFT); + $ParseRow['RowTitle'] = $Point['Txt']; + if($ScanKey == 'Summary' OR $Data['LogID'] <= 0) + { + $ParseRow['HideLogID'] = $Hide; + } + else + { + $ParseRow['RowLogID'] = str_pad($Data['LogID'], $LastLogIDLen, '0', STR_PAD_LEFT); + if($Data['LogNo'] > 0) + { + $ParseRow['RowLogID'] .= '
LogNo: '.$Data['LogNo']; + } + } + if($Point['GenerateDataList'] === true) + { + if(!empty($Data['Data'])) + { + foreach($Data['Data'] as $DataID => $DataVal) + { + $Data['GeneratedDataList'][] = eval('return "'.$Point['DataListEvalCode'].'";'); + } + $Data['GeneratedDataList'] = implode($Point['DataListGlue'], $Data['GeneratedDataList']); + } + } + if(!empty($Point['Eval'])) + { + $ParseRow['RowData'] = eval('return "'.$Point['Eval'].'";'); + } + else + { + $ParseRow['RowData'] = '-'; + } + + if($ScanKey == 'Notice') + { + $ParseRow['IsCollapsed'] = 'collapsed'; + } + + if(!isset($_Lang['PHP_AllFound'.$ScanKey.'s'])) + { + $_Lang['PHP_AllFound'.$ScanKey.'s'] = ''; + } + $_Lang['PHP_AllFound'.$ScanKey.'s'] .= parsetemplate($ResultRowTPL, $ParseRow); + } + } + else + { + $_Lang['PHP_HideFound'.$ScanKey.'s'] = $Hide; + $_Lang['PHP_HideFound'.$ScanKey.'s2'] = 'hide'; + } + } + + if(empty($ScanLog['Summary'])) + { + $_Lang['PHP_OverallResultColor'] = 'lime'; + $_Lang['PHP_OverallResultText'] = $_Lang['FoundSummarys']['000']['Txt1']; + } + else + { + $_Lang['PHP_OverallResultColor'] = 'red'; + $_Lang['PHP_OverallResultText'] = $_Lang['FoundSummarys']['000']['Txt2']; + } + } + + $Page = parsetemplate(gettemplate('admin/userdevscanner_result'), $_Lang); +} +else +{ + if(empty($_Lang['Error_Found'])) + { + $_Lang['PHP_ShowError'] = $Hide; + } + + $Page = parsetemplate(gettemplate('admin/userdevscanner_form'), $_Lang); +} + +display($Page, $_Lang['UserDevScanner_Title'], false, true); + +?> diff --git a/admin/action_logs/index.php b/admin/action_logs/index.php index 58f7bb163..8ea442135 100644 --- a/admin/action_logs/index.php +++ b/admin/action_logs/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/admin/addMoon.php b/admin/addMoon.php index 3b3c28b29..285957fa9 100644 --- a/admin/addMoon.php +++ b/admin/addMoon.php @@ -1,86 +1,86 @@ - 0) - { - if(empty($Set_MoonName) || preg_match(REGEXP_PLANETNAME_ABSOLUTE, $Set_MoonName)) - { - $Query_GetPlanetData = "SELECT `galaxy`, `system`, `planet`, `id_owner` FROM {{table}} WHERE `id` = {$Set_PlanetID} LIMIT 1; -- admin/addMoon.php - Query #1"; - $QResult_GetPlanetData = doquery($Query_GetPlanetData, 'planets', true); - $PlData = &$QResult_GetPlanetData; - - if($PlData['id_owner'] > 0) - { - include($_EnginePath.'includes/functions/CreateOneMoonRecord.php'); - if(CreateOneMoonRecord($PlData['galaxy'], $PlData['system'], $PlData['planet'], $PlData['id_owner'], $Set_MoonName, 20, $Set_Diameter) != false) - { - $_Lang['PHP_InfoBox_Text'] = $_Lang['AddMoon_Success']; - $_Lang['PHP_InfoBox_Color'] = 'lime'; - } - else - { - $_Lang['PHP_InfoBox_Text'] = $_Lang['AddMoon_Fail_MoonExists']; - $_Lang['PHP_InfoBox_Color'] = 'red'; - } - } - else - { - $_Lang['PHP_InfoBox_Text'] = $_Lang['AddMoon_Fail_NoPlanet']; - $_Lang['PHP_InfoBox_Color'] = 'red'; - } - } - else - { - $_Lang['PHP_InfoBox_Text'] = $_Lang['AddMoon_Fail_NameBadSigns']; - $_Lang['PHP_InfoBox_Color'] = 'red'; - } - } - else - { - $_Lang['PHP_InfoBox_Text'] = $_Lang['AddMoon_Fail_BadID']; - $_Lang['PHP_InfoBox_Color'] = 'red'; - } - } - - if(empty($_Lang['PHP_InfoBox_Text'])) - { - $_Lang['PHP_InfoBox_Hide'] = 'display: none;'; - } - - $Page = parsetemplate($PageTpl, $_Lang); - - display($Page, $_Lang['AddMoon_Title'], false, true); - -?> \ No newline at end of file + 0) + { + if(empty($Set_MoonName) || preg_match(REGEXP_PLANETNAME_ABSOLUTE, $Set_MoonName)) + { + $Query_GetPlanetData = "SELECT `galaxy`, `system`, `planet`, `id_owner` FROM {{table}} WHERE `id` = {$Set_PlanetID} LIMIT 1; -- admin/addMoon.php - Query #1"; + $QResult_GetPlanetData = doquery($Query_GetPlanetData, 'planets', true); + $PlData = &$QResult_GetPlanetData; + + if($PlData['id_owner'] > 0) + { + include($_EnginePath.'includes/functions/CreateOneMoonRecord.php'); + if(CreateOneMoonRecord($PlData['galaxy'], $PlData['system'], $PlData['planet'], $PlData['id_owner'], $Set_MoonName, 20, $Set_Diameter) != false) + { + $_Lang['PHP_InfoBox_Text'] = $_Lang['AddMoon_Success']; + $_Lang['PHP_InfoBox_Color'] = 'lime'; + } + else + { + $_Lang['PHP_InfoBox_Text'] = $_Lang['AddMoon_Fail_MoonExists']; + $_Lang['PHP_InfoBox_Color'] = 'red'; + } + } + else + { + $_Lang['PHP_InfoBox_Text'] = $_Lang['AddMoon_Fail_NoPlanet']; + $_Lang['PHP_InfoBox_Color'] = 'red'; + } + } + else + { + $_Lang['PHP_InfoBox_Text'] = $_Lang['AddMoon_Fail_NameBadSigns']; + $_Lang['PHP_InfoBox_Color'] = 'red'; + } + } + else + { + $_Lang['PHP_InfoBox_Text'] = $_Lang['AddMoon_Fail_BadID']; + $_Lang['PHP_InfoBox_Color'] = 'red'; + } +} + +if(empty($_Lang['PHP_InfoBox_Text'])) +{ + $_Lang['PHP_InfoBox_Hide'] = 'display: none;'; +} + +$Page = parsetemplate($PageTpl, $_Lang); + +display($Page, $_Lang['AddMoon_Title'], false, true); + +?> diff --git a/admin/alerts_filters.php b/admin/alerts_filters.php index fa0c2f231..05c8487be 100644 --- a/admin/alerts_filters.php +++ b/admin/alerts_filters.php @@ -1,584 +1,584 @@ - array - ( - 'regexp' => 'userPresent\((.*?)\)', - 'replace' => 'in_array(\\1, $FiltersData[\'users\'])', - 'arg_regexp' => '[0-9]+', - 'badsyn' => '1', - 'arg_badsyn' => '1', - 'search' => 'USER', - 'info' => '1', - ), - 'ipPresent' => array - ( - 'regexp' => 'ipPresent\((.*?)\)', - 'replace' => 'in_array(\\1, $FiltersData[\'ips\'])', - 'arg_regexp' => '[0-9]+', - 'badsyn' => '1', - 'arg_badsyn' => '1', - 'search' => 'IP', - 'info' => '2', - ), - 'userIsSender' => array - ( - 'regexp' => 'userIsSender\((.*?)\)', - 'replace' => '\\1 == $FiltersData[\'sender\']', - 'arg_regexp' => '[0-9]+', - 'badsyn' => '1', - 'arg_badsyn' => '1', - 'search' => 'USER', - 'info' => '3', - ), - 'userIsTarget' => array - ( - 'regexp' => 'userIsTarget\((.*?)\)', - 'replace' => '\\1 == $FiltersData[\'target\']', - 'arg_regexp' => '[0-9]+', - 'badsyn' => '1', - 'arg_badsyn' => '1', - 'search' => 'USER', - 'info' => '4', - ), - 'logIPCount' => array - ( - 'regexp' => 'logIPCount\((.*?)(\, |\,){1}(.*?)(\, |\,){1}([0-9]{1,})\)', - 'replace' => '$FiltersData[\'logcount\'][\\3][\\1] <= \\5', - 'arg_regexp' => array(0 => '[0-9]+', 2 => '[0-9]+'), - 'badsyn' => '1', - 'arg_badsyn' => '1', - 'search' => array(0 => 'USER', 2 => 'IP'), - 'info' => '5', - ), - 'inPlace' => array - ( - 'regexp' => 'inPlace\((.*?)\)', - 'replace' => '\\1 == $FiltersData[\'place\']', - 'arg_regexp' => '[0-9]+', - 'badsyn' => '1', - 'arg_badsyn' => '1', - 'search' => 'PLACE', - 'info' => '6', - ), - 'AlertSenderIs' => array - ( - 'regexp' => 'AlertSenderIs\((.*?)\)', - 'replace' => '\\1 == $FiltersData[\'alertsender\']', - 'arg_regexp' => '[0-9]+', - 'badsyn' => '1', - 'arg_badsyn' => '1', - 'search' => 'ALERTSENDER', - 'info' => '7', - ), - ); - - function prettySyntax($Code) - { - global $FunctionsSyntaxes; - - foreach($FunctionsSyntaxes as $Function => $Data) - { - if(strstr($Code, $Function) !== FALSE) - { - $Code = preg_replace('#('.$Data['regexp'].')#si', '\\1', $Code); - } - } - - return $Code; - } - - // Deleting is here - if(isset($_GET['cmd']) && $_GET['cmd'] == 'del') - { - $_GET['cmd'] = ''; - $DeleteID = isset($_GET['id']) ? intval($_GET['id']) : 0; - - if($DeleteID > 0) - { - doquery("DELETE FROM {{table}} WHERE `ID` = {$DeleteID} LIMIT 1;", 'system_alerts_filters'); - if(mysql_affected_rows() == 1) - { - $MSG = $_Lang['Info_FilterDeleted']; - $MSGColor = 'lime'; - } - else - { - $MSG = $_Lang['Error_NoSuchFilter']; - $MSGColor = 'red'; - } - } - else - { - $MSG = $_Lang['Error_BadFilterID']; - $MSGColor = 'red'; - } - } - else if(isset($_GET['cmd']) && $_GET['cmd'] == 'delpost') - { - $_GET['cmd'] = ''; - if(!empty($_POST['f'])) - { - foreach($_POST['f'] as $FilterID => $Status) - { - if($Status == 'on') - { - $FilterID = intval($FilterID); - if($FilterID > 0) - { - $Filters2Delete[] = $FilterID; - } - } - } - } - $DeleteCount = count($Filters2Delete); - if($DeleteCount > 0) - { - doquery("DELETE FROM {{table}} WHERE `ID` IN (".implode(', ', $Filters2Delete).");", 'system_alerts_filters'); - $AffectedRows = mysql_affected_rows(); - if($AffectedRows > 0) - { - if($AffectedRows == $DeleteCount) - { - $MSG = $_Lang['Info_AllSelectsDeleted']; - $MSGColor = 'lime'; - } - else - { - $MSG = sprintf($_Lang['Warn_NotAllSelectsDeleted'], $AffectedRows, $DeleteCount); - $MSGColor = 'orange'; - } - } - else - { - $MSG = $_Lang['Error_NothingDeleted']; - $MSGColor = 'red'; - } - } - else - { - $MSG = $_Lang['Error_Nothing2Delete']; - $MSGColor = 'red'; - } - } - - if(isset($_GET['cmd']) && ($_GET['cmd'] == 'add' OR $_GET['cmd'] == 'edit')) - { - $AllowProceed = false; - $WhatAreWeDoint = $_GET['cmd']; - if($_GET['cmd'] == 'edit') - { - $EditID = isset($_GET['id']) ? intval($_GET['id']) : 0; - if($EditID <= 0) - { - $_GET['cmd'] = ''; - $MSG = $_Lang['Error_NoIDGiven']; - $MSGColor = 'red'; - } - else - { - $SelectFilter = doquery("SELECT * FROM {{table}} WHERE `ID` = {$EditID} LIMIT 1;", 'system_alerts_filters', true); - if($SelectFilter['ID'] != $EditID) - { - $_GET['cmd'] = ''; - $MSG = $_Lang['Error_NoSuchFilter']; - $MSGColor = 'red'; - } - else - { - $AllowProceed = true; - } - } - } - else - { - $AllowProceed = true; - } - - if($AllowProceed === true) - { - $PageTPL = gettemplate('admin/alertsfilters_add'); - $Parse = $_Lang; - $Parse['Rows'] = ''; - if($WhatAreWeDoint == 'edit') - { - $Parse['InsertOnEdit'] = ''; - $Parse['Filters_Add'] = $_Lang['Filters_Edit']; - $Parse['AddFilter'] = $_Lang['EditFilter']; - $Parse['AreYouSure_Add'] = $_Lang['AreYouSure_Edit']; - $Parse['ThisFormAction'] = '?cmd=edit&id='.$EditID; - } - else - { - $Parse['ThisFormAction'] = '?cmd=add'; - } - - if($WhatAreWeDoint == 'add' OR ($WhatAreWeDoint == 'edit' && isset($_POST['editid']) && $_POST['editid'] == $EditID)) - { - $Code = isset($_POST['code']) ? trim(stripslashes($_POST['code'])) : null; - $Action = isset($_POST['action']) ? intval($_POST['action']) : 0; - $Enabled = (isset($_POST['turnoff']) && $_POST['turnoff'] == 'on' ? '0' : '1'); - $AllowSave = true; - } - else - { - $Code = stripslashes($SelectFilter['HighCode']); - $Action = $SelectFilter['ActionType']; - $Enabled = $SelectFilter['Enabled']; - } - - $Parse['CodePost'] = $Code; - $Parse['ActionType_Select'.$Action] = 'selected'; - if($Enabled == '0') - { - $Parse['TurnOffChecked'] = 'checked'; - } - - if(isset($_POST['doWhat']) && $_POST['doWhat'] == 'check') - { - $BracketOpenCount = substr_count($Code, '('); - $BracketCloseCount = substr_count($Code, ')'); - - if($BracketOpenCount > $BracketCloseCount) - { - $Warnings[] = $_Lang['Warn_BadSyntax_BracketOpen']; - } - else if($BracketOpenCount < $BracketCloseCount) - { - $Warnings[] = $_Lang['Warn_BadSyntax_BracketClose']; - } - - foreach($FunctionsSyntaxes as $Function => $Data) - { - if(strstr($Code, $Function) !== FALSE) - { - $Matches = false; - $ThisFunctionCount = substr_count($Code, $Function); - preg_match_all('#'.$Data['regexp'].'#si', $Code, $Matches); - $ErrorsCount = $ThisFunctionCount - count($Matches[0]); - if($ErrorsCount > 0) - { - $Warnings[] = sprintf($_Lang['Warn_BadSyntax_'.$Data['badsyn']], $Function, $ErrorsCount); - } - $ErrorsCount = 0; - - if(count($Matches) == 2) - { - $ArgumentRegExp = '/^'.$Data['arg_regexp'].'$/D'; - foreach($Matches[1] as $Argument) - { - if(!preg_match($ArgumentRegExp, $Argument)) - { - $ErrorsCount += 1; - } - } - } - else - { - foreach($Matches as $MatchID => $MatchArg) - { - if($MatchID == 0) - { - continue; - } - $MatchID -= 1; - if(!empty($Data['arg_regexp'][$MatchID])) - { - if(!preg_match('/^'.$Data['arg_regexp'][$MatchID].'$/D', $MatchArg[0])) - { - $ErrorsCount += 1; - } - } - } - } - if($ErrorsCount > 0) - { - $Warnings[] = sprintf($_Lang['Warn_ArgBadSyntax_'.$Data['arg_badsyn']], $Function, $ErrorsCount); - } - } - } - - if(!empty($Warnings)) - { - $Parse['System_MSG'] = ''.implode('
', $Warnings).''; - } - else - { - $Parse['System_MSG'] = ''.$_Lang['Info_CodeLooksFine'].''; - } - } - else if(isset($_POST['doWhat']) && $_POST['doWhat'] == 'save') - { - if($WhatAreWeDoint == 'edit' AND $AllowSave === false) - { - $Code = ''; - $Errors[] = $_Lang['Error_IDIsMalformed']; - } - - if(empty($Code)) - { - $Errors[] = $_Lang['Error_CodeEmpty']; - } - if($Action <= 0) - { - $Errors[] = $_Lang['Error_BadAction']; - } - - if(!empty($Code)) - { - foreach($FunctionsSyntaxes as $Function => $Data) - { - if(strstr($Code, $Function) !== FALSE) - { - $Matches = false; - $ThisFunctionCount = substr_count($Code, $Function); - preg_match_all('#'.$Data['regexp'].'#si', $Code, $Matches); - $ErrorsCount = $ThisFunctionCount - count($Matches[0]); - if($ErrorsCount > 0) - { - $Errors[] = sprintf($_Lang['Warn_BadSyntax_'.$Data['badsyn']], $Function, $ErrorsCount); - } - $ErrorsCount = 0; - if(count($Matches) == 2) - { - $ArgumentRegExp = '/^'.$Data['arg_regexp'].'$/D'; - foreach($Matches[1] as $Argument) - { - if(!preg_match($ArgumentRegExp, $Argument)) - { - $ErrorsCount += 1; - } - else - { - if(empty($SearchData[$Data['search']]) OR !in_array($Argument, $SearchData[$Data['search']])) - { - $SearchData[$Data['search']][] = $Argument; - } - } - } - } - else - { - foreach($Matches as $MatchID => $MatchArg) - { - if($MatchID == 0) - { - continue; - } - $MatchID -= 1; - if(!empty($Data['arg_regexp'][$MatchID])) - { - if(!preg_match('/^'.$Data['arg_regexp'][$MatchID].'$/D', $MatchArg[0])) - { - $ErrorsCount += 1; - } - else - { - if(empty($SearchData[$Data['search'][$MatchID]]) OR !in_array($MatchArg[0], $SearchData[$Data['search'][$MatchID]])) - { - $SearchData[$Data['search'][$MatchID]][] = $MatchArg[0]; - } - } - } - } - } - if($ErrorsCount > 0) - { - $Errors[] = sprintf($_Lang['Warn_ArgBadSyntax_'.$Data['arg_badsyn']], $Function, $ErrorsCount); - } - } - } - } - - if(!empty($Errors)) - { - $Parse['System_MSG'] = ''.implode('
', $Errors).''; - } - else - { - foreach($FunctionsSyntaxes as $Data) - { - if(empty($Data['replace_callback'])) - { - $Patterns[] = '#'.$Data['regexp'].'#si'; - $Replaces[] = $Data['replace']; - } - else - { - $Patterns_Callback[] = '#'.$Data['regexp'].'#si'; - $Replaces_Callback[] = $Data['replace_callback']; - } - } - $EvalCode = $Code; - - if(!empty($Patterns)) - { - foreach($Patterns as $PatternIndex => $PatternData) - { - $EvalCode = preg_replace($PatternData, $Replaces[$PatternIndex], $EvalCode); - } - } - if(!empty($Patterns_Callback)) - { - foreach($Patterns_Callback as $PatternIndex => $PatternData) - { - $EvalCode = preg_replace_callback($PatternData, $Replaces_Callback[$PatternIndex], $EvalCode); - } - } - $EvalCode = addslashes($EvalCode); - $Code = addslashes($Code); - - $SearchDataArray = ''; - if(!empty($SearchData)) - { - foreach($SearchData as $Type => $Values) - { - foreach($Values as $Value) - { - $SearchDataArray .= "{{$Type}_{$Value}}"; - } - } - } - - if($WhatAreWeDoint == 'add') - { - doquery("INSERT INTO {{table}} SET `Date` = UNIX_TIMESTAMP(), `Enabled` = {$Enabled}, `ActionType` = {$Action}, `SearchData` = '{$SearchDataArray}', `HighCode` = '{$Code}', `EvalCode` = '{$EvalCode}';", 'system_alerts_filters'); - $Parse['System_MSG'] = ''.$_Lang['Info_FilterAdded'].''; - } - else - { - doquery("UPDATE {{table}} SET `Enabled` = {$Enabled}, `ActionType` = {$Action}, `SearchData` = '{$SearchDataArray}', `HighCode` = '{$Code}', `EvalCode` = '{$EvalCode}' WHERE `ID` = {$EditID};", 'system_alerts_filters'); - $Parse['System_MSG'] = ''.$_Lang['Info_FilterEdited'].''; - } - } - } - } - } - - if(empty($_GET['cmd'])) - { - $_GET['cmd'] = 'list'; - } - - if($_GET['cmd'] == 'list') - { - $PageTPL = gettemplate('admin/alertsfilters_body'); - $RowsTPL = gettemplate('admin/alertsfilters_rows'); - - $CurrentPage = 0; - if(!empty($_GET['page'])) - { - $CurrentPage = intval($_GET['page']); - } - if($CurrentPage <= 0) - { - $CurrentPage = 1; - } - $_Lang['CurrentPage'] = $CurrentPage; - - $PerPage = 0; - if(!empty($_COOKIE['alertsfilter_pp'])) - { - $PerPage = intval($_COOKIE['alertsfilter_pp']); - } - if($PerPage <= 0) - { - $PerPage = 20; - } - if(isset($_GET['pp']) && $_GET['pp'] > 0 && $_GET['pp'] != $PerPage) - { - $TempPerPage = intval($_GET['pp']); - if($TempPerPage > 0 AND $TempPerPage != $PerPage) - { - $PerPage = $TempPerPage; - setcookie('alertsfilter_pp', $PerPage, $Now + TIME_YEAR); - } - } - $_Lang['perpage_select_'.$PerPage] = 'selected'; - - $GetStart = (string) ((($CurrentPage - 1) * $PerPage) + 0); - - $Query = doquery("SELECT * FROM {{table}} ORDER BY `Date` DESC LIMIT {$GetStart}, {$PerPage};", 'system_alerts_filters'); - $GetCount = doquery("SELECT COUNT(`ID`) AS `Count` FROM {{table}};", 'system_alerts_filters', true); - $GetCount = $GetCount['Count']; - - $Parse = $_Lang; - $Parse['Rows'] = ''; - if(!empty($MSG)) - { - $Parse['System_MSG'] = ''.$MSG.''; - } - - if($GetCount > 0) - { - include_once($_EnginePath.'includes/functions/Pagination.php'); - $Pagin = CreatePaginationArray($GetCount, $PerPage, $CurrentPage, 7); - $PaginationTPL = ''; - $PaginationViewOpt = array('CurrentPage_Classes' => 'fatB orange', 'Breaker_View' => '...'); - $CreatePagination = implode(' ', ParsePaginationArray($Pagin, $CurrentPage, $PaginationTPL, $PaginationViewOpt)); - $Parse['Pagination'] = $CreatePagination; - } - else - { - $Parse['HidePaginRow'] = ' class="hide"'; - } - - if(mysql_num_rows($Query) > 0) - { - $Parse['BlankCellFix'] = 'hide'; - while($Filter = mysql_fetch_assoc($Query)) - { - $Row = $_Lang; - - $Row['CheckBox'] = ''; - $Row['ID'] = $Filter['ID']; - $Row['Date'] = date('d.m.Y', $Filter['Date']).'
'.date('H:i:s', $Filter['Date']); - $Row['Enabled'] = ($Filter['Enabled'] == 1 ? '' : ''); - $Row['ActionType'] = $_Lang['ActionTypes'][$Filter['ActionType']]; - $Row['Conditions'] = prettySyntax($Filter['HighCode']); - $Row['UseCount'] = (string) ($Filter['UseCount'] + 0); - - $Parse['Rows'] .= parsetemplate( $RowsTPL, $Row ); - } - } - else - { - if($CurrentPage > 1 AND $GetCount > 0) - { - $ThisWarning = $_Lang['No_Filters_ThisPage']; - } - else - { - $ThisWarning = $_Lang['No_Filters']; - } - $Parse['Rows'] = ''.$ThisWarning.''; - $Parse['HideSelectors'] = 'hide'; - $Parse['BlankCellFix'] = 'inv'; - } - } - - $Page = parsetemplate($PageTPL, $Parse); - display($Page, $_Lang['PageTitle'], false, true); - -?> \ No newline at end of file + array + ( + 'regexp' => 'userPresent\((.*?)\)', + 'replace' => 'in_array(\\1, $FiltersData[\'users\'])', + 'arg_regexp' => '[0-9]+', + 'badsyn' => '1', + 'arg_badsyn' => '1', + 'search' => 'USER', + 'info' => '1', + ), + 'ipPresent' => array + ( + 'regexp' => 'ipPresent\((.*?)\)', + 'replace' => 'in_array(\\1, $FiltersData[\'ips\'])', + 'arg_regexp' => '[0-9]+', + 'badsyn' => '1', + 'arg_badsyn' => '1', + 'search' => 'IP', + 'info' => '2', + ), + 'userIsSender' => array + ( + 'regexp' => 'userIsSender\((.*?)\)', + 'replace' => '\\1 == $FiltersData[\'sender\']', + 'arg_regexp' => '[0-9]+', + 'badsyn' => '1', + 'arg_badsyn' => '1', + 'search' => 'USER', + 'info' => '3', + ), + 'userIsTarget' => array + ( + 'regexp' => 'userIsTarget\((.*?)\)', + 'replace' => '\\1 == $FiltersData[\'target\']', + 'arg_regexp' => '[0-9]+', + 'badsyn' => '1', + 'arg_badsyn' => '1', + 'search' => 'USER', + 'info' => '4', + ), + 'logIPCount' => array + ( + 'regexp' => 'logIPCount\((.*?)(\, |\,){1}(.*?)(\, |\,){1}([0-9]{1,})\)', + 'replace' => '$FiltersData[\'logcount\'][\\3][\\1] <= \\5', + 'arg_regexp' => array(0 => '[0-9]+', 2 => '[0-9]+'), + 'badsyn' => '1', + 'arg_badsyn' => '1', + 'search' => array(0 => 'USER', 2 => 'IP'), + 'info' => '5', + ), + 'inPlace' => array + ( + 'regexp' => 'inPlace\((.*?)\)', + 'replace' => '\\1 == $FiltersData[\'place\']', + 'arg_regexp' => '[0-9]+', + 'badsyn' => '1', + 'arg_badsyn' => '1', + 'search' => 'PLACE', + 'info' => '6', + ), + 'AlertSenderIs' => array + ( + 'regexp' => 'AlertSenderIs\((.*?)\)', + 'replace' => '\\1 == $FiltersData[\'alertsender\']', + 'arg_regexp' => '[0-9]+', + 'badsyn' => '1', + 'arg_badsyn' => '1', + 'search' => 'ALERTSENDER', + 'info' => '7', + ), +); + +function prettySyntax($Code) +{ + global $FunctionsSyntaxes; + + foreach($FunctionsSyntaxes as $Function => $Data) + { + if(strstr($Code, $Function) !== FALSE) + { + $Code = preg_replace('#('.$Data['regexp'].')#si', '\\1', $Code); + } + } + + return $Code; +} + +// Deleting is here +if(isset($_GET['cmd']) && $_GET['cmd'] == 'del') +{ + $_GET['cmd'] = ''; + $DeleteID = isset($_GET['id']) ? intval($_GET['id']) : 0; + + if($DeleteID > 0) + { + doquery("DELETE FROM {{table}} WHERE `ID` = {$DeleteID} LIMIT 1;", 'system_alerts_filters'); + if(mysql_affected_rows() == 1) + { + $MSG = $_Lang['Info_FilterDeleted']; + $MSGColor = 'lime'; + } + else + { + $MSG = $_Lang['Error_NoSuchFilter']; + $MSGColor = 'red'; + } + } + else + { + $MSG = $_Lang['Error_BadFilterID']; + $MSGColor = 'red'; + } +} +else if(isset($_GET['cmd']) && $_GET['cmd'] == 'delpost') +{ + $_GET['cmd'] = ''; + if(!empty($_POST['f'])) + { + foreach($_POST['f'] as $FilterID => $Status) + { + if($Status == 'on') + { + $FilterID = intval($FilterID); + if($FilterID > 0) + { + $Filters2Delete[] = $FilterID; + } + } + } + } + $DeleteCount = count($Filters2Delete); + if($DeleteCount > 0) + { + doquery("DELETE FROM {{table}} WHERE `ID` IN (".implode(', ', $Filters2Delete).");", 'system_alerts_filters'); + $AffectedRows = mysql_affected_rows(); + if($AffectedRows > 0) + { + if($AffectedRows == $DeleteCount) + { + $MSG = $_Lang['Info_AllSelectsDeleted']; + $MSGColor = 'lime'; + } + else + { + $MSG = sprintf($_Lang['Warn_NotAllSelectsDeleted'], $AffectedRows, $DeleteCount); + $MSGColor = 'orange'; + } + } + else + { + $MSG = $_Lang['Error_NothingDeleted']; + $MSGColor = 'red'; + } + } + else + { + $MSG = $_Lang['Error_Nothing2Delete']; + $MSGColor = 'red'; + } +} + +if(isset($_GET['cmd']) && ($_GET['cmd'] == 'add' OR $_GET['cmd'] == 'edit')) +{ + $AllowProceed = false; + $WhatAreWeDoint = $_GET['cmd']; + if($_GET['cmd'] == 'edit') + { + $EditID = isset($_GET['id']) ? intval($_GET['id']) : 0; + if($EditID <= 0) + { + $_GET['cmd'] = ''; + $MSG = $_Lang['Error_NoIDGiven']; + $MSGColor = 'red'; + } + else + { + $SelectFilter = doquery("SELECT * FROM {{table}} WHERE `ID` = {$EditID} LIMIT 1;", 'system_alerts_filters', true); + if($SelectFilter['ID'] != $EditID) + { + $_GET['cmd'] = ''; + $MSG = $_Lang['Error_NoSuchFilter']; + $MSGColor = 'red'; + } + else + { + $AllowProceed = true; + } + } + } + else + { + $AllowProceed = true; + } + + if($AllowProceed === true) + { + $PageTPL = gettemplate('admin/alertsfilters_add'); + $Parse = $_Lang; + $Parse['Rows'] = ''; + if($WhatAreWeDoint == 'edit') + { + $Parse['InsertOnEdit'] = ''; + $Parse['Filters_Add'] = $_Lang['Filters_Edit']; + $Parse['AddFilter'] = $_Lang['EditFilter']; + $Parse['AreYouSure_Add'] = $_Lang['AreYouSure_Edit']; + $Parse['ThisFormAction'] = '?cmd=edit&id='.$EditID; + } + else + { + $Parse['ThisFormAction'] = '?cmd=add'; + } + + if($WhatAreWeDoint == 'add' OR ($WhatAreWeDoint == 'edit' && isset($_POST['editid']) && $_POST['editid'] == $EditID)) + { + $Code = isset($_POST['code']) ? trim(stripslashes($_POST['code'])) : null; + $Action = isset($_POST['action']) ? intval($_POST['action']) : 0; + $Enabled = (isset($_POST['turnoff']) && $_POST['turnoff'] == 'on' ? '0' : '1'); + $AllowSave = true; + } + else + { + $Code = stripslashes($SelectFilter['HighCode']); + $Action = $SelectFilter['ActionType']; + $Enabled = $SelectFilter['Enabled']; + } + + $Parse['CodePost'] = $Code; + $Parse['ActionType_Select'.$Action] = 'selected'; + if($Enabled == '0') + { + $Parse['TurnOffChecked'] = 'checked'; + } + + if(isset($_POST['doWhat']) && $_POST['doWhat'] == 'check') + { + $BracketOpenCount = substr_count($Code, '('); + $BracketCloseCount = substr_count($Code, ')'); + + if($BracketOpenCount > $BracketCloseCount) + { + $Warnings[] = $_Lang['Warn_BadSyntax_BracketOpen']; + } + else if($BracketOpenCount < $BracketCloseCount) + { + $Warnings[] = $_Lang['Warn_BadSyntax_BracketClose']; + } + + foreach($FunctionsSyntaxes as $Function => $Data) + { + if(strstr($Code, $Function) !== FALSE) + { + $Matches = false; + $ThisFunctionCount = substr_count($Code, $Function); + preg_match_all('#'.$Data['regexp'].'#si', $Code, $Matches); + $ErrorsCount = $ThisFunctionCount - count($Matches[0]); + if($ErrorsCount > 0) + { + $Warnings[] = sprintf($_Lang['Warn_BadSyntax_'.$Data['badsyn']], $Function, $ErrorsCount); + } + $ErrorsCount = 0; + + if(count($Matches) == 2) + { + $ArgumentRegExp = '/^'.$Data['arg_regexp'].'$/D'; + foreach($Matches[1] as $Argument) + { + if(!preg_match($ArgumentRegExp, $Argument)) + { + $ErrorsCount += 1; + } + } + } + else + { + foreach($Matches as $MatchID => $MatchArg) + { + if($MatchID == 0) + { + continue; + } + $MatchID -= 1; + if(!empty($Data['arg_regexp'][$MatchID])) + { + if(!preg_match('/^'.$Data['arg_regexp'][$MatchID].'$/D', $MatchArg[0])) + { + $ErrorsCount += 1; + } + } + } + } + if($ErrorsCount > 0) + { + $Warnings[] = sprintf($_Lang['Warn_ArgBadSyntax_'.$Data['arg_badsyn']], $Function, $ErrorsCount); + } + } + } + + if(!empty($Warnings)) + { + $Parse['System_MSG'] = ''.implode('
', $Warnings).''; + } + else + { + $Parse['System_MSG'] = ''.$_Lang['Info_CodeLooksFine'].''; + } + } + else if(isset($_POST['doWhat']) && $_POST['doWhat'] == 'save') + { + if($WhatAreWeDoint == 'edit' AND $AllowSave === false) + { + $Code = ''; + $Errors[] = $_Lang['Error_IDIsMalformed']; + } + + if(empty($Code)) + { + $Errors[] = $_Lang['Error_CodeEmpty']; + } + if($Action <= 0) + { + $Errors[] = $_Lang['Error_BadAction']; + } + + if(!empty($Code)) + { + foreach($FunctionsSyntaxes as $Function => $Data) + { + if(strstr($Code, $Function) !== FALSE) + { + $Matches = false; + $ThisFunctionCount = substr_count($Code, $Function); + preg_match_all('#'.$Data['regexp'].'#si', $Code, $Matches); + $ErrorsCount = $ThisFunctionCount - count($Matches[0]); + if($ErrorsCount > 0) + { + $Errors[] = sprintf($_Lang['Warn_BadSyntax_'.$Data['badsyn']], $Function, $ErrorsCount); + } + $ErrorsCount = 0; + if(count($Matches) == 2) + { + $ArgumentRegExp = '/^'.$Data['arg_regexp'].'$/D'; + foreach($Matches[1] as $Argument) + { + if(!preg_match($ArgumentRegExp, $Argument)) + { + $ErrorsCount += 1; + } + else + { + if(empty($SearchData[$Data['search']]) OR !in_array($Argument, $SearchData[$Data['search']])) + { + $SearchData[$Data['search']][] = $Argument; + } + } + } + } + else + { + foreach($Matches as $MatchID => $MatchArg) + { + if($MatchID == 0) + { + continue; + } + $MatchID -= 1; + if(!empty($Data['arg_regexp'][$MatchID])) + { + if(!preg_match('/^'.$Data['arg_regexp'][$MatchID].'$/D', $MatchArg[0])) + { + $ErrorsCount += 1; + } + else + { + if(empty($SearchData[$Data['search'][$MatchID]]) OR !in_array($MatchArg[0], $SearchData[$Data['search'][$MatchID]])) + { + $SearchData[$Data['search'][$MatchID]][] = $MatchArg[0]; + } + } + } + } + } + if($ErrorsCount > 0) + { + $Errors[] = sprintf($_Lang['Warn_ArgBadSyntax_'.$Data['arg_badsyn']], $Function, $ErrorsCount); + } + } + } + } + + if(!empty($Errors)) + { + $Parse['System_MSG'] = ''.implode('
', $Errors).''; + } + else + { + foreach($FunctionsSyntaxes as $Data) + { + if(empty($Data['replace_callback'])) + { + $Patterns[] = '#'.$Data['regexp'].'#si'; + $Replaces[] = $Data['replace']; + } + else + { + $Patterns_Callback[] = '#'.$Data['regexp'].'#si'; + $Replaces_Callback[] = $Data['replace_callback']; + } + } + $EvalCode = $Code; + + if(!empty($Patterns)) + { + foreach($Patterns as $PatternIndex => $PatternData) + { + $EvalCode = preg_replace($PatternData, $Replaces[$PatternIndex], $EvalCode); + } + } + if(!empty($Patterns_Callback)) + { + foreach($Patterns_Callback as $PatternIndex => $PatternData) + { + $EvalCode = preg_replace_callback($PatternData, $Replaces_Callback[$PatternIndex], $EvalCode); + } + } + $EvalCode = addslashes($EvalCode); + $Code = addslashes($Code); + + $SearchDataArray = ''; + if(!empty($SearchData)) + { + foreach($SearchData as $Type => $Values) + { + foreach($Values as $Value) + { + $SearchDataArray .= "{{$Type}_{$Value}}"; + } + } + } + + if($WhatAreWeDoint == 'add') + { + doquery("INSERT INTO {{table}} SET `Date` = UNIX_TIMESTAMP(), `Enabled` = {$Enabled}, `ActionType` = {$Action}, `SearchData` = '{$SearchDataArray}', `HighCode` = '{$Code}', `EvalCode` = '{$EvalCode}';", 'system_alerts_filters'); + $Parse['System_MSG'] = ''.$_Lang['Info_FilterAdded'].''; + } + else + { + doquery("UPDATE {{table}} SET `Enabled` = {$Enabled}, `ActionType` = {$Action}, `SearchData` = '{$SearchDataArray}', `HighCode` = '{$Code}', `EvalCode` = '{$EvalCode}' WHERE `ID` = {$EditID};", 'system_alerts_filters'); + $Parse['System_MSG'] = ''.$_Lang['Info_FilterEdited'].''; + } + } + } + } +} + +if(empty($_GET['cmd'])) +{ + $_GET['cmd'] = 'list'; +} + +if($_GET['cmd'] == 'list') +{ + $PageTPL = gettemplate('admin/alertsfilters_body'); + $RowsTPL = gettemplate('admin/alertsfilters_rows'); + + $CurrentPage = 0; + if(!empty($_GET['page'])) + { + $CurrentPage = intval($_GET['page']); + } + if($CurrentPage <= 0) + { + $CurrentPage = 1; + } + $_Lang['CurrentPage'] = $CurrentPage; + + $PerPage = 0; + if(!empty($_COOKIE['alertsfilter_pp'])) + { + $PerPage = intval($_COOKIE['alertsfilter_pp']); + } + if($PerPage <= 0) + { + $PerPage = 20; + } + if(isset($_GET['pp']) && $_GET['pp'] > 0 && $_GET['pp'] != $PerPage) + { + $TempPerPage = intval($_GET['pp']); + if($TempPerPage > 0 AND $TempPerPage != $PerPage) + { + $PerPage = $TempPerPage; + setcookie('alertsfilter_pp', $PerPage, $Now + TIME_YEAR); + } + } + $_Lang['perpage_select_'.$PerPage] = 'selected'; + + $GetStart = (string) ((($CurrentPage - 1) * $PerPage) + 0); + + $Query = doquery("SELECT * FROM {{table}} ORDER BY `Date` DESC LIMIT {$GetStart}, {$PerPage};", 'system_alerts_filters'); + $GetCount = doquery("SELECT COUNT(`ID`) AS `Count` FROM {{table}};", 'system_alerts_filters', true); + $GetCount = $GetCount['Count']; + + $Parse = $_Lang; + $Parse['Rows'] = ''; + if(!empty($MSG)) + { + $Parse['System_MSG'] = ''.$MSG.''; + } + + if($GetCount > 0) + { + include_once($_EnginePath.'includes/functions/Pagination.php'); + $Pagin = CreatePaginationArray($GetCount, $PerPage, $CurrentPage, 7); + $PaginationTPL = ''; + $PaginationViewOpt = array('CurrentPage_Classes' => 'fatB orange', 'Breaker_View' => '...'); + $CreatePagination = implode(' ', ParsePaginationArray($Pagin, $CurrentPage, $PaginationTPL, $PaginationViewOpt)); + $Parse['Pagination'] = $CreatePagination; + } + else + { + $Parse['HidePaginRow'] = ' class="hide"'; + } + + if(mysql_num_rows($Query) > 0) + { + $Parse['BlankCellFix'] = 'hide'; + while($Filter = mysql_fetch_assoc($Query)) + { + $Row = $_Lang; + + $Row['CheckBox'] = ''; + $Row['ID'] = $Filter['ID']; + $Row['Date'] = date('d.m.Y', $Filter['Date']).'
'.date('H:i:s', $Filter['Date']); + $Row['Enabled'] = ($Filter['Enabled'] == 1 ? '' : ''); + $Row['ActionType'] = $_Lang['ActionTypes'][$Filter['ActionType']]; + $Row['Conditions'] = prettySyntax($Filter['HighCode']); + $Row['UseCount'] = (string) ($Filter['UseCount'] + 0); + + $Parse['Rows'] .= parsetemplate( $RowsTPL, $Row ); + } + } + else + { + if($CurrentPage > 1 AND $GetCount > 0) + { + $ThisWarning = $_Lang['No_Filters_ThisPage']; + } + else + { + $ThisWarning = $_Lang['No_Filters']; + } + $Parse['Rows'] = ''.$ThisWarning.''; + $Parse['HideSelectors'] = 'hide'; + $Parse['BlankCellFix'] = 'inv'; + } +} + +$Page = parsetemplate($PageTPL, $Parse); +display($Page, $_Lang['PageTitle'], false, true); + +?> diff --git a/admin/alerts_list.php b/admin/alerts_list.php index 7f58c6a49..6870041db 100644 --- a/admin/alerts_list.php +++ b/admin/alerts_list.php @@ -1,944 +1,944 @@ - 0 && $_GET['pp'] != $PerPage) - { - $TempPerPage = intval($_GET['pp']); - if($TempPerPage > 0 AND $TempPerPage != $PerPage) - { - $PerPage = $TempPerPage; - setcookie('alertslist_pp', $PerPage, $Now + TIME_YEAR); - } - } - $_Lang['perpage_select_'.$PerPage] = 'selected'; - - $GetStart = (string) ((($CurrentPage - 1) * $PerPage) + 0); - - if(!empty($_GET['action'])) - { - $MSGColor = 'red'; - $ID = isset($_GET['id']) ? intval($_GET['id']) : 0; - if($ID > 0) - { - $ThisAction = $_GET['action']; - if($ThisAction == 'delete') - { - doquery("DELETE FROM {{table}} WHERE `ID` = {$ID};", 'system_alerts'); - if(mysql_affected_rows() > 0) - { - $MSG = $_Lang['Alert_deleted']; - $MSGColor = 'lime'; - } - else - { - $MSG = $_Lang['Alert_noexist']; - } - } - else if($ThisAction == 'change_status') - { - $Query_GetAlert = ''; - $Query_GetAlert .= "SELECT `ID`, `Status` FROM {{table}} "; - $Query_GetAlert .= "WHERE `ID` = {$ID} LIMIT 1;"; - $GetAlert = doquery($Query_GetAlert, 'system_alerts', true); - if($GetAlert['ID'] == $ID) - { - $Status = intval($_GET['set_status']); - if($Status < 0) - { - $MSG = $_Lang['Alert_no_status_given']; - } - else - { - if($GetAlert['Status'] == $Status) - { - $MSG = $_Lang['Alert_same_status']; - $MSGColor = 'orange'; - } - else - { - if(!empty($_Lang['StatusList'][$Status])) - { - doquery("UPDATE {{table}} SET `Status` = {$Status} WHERE `ID` = {$ID};", 'system_alerts'); - $MSG = sprintf($_Lang['Alert_status_changed'], $_Lang['StatusList'][$GetAlert['Status']]); - $MSGColor = 'lime'; - } - else - { - $MSG = $_Lang['Alert_status_noexist']; - } - } - } - } - else - { - $MSG = $_Lang['Alert_noexist']; - } - } - } - else - { - $MSG = $_Lang['No_id_given']; - } - } - - if($BlockSelectQuery !== true) - { - $Query_GetTotalCount = "SELECT COUNT(*) AS `Count` FROM {{table}};"; - $Result_GetTotalCount = doquery($Query_GetTotalCount, 'system_alerts', true); - $_TotalCount = $Result_GetTotalCount['Count']; - if($_TotalCount > 0) - { - if($GetStart >= $_TotalCount) - { - $GetStart = 0; - } - - $Query_GetAlerts = ''; - $Query_GetAlerts .= "SELECT `Alerts`.*, `Users`.`username` AS `Username` "; - $Query_GetAlerts .= "FROM {{table}} AS `Alerts` "; - $Query_GetAlerts .= "LEFT JOIN {{prefix}}users AS `Users` ON `Alerts`.`User_ID` = `Users`.`id` "; - $Query_GetAlerts .= "ORDER BY `Alerts`.`ID` DESC "; - $Query_GetAlerts .= "LIMIT {$GetStart}, {$PerPage};"; - $Result_GetAlerts = doquery($Query_GetAlerts, 'system_alerts'); - } - } - - $Parse = $_Lang; - $Parse['Rows'] = ''; - if(!empty($MSG)) - { - $Parse['System_MSG'] = ''.$MSG.''; - } - - if(isset($_TotalCount) && $_TotalCount > 0) - { - include_once($_EnginePath.'includes/functions/Pagination.php'); - $Pagin = CreatePaginationArray($_TotalCount, $PerPage, $CurrentPage, 7); - $PaginationTPL = ''; - $PaginationViewOpt = array('CurrentPage_Classes' => 'fatB orange', 'Breaker_View' => '...'); - $CreatePagination = implode(' ', ParsePaginationArray($Pagin, $CurrentPage, $PaginationTPL, $PaginationViewOpt)); - $Parse['Pagination'] = $CreatePagination; - } - else - { - $Parse['HidePaginRow'] = ' class="hide"'; - } - - if(!empty($Result_GetAlerts) AND mysql_num_rows($Result_GetAlerts) > 0) - { - $GetData = array('users' => array(), 'ips' => array()); - while($FetchData = mysql_fetch_assoc($Result_GetAlerts)) - { - $FetchData['mainusers'][$FetchData['User_ID']] = $FetchData['User_ID']; - $FetchData['alertusers'][$FetchData['User_ID']] = $FetchData['User_ID']; - $GetData['users'][$FetchData['User_ID']] = $FetchData['User_ID']; - - if($FetchData['Status'] == 0) - { - $MarkAlerts[] = $FetchData['ID']; - } - - if(!empty($FetchData['Other_Data'])) - { - $FetchData['Other_Data'] = json_decode($FetchData['Other_Data'], true); - if($FetchData['Code'] == 1) - { - $FetchData['mainusers'][$FetchData['Other_Data']['TargetUserID']] = $FetchData['Other_Data']['TargetUserID']; - $FetchData['alertusers'][$FetchData['Other_Data']['TargetUserID']] = $FetchData['Other_Data']['TargetUserID']; - $GetData['users'][$FetchData['Other_Data']['TargetUserID']] = $FetchData['Other_Data']['TargetUserID']; - if(!empty($FetchData['Other_Data']['OtherUsers'])) - { - foreach($FetchData['Other_Data']['OtherUsers'] as $ThisUserID) - { - $FetchData['alertusers'][$ThisUserID] = $ThisUserID; - $GetData['users'][$ThisUserID] = $ThisUserID; - } - } - foreach($FetchData['Other_Data']['Intersect'] as $IPData) - { - $GetData['ips'][$IPData['IPID']] = $IPData['IPID']; - } - } - else if($FetchData['Code'] == 2) - { - $FetchData['mainusers'][$FetchData['Other_Data']['ReferrerID']] = $FetchData['Other_Data']['ReferrerID']; - $FetchData['alertusers'][$FetchData['Other_Data']['ReferrerID']] = $FetchData['Other_Data']['ReferrerID']; - $GetData['users'][$FetchData['Other_Data']['ReferrerID']] = $FetchData['Other_Data']['ReferrerID']; - if(!empty($FetchData['Other_Data']['OtherUsers'])) - { - foreach($FetchData['Other_Data']['OtherUsers'] as $ThisUserID) - { - $FetchData['alertusers'][$ThisUserID] = $ThisUserID; - $GetData['users'][$ThisUserID] = $ThisUserID; - } - } - foreach($FetchData['Other_Data']['Intersect'] as $IPData) - { - $GetData['ips'][$IPData['IPID']] = $IPData['IPID']; - } - } - else if($FetchData['Code'] == 3) - { - $GetData['ips'][$FetchData['Other_Data']['IPID']] = $FetchData['Other_Data']['IPID']; - } - else if($FetchData['Code'] == 4) - { - $FetchData['mainusers'][$FetchData['Other_Data']['TargetUserID']] = $FetchData['Other_Data']['TargetUserID']; - $FetchData['alertusers'][$FetchData['Other_Data']['TargetUserID']] = $FetchData['Other_Data']['TargetUserID']; - $GetData['users'][$FetchData['Other_Data']['TargetUserID']] = $FetchData['Other_Data']['TargetUserID']; - if($FetchData['Other_Data']['SameAlly'] > 0) - { - $GetData['allys'][$FetchData['Other_Data']['SameAlly']] = $FetchData['Other_Data']['SameAlly']; - } - else if(!empty($FetchData['Other_Data']['AllyPact'])) - { - $GetData['allys'][$FetchData['Other_Data']['AllyPact']['SenderAlly']] = $FetchData['Other_Data']['AllyPact']['SenderAlly']; - $GetData['allys'][$FetchData['Other_Data']['AllyPact']['TargetAlly']] = $FetchData['Other_Data']['AllyPact']['TargetAlly']; - } - $GetData['fleets'][$FetchData['Other_Data']['FleetID']] = $FetchData['Other_Data']['FleetID']; - } - } - - $FetchData['Sender'] = $_Lang['Senders'][$FetchData['Sender']]; - $FetchData['ThisDate'] = prettyDate('d m Y', $FetchData['Date'], 1); - $FetchData['ThisTime'] = date('H:i:s', $FetchData['Date']); - $FetchData['Type'] = $_Lang['Types'][$FetchData['Type']]; - $FetchData['Importance'] = $FetchData['Importance']; - $FetchData['Status'] = $_Lang['StatusList'][$FetchData['Status']]; - $FetchData['AllUsers'] = implode('|', $FetchData['alertusers']); - $FetchData['MainUsers'] = implode('|', $FetchData['mainusers']); - - $Rows[] = $FetchData; - } - } - - if(!empty($Rows)) - { - if(!empty($MarkAlerts)) - { - $Query_UpdateAlerts = "UPDATE {{table}} SET `Status` = 1 WHERE `ID` IN (".implode(', ', $MarkAlerts).");"; - doquery($Query_UpdateAlerts, 'system_alerts'); - } - if(!empty($GetData['users'])) - { - $Query_GetUsers = ''; - $Query_GetUsers .= "SELECT `id`, `username` FROM {{table}} WHERE "; - $Query_GetUsers .= "`id` IN (".implode(', ', $GetData['users']).") "; - $Query_GetUsers .= "LIMIT ".count($GetData['users']).";"; - $Result_GetUsers = doquery($Query_GetUsers, 'users'); - if(mysql_num_rows($Result_GetUsers) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_GetUsers)) - { - $DataArray['users'][$FetchData['id']] = array('username' => $FetchData['username']); - } - } - foreach($GetData['users'] as $ThisUserID) - { - if(empty($DataArray['users'][$ThisUserID])) - { - $DataArray['users'][$ThisUserID] = array('username' => $_Lang['AlertCodes_Texts']['DeletedUser'], 'deleted' => true); - } - } - } - if(!empty($GetData['allys'])) - { - $Query_GetAllys = ''; - $Query_GetAllys .= "SELECT `id`, `ally_name`, `ally_tag` FROM {{table}} WHERE "; - $Query_GetAllys .= "`id` IN (".implode(', ', $GetData['allys']).") "; - $Query_GetAllys .= "LIMIT ".count($GetData['allys']).";"; - $Result_GetAllys = doquery($Query_GetAllys, 'alliance'); - if(mysql_num_rows($Result_GetAllys) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_GetAllys)) - { - $DataArray['allys'][$FetchData['id']] = array('ally_name' => $FetchData['ally_name'], 'ally_tag' => $FetchData['ally_tag']); - } - } - foreach($GetData['allys'] as $ThisAllyID) - { - if(empty($DataArray['allys'][$ThisAllyID])) - { - $DataArray['allys'][$ThisAllyID] = array('ally_name' => $_Lang['AlertCodes_Texts']['DeletedAlly'], 'deleted' => true); - } - } - } - if(!empty($GetData['ips'])) - { - $Query_GetIPs = ''; - $Query_GetIPs .= "SELECT `ID`, `Value` FROM {{table}} WHERE "; - $Query_GetIPs .= "`ID` IN (".implode(', ', $GetData['ips']).") "; - $Query_GetIPs .= "LIMIT ".count($GetData['ips']).";"; - $Result_GetIPs = doquery($Query_GetIPs, 'used_ip_and_ua'); - if(mysql_num_rows($Result_GetIPs) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_GetIPs)) - { - $DataArray['ips'][$FetchData['ID']] = array('Value' => $FetchData['Value']); - } - } - } - if(!empty($GetData['fleets'])) - { - $Query_GetFleets = ''; - $Query_GetFleets .= "SELECT `Fleet_ID`, `Fleet_Time_Start`, `Fleet_Calculated_Mission`, `Fleet_TurnedBack` "; - $Query_GetFleets .= "FROM {{table}} WHERE "; - $Query_GetFleets .= "`Fleet_ID` IN (".implode(', ', $GetData['fleets']).") "; - $Query_GetFleets .= "LIMIT ".count($GetData['fleets']).";"; - $Result_GetFleets = doquery($Query_GetFleets, 'fleet_archive'); - if(mysql_num_rows($Result_GetFleets) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_GetFleets)) - { - $DataArray['fleets'][$FetchData['Fleet_ID']] = $FetchData; - } - } - } - - foreach($Rows as $RowData) - { - if(!empty($RowData['Other_Data'])) - { - if($RowData['Code'] == 1) - { - // --- Fleet MultiAcc Detected --- - // Parse User - Alert Sender - if(!isset($DataArray['users'][$RowData['User_ID']]['deleted'])) - { - $RowData['CodeVars'][0] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array - ( - $RowData['User_ID'], $DataArray['users'][$RowData['User_ID']]['username'], $RowData['User_ID'] - )); - } - else - { - $RowData['CodeVars'][0] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array - ( - $RowData['User_ID'] - )); - } - // Parse Mission Type - $RowData['CodeVars'][1] = vsprintf($_Lang['AlertCodes_Texts']['FleetInfo'], array - ( - $_Lang['type_mission'][$RowData['Other_Data']['MissionID']] - )); - // Parse User - Target Owner - if(!isset($DataArray['users'][$RowData['Other_Data']['TargetUserID']]['deleted'])) - { - $RowData['CodeVars'][2] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array - ( - $RowData['Other_Data']['TargetUserID'], $DataArray['users'][$RowData['Other_Data']['TargetUserID']]['username'], $RowData['Other_Data']['TargetUserID'] - )); - } - else - { - $RowData['CodeVars'][2] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array - ( - $RowData['Other_Data']['TargetUserID'] - )); - } - // Parse FleetID - if($RowData['Other_Data']['FleetID'] > 0) - { - $RowData['CodeVars'][3] = vsprintf($_Lang['AlertCodes_Texts']['FleetBlock_NonBlocked_Text'], array - ( - $RowData['Other_Data']['FleetID'] - )); - } - else - { - $RowData['CodeVars'][3] = $_Lang['AlertCodes_Texts']['FleetBlock_Blocked_Text']; - } - // Parse DeclarationID - if(isset($RowData['Other_Data']['DeclarationID']) && $RowData['Other_Data']['DeclarationID'] > 0) - { - $RowData['CodeVars'][4] = vsprintf($_Lang['AlertCodes_Texts']['MultiACCDeclaration_Exists_Text'], array - ( - $RowData['Other_Data']['DeclarationID'] - )); - } - else - { - $RowData['CodeVars'][4] = $_Lang['AlertCodes_Texts']['MultiACCDeclaration_None_Text']; - } - - // Parse IP Intersection - foreach($RowData['Other_Data']['Intersect'] as $ThisIPData) - { - $ThisIPData['TimeMax'] = ($ThisIPData['SenderData']['LastTime'] > $ThisIPData['TargetData']['LastTime'] ? $ThisIPData['SenderData']['LastTime'] : $ThisIPData['TargetData']['LastTime']); - $ThisIPData['TimeMaxDiff'] = $Now - (SERVER_MAINOPEN_TSTAMP + $ThisIPData['TimeMax']); - if($ThisIPData['TimeMaxDiff'] >= (TIME_DAY * 30)) - { - $ThisIPData['TimeMaxDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Big']; - } - else if($ThisIPData['TimeMaxDiff'] >= (TIME_DAY * 1.5)) - { - $ThisIPData['TimeMaxDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Medium']; - } - else - { - $ThisIPData['TimeMaxDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Small']; - } - - $ThisIPData['TimeDiff'] = $ThisIPData['SenderData']['LastTime'] - $ThisIPData['TargetData']['LastTime']; - if($ThisIPData['TimeDiff'] < 0) - { - $ThisIPData['TimeDiff'] *= -1; - } - if($ThisIPData['TimeDiff'] >= (TIME_DAY * 30)) - { - $ThisIPData['TimeDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Big']; - } - else if($ThisIPData['TimeDiff'] >= (TIME_DAY * 1.5)) - { - $ThisIPData['TimeDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Medium']; - } - else - { - $ThisIPData['TimeDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Small']; - } - - // Parse IP Intersection User - Alert Sender - $ThisIPData['SenderData']['LastTimeStamp'] = SERVER_MAINOPEN_TSTAMP + $ThisIPData['SenderData']['LastTime']; - if(!isset($DataArray['users'][$RowData['User_ID']]['deleted'])) - { - $ThisIPData['UsersData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_UserExist'], array - ( - $RowData['User_ID'], $DataArray['users'][$RowData['User_ID']]['username'], $RowData['User_ID'], - prettyNumber($ThisIPData['SenderData']['Count']), prettyDate('d m Y, H:i:s', $ThisIPData['SenderData']['LastTimeStamp'], 1) - )); - } - else - { - $ThisIPData['UsersData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_UserDeleted'], array - ( - $RowData['User_ID'], - prettyNumber($ThisIPData['SenderData']['Count']), prettyDate('d m Y, H:i:s', $ThisIPData['SenderData']['LastTimeStamp'], 1) - )); - } - // Parse IP Intersection User - Target Owner - $ThisIPData['TargetData']['LastTimeStamp'] = SERVER_MAINOPEN_TSTAMP + $ThisIPData['TargetData']['LastTime']; - if(!isset($DataArray['users'][$RowData['Other_Data']['TargetUserID']]['deleted'])) - { - $ThisIPData['UsersData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_UserExist'], array - ( - $RowData['Other_Data']['TargetUserID'], $DataArray['users'][$RowData['Other_Data']['TargetUserID']]['username'], $RowData['Other_Data']['TargetUserID'], - prettyNumber($ThisIPData['TargetData']['Count']), prettyDate('d m Y, H:i:s', $ThisIPData['TargetData']['LastTimeStamp'], 1) - )); - } - else - { - $ThisIPData['UsersData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_UserDeleted'], array - ( - $RowData['Other_Data']['TargetUserID'], - prettyNumber($ThisIPData['TargetData']['Count']), prettyDate('d m Y, H:i:s', $ThisIPData['TargetData']['LastTimeStamp'], 1) - )); - } - // Parse IP Intersection Row - $RowData['IntersectData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_Main'], array - ( - $ThisIPData['IPID'], $DataArray['ips'][$ThisIPData['IPID']]['Value'], $ThisIPData['IPID'], - $ThisIPData['TimeDiff_Color'], pretty_time($ThisIPData['TimeDiff']), - $ThisIPData['TimeMaxDiff_Color'], pretty_time($ThisIPData['TimeMaxDiff']), - implode('
', $ThisIPData['UsersData']) - )); - } - $RowData['CodeVars'][5] = implode('
', $RowData['IntersectData']); - // Parse Other Users - if(!empty($RowData['Other_Data']['OtherUsers'])) - { - foreach($RowData['Other_Data']['OtherUsers'] as $ThisUserID) - { - if(!isset($DataArray['users'][$ThisUserID]['deleted'])) - { - $RowData['CodeVars'][7][] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array - ( - $ThisUserID, $DataArray['users'][$ThisUserID]['username'], $ThisUserID - )); - } - else - { - $RowData['CodeVars'][7][] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array - ( - $ThisUserID, - )); - } - } - $RowData['CodeVars'][6] = vsprintf($_Lang['AlertCodes_Texts']['OtherUsers_Count'], array - ( - prettyNumber(count($RowData['CodeVars'][7])) - )); - $RowData['CodeVars'][7] = implode(', ', $RowData['CodeVars'][7]); - } - else - { - $RowData['CodeVars'][6] = ''; - $RowData['CodeVars'][7] = $_Lang['AlertCodes_Texts']['OtherUsers_None']; - } - } - else if($RowData['Code'] == 2) - { - // --- Register MultiAcc Detected --- - // Include Tasks Lang - if(!isset($_Included_TasksLang)) - { - includeLang('tasks'); - $_Included_TasksLang = true; - } - // Parse User - New User - if(!isset($DataArray['users'][$RowData['User_ID']]['deleted'])) - { - $RowData['CodeVars'][0] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array - ( - $RowData['User_ID'], $DataArray['users'][$RowData['User_ID']]['username'], $RowData['User_ID'] - )); - } - else - { - $RowData['CodeVars'][0] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array - ( - $RowData['User_ID'] - )); - } - // Parse User - Referrer User - if(!isset($DataArray['users'][$RowData['Other_Data']['ReferrerID']]['deleted'])) - { - $RowData['CodeVars'][1] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array - ( - $RowData['Other_Data']['ReferrerID'], $DataArray['users'][$RowData['Other_Data']['ReferrerID']]['username'], $RowData['Other_Data']['ReferrerID'] - )); - } - else - { - $RowData['CodeVars'][1] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array - ( - $RowData['Other_Data']['ReferrerID'] - )); - } - - // Parse Tasks Data - if(!empty($RowData['Other_Data']['Tasks'])) - { - foreach($RowData['Other_Data']['Tasks'] as $ThisData) - { - $RowData['CodeVars'][2][] = vsprintf($_Lang['AlertCodes_Texts']['TaskData'], array - ( - $_Lang['Tasks'][$ThisData['TaskID']]['name'], $ThisData['TaskID'], - ($ThisData['TaskStatus'] >= $ThisData['TaskLimit'] ? $_Lang['AlertCodes_Texts']['TaskData_StatusDone'] : $_Lang['AlertCodes_Texts']['TaskData_StatusNotDone']), - $ThisData['TaskStatus'], $ThisData['TaskLimit'] - )); - } - $RowData['CodeVars'][2] = implode('
', $RowData['CodeVars'][2]); - } - else - { - $RowData['CodeVars'][2] = $_Lang['AlertCodes_Texts']['NewUser_NoTasks']; - } - - // Parse IP Intersection - foreach($RowData['Other_Data']['Intersect'] as $ThisIPData) - { - $ThisIPData['TimeMax'] = ($ThisIPData['NewUser']['LastTime'] > $ThisIPData['OldUser']['LastTime'] ? $ThisIPData['NewUser']['LastTime'] : $ThisIPData['OldUser']['LastTime']); - $ThisIPData['TimeMaxDiff'] = $Now - (SERVER_MAINOPEN_TSTAMP + $ThisIPData['TimeMax']); - if($ThisIPData['TimeMaxDiff'] >= (TIME_DAY * 30)) - { - $ThisIPData['TimeMaxDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Big']; - } - else if($ThisIPData['TimeMaxDiff'] >= (TIME_DAY * 1.5)) - { - $ThisIPData['TimeMaxDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Medium']; - } - else - { - $ThisIPData['TimeMaxDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Small']; - } - - $ThisIPData['TimeDiff'] = $ThisIPData['NewUser']['LastTime'] - $ThisIPData['OldUser']['LastTime']; - if($ThisIPData['TimeDiff'] < 0) - { - $ThisIPData['TimeDiff'] *= -1; - } - if($ThisIPData['TimeDiff'] >= (TIME_DAY * 30)) - { - $ThisIPData['TimeDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Big']; - } - else if($ThisIPData['TimeDiff'] >= (TIME_DAY * 1.5)) - { - $ThisIPData['TimeDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Medium']; - } - else - { - $ThisIPData['TimeDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Small']; - } - - // Parse IP Intersection User - New User - $ThisIPData['NewUser']['LastTimeStamp'] = SERVER_MAINOPEN_TSTAMP + $ThisIPData['NewUser']['LastTime']; - if(!isset($DataArray['users'][$RowData['User_ID']]['deleted'])) - { - $ThisIPData['UsersData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_UserExist'], array - ( - $RowData['User_ID'], $DataArray['users'][$RowData['User_ID']]['username'], $RowData['User_ID'], - prettyNumber($ThisIPData['NewUser']['Count']), prettyDate('d m Y, H:i:s', $ThisIPData['NewUser']['LastTimeStamp'], 1) - )); - } - else - { - $ThisIPData['UsersData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_UserDeleted'], array - ( - $RowData['User_ID'], - prettyNumber($ThisIPData['NewUser']['Count']), prettyDate('d m Y, H:i:s', $ThisIPData['NewUser']['LastTimeStamp'], 1) - )); - } - // Parse IP Intersection User - Referrer User - $ThisIPData['OldUser']['LastTimeStamp'] = SERVER_MAINOPEN_TSTAMP + $ThisIPData['OldUser']['LastTime']; - if(!isset($DataArray['users'][$RowData['Other_Data']['ReferrerID']]['deleted'])) - { - $ThisIPData['UsersData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_UserExist'], array - ( - $RowData['Other_Data']['ReferrerID'], $DataArray['users'][$RowData['Other_Data']['ReferrerID']]['username'], $RowData['Other_Data']['ReferrerID'], - prettyNumber($ThisIPData['OldUser']['Count']), prettyDate('d m Y, H:i:s', $ThisIPData['OldUser']['LastTimeStamp'], 1) - )); - } - else - { - $ThisIPData['UsersData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_UserDeleted'], array - ( - $RowData['Other_Data']['ReferrerID'], - prettyNumber($ThisIPData['OldUser']['Count']), prettyDate('d m Y, H:i:s', $ThisIPData['OldUser']['LastTimeStamp'], 1) - )); - } - // Parse IP Intersection Row - $RowData['IntersectData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_Main'], array - ( - $ThisIPData['IPID'], $DataArray['ips'][$ThisIPData['IPID']]['Value'], $ThisIPData['IPID'], - $ThisIPData['TimeDiff_Color'], pretty_time($ThisIPData['TimeDiff']), - $ThisIPData['TimeMaxDiff_Color'], pretty_time($ThisIPData['TimeMaxDiff']), - implode('
', $ThisIPData['UsersData']) - )); - } - $RowData['CodeVars'][3] = implode('
', $RowData['IntersectData']); - - // Parse Other Users - if(!empty($RowData['Other_Data']['OtherUsers'])) - { - foreach($RowData['Other_Data']['OtherUsers'] as $ThisUserID) - { - if(!isset($DataArray['users'][$ThisUserID]['deleted'])) - { - $RowData['CodeVars'][5][] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array - ( - $ThisUserID, $DataArray['users'][$ThisUserID]['username'], $ThisUserID - )); - } - else - { - $RowData['CodeVars'][5][] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array - ( - $ThisUserID, - )); - } - } - $RowData['CodeVars'][4] = vsprintf($_Lang['AlertCodes_Texts']['OtherUsers_Count'], array - ( - prettyNumber(count($RowData['CodeVars'][5])) - )); - $RowData['CodeVars'][5] = implode(', ', $RowData['CodeVars'][5]); - } - else - { - $RowData['CodeVars'][4] = ''; - $RowData['CodeVars'][5] = $_Lang['AlertCodes_Texts']['OtherUsers_None']; - } - } - else if($RowData['Code'] == 3) - { - // --- Register with Proxy Detected --- - // Parse User - New User - if(!isset($DataArray['users'][$RowData['User_ID']]['deleted'])) - { - $RowData['CodeVars'][0] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array - ( - $RowData['User_ID'], $DataArray['users'][$RowData['User_ID']]['username'], $RowData['User_ID'] - )); - } - else - { - $RowData['CodeVars'][0] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array - ( - $RowData['User_ID'] - )); - } - // Parse IP - $RowData['CodeVars'][1] = vsprintf($_Lang['AlertCodes_Texts']['NewUser_IPProxy'], array - ( - $RowData['Other_Data']['IPID'], $DataArray['ips'][$RowData['Other_Data']['IPID']]['Value'], $RowData['Other_Data']['IPID'], - ($RowData['Other_Data']['RegIP'] ? $_Lang['AlertCodes_Texts']['NewUser_IPProxy_RegIP'] : $_Lang['AlertCodes_Texts']['NewUser_IPProxy_NoRegIP']) - )); - } - else if($RowData['Code'] == 4) - { - // --- ResourcePush Detected --- - // Parse User - Alert Sender - if(!isset($DataArray['users'][$RowData['User_ID']]['deleted'])) - { - $RowData['CodeVars'][0] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array - ( - $RowData['User_ID'], $DataArray['users'][$RowData['User_ID']]['username'], $RowData['User_ID'] - )); - } - else - { - $RowData['CodeVars'][0] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array - ( - $RowData['User_ID'] - )); - } - // Parse User - Target Owner - if(!isset($DataArray['users'][$RowData['Other_Data']['TargetUserID']]['deleted'])) - { - $RowData['CodeVars'][1] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array - ( - $RowData['Other_Data']['TargetUserID'], $DataArray['users'][$RowData['Other_Data']['TargetUserID']]['username'], $RowData['Other_Data']['TargetUserID'] - )); - } - else - { - $RowData['CodeVars'][1] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array - ( - $RowData['Other_Data']['TargetUserID'] - )); - } - // Parse Users Acquaintance - if($RowData['Other_Data']['SameAlly'] > 0) - { - if(!isset($DataArray['allys'][$RowData['Other_Data']['SameAlly']]['deleted'])) - { - $RowData['CodeVars'][2][0] = vsprintf($_Lang['AlertCodes_Texts']['AllyLink'], array - ( - $DataArray['allys'][$RowData['Other_Data']['SameAlly']]['ally_name'], - $DataArray['allys'][$RowData['Other_Data']['SameAlly']]['ally_tag'], - $RowData['Other_Data']['SameAlly'] - )); - } - else - { - $RowData['CodeVars'][2][0] = vsprintf($_Lang['AlertCodes_Texts']['DeletedAllyID'], array - ( - $RowData['Other_Data']['SameAlly'] - )); - } - $RowData['CodeVars'][2][0] = vsprintf($_Lang['AlertCodes_Texts']['PushAlert_UsersInAlly'], $RowData['CodeVars'][2][0]); - } - else if(!empty($RowData['Other_Data']['AllyPact'])) - { - if(!isset($DataArray['allys'][$RowData['Other_Data']['AllyPact']['SenderAlly']]['deleted'])) - { - $RowData['CodeVars'][2][1][] = vsprintf($_Lang['AlertCodes_Texts']['AllyLink'], array - ( - $DataArray['allys'][$RowData['Other_Data']['AllyPact']['SenderAlly']]['ally_name'], - $DataArray['allys'][$RowData['Other_Data']['AllyPact']['SenderAlly']]['ally_tag'], - $RowData['Other_Data']['AllyPact']['SenderAlly'] - )); - } - else - { - $RowData['CodeVars'][2][1][] = vsprintf($_Lang['AlertCodes_Texts']['DeletedAllyID'], array - ( - $RowData['Other_Data']['AllyPact']['SenderAlly'] - )); - } - if(!isset($DataArray['allys'][$RowData['Other_Data']['AllyPact']['TargetAlly']]['deleted'])) - { - $RowData['CodeVars'][2][1][] = vsprintf($_Lang['AlertCodes_Texts']['AllyLink'], array - ( - $DataArray['allys'][$RowData['Other_Data']['AllyPact']['TargetAlly']]['ally_name'], - $DataArray['allys'][$RowData['Other_Data']['AllyPact']['TargetAlly']]['ally_tag'], - $RowData['Other_Data']['AllyPact']['TargetAlly'] - )); - } - else - { - $RowData['CodeVars'][2][1][] = vsprintf($_Lang['AlertCodes_Texts']['DeletedAllyID'], array - ( - $RowData['Other_Data']['AllyPact']['TargetAlly'] - )); - } - $RowData['CodeVars'][2][1] = vsprintf($_Lang['AlertCodes_Texts']['PushAlert_UsersHasPact'], $RowData['CodeVars'][2][1]); - } - if($RowData['Other_Data']['BuddyFriends'] === true) - { - $RowData['CodeVars'][2][2] = $_Lang['AlertCodes_Texts']['PushAlert_UsersAreBuddy']; - } - if(!empty($RowData['CodeVars'][2])) - { - $RowData['CodeVars'][2] = implode(', ', $RowData['CodeVars'][2]); - } - else - { - $RowData['CodeVars'][2] = $_Lang['AlertCodes_Texts']['PushAlert_UsersDontKnowEachother']; - } - // Parse User Stats Difference - $RowData['CodeVars'][3] = prettyNumber($RowData['Other_Data']['Stats']['Target']['Points'] - $RowData['Other_Data']['Stats']['Sender']['Points']); - if($RowData['Other_Data']['Stats']['Sender']['Points'] > 0) - { - $RowData['CodeVars'][4] = prettyNumber(($RowData['Other_Data']['Stats']['Target']['Points'] / $RowData['Other_Data']['Stats']['Sender']['Points']) * 100); - } - else - { - $RowData['CodeVars'][4] = '∞'; - } - $RowData['CodeVars'][5] = prettyNumber($RowData['Other_Data']['Stats']['Sender']['Position'] - $RowData['Other_Data']['Stats']['Target']['Position']); - // Parse Users StatsInfo - if(!isset($DataArray['users'][$RowData['User_ID']]['deleted'])) - { - $RowData['CodeVars'][6] = vsprintf($_Lang['AlertCodes_Texts']['PushAlert_UserExist'], array - ( - $RowData['User_ID'], $DataArray['users'][$RowData['User_ID']]['username'], $RowData['User_ID'], - prettyNumber($RowData['Other_Data']['Stats']['Sender']['Points']), - prettyNumber($RowData['Other_Data']['Stats']['Sender']['Position']) - )); - } - else - { - $RowData['CodeVars'][6] = vsprintf($_Lang['AlertCodes_Texts']['PushAlert_UserDeleted'], array - ( - $RowData['User_ID'], - prettyNumber($RowData['Other_Data']['Stats']['Sender']['Points']), - prettyNumber($RowData['Other_Data']['Stats']['Sender']['Position']) - )); - } - if(!isset($DataArray['users'][$RowData['Other_Data']['TargetUserID']]['deleted'])) - { - $RowData['CodeVars'][7] = vsprintf($_Lang['AlertCodes_Texts']['PushAlert_UserExist'], array - ( - $RowData['Other_Data']['TargetUserID'], $DataArray['users'][$RowData['Other_Data']['TargetUserID']]['username'], $RowData['Other_Data']['TargetUserID'], - prettyNumber($RowData['Other_Data']['Stats']['Target']['Points']), - prettyNumber($RowData['Other_Data']['Stats']['Target']['Position']) - )); - } - else - { - $RowData['CodeVars'][7] = vsprintf($_Lang['AlertCodes_Texts']['PushAlert_UserDeleted'], array - ( - $RowData['Other_Data']['TargetUserID'], - prettyNumber($RowData['Other_Data']['Stats']['Target']['Points']), - prettyNumber($RowData['Other_Data']['Stats']['Target']['Position']) - )); - } - // Parse FleetID - if($DataArray['fleets'][$RowData['Other_Data']['FleetID']]['Fleet_Calculated_Mission'] == 1) - { - $RowData['CodeVars'][8] = $_Lang['AlertCodes_Texts']['PushAlert_FleetState_Delivered']; - } - else if($DataArray['fleets'][$RowData['Other_Data']['FleetID']]['Fleet_Time_Start'] <= $Now) - { - $RowData['CodeVars'][8] = $_Lang['AlertCodes_Texts']['PushAlert_FleetState_GoalAchieved']; - } - else if($DataArray['fleets'][$RowData['Other_Data']['FleetID']]['Fleet_TurnedBack']) - { - $RowData['CodeVars'][8] = $_Lang['AlertCodes_Texts']['PushAlert_FleetState_TurnedBack']; - } - else - { - $RowData['CodeVars'][8] = sprintf($_Lang['AlertCodes_Texts']['PushAlert_FleetState_Flying'], pretty_time($DataArray['fleets'][$RowData['Other_Data']['FleetID']]['Fleet_Time_Start'] - $Now)); - } - $RowData['CodeVars'][9] = $RowData['Other_Data']['FleetID']; - // Parse Resources - foreach($RowData['Other_Data']['Resources'] as $ThisKey => $ThisValue) - { - if($ThisValue > 0) - { - $RowData['CodeVars'][10][] = vsprintf($_Lang['AlertCodes_Texts']['PushAlert_ResourceLine'], array - ( - $_Lang['AlertCodes_Texts']['PushAlert_Res_'.$ThisKey], prettyNumber($ThisValue) - )); - } - } - $RowData['CodeVars'][10] = implode('
', $RowData['CodeVars'][10]); - } - ksort($RowData['CodeVars']); - $RowData['Data'] = vsprintf($_Lang['AlertCodes'][$RowData['Code']], $RowData['CodeVars']); - } - else - { - $RowData['Data'] = ' '; - } - - $Parse['Rows'] .= parsetemplate($RowsTPL, $RowData); - } - } - else - { - if($CurrentPage > 1 AND $_TotalCount > 0) - { - $ThisWarning = $_Lang['No_Alerts_ThisPage']; - } - else - { - $ThisWarning = $_Lang['No_Alerts']; - } - $Parse['Rows'] = ''.$ThisWarning.''; - } - - $Page = parsetemplate($PageTPL, $Parse); - display($Page, $PageTitle, false, true); - -?> \ No newline at end of file + 0 && $_GET['pp'] != $PerPage) +{ + $TempPerPage = intval($_GET['pp']); + if($TempPerPage > 0 AND $TempPerPage != $PerPage) + { + $PerPage = $TempPerPage; + setcookie('alertslist_pp', $PerPage, $Now + TIME_YEAR); + } +} +$_Lang['perpage_select_'.$PerPage] = 'selected'; + +$GetStart = (string) ((($CurrentPage - 1) * $PerPage) + 0); + +if(!empty($_GET['action'])) +{ + $MSGColor = 'red'; + $ID = isset($_GET['id']) ? intval($_GET['id']) : 0; + if($ID > 0) + { + $ThisAction = $_GET['action']; + if($ThisAction == 'delete') + { + doquery("DELETE FROM {{table}} WHERE `ID` = {$ID};", 'system_alerts'); + if(mysql_affected_rows() > 0) + { + $MSG = $_Lang['Alert_deleted']; + $MSGColor = 'lime'; + } + else + { + $MSG = $_Lang['Alert_noexist']; + } + } + else if($ThisAction == 'change_status') + { + $Query_GetAlert = ''; + $Query_GetAlert .= "SELECT `ID`, `Status` FROM {{table}} "; + $Query_GetAlert .= "WHERE `ID` = {$ID} LIMIT 1;"; + $GetAlert = doquery($Query_GetAlert, 'system_alerts', true); + if($GetAlert['ID'] == $ID) + { + $Status = intval($_GET['set_status']); + if($Status < 0) + { + $MSG = $_Lang['Alert_no_status_given']; + } + else + { + if($GetAlert['Status'] == $Status) + { + $MSG = $_Lang['Alert_same_status']; + $MSGColor = 'orange'; + } + else + { + if(!empty($_Lang['StatusList'][$Status])) + { + doquery("UPDATE {{table}} SET `Status` = {$Status} WHERE `ID` = {$ID};", 'system_alerts'); + $MSG = sprintf($_Lang['Alert_status_changed'], $_Lang['StatusList'][$GetAlert['Status']]); + $MSGColor = 'lime'; + } + else + { + $MSG = $_Lang['Alert_status_noexist']; + } + } + } + } + else + { + $MSG = $_Lang['Alert_noexist']; + } + } + } + else + { + $MSG = $_Lang['No_id_given']; + } +} + +if($BlockSelectQuery !== true) +{ + $Query_GetTotalCount = "SELECT COUNT(*) AS `Count` FROM {{table}};"; + $Result_GetTotalCount = doquery($Query_GetTotalCount, 'system_alerts', true); + $_TotalCount = $Result_GetTotalCount['Count']; + if($_TotalCount > 0) + { + if($GetStart >= $_TotalCount) + { + $GetStart = 0; + } + + $Query_GetAlerts = ''; + $Query_GetAlerts .= "SELECT `Alerts`.*, `Users`.`username` AS `Username` "; + $Query_GetAlerts .= "FROM {{table}} AS `Alerts` "; + $Query_GetAlerts .= "LEFT JOIN {{prefix}}users AS `Users` ON `Alerts`.`User_ID` = `Users`.`id` "; + $Query_GetAlerts .= "ORDER BY `Alerts`.`ID` DESC "; + $Query_GetAlerts .= "LIMIT {$GetStart}, {$PerPage};"; + $Result_GetAlerts = doquery($Query_GetAlerts, 'system_alerts'); + } +} + +$Parse = $_Lang; +$Parse['Rows'] = ''; +if(!empty($MSG)) +{ + $Parse['System_MSG'] = ''.$MSG.''; +} + +if(isset($_TotalCount) && $_TotalCount > 0) +{ + include_once($_EnginePath.'includes/functions/Pagination.php'); + $Pagin = CreatePaginationArray($_TotalCount, $PerPage, $CurrentPage, 7); + $PaginationTPL = ''; + $PaginationViewOpt = array('CurrentPage_Classes' => 'fatB orange', 'Breaker_View' => '...'); + $CreatePagination = implode(' ', ParsePaginationArray($Pagin, $CurrentPage, $PaginationTPL, $PaginationViewOpt)); + $Parse['Pagination'] = $CreatePagination; +} +else +{ + $Parse['HidePaginRow'] = ' class="hide"'; +} + +if(!empty($Result_GetAlerts) AND mysql_num_rows($Result_GetAlerts) > 0) +{ + $GetData = array('users' => array(), 'ips' => array()); + while($FetchData = mysql_fetch_assoc($Result_GetAlerts)) + { + $FetchData['mainusers'][$FetchData['User_ID']] = $FetchData['User_ID']; + $FetchData['alertusers'][$FetchData['User_ID']] = $FetchData['User_ID']; + $GetData['users'][$FetchData['User_ID']] = $FetchData['User_ID']; + + if($FetchData['Status'] == 0) + { + $MarkAlerts[] = $FetchData['ID']; + } + + if(!empty($FetchData['Other_Data'])) + { + $FetchData['Other_Data'] = json_decode($FetchData['Other_Data'], true); + if($FetchData['Code'] == 1) + { + $FetchData['mainusers'][$FetchData['Other_Data']['TargetUserID']] = $FetchData['Other_Data']['TargetUserID']; + $FetchData['alertusers'][$FetchData['Other_Data']['TargetUserID']] = $FetchData['Other_Data']['TargetUserID']; + $GetData['users'][$FetchData['Other_Data']['TargetUserID']] = $FetchData['Other_Data']['TargetUserID']; + if(!empty($FetchData['Other_Data']['OtherUsers'])) + { + foreach($FetchData['Other_Data']['OtherUsers'] as $ThisUserID) + { + $FetchData['alertusers'][$ThisUserID] = $ThisUserID; + $GetData['users'][$ThisUserID] = $ThisUserID; + } + } + foreach($FetchData['Other_Data']['Intersect'] as $IPData) + { + $GetData['ips'][$IPData['IPID']] = $IPData['IPID']; + } + } + else if($FetchData['Code'] == 2) + { + $FetchData['mainusers'][$FetchData['Other_Data']['ReferrerID']] = $FetchData['Other_Data']['ReferrerID']; + $FetchData['alertusers'][$FetchData['Other_Data']['ReferrerID']] = $FetchData['Other_Data']['ReferrerID']; + $GetData['users'][$FetchData['Other_Data']['ReferrerID']] = $FetchData['Other_Data']['ReferrerID']; + if(!empty($FetchData['Other_Data']['OtherUsers'])) + { + foreach($FetchData['Other_Data']['OtherUsers'] as $ThisUserID) + { + $FetchData['alertusers'][$ThisUserID] = $ThisUserID; + $GetData['users'][$ThisUserID] = $ThisUserID; + } + } + foreach($FetchData['Other_Data']['Intersect'] as $IPData) + { + $GetData['ips'][$IPData['IPID']] = $IPData['IPID']; + } + } + else if($FetchData['Code'] == 3) + { + $GetData['ips'][$FetchData['Other_Data']['IPID']] = $FetchData['Other_Data']['IPID']; + } + else if($FetchData['Code'] == 4) + { + $FetchData['mainusers'][$FetchData['Other_Data']['TargetUserID']] = $FetchData['Other_Data']['TargetUserID']; + $FetchData['alertusers'][$FetchData['Other_Data']['TargetUserID']] = $FetchData['Other_Data']['TargetUserID']; + $GetData['users'][$FetchData['Other_Data']['TargetUserID']] = $FetchData['Other_Data']['TargetUserID']; + if($FetchData['Other_Data']['SameAlly'] > 0) + { + $GetData['allys'][$FetchData['Other_Data']['SameAlly']] = $FetchData['Other_Data']['SameAlly']; + } + else if(!empty($FetchData['Other_Data']['AllyPact'])) + { + $GetData['allys'][$FetchData['Other_Data']['AllyPact']['SenderAlly']] = $FetchData['Other_Data']['AllyPact']['SenderAlly']; + $GetData['allys'][$FetchData['Other_Data']['AllyPact']['TargetAlly']] = $FetchData['Other_Data']['AllyPact']['TargetAlly']; + } + $GetData['fleets'][$FetchData['Other_Data']['FleetID']] = $FetchData['Other_Data']['FleetID']; + } + } + + $FetchData['Sender'] = $_Lang['Senders'][$FetchData['Sender']]; + $FetchData['ThisDate'] = prettyDate('d m Y', $FetchData['Date'], 1); + $FetchData['ThisTime'] = date('H:i:s', $FetchData['Date']); + $FetchData['Type'] = $_Lang['Types'][$FetchData['Type']]; + $FetchData['Importance'] = $FetchData['Importance']; + $FetchData['Status'] = $_Lang['StatusList'][$FetchData['Status']]; + $FetchData['AllUsers'] = implode('|', $FetchData['alertusers']); + $FetchData['MainUsers'] = implode('|', $FetchData['mainusers']); + + $Rows[] = $FetchData; + } +} + +if(!empty($Rows)) +{ + if(!empty($MarkAlerts)) + { + $Query_UpdateAlerts = "UPDATE {{table}} SET `Status` = 1 WHERE `ID` IN (".implode(', ', $MarkAlerts).");"; + doquery($Query_UpdateAlerts, 'system_alerts'); + } + if(!empty($GetData['users'])) + { + $Query_GetUsers = ''; + $Query_GetUsers .= "SELECT `id`, `username` FROM {{table}} WHERE "; + $Query_GetUsers .= "`id` IN (".implode(', ', $GetData['users']).") "; + $Query_GetUsers .= "LIMIT ".count($GetData['users']).";"; + $Result_GetUsers = doquery($Query_GetUsers, 'users'); + if(mysql_num_rows($Result_GetUsers) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_GetUsers)) + { + $DataArray['users'][$FetchData['id']] = array('username' => $FetchData['username']); + } + } + foreach($GetData['users'] as $ThisUserID) + { + if(empty($DataArray['users'][$ThisUserID])) + { + $DataArray['users'][$ThisUserID] = array('username' => $_Lang['AlertCodes_Texts']['DeletedUser'], 'deleted' => true); + } + } + } + if(!empty($GetData['allys'])) + { + $Query_GetAllys = ''; + $Query_GetAllys .= "SELECT `id`, `ally_name`, `ally_tag` FROM {{table}} WHERE "; + $Query_GetAllys .= "`id` IN (".implode(', ', $GetData['allys']).") "; + $Query_GetAllys .= "LIMIT ".count($GetData['allys']).";"; + $Result_GetAllys = doquery($Query_GetAllys, 'alliance'); + if(mysql_num_rows($Result_GetAllys) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_GetAllys)) + { + $DataArray['allys'][$FetchData['id']] = array('ally_name' => $FetchData['ally_name'], 'ally_tag' => $FetchData['ally_tag']); + } + } + foreach($GetData['allys'] as $ThisAllyID) + { + if(empty($DataArray['allys'][$ThisAllyID])) + { + $DataArray['allys'][$ThisAllyID] = array('ally_name' => $_Lang['AlertCodes_Texts']['DeletedAlly'], 'deleted' => true); + } + } + } + if(!empty($GetData['ips'])) + { + $Query_GetIPs = ''; + $Query_GetIPs .= "SELECT `ID`, `Value` FROM {{table}} WHERE "; + $Query_GetIPs .= "`ID` IN (".implode(', ', $GetData['ips']).") "; + $Query_GetIPs .= "LIMIT ".count($GetData['ips']).";"; + $Result_GetIPs = doquery($Query_GetIPs, 'used_ip_and_ua'); + if(mysql_num_rows($Result_GetIPs) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_GetIPs)) + { + $DataArray['ips'][$FetchData['ID']] = array('Value' => $FetchData['Value']); + } + } + } + if(!empty($GetData['fleets'])) + { + $Query_GetFleets = ''; + $Query_GetFleets .= "SELECT `Fleet_ID`, `Fleet_Time_Start`, `Fleet_Calculated_Mission`, `Fleet_TurnedBack` "; + $Query_GetFleets .= "FROM {{table}} WHERE "; + $Query_GetFleets .= "`Fleet_ID` IN (".implode(', ', $GetData['fleets']).") "; + $Query_GetFleets .= "LIMIT ".count($GetData['fleets']).";"; + $Result_GetFleets = doquery($Query_GetFleets, 'fleet_archive'); + if(mysql_num_rows($Result_GetFleets) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_GetFleets)) + { + $DataArray['fleets'][$FetchData['Fleet_ID']] = $FetchData; + } + } + } + + foreach($Rows as $RowData) + { + if(!empty($RowData['Other_Data'])) + { + if($RowData['Code'] == 1) + { + // --- Fleet MultiAcc Detected --- + // Parse User - Alert Sender + if(!isset($DataArray['users'][$RowData['User_ID']]['deleted'])) + { + $RowData['CodeVars'][0] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array + ( + $RowData['User_ID'], $DataArray['users'][$RowData['User_ID']]['username'], $RowData['User_ID'] + )); + } + else + { + $RowData['CodeVars'][0] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array + ( + $RowData['User_ID'] + )); + } + // Parse Mission Type + $RowData['CodeVars'][1] = vsprintf($_Lang['AlertCodes_Texts']['FleetInfo'], array + ( + $_Lang['type_mission'][$RowData['Other_Data']['MissionID']] + )); + // Parse User - Target Owner + if(!isset($DataArray['users'][$RowData['Other_Data']['TargetUserID']]['deleted'])) + { + $RowData['CodeVars'][2] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array + ( + $RowData['Other_Data']['TargetUserID'], $DataArray['users'][$RowData['Other_Data']['TargetUserID']]['username'], $RowData['Other_Data']['TargetUserID'] + )); + } + else + { + $RowData['CodeVars'][2] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array + ( + $RowData['Other_Data']['TargetUserID'] + )); + } + // Parse FleetID + if($RowData['Other_Data']['FleetID'] > 0) + { + $RowData['CodeVars'][3] = vsprintf($_Lang['AlertCodes_Texts']['FleetBlock_NonBlocked_Text'], array + ( + $RowData['Other_Data']['FleetID'] + )); + } + else + { + $RowData['CodeVars'][3] = $_Lang['AlertCodes_Texts']['FleetBlock_Blocked_Text']; + } + // Parse DeclarationID + if(isset($RowData['Other_Data']['DeclarationID']) && $RowData['Other_Data']['DeclarationID'] > 0) + { + $RowData['CodeVars'][4] = vsprintf($_Lang['AlertCodes_Texts']['MultiACCDeclaration_Exists_Text'], array + ( + $RowData['Other_Data']['DeclarationID'] + )); + } + else + { + $RowData['CodeVars'][4] = $_Lang['AlertCodes_Texts']['MultiACCDeclaration_None_Text']; + } + + // Parse IP Intersection + foreach($RowData['Other_Data']['Intersect'] as $ThisIPData) + { + $ThisIPData['TimeMax'] = ($ThisIPData['SenderData']['LastTime'] > $ThisIPData['TargetData']['LastTime'] ? $ThisIPData['SenderData']['LastTime'] : $ThisIPData['TargetData']['LastTime']); + $ThisIPData['TimeMaxDiff'] = $Now - (SERVER_MAINOPEN_TSTAMP + $ThisIPData['TimeMax']); + if($ThisIPData['TimeMaxDiff'] >= (TIME_DAY * 30)) + { + $ThisIPData['TimeMaxDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Big']; + } + else if($ThisIPData['TimeMaxDiff'] >= (TIME_DAY * 1.5)) + { + $ThisIPData['TimeMaxDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Medium']; + } + else + { + $ThisIPData['TimeMaxDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Small']; + } + + $ThisIPData['TimeDiff'] = $ThisIPData['SenderData']['LastTime'] - $ThisIPData['TargetData']['LastTime']; + if($ThisIPData['TimeDiff'] < 0) + { + $ThisIPData['TimeDiff'] *= -1; + } + if($ThisIPData['TimeDiff'] >= (TIME_DAY * 30)) + { + $ThisIPData['TimeDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Big']; + } + else if($ThisIPData['TimeDiff'] >= (TIME_DAY * 1.5)) + { + $ThisIPData['TimeDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Medium']; + } + else + { + $ThisIPData['TimeDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Small']; + } + + // Parse IP Intersection User - Alert Sender + $ThisIPData['SenderData']['LastTimeStamp'] = SERVER_MAINOPEN_TSTAMP + $ThisIPData['SenderData']['LastTime']; + if(!isset($DataArray['users'][$RowData['User_ID']]['deleted'])) + { + $ThisIPData['UsersData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_UserExist'], array + ( + $RowData['User_ID'], $DataArray['users'][$RowData['User_ID']]['username'], $RowData['User_ID'], + prettyNumber($ThisIPData['SenderData']['Count']), prettyDate('d m Y, H:i:s', $ThisIPData['SenderData']['LastTimeStamp'], 1) + )); + } + else + { + $ThisIPData['UsersData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_UserDeleted'], array + ( + $RowData['User_ID'], + prettyNumber($ThisIPData['SenderData']['Count']), prettyDate('d m Y, H:i:s', $ThisIPData['SenderData']['LastTimeStamp'], 1) + )); + } + // Parse IP Intersection User - Target Owner + $ThisIPData['TargetData']['LastTimeStamp'] = SERVER_MAINOPEN_TSTAMP + $ThisIPData['TargetData']['LastTime']; + if(!isset($DataArray['users'][$RowData['Other_Data']['TargetUserID']]['deleted'])) + { + $ThisIPData['UsersData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_UserExist'], array + ( + $RowData['Other_Data']['TargetUserID'], $DataArray['users'][$RowData['Other_Data']['TargetUserID']]['username'], $RowData['Other_Data']['TargetUserID'], + prettyNumber($ThisIPData['TargetData']['Count']), prettyDate('d m Y, H:i:s', $ThisIPData['TargetData']['LastTimeStamp'], 1) + )); + } + else + { + $ThisIPData['UsersData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_UserDeleted'], array + ( + $RowData['Other_Data']['TargetUserID'], + prettyNumber($ThisIPData['TargetData']['Count']), prettyDate('d m Y, H:i:s', $ThisIPData['TargetData']['LastTimeStamp'], 1) + )); + } + // Parse IP Intersection Row + $RowData['IntersectData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_Main'], array + ( + $ThisIPData['IPID'], $DataArray['ips'][$ThisIPData['IPID']]['Value'], $ThisIPData['IPID'], + $ThisIPData['TimeDiff_Color'], pretty_time($ThisIPData['TimeDiff']), + $ThisIPData['TimeMaxDiff_Color'], pretty_time($ThisIPData['TimeMaxDiff']), + implode('
', $ThisIPData['UsersData']) + )); + } + $RowData['CodeVars'][5] = implode('
', $RowData['IntersectData']); + // Parse Other Users + if(!empty($RowData['Other_Data']['OtherUsers'])) + { + foreach($RowData['Other_Data']['OtherUsers'] as $ThisUserID) + { + if(!isset($DataArray['users'][$ThisUserID]['deleted'])) + { + $RowData['CodeVars'][7][] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array + ( + $ThisUserID, $DataArray['users'][$ThisUserID]['username'], $ThisUserID + )); + } + else + { + $RowData['CodeVars'][7][] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array + ( + $ThisUserID, + )); + } + } + $RowData['CodeVars'][6] = vsprintf($_Lang['AlertCodes_Texts']['OtherUsers_Count'], array + ( + prettyNumber(count($RowData['CodeVars'][7])) + )); + $RowData['CodeVars'][7] = implode(', ', $RowData['CodeVars'][7]); + } + else + { + $RowData['CodeVars'][6] = ''; + $RowData['CodeVars'][7] = $_Lang['AlertCodes_Texts']['OtherUsers_None']; + } + } + else if($RowData['Code'] == 2) + { + // --- Register MultiAcc Detected --- + // Include Tasks Lang + if(!isset($_Included_TasksLang)) + { + includeLang('tasks'); + $_Included_TasksLang = true; + } + // Parse User - New User + if(!isset($DataArray['users'][$RowData['User_ID']]['deleted'])) + { + $RowData['CodeVars'][0] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array + ( + $RowData['User_ID'], $DataArray['users'][$RowData['User_ID']]['username'], $RowData['User_ID'] + )); + } + else + { + $RowData['CodeVars'][0] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array + ( + $RowData['User_ID'] + )); + } + // Parse User - Referrer User + if(!isset($DataArray['users'][$RowData['Other_Data']['ReferrerID']]['deleted'])) + { + $RowData['CodeVars'][1] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array + ( + $RowData['Other_Data']['ReferrerID'], $DataArray['users'][$RowData['Other_Data']['ReferrerID']]['username'], $RowData['Other_Data']['ReferrerID'] + )); + } + else + { + $RowData['CodeVars'][1] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array + ( + $RowData['Other_Data']['ReferrerID'] + )); + } + + // Parse Tasks Data + if(!empty($RowData['Other_Data']['Tasks'])) + { + foreach($RowData['Other_Data']['Tasks'] as $ThisData) + { + $RowData['CodeVars'][2][] = vsprintf($_Lang['AlertCodes_Texts']['TaskData'], array + ( + $_Lang['Tasks'][$ThisData['TaskID']]['name'], $ThisData['TaskID'], + ($ThisData['TaskStatus'] >= $ThisData['TaskLimit'] ? $_Lang['AlertCodes_Texts']['TaskData_StatusDone'] : $_Lang['AlertCodes_Texts']['TaskData_StatusNotDone']), + $ThisData['TaskStatus'], $ThisData['TaskLimit'] + )); + } + $RowData['CodeVars'][2] = implode('
', $RowData['CodeVars'][2]); + } + else + { + $RowData['CodeVars'][2] = $_Lang['AlertCodes_Texts']['NewUser_NoTasks']; + } + + // Parse IP Intersection + foreach($RowData['Other_Data']['Intersect'] as $ThisIPData) + { + $ThisIPData['TimeMax'] = ($ThisIPData['NewUser']['LastTime'] > $ThisIPData['OldUser']['LastTime'] ? $ThisIPData['NewUser']['LastTime'] : $ThisIPData['OldUser']['LastTime']); + $ThisIPData['TimeMaxDiff'] = $Now - (SERVER_MAINOPEN_TSTAMP + $ThisIPData['TimeMax']); + if($ThisIPData['TimeMaxDiff'] >= (TIME_DAY * 30)) + { + $ThisIPData['TimeMaxDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Big']; + } + else if($ThisIPData['TimeMaxDiff'] >= (TIME_DAY * 1.5)) + { + $ThisIPData['TimeMaxDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Medium']; + } + else + { + $ThisIPData['TimeMaxDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Small']; + } + + $ThisIPData['TimeDiff'] = $ThisIPData['NewUser']['LastTime'] - $ThisIPData['OldUser']['LastTime']; + if($ThisIPData['TimeDiff'] < 0) + { + $ThisIPData['TimeDiff'] *= -1; + } + if($ThisIPData['TimeDiff'] >= (TIME_DAY * 30)) + { + $ThisIPData['TimeDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Big']; + } + else if($ThisIPData['TimeDiff'] >= (TIME_DAY * 1.5)) + { + $ThisIPData['TimeDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Medium']; + } + else + { + $ThisIPData['TimeDiff_Color'] = $_Lang['AlertCodes_Texts']['IPIntersect_TimeDiff_Small']; + } + + // Parse IP Intersection User - New User + $ThisIPData['NewUser']['LastTimeStamp'] = SERVER_MAINOPEN_TSTAMP + $ThisIPData['NewUser']['LastTime']; + if(!isset($DataArray['users'][$RowData['User_ID']]['deleted'])) + { + $ThisIPData['UsersData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_UserExist'], array + ( + $RowData['User_ID'], $DataArray['users'][$RowData['User_ID']]['username'], $RowData['User_ID'], + prettyNumber($ThisIPData['NewUser']['Count']), prettyDate('d m Y, H:i:s', $ThisIPData['NewUser']['LastTimeStamp'], 1) + )); + } + else + { + $ThisIPData['UsersData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_UserDeleted'], array + ( + $RowData['User_ID'], + prettyNumber($ThisIPData['NewUser']['Count']), prettyDate('d m Y, H:i:s', $ThisIPData['NewUser']['LastTimeStamp'], 1) + )); + } + // Parse IP Intersection User - Referrer User + $ThisIPData['OldUser']['LastTimeStamp'] = SERVER_MAINOPEN_TSTAMP + $ThisIPData['OldUser']['LastTime']; + if(!isset($DataArray['users'][$RowData['Other_Data']['ReferrerID']]['deleted'])) + { + $ThisIPData['UsersData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_UserExist'], array + ( + $RowData['Other_Data']['ReferrerID'], $DataArray['users'][$RowData['Other_Data']['ReferrerID']]['username'], $RowData['Other_Data']['ReferrerID'], + prettyNumber($ThisIPData['OldUser']['Count']), prettyDate('d m Y, H:i:s', $ThisIPData['OldUser']['LastTimeStamp'], 1) + )); + } + else + { + $ThisIPData['UsersData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_UserDeleted'], array + ( + $RowData['Other_Data']['ReferrerID'], + prettyNumber($ThisIPData['OldUser']['Count']), prettyDate('d m Y, H:i:s', $ThisIPData['OldUser']['LastTimeStamp'], 1) + )); + } + // Parse IP Intersection Row + $RowData['IntersectData'][] = vsprintf($_Lang['AlertCodes_Texts']['IPIntersect_Main'], array + ( + $ThisIPData['IPID'], $DataArray['ips'][$ThisIPData['IPID']]['Value'], $ThisIPData['IPID'], + $ThisIPData['TimeDiff_Color'], pretty_time($ThisIPData['TimeDiff']), + $ThisIPData['TimeMaxDiff_Color'], pretty_time($ThisIPData['TimeMaxDiff']), + implode('
', $ThisIPData['UsersData']) + )); + } + $RowData['CodeVars'][3] = implode('
', $RowData['IntersectData']); + + // Parse Other Users + if(!empty($RowData['Other_Data']['OtherUsers'])) + { + foreach($RowData['Other_Data']['OtherUsers'] as $ThisUserID) + { + if(!isset($DataArray['users'][$ThisUserID]['deleted'])) + { + $RowData['CodeVars'][5][] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array + ( + $ThisUserID, $DataArray['users'][$ThisUserID]['username'], $ThisUserID + )); + } + else + { + $RowData['CodeVars'][5][] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array + ( + $ThisUserID, + )); + } + } + $RowData['CodeVars'][4] = vsprintf($_Lang['AlertCodes_Texts']['OtherUsers_Count'], array + ( + prettyNumber(count($RowData['CodeVars'][5])) + )); + $RowData['CodeVars'][5] = implode(', ', $RowData['CodeVars'][5]); + } + else + { + $RowData['CodeVars'][4] = ''; + $RowData['CodeVars'][5] = $_Lang['AlertCodes_Texts']['OtherUsers_None']; + } + } + else if($RowData['Code'] == 3) + { + // --- Register with Proxy Detected --- + // Parse User - New User + if(!isset($DataArray['users'][$RowData['User_ID']]['deleted'])) + { + $RowData['CodeVars'][0] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array + ( + $RowData['User_ID'], $DataArray['users'][$RowData['User_ID']]['username'], $RowData['User_ID'] + )); + } + else + { + $RowData['CodeVars'][0] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array + ( + $RowData['User_ID'] + )); + } + // Parse IP + $RowData['CodeVars'][1] = vsprintf($_Lang['AlertCodes_Texts']['NewUser_IPProxy'], array + ( + $RowData['Other_Data']['IPID'], $DataArray['ips'][$RowData['Other_Data']['IPID']]['Value'], $RowData['Other_Data']['IPID'], + ($RowData['Other_Data']['RegIP'] ? $_Lang['AlertCodes_Texts']['NewUser_IPProxy_RegIP'] : $_Lang['AlertCodes_Texts']['NewUser_IPProxy_NoRegIP']) + )); + } + else if($RowData['Code'] == 4) + { + // --- ResourcePush Detected --- + // Parse User - Alert Sender + if(!isset($DataArray['users'][$RowData['User_ID']]['deleted'])) + { + $RowData['CodeVars'][0] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array + ( + $RowData['User_ID'], $DataArray['users'][$RowData['User_ID']]['username'], $RowData['User_ID'] + )); + } + else + { + $RowData['CodeVars'][0] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array + ( + $RowData['User_ID'] + )); + } + // Parse User - Target Owner + if(!isset($DataArray['users'][$RowData['Other_Data']['TargetUserID']]['deleted'])) + { + $RowData['CodeVars'][1] = vsprintf($_Lang['AlertCodes_Texts']['UserLink'], array + ( + $RowData['Other_Data']['TargetUserID'], $DataArray['users'][$RowData['Other_Data']['TargetUserID']]['username'], $RowData['Other_Data']['TargetUserID'] + )); + } + else + { + $RowData['CodeVars'][1] = vsprintf($_Lang['AlertCodes_Texts']['DeletedUserID'], array + ( + $RowData['Other_Data']['TargetUserID'] + )); + } + // Parse Users Acquaintance + if($RowData['Other_Data']['SameAlly'] > 0) + { + if(!isset($DataArray['allys'][$RowData['Other_Data']['SameAlly']]['deleted'])) + { + $RowData['CodeVars'][2][0] = vsprintf($_Lang['AlertCodes_Texts']['AllyLink'], array + ( + $DataArray['allys'][$RowData['Other_Data']['SameAlly']]['ally_name'], + $DataArray['allys'][$RowData['Other_Data']['SameAlly']]['ally_tag'], + $RowData['Other_Data']['SameAlly'] + )); + } + else + { + $RowData['CodeVars'][2][0] = vsprintf($_Lang['AlertCodes_Texts']['DeletedAllyID'], array + ( + $RowData['Other_Data']['SameAlly'] + )); + } + $RowData['CodeVars'][2][0] = vsprintf($_Lang['AlertCodes_Texts']['PushAlert_UsersInAlly'], $RowData['CodeVars'][2][0]); + } + else if(!empty($RowData['Other_Data']['AllyPact'])) + { + if(!isset($DataArray['allys'][$RowData['Other_Data']['AllyPact']['SenderAlly']]['deleted'])) + { + $RowData['CodeVars'][2][1][] = vsprintf($_Lang['AlertCodes_Texts']['AllyLink'], array + ( + $DataArray['allys'][$RowData['Other_Data']['AllyPact']['SenderAlly']]['ally_name'], + $DataArray['allys'][$RowData['Other_Data']['AllyPact']['SenderAlly']]['ally_tag'], + $RowData['Other_Data']['AllyPact']['SenderAlly'] + )); + } + else + { + $RowData['CodeVars'][2][1][] = vsprintf($_Lang['AlertCodes_Texts']['DeletedAllyID'], array + ( + $RowData['Other_Data']['AllyPact']['SenderAlly'] + )); + } + if(!isset($DataArray['allys'][$RowData['Other_Data']['AllyPact']['TargetAlly']]['deleted'])) + { + $RowData['CodeVars'][2][1][] = vsprintf($_Lang['AlertCodes_Texts']['AllyLink'], array + ( + $DataArray['allys'][$RowData['Other_Data']['AllyPact']['TargetAlly']]['ally_name'], + $DataArray['allys'][$RowData['Other_Data']['AllyPact']['TargetAlly']]['ally_tag'], + $RowData['Other_Data']['AllyPact']['TargetAlly'] + )); + } + else + { + $RowData['CodeVars'][2][1][] = vsprintf($_Lang['AlertCodes_Texts']['DeletedAllyID'], array + ( + $RowData['Other_Data']['AllyPact']['TargetAlly'] + )); + } + $RowData['CodeVars'][2][1] = vsprintf($_Lang['AlertCodes_Texts']['PushAlert_UsersHasPact'], $RowData['CodeVars'][2][1]); + } + if($RowData['Other_Data']['BuddyFriends'] === true) + { + $RowData['CodeVars'][2][2] = $_Lang['AlertCodes_Texts']['PushAlert_UsersAreBuddy']; + } + if(!empty($RowData['CodeVars'][2])) + { + $RowData['CodeVars'][2] = implode(', ', $RowData['CodeVars'][2]); + } + else + { + $RowData['CodeVars'][2] = $_Lang['AlertCodes_Texts']['PushAlert_UsersDontKnowEachother']; + } + // Parse User Stats Difference + $RowData['CodeVars'][3] = prettyNumber($RowData['Other_Data']['Stats']['Target']['Points'] - $RowData['Other_Data']['Stats']['Sender']['Points']); + if($RowData['Other_Data']['Stats']['Sender']['Points'] > 0) + { + $RowData['CodeVars'][4] = prettyNumber(($RowData['Other_Data']['Stats']['Target']['Points'] / $RowData['Other_Data']['Stats']['Sender']['Points']) * 100); + } + else + { + $RowData['CodeVars'][4] = '∞'; + } + $RowData['CodeVars'][5] = prettyNumber($RowData['Other_Data']['Stats']['Sender']['Position'] - $RowData['Other_Data']['Stats']['Target']['Position']); + // Parse Users StatsInfo + if(!isset($DataArray['users'][$RowData['User_ID']]['deleted'])) + { + $RowData['CodeVars'][6] = vsprintf($_Lang['AlertCodes_Texts']['PushAlert_UserExist'], array + ( + $RowData['User_ID'], $DataArray['users'][$RowData['User_ID']]['username'], $RowData['User_ID'], + prettyNumber($RowData['Other_Data']['Stats']['Sender']['Points']), + prettyNumber($RowData['Other_Data']['Stats']['Sender']['Position']) + )); + } + else + { + $RowData['CodeVars'][6] = vsprintf($_Lang['AlertCodes_Texts']['PushAlert_UserDeleted'], array + ( + $RowData['User_ID'], + prettyNumber($RowData['Other_Data']['Stats']['Sender']['Points']), + prettyNumber($RowData['Other_Data']['Stats']['Sender']['Position']) + )); + } + if(!isset($DataArray['users'][$RowData['Other_Data']['TargetUserID']]['deleted'])) + { + $RowData['CodeVars'][7] = vsprintf($_Lang['AlertCodes_Texts']['PushAlert_UserExist'], array + ( + $RowData['Other_Data']['TargetUserID'], $DataArray['users'][$RowData['Other_Data']['TargetUserID']]['username'], $RowData['Other_Data']['TargetUserID'], + prettyNumber($RowData['Other_Data']['Stats']['Target']['Points']), + prettyNumber($RowData['Other_Data']['Stats']['Target']['Position']) + )); + } + else + { + $RowData['CodeVars'][7] = vsprintf($_Lang['AlertCodes_Texts']['PushAlert_UserDeleted'], array + ( + $RowData['Other_Data']['TargetUserID'], + prettyNumber($RowData['Other_Data']['Stats']['Target']['Points']), + prettyNumber($RowData['Other_Data']['Stats']['Target']['Position']) + )); + } + // Parse FleetID + if($DataArray['fleets'][$RowData['Other_Data']['FleetID']]['Fleet_Calculated_Mission'] == 1) + { + $RowData['CodeVars'][8] = $_Lang['AlertCodes_Texts']['PushAlert_FleetState_Delivered']; + } + else if($DataArray['fleets'][$RowData['Other_Data']['FleetID']]['Fleet_Time_Start'] <= $Now) + { + $RowData['CodeVars'][8] = $_Lang['AlertCodes_Texts']['PushAlert_FleetState_GoalAchieved']; + } + else if($DataArray['fleets'][$RowData['Other_Data']['FleetID']]['Fleet_TurnedBack']) + { + $RowData['CodeVars'][8] = $_Lang['AlertCodes_Texts']['PushAlert_FleetState_TurnedBack']; + } + else + { + $RowData['CodeVars'][8] = sprintf($_Lang['AlertCodes_Texts']['PushAlert_FleetState_Flying'], pretty_time($DataArray['fleets'][$RowData['Other_Data']['FleetID']]['Fleet_Time_Start'] - $Now)); + } + $RowData['CodeVars'][9] = $RowData['Other_Data']['FleetID']; + // Parse Resources + foreach($RowData['Other_Data']['Resources'] as $ThisKey => $ThisValue) + { + if($ThisValue > 0) + { + $RowData['CodeVars'][10][] = vsprintf($_Lang['AlertCodes_Texts']['PushAlert_ResourceLine'], array + ( + $_Lang['AlertCodes_Texts']['PushAlert_Res_'.$ThisKey], prettyNumber($ThisValue) + )); + } + } + $RowData['CodeVars'][10] = implode('
', $RowData['CodeVars'][10]); + } + ksort($RowData['CodeVars']); + $RowData['Data'] = vsprintf($_Lang['AlertCodes'][$RowData['Code']], $RowData['CodeVars']); + } + else + { + $RowData['Data'] = ' '; + } + + $Parse['Rows'] .= parsetemplate($RowsTPL, $RowData); + } +} +else +{ + if($CurrentPage > 1 AND $_TotalCount > 0) + { + $ThisWarning = $_Lang['No_Alerts_ThisPage']; + } + else + { + $ThisWarning = $_Lang['No_Alerts']; + } + $Parse['Rows'] = ''.$ThisWarning.''; +} + +$Page = parsetemplate($PageTPL, $Parse); +display($Page, $PageTitle, false, true); + +?> diff --git a/admin/autogziplogs.php b/admin/autogziplogs.php index bb47842bb..ff65194b0 100644 --- a/admin/autogziplogs.php +++ b/admin/autogziplogs.php @@ -1,125 +1,125 @@ - 0 AND CheckAuth('programmer')) || ((!isset($_User['id']) || $_User['id'] <= 0) && md5($_GET['pass']) == AUTOTOOL_ZIPLOGS_PASSWORDHASH))) - { - AdminMessage($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); - } - - $FilesZipped = 0; - $StartTime = microtime(true); - - $TodayDate = date('Y_m_d', mktime(0, 0, 1) - (12 * TIME_HOUR)); - $TodayLogsDir = 'logs_'.$TodayDate; - // First, GZIP all game Logs and then move them to proper directory - $DirArray = false; - if(file_exists('../action_logs/')) - { - $DirsCompressed[] = 'action_logs'; - $DirList = scandir('../action_logs/'); - - foreach($DirList as $FileName) - { - if($FileName != '.' AND $FileName != '..' AND $FileName != $TodayLogsDir AND strstr($FileName, '.php') === FALSE) - { - $DirArray[] = $FileName; - } - } - - if(!empty($DirArray)) - { - if(!file_exists('../action_logs/'.$TodayLogsDir)) - { - mkdir('../action_logs/'.$TodayLogsDir); - } - foreach($DirArray as $UserID) - { - $PlainFilename = 'Log_U_'.$UserID.'_D_'.$TodayDate.'.php'; - $FileName = '../action_logs/'.$UserID.'/Log_U_'.$UserID.'_D_'.$TodayDate.'.php'; - if(file_exists($FileName)) - { - // Get FileData - $fp = fopen($FileName, 'r'); - $data = fread ($fp, filesize($FileName)); - fclose($fp); - // Create Archive - $zp = gzopen($FileName.'.gz', 'w9'); - gzwrite($zp, $data); - gzclose($zp); - // Delete OldFile - unlink($FileName); - // Move new file to proper directory (today logs dir) - rename($FileName.'.gz', '../action_logs/'.$TodayLogsDir.'/'.$PlainFilename.'.gz'); - // Increase Counter - $FilesZipped += 1; - } - } - } - } - // Second, GZIP all Admin Logs - $DirArray = false; - if(file_exists('./action_logs/')) - { - $DirsCompressed[] = 'admin/action_logs'; - $DirList = scandir('./action_logs/'); - - foreach($DirList as $FileName) - { - if($FileName != '.' AND $FileName != '..' AND strstr($FileName, '.php') === FALSE) - { - $DirArray[] = $FileName; - } - } - - if(!empty($DirArray)) - { - if(!file_exists('./action_logs/'.$TodayLogsDir)) - { - mkdir('./action_logs/'.$TodayLogsDir); - } - foreach($DirArray as $UserID) - { - $PlainFilename = 'Log_U_'.$UserID.'_D_'.$TodayDate.'.php'; - $FileName = './action_logs/'.$UserID.'/Log_U_'.$UserID.'_D_'.$TodayDate.'.php'; - if(file_exists($FileName)) - { - // Get FileData - $fp = fopen($FileName, 'r'); - $data = fread ($fp, filesize($FileName)); - fclose($fp); - // Create Archive - $zp = gzopen($FileName.'.gz', 'w9'); - gzwrite($zp, $data); - gzclose($zp); - // Delete OldFile - unlink($FileName); - // Move new file to proper directory (today logs dir) - rename($FileName.'.gz', './action_logs/'.$TodayLogsDir.'/'.$PlainFilename.'.gz'); - // Increase Counter - $FilesZipped += 1; - } - } - } - } - - $EndTime = microtime(true); - - if(empty($DirsCompressed)) - { - $DirsCompressed[] = $_Lang['AutoGZipLogs_NoDirs']; - } - - AdminMessage(sprintf($_Lang['AutoGZipLogs_Success'], $FilesZipped, sprintf('%0.6f', $EndTime - $StartTime), implode(', ', $DirsCompressed)), $_Lang['AutoGZipLogs_Title']); - -?> \ No newline at end of file + 0 AND CheckAuth('programmer')) || ((!isset($_User['id']) || $_User['id'] <= 0) && md5($_GET['pass']) == AUTOTOOL_ZIPLOGS_PASSWORDHASH))) +{ + AdminMessage($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); +} + +$FilesZipped = 0; +$StartTime = microtime(true); + +$TodayDate = date('Y_m_d', mktime(0, 0, 1) - (12 * TIME_HOUR)); +$TodayLogsDir = 'logs_'.$TodayDate; +// First, GZIP all game Logs and then move them to proper directory +$DirArray = false; +if(file_exists('../action_logs/')) +{ + $DirsCompressed[] = 'action_logs'; + $DirList = scandir('../action_logs/'); + + foreach($DirList as $FileName) + { + if($FileName != '.' AND $FileName != '..' AND $FileName != $TodayLogsDir AND strstr($FileName, '.php') === FALSE) + { + $DirArray[] = $FileName; + } + } + + if(!empty($DirArray)) + { + if(!file_exists('../action_logs/'.$TodayLogsDir)) + { + mkdir('../action_logs/'.$TodayLogsDir); + } + foreach($DirArray as $UserID) + { + $PlainFilename = 'Log_U_'.$UserID.'_D_'.$TodayDate.'.php'; + $FileName = '../action_logs/'.$UserID.'/Log_U_'.$UserID.'_D_'.$TodayDate.'.php'; + if(file_exists($FileName)) + { + // Get FileData + $fp = fopen($FileName, 'r'); + $data = fread ($fp, filesize($FileName)); + fclose($fp); + // Create Archive + $zp = gzopen($FileName.'.gz', 'w9'); + gzwrite($zp, $data); + gzclose($zp); + // Delete OldFile + unlink($FileName); + // Move new file to proper directory (today logs dir) + rename($FileName.'.gz', '../action_logs/'.$TodayLogsDir.'/'.$PlainFilename.'.gz'); + // Increase Counter + $FilesZipped += 1; + } + } + } +} +// Second, GZIP all Admin Logs +$DirArray = false; +if(file_exists('./action_logs/')) +{ + $DirsCompressed[] = 'admin/action_logs'; + $DirList = scandir('./action_logs/'); + + foreach($DirList as $FileName) + { + if($FileName != '.' AND $FileName != '..' AND strstr($FileName, '.php') === FALSE) + { + $DirArray[] = $FileName; + } + } + + if(!empty($DirArray)) + { + if(!file_exists('./action_logs/'.$TodayLogsDir)) + { + mkdir('./action_logs/'.$TodayLogsDir); + } + foreach($DirArray as $UserID) + { + $PlainFilename = 'Log_U_'.$UserID.'_D_'.$TodayDate.'.php'; + $FileName = './action_logs/'.$UserID.'/Log_U_'.$UserID.'_D_'.$TodayDate.'.php'; + if(file_exists($FileName)) + { + // Get FileData + $fp = fopen($FileName, 'r'); + $data = fread ($fp, filesize($FileName)); + fclose($fp); + // Create Archive + $zp = gzopen($FileName.'.gz', 'w9'); + gzwrite($zp, $data); + gzclose($zp); + // Delete OldFile + unlink($FileName); + // Move new file to proper directory (today logs dir) + rename($FileName.'.gz', './action_logs/'.$TodayLogsDir.'/'.$PlainFilename.'.gz'); + // Increase Counter + $FilesZipped += 1; + } + } + } +} + +$EndTime = microtime(true); + +if(empty($DirsCompressed)) +{ + $DirsCompressed[] = $_Lang['AutoGZipLogs_NoDirs']; +} + +AdminMessage(sprintf($_Lang['AutoGZipLogs_Success'], $FilesZipped, sprintf('%0.6f', $EndTime - $StartTime), implode(', ', $DirsCompressed)), $_Lang['AutoGZipLogs_Title']); + +?> diff --git a/admin/autostatbuilder.php b/admin/autostatbuilder.php index 61bacc213..b48746c8d 100644 --- a/admin/autostatbuilder.php +++ b/admin/autostatbuilder.php @@ -1,1017 +1,1017 @@ -showSimpleCountSwitch(); - $Bench->echoTableSwitch(); - - // Load StatFunctions - include($_EnginePath.'admin/autostatbuilder_functions.php'); - - // Init Time - $StatDate = time(); - includeLang('admin'); - includeLang('admin/autostatbuilder'); - - if(!((isset($_User['id']) && $_User['id'] > 0 AND CheckAuth('programmer')) || ((!isset($_User['id']) || $_User['id'] <= 0) && md5($_GET['pass']) == AUTOTOOL_STATBUILDER_PASSWORDHASH))) - { - AdminMessage($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); - } - - $CounterNames[] = 'Init & Delete old stats'; - $Bench->simpleCountStart(); - - // Initialization - $StartTime = microtime(true); - - $Users = array(); - $Allys = array(); - - $UsersBuilds = array(); - $UsersDefs = array(); - $UsersFleets = array(); - $UsersTech = array(); - $UsersTotal = array(); - - $AllysBuilds = array(); - $AllysDefs = array(); - $AllysFleets = array(); - $AllysTech = array(); - $AllysTotal = array(); - $DailyStatsDiff = $StatDate - $_GameConfig['last_stats_daily']; - $Loop = 0; - - $ForceDailyStats = (isset($_GET['force_yesterday']) && $_GET['force_yesterday'] == 'true' ? true : false); - $ShowOutput = (isset($_User['id']) && $_User['id'] > 0 ? true : false); - //END-OF-Initialization - - /////////// USERS /////////// - - // Techs needen fields - foreach($_Vars_ElementCategories['tech'] as $ID) - { - if(!empty($_Vars_GameElements[$ID])) - { - $CreateTechFieldsList[] = "`user`.`{$_Vars_GameElements[$ID]}`"; - } - } - // Planet needen fields - $CreatePlanetFieldsList[] = 'id'; - $CreatePlanetFieldsList[] = 'id_owner'; - foreach($_Vars_ElementCategories as $ResType => $ResLists) - { - if($ResType != 'build' AND $ResType != 'defense' AND $ResType != 'fleet') - { - continue; - } - foreach($ResLists as $ID) - { - $CreatePlanetFieldsList[] = "`{$_Vars_GameElements[$ID]}`"; - } - } - - // Needen fields - $CreateFleetFieldsList = "`fleet_owner`, `fleet_array`"; - $CreateStatFieldsList = "`id_owner`, `total_rank`, `tech_rank`, `build_rank`, `defs_rank`, `fleet_rank`, `tech_yesterday_rank`, `build_yesterday_rank`, `defs_yesterday_rank`, `fleet_yesterday_rank`, `total_yesterday_rank`"; - $CreateTechFieldsList = implode(', ', $CreateTechFieldsList); - $CreatePlanetFieldsList = implode(', ', $CreatePlanetFieldsList); - $UserNeedenFields = "`user`.`id`, `user`.`username`, `user`.`ally_id`, `is_ondeletion`, `deletion_endtime`, `pro_time`, `is_onvacation`, `vacation_endtime`, `is_banned`, `ban_endtime`, {$CreateTechFieldsList}"; - - $Bench->simpleCountStop(); - $CounterNames[] = 'User Stats Select'; - $Bench->simpleCountStart(); - - $CounterNames[] = '> Getting UsersData'; - $Bench->simpleCountStart(); - $GameUsers = doquery("SELECT {$UserNeedenFields} FROM {{table}} as `user` WHERE `user`.`authlevel` = 0 ORDER BY `user`.`id` ASC;", 'users'); - if(mysql_num_rows($GameUsers) <= 0) - { - AdminMessage('No Users Found', 'StatBuilder'); - } - - $Bench->simpleCountStop(); - $CounterNames[] = '> Getting StatPoints'; - $Bench->simpleCountStart(); - $UsersStats = doquery("SELECT {$CreateStatFieldsList} FROM {{table}} WHERE `stat_type` = 1;", 'statpoints'); - - $Bench->simpleCountStop(); - $CounterNames[] = '> Getting PlanetsData'; - $Bench->simpleCountStart(); - $AllPlanets = doquery("SELECT {$CreatePlanetFieldsList} FROM {{table}};", 'planets'); - - $Bench->simpleCountStop(); - $CounterNames[] = '> Getting FleetsData'; - $Bench->simpleCountStart(); - $AllFleets= doquery("SELECT {$CreateFleetFieldsList} FROM {{table}};", 'fleets'); - - $Bench->simpleCountStop(); - $CounterNames[] = '> Parsing PlanetsData'; - $Bench->simpleCountStart(); - while($PlanetsData = mysql_fetch_array($AllPlanets, MYSQL_ASSOC)) - { - $Planets[$PlanetsData['id_owner']][] = $PlanetsData; - } - - $Bench->simpleCountStop(); - $CounterNames[] = '> Parsing FleetsData'; - $Bench->simpleCountStart(); - while($FleetsData = mysql_fetch_array($AllFleets, MYSQL_ASSOC)) - { - $Fleets[$FleetsData['fleet_owner']][] = $FleetsData; - } - - $Bench->simpleCountStop(); - $CounterNames[] = '> Parsing StatsData'; - $Bench->simpleCountStart(); - while($StatsData = mysql_fetch_array($UsersStats, MYSQL_ASSOC)) - { - $Stats[$StatsData['id_owner']] = $StatsData; - } - $Bench->simpleCountStop(); - - $Bench->simpleCountStop(); - $CounterNames[] = 'User Stats Calculation'; - $Bench->simpleCountStart(); - - $OnlyOnce = true; - - while($CurUser = mysql_fetch_array($GameUsers, MYSQL_ASSOC)) - { - // Delete User with DeletionRequest - if($CurUser['is_ondeletion'] == 1 AND $CurUser['deletion_endtime'] < $StatDate) - { - $UsersToDelete[] = $CurUser['id']; - continue; - } - if(!empty($CurUser['activation_code'])) - { - continue; - } - - // Remove "too long" Vacation Users - if(isOnVacation($CurUser) AND $CurUser['vacation_endtime'] != 0 AND $CurUser['vacation_endtime'] < $StatDate) - { - $UsersToRemoveVacations[] = $CurUser['id']; - } - - // Remove elapsed Bans - if($CurUser['is_banned'] == 1 AND $CurUser['ban_endtime'] < $StatDate) - { - $UsersToRemoveBan[] = $CurUser['id']; - } - - if($OnlyOnce) - { - $CounterNames[] = '> Set OldData'; - $Bench->simpleCountStart(); - } - $CurrentUserDefense = array(); - $CurrentUserFleet = array(); - - if(!isset($Stats[$CurUser['id']])) - { - $OldTotalRank = 0; - $OldTechRank = 0; - $OldBuildRank = 0; - $OldDefsRank = 0; - $OldFleetRank = 0; - } - else - { - $OldTotalRank = $Stats[$CurUser['id']]['total_rank']; - $OldTechRank = $Stats[$CurUser['id']]['tech_rank']; - $OldBuildRank = $Stats[$CurUser['id']]['build_rank']; - $OldDefsRank = $Stats[$CurUser['id']]['defs_rank']; - $OldFleetRank = $Stats[$CurUser['id']]['fleet_rank']; - } - - if($OnlyOnce) - { - $Bench->simpleCountStop(); - $CounterNames[] = '> Calc TechnoPoints'; - $Bench->simpleCountStart(); - } - - $Points = GetTechnoPoints($CurUser); - $TTechCount = $Points['TechCount']; - $TTechPoints = ($Points['TechPoint'] / $_GameConfig['stat_settings']); - - // Get Tech Records - if($Points['TechCount'] > 0) - { - foreach($Points['TechArr'] as $TechID => $Level) - { - if(!isset($TechRecords[$TechID]['lvl']) || $Level > $TechRecords[$TechID]['lvl']) - { - $TechRecords[$TechID] = array('lvl' => $Level, 'user' => $CurUser['id']); - } - } - } - - $TBuildCount = 0; - $TBuildPoints = 0; - $TDefsCount = 0; - $TDefsPoints = 0; - $TFleetCount = 0; - $TFleetPoints = 0; - $GCount = $TTechCount; - $GPoints = $TTechPoints; - - if($OnlyOnce) - { - $Bench->simpleCountStop(); - $CounterNames[] = '> Calc Planets Points'; - $Bench->simpleCountStart(); - } - - if(!empty($Planets[$CurUser['id']])) - { - foreach($Planets[$CurUser['id']] as $PlanetKey => $CurPlanet) - { - if($CurPlanet['id'] > 0) - { - // Calculate BuildingPoints - $Points = GetBuildPoints($CurPlanet); - $TBuildCount += $Points['BuildCount']; - $GCount += $Points['BuildCount']; - $PlanetPoints = ($Points['BuildPoint'] / $_GameConfig['stat_settings']); - $TBuildPoints += $PlanetPoints; - if($Points['BuildCount'] > 0) - { - foreach($Points['BuildArr'] as $ID => $Level) - { - if(!isset($BuildingRecords[$ID]['lvl']) || $Level > $BuildingRecords[$ID]['lvl']) - { - $BuildingRecords[$ID] = array('lvl' => $Level, 'user' => $CurUser['id']); - } - } - } - - // Calculate DefensePoints - $Points = GetDefensePoints($CurPlanet); - $TDefsCount += $Points['DefenseCount']; - $GCount += $Points['DefenseCount']; - $DefsPoints = ($Points['DefensePoint'] / $_GameConfig['stat_settings']); - $PlanetPoints += $DefsPoints; - $TDefsPoints += $DefsPoints; - if($Points['DefenseCount'] > 0) - { - foreach($Points['DefenseArr'] as $ID => $Count) - { - if(!isset($CurrentUserDefense[$ID])) - { - $CurrentUserDefense[$ID] = 0; - } - $CurrentUserDefense[$ID] += $Count; - } - } - - // Calculate FleetPoints (on Planet) - $Points = GetFleetPoints($CurPlanet); - $TFleetCount += $Points['FleetCount']; - $GCount += $Points['FleetCount']; - $FleetsPoints = ($Points['FleetPoint'] / $_GameConfig['stat_settings']); - $PlanetPoints += $FleetsPoints; - $TFleetPoints += $FleetsPoints; - if($Points['FleetCount'] > 0) - { - foreach($Points['FleetArr'] as $ID => $Count) - { - if(!isset($CurrentUserFleet[$ID])) - { - $CurrentUserFleet[$ID] = 0; - } - $CurrentUserFleet[$ID] += $Count; - } - } - $GPoints += $PlanetPoints; - - if($PlanetPoints == 0) - { - $PlanetPoints = '0'; - } - $PlanetsUpdate[] = '('.$CurPlanet['id'].', '.$PlanetPoints.')'; - } - unset($Planets[$CurUser['id']][$PlanetKey]); - } - - if(!empty($CurrentUserDefense)) - { - foreach($CurrentUserDefense as $ID => $Count) - { - if(!isset($DefenseRecords[$ID]['count']) || $Count > $DefenseRecords[$ID]['count']) - { - $DefenseRecords[$ID] = array('count' => $Count, 'user' => $CurUser['id']); - } - } - } - } - - if($OnlyOnce) - { - $Bench->simpleCountStop(); - $CounterNames[] = '> Calc FleetInFlight Points'; - $Bench->simpleCountStart(); - } - - if(!empty($Fleets[$CurUser['id']])) - { - foreach($Fleets[$CurUser['id']] as $FleetKey => $CurFleet) - { - $Points = GetFleetPointsOnTour($CurFleet['fleet_array']); - $TFleetCount += $Points['FleetCount']; - $GCount += $Points['FleetCount']; - $FleetsPoints = ($Points['FleetPoint'] / $_GameConfig['stat_settings']); - $TFleetPoints += $FleetsPoints; - $GPoints += $FleetsPoints; - if($Points['FleetCount'] > 0) - { - foreach($Points['FleetArr'] as $ID => $Count) - { - if(!isset($CurrentUserFleet[$ID])) - { - $CurrentUserFleet[$ID] = 0; - } - $CurrentUserFleet[$ID] += $Count; - } - } - - unset($Fleets[$CurUser['id']][$FleetKey]); - } - } - - if(!empty($CurrentUserFleet)) - { - foreach($CurrentUserFleet as $ID => $Count) - { - if(!isset($FleetRecords[$ID]['count']) || $Count > $FleetRecords[$ID]['count']) - { - $FleetRecords[$ID] = array('count' => $Count, 'user' => $CurUser['id']); - } - } - } - - if($OnlyOnce) - { - $Bench->simpleCountStop(); - $CounterNames[] = '> Set Data to Array'; - $Bench->simpleCountStart(); - } - - $Users[$Loop]['id'] = $CurUser['id']; - $Users[$Loop]['tech_points'] = $TTechPoints; - $Users[$Loop]['tech_count'] = $TTechCount; - $Users[$Loop]['tech_old_rank'] = $OldTechRank; - $Users[$Loop]['build_points'] = $TBuildPoints; - $Users[$Loop]['build_count'] = $TBuildCount; - $Users[$Loop]['build_old_rank'] = $OldBuildRank; - $Users[$Loop]['defs_points'] = $TDefsPoints; - $Users[$Loop]['defs_count'] = $TDefsCount; - $Users[$Loop]['defs_old_rank'] = $OldDefsRank; - $Users[$Loop]['fleet_points'] = $TFleetPoints; - $Users[$Loop]['fleet_count'] = $TFleetCount; - $Users[$Loop]['fleet_old_rank'] = $OldFleetRank; - $Users[$Loop]['total_points'] = $GPoints; - $Users[$Loop]['total_count'] = $GCount; - $Users[$Loop]['total_old_rank'] = $OldTotalRank; - if(!isset($Stats[$CurUser['id']])) - { - $Users[$Loop]['tech_yesterday_rank'] = 0; - $Users[$Loop]['build_yesterday_rank'] = 0; - $Users[$Loop]['defs_yesterday_rank'] = 0; - $Users[$Loop]['fleet_yesterday_rank'] = 0; - $Users[$Loop]['total_yesterday_rank'] = 0; - } - else - { - $Users[$Loop]['tech_yesterday_rank'] = $Stats[$CurUser['id']]['tech_yesterday_rank']; - $Users[$Loop]['build_yesterday_rank'] = $Stats[$CurUser['id']]['build_yesterday_rank']; - $Users[$Loop]['defs_yesterday_rank'] = $Stats[$CurUser['id']]['defs_yesterday_rank']; - $Users[$Loop]['fleet_yesterday_rank'] = $Stats[$CurUser['id']]['fleet_yesterday_rank']; - $Users[$Loop]['total_yesterday_rank'] = $Stats[$CurUser['id']]['total_yesterday_rank']; - } - - $UsersUpdate[] = "({$CurUser['id']}, ".(floor((($TTechPoints + $TBuildPoints) / 2) + $TFleetPoints + ($TDefsPoints * (3/4)))).")"; - - if($CurUser['ally_id'] > 0) - { - if(!isset($AllyStats[$CurUser['ally_id']])) - { - $AllyStats[$CurUser['ally_id']]['TechPoint'] = 0; - $AllyStats[$CurUser['ally_id']]['TechCount'] = 0; - $AllyStats[$CurUser['ally_id']]['BuildPoint'] = 0; - $AllyStats[$CurUser['ally_id']]['BuildCount'] = 0; - $AllyStats[$CurUser['ally_id']]['DefsPoint'] = 0; - $AllyStats[$CurUser['ally_id']]['DefsCount'] = 0; - $AllyStats[$CurUser['ally_id']]['FleetPoint'] = 0; - $AllyStats[$CurUser['ally_id']]['FleetCount'] = 0; - $AllyStats[$CurUser['ally_id']]['TotalPoint'] = 0; - $AllyStats[$CurUser['ally_id']]['TotalCount'] = 0; - } - $AllyStats[$CurUser['ally_id']]['TechPoint'] += $TTechPoints; - $AllyStats[$CurUser['ally_id']]['TechCount'] += $TTechCount; - $AllyStats[$CurUser['ally_id']]['BuildPoint'] += $TBuildPoints; - $AllyStats[$CurUser['ally_id']]['BuildCount'] += $TBuildCount; - $AllyStats[$CurUser['ally_id']]['DefsPoint'] += $TDefsPoints; - $AllyStats[$CurUser['ally_id']]['DefsCount'] += $TDefsCount; - $AllyStats[$CurUser['ally_id']]['FleetPoint'] += $TFleetPoints; - $AllyStats[$CurUser['ally_id']]['FleetCount'] += $TFleetCount; - $AllyStats[$CurUser['ally_id']]['TotalPoint'] += $GPoints; - $AllyStats[$CurUser['ally_id']]['TotalCount'] += $GCount; - } - - $UsersBuilds[$Loop] = $TBuildPoints; - $UsersTech[$Loop] = $TTechPoints; - $UsersDefs[$Loop] = $TDefsPoints; - $UsersFleets[$Loop] = $TFleetPoints; - $UsersTotal[$Loop] = $GPoints; - - $Loop += 1; - - if($OnlyOnce) - { - $Bench->simpleCountStop(); - $OnlyOnce = false; - } - } - $Bench->simpleCountStop(); - $CounterNames[] = 'User Stats Insertion'; - $Bench->simpleCountStart(); - - $CounterNames[] = '> Users Update'; - $Bench->simpleCountStart(); - - $Query_UpdateUsers = ''; - $Query_UpdateUsers .= "INSERT INTO {{table}} (`id`, `morale_points`) VALUES "; - $Query_UpdateUsers .= implode(',', $UsersUpdate); - $Query_UpdateUsers .= "ON DUPLICATE KEY UPDATE "; - $Query_UpdateUsers .= "`morale_points` = VALUES(`morale_points`);"; - doquery($Query_UpdateUsers, 'users'); - unset($UsersUpdate); - unset($Stats); - - $Bench->simpleCountStop(); - - $CounterNames[] = '> Planets Update'; - $Bench->simpleCountStart(); - - $QryPlanetsUpdate = "INSERT INTO {{table}} (`id`, `points`) VALUES "; - $QryPlanetsUpdate .= implode(', ', $PlanetsUpdate); - $QryPlanetsUpdate .= "ON DUPLICATE KEY UPDATE "; - $QryPlanetsUpdate .= "`points` = VALUES(`points`);"; - doquery($QryPlanetsUpdate, 'planets'); - unset($QryPlanetsUpdate); - unset($PlanetsUpdate); - unset($Planets); - - $Bench->simpleCountStop(); - $CounterNames[] = '> Sorting tables'; - $Bench->simpleCountStart(); - - arsort($UsersBuilds); - arsort($UsersTech); - arsort($UsersDefs); - arsort($UsersFleets); - arsort($UsersTotal); - - $Bench->simpleCountStop(); - $CounterNames[] = '> Creating rank numbers'; - $Bench->simpleCountStart(); - $Loop = 1; - foreach($UsersBuilds as $Key => $Val) - { - $Users[$Key]['build_rank'] = $Loop; - $Loop += 1; - } - unset($UsersBuilds); - $Loop = 1; - foreach($UsersTech as $Key => $Val) - { - $Users[$Key]['tech_rank'] = $Loop; - $Loop += 1; - } - unset($UsersTech); - $Loop = 1; - foreach($UsersDefs as $Key => $Val) - { - $Users[$Key]['defs_rank'] = $Loop; - $Loop += 1; - } - unset($UsersDefs); - $Loop = 1; - foreach($UsersFleets as $Key => $Val) - { - $Users[$Key]['fleets_rank'] = $Loop; - $Loop += 1; - } - unset($UsersFleets); - $Loop = 1; - foreach($UsersTotal as $Key => $Val) - { - $Users[$Key]['total_rank'] = $Loop; - $Loop += 1; - } - unset($UsersTotal); - - $Bench->simpleCountStop(); - $CounterNames[] = '> Deleting old Stats'; - $Bench->simpleCountStart(); - doquery("DELETE FROM {{table}} WHERE `stat_type` = '1';", 'statpoints'); - $Bench->simpleCountStop(); - - if(count($Users) > 0) - { - $CounterNames[] = '> Making Query'; - $Bench->simpleCountStart(); - - $QryInsertUserStats = 'INSERT INTO {{table}} (`id_owner`, `stat_type`, `tech_rank`, `tech_old_rank`, `tech_yesterday_rank`, `tech_points`, `tech_count`, `build_rank`, `build_old_rank`, `build_yesterday_rank`, `build_points`, `build_count`, `defs_rank`, `defs_old_rank`, `defs_yesterday_rank`, `defs_points`, `defs_count`, `fleet_rank`, `fleet_old_rank`, `fleet_yesterday_rank`, `fleet_points`, `fleet_count`, `total_rank`, `total_old_rank`, `total_yesterday_rank`, `total_points`, `total_count`) VALUES '; - foreach($Users as $Val) - { - if($Val['tech_old_rank'] <= 0) - { - $Val['tech_old_rank'] = $Val['tech_rank']; - } - if($Val['build_old_rank'] <= 0) - { - $Val['build_old_rank'] = $Val['build_rank']; - } - if($Val['defs_old_rank'] <= 0) - { - $Val['defs_old_rank'] = $Val['defs_rank']; - } - if($Val['fleet_old_rank'] <= 0) - { - $Val['fleet_old_rank'] = $Val['fleets_rank']; - } - if($Val['total_old_rank'] <= 0) - { - $Val['total_old_rank'] = $Val['total_rank']; - } - if($Val['tech_yesterday_rank'] <= 0) - { - $Val['tech_yesterday_rank'] = $Val['tech_old_rank']; - } - if($Val['build_yesterday_rank'] <= 0) - { - $Val['build_yesterday_rank'] = $Val['build_old_rank']; - } - if($Val['defs_yesterday_rank'] <= 0) - { - $Val['defs_yesterday_rank'] = $Val['defs_old_rank']; - } - if($Val['fleet_yesterday_rank'] <= 0) - { - $Val['fleet_yesterday_rank'] = $Val['fleet_old_rank']; - } - if($Val['total_yesterday_rank'] <= 0) - { - $Val['total_yesterday_rank'] = $Val['total_old_rank']; - } - - foreach($Val as $key => $value) - { - if(empty($value)) - { - $Val[$key] = '0'; - } - } - - if($DailyStatsDiff > TIME_DAY OR $ForceDailyStats) - { - $Val['tech_yesterday_rank'] = $Val['tech_old_rank']; - $Val['build_yesterday_rank']= $Val['build_old_rank']; - $Val['defs_yesterday_rank'] = $Val['defs_old_rank']; - $Val['fleet_yesterday_rank']= $Val['fleet_old_rank']; - $Val['total_yesterday_rank']= $Val['total_old_rank']; - } - - $CreateQryRow = "({$Val['id']}, 1, "; - $CreateQryRow .= "{$Val['tech_rank']}, {$Val['tech_old_rank']}, {$Val['tech_yesterday_rank']}, {$Val['tech_points']}, {$Val['tech_count']}, "; - $CreateQryRow .= "{$Val['build_rank']}, {$Val['build_old_rank']}, {$Val['build_yesterday_rank']}, {$Val['build_points']}, {$Val['build_count']}, "; - $CreateQryRow .= "{$Val['defs_rank']}, {$Val['defs_old_rank']}, {$Val['defs_yesterday_rank']}, {$Val['defs_points']}, {$Val['defs_count']}, "; - $CreateQryRow .= "{$Val['fleets_rank']}, {$Val['fleet_old_rank']}, {$Val['fleet_yesterday_rank']}, {$Val['fleet_points']}, {$Val['fleet_count']}, "; - $CreateQryRow .= "{$Val['total_rank']}, {$Val['total_old_rank']}, {$Val['total_yesterday_rank']}, {$Val['total_points']}, {$Val['total_count']}"; - $CreateQryRow .= ")"; - - $QryInsertUserStatsArr[] = $CreateQryRow; - } - $QryInsertUserStats .= implode(', ', $QryInsertUserStatsArr).';'; - - $Bench->simpleCountStop(); - $CounterNames[] = '> Sending Query'; - $Bench->simpleCountStart(); - - doquery($QryInsertUserStats, 'statpoints'); - unset($QryInsertUserStatsArr); - unset($QryInsertUserStats); - unset($Users); - - $Bench->simpleCountStop(); - } - $Bench->simpleCountStop(); - - $CounterNames[] = 'Allys data Calculation and Insertion'; - $Bench->simpleCountStart(); - - ///////////////////// ALLIANCES //////////////////// - $AllysNeedenFields = "{{prefix}}statpoints.total_rank, {{prefix}}statpoints.tech_rank, {{prefix}}statpoints.build_rank, {{prefix}}statpoints.defs_rank, {{prefix}}statpoints.fleet_rank, {{prefix}}statpoints.tech_yesterday_rank,{{prefix}}statpoints.build_yesterday_rank,{{prefix}}statpoints.defs_yesterday_rank,{{prefix}}statpoints.fleet_yesterday_rank,{{prefix}}statpoints.total_yesterday_rank"; - $GameAllys = doquery("SELECT {{table}}.*, {$AllysNeedenFields} FROM {{table}} LEFT JOIN {{prefix}}statpoints ON `stat_type` = 2 AND {{prefix}}statpoints.id_owner = {{table}}.id GROUP BY {{table}}.id", 'alliance'); - - $Loop = 0; - while($CurAlly = mysql_fetch_array($GameAllys, MYSQL_ASSOC)) - { - $OldTotalRank = $CurAlly['total_rank']; - $OldTechRank = $CurAlly['tech_rank']; - $OldBuildRank = $CurAlly['build_rank']; - $OldDefsRank = $CurAlly['defs_rank']; - $OldFleetRank = $CurAlly['fleet_rank']; - - if(isset($AllyStats[$CurAlly['id']])) - { - $Points = $AllyStats[$CurAlly['id']]; - } - else - { - $Points = array( - 'TechCount' => 0, - 'TechPoint' => 0, - 'BuildCount' => 0, - 'BuildPoint' => 0, - 'DefsCount' => 0, - 'DefsPoint' => 0, - 'FleetCount' => 0, - 'FleetPoint' => 0, - 'TotalCount' => 0, - 'TotalPoint' => 0 - ); - } - - $TTechCount = $Points['TechCount']; - $TTechPoints = $Points['TechPoint']; - $TBuildCount = $Points['BuildCount']; - $TBuildPoints = $Points['BuildPoint']; - $TDefsCount = $Points['DefsCount']; - $TDefsPoints = $Points['DefsPoint']; - $TFleetCount = $Points['FleetCount']; - $TFleetPoints = $Points['FleetPoint']; - $GCount = $Points['TotalCount']; - $GPoints = $Points['TotalPoint']; - - $Allys[$Loop]['id'] = $CurAlly['id']; - $Allys[$Loop]['tech_points'] = $TTechPoints; - $Allys[$Loop]['tech_count'] = $TTechCount; - $Allys[$Loop]['tech_old_rank'] = $OldTechRank; - $Allys[$Loop]['build_points'] = $TBuildPoints; - $Allys[$Loop]['build_count'] = $TBuildCount; - $Allys[$Loop]['build_old_rank'] = $OldBuildRank; - $Allys[$Loop]['defs_points'] = $TDefsPoints; - $Allys[$Loop]['defs_count'] = $TDefsCount; - $Allys[$Loop]['defs_old_rank'] = $OldDefsRank; - $Allys[$Loop]['fleet_points'] = $TFleetPoints; - $Allys[$Loop]['fleet_count'] = $TFleetCount; - $Allys[$Loop]['fleet_old_rank'] = $OldFleetRank; - $Allys[$Loop]['total_points'] = $GPoints; - $Allys[$Loop]['total_count'] = $GCount; - $Allys[$Loop]['total_old_rank'] = $OldTotalRank; - $Allys[$Loop]['tech_yesterday_rank'] = $CurAlly['tech_yesterday_rank']; - $Allys[$Loop]['build_yesterday_rank'] = $CurAlly['build_yesterday_rank']; - $Allys[$Loop]['defs_yesterday_rank'] = $CurAlly['defs_yesterday_rank']; - $Allys[$Loop]['fleet_yesterday_rank'] = $CurAlly['fleet_yesterday_rank']; - $Allys[$Loop]['total_yesterday_rank'] = $CurAlly['total_yesterday_rank']; - - $AllysBuilds[$Loop] = $TBuildPoints; - $AllysTech[$Loop] = $TTechPoints; - $AllysDefs[$Loop] = $TDefsPoints; - $AllysFleets[$Loop] = $TFleetPoints; - $AllysTotal[$Loop] = $GPoints; - - $Loop += 1; - } - - arsort($AllysBuilds); - arsort($AllysTech); - arsort($AllysDefs); - arsort($AllysFleets); - arsort($AllysTotal); - $Loop = 1; - foreach($AllysBuilds as $Key => $Val) - { - $Allys[$Key]['build_rank'] = $Loop; - $Loop += 1; - } - unset($AllysBuilds); - $Loop = 1; - foreach($AllysTech as $Key => $Val) - { - $Allys[$Key]['tech_rank'] = $Loop; - $Loop += 1; - } - unset($AllysTech); - $Loop = 1; - foreach($AllysDefs as $Key => $Val) - { - $Allys[$Key]['defs_rank'] = $Loop; - $Loop += 1; - } - unset($AllysDefs); - $Loop = 1; - foreach($AllysFleets as $Key => $Val) - { - $Allys[$Key]['fleets_rank'] = $Loop; - $Loop += 1; - } - unset($AllysFleets); - $Loop = 1; - foreach($AllysTotal as $Key => $Val) - { - $Allys[$Key]['total_rank'] = $Loop; - $Loop += 1; - } - unset($AllysTotal); - - doquery("DELETE FROM {{table}} WHERE `stat_type` = '2';", 'statpoints'); - - if(count($Allys) > 0) - { - $QryInsertAllyStats = 'INSERT INTO {{table}} (`id_owner`, `stat_type`, `tech_rank`, `tech_old_rank`, `tech_yesterday_rank`, `tech_points`, `tech_count`, `build_rank`, `build_old_rank`, `build_yesterday_rank`, `build_points`, `build_count`, `defs_rank`, `defs_old_rank`, `defs_yesterday_rank`, `defs_points`, `defs_count`, `fleet_rank`, `fleet_old_rank`, `fleet_yesterday_rank`, `fleet_points`, `fleet_count`, `total_rank`, `total_old_rank`, `total_yesterday_rank`, `total_points`, `total_count`) VALUES '; - foreach($Allys as $Val) - { - if($Val['tech_old_rank'] <= 0) - { - $Val['tech_old_rank'] = $Val['tech_rank']; - } - if($Val['build_old_rank'] <= 0) - { - $Val['build_old_rank'] = $Val['build_rank']; - } - if($Val['defs_old_rank'] <= 0) - { - $Val['defs_old_rank'] = $Val['defs_rank']; - } - if($Val['fleet_old_rank'] <= 0) - { - $Val['fleet_old_rank'] = $Val['fleets_rank']; - } - if($Val['total_old_rank'] <= 0) - { - $Val['total_old_rank'] = $Val['total_rank']; - } - if($Val['tech_yesterday_rank'] <= 0) - { - $Val['tech_yesterday_rank'] = $Val['tech_old_rank']; - } - if($Val['build_yesterday_rank'] <= 0) - { - $Val['build_yesterday_rank'] = $Val['build_old_rank']; - } - if($Val['defs_yesterday_rank'] <= 0) - { - $Val['defs_yesterday_rank'] = $Val['defs_old_rank']; - } - if($Val['fleet_yesterday_rank'] <= 0) - { - $Val['fleet_yesterday_rank'] = $Val['fleet_old_rank']; - } - if($Val['total_yesterday_rank'] <= 0) - { - $Val['total_yesterday_rank'] = $Val['total_old_rank']; - } - - foreach($Val as $key => $value) - { - if(empty($value)) - { - $Val[$key] = '0'; - } - } - - if($DailyStatsDiff > TIME_DAY OR $ForceDailyStats) - { - $Val['tech_yesterday_rank'] = $Val['tech_old_rank']; - $Val['build_yesterday_rank'] = $Val['build_old_rank']; - $Val['defs_yesterday_rank'] = $Val['defs_old_rank']; - $Val['fleet_yesterday_rank'] = $Val['fleet_old_rank']; - $Val['total_yesterday_rank'] = $Val['total_old_rank']; - } - - $CreateQryRow = "({$Val['id']}, 2, "; - $CreateQryRow .= "{$Val['tech_rank']}, {$Val['tech_old_rank']}, {$Val['tech_yesterday_rank']}, {$Val['tech_points']}, {$Val['tech_count']}, "; - $CreateQryRow .= "{$Val['build_rank']}, {$Val['build_old_rank']}, {$Val['build_yesterday_rank']}, {$Val['build_points']}, {$Val['build_count']}, "; - $CreateQryRow .= "{$Val['defs_rank']}, {$Val['defs_old_rank']}, {$Val['defs_yesterday_rank']}, {$Val['defs_points']}, {$Val['defs_count']}, "; - $CreateQryRow .= "{$Val['fleets_rank']}, {$Val['fleet_old_rank']}, {$Val['fleet_yesterday_rank']}, {$Val['fleet_points']}, {$Val['fleet_count']}, "; - $CreateQryRow .= "{$Val['total_rank']}, {$Val['total_old_rank']}, {$Val['total_yesterday_rank']}, {$Val['total_points']}, {$Val['total_count']}"; - $CreateQryRow .= ")"; - - $QryInsertAllyStatsArr[] = $CreateQryRow; - } - $QryInsertAllyStats .= implode(', ', $QryInsertAllyStatsArr).';'; - - doquery($QryInsertAllyStats, 'statpoints'); - unset($QryInsertAllyStatsArr); - unset($QryInsertAllyStats); - unset($Allys); - } - $Bench->simpleCountStop(); - $CounterNames[] = 'Records Calculation and Insertion'; - $Bench->simpleCountStart(); - - //////////////// RECORDS ///////////////////// - doquery("DELETE FROM {{table}};", 'records'); - $records = array(); - $Loop = 0; - - foreach($_Vars_GameElements as $Element => $ElementName) - { - if(!empty($ElementName)) - { - $UserID = 0; - $ElementCount = 0; - $Allow = true; - if(($Element >= 1 AND $Element <= 39) OR $Element == 44) - { - // Buildings - $UserID = isset($BuildingRecords[$Element]['user']) ? $BuildingRecords[$Element]['user'] : null; - $ElementCount = isset($BuildingRecords[$Element]['lvl']) ? $BuildingRecords[$Element]['lvl'] : null; - } - elseif($Element >= 41 AND $Element <= 99 AND $Element != 44 AND $Element != 50) - { - // Special buildings - $UserID = isset($BuildingRecords[$Element]['user']) ? $BuildingRecords[$Element]['user'] : null; - $ElementCount = isset($BuildingRecords[$Element]['lvl']) ? $BuildingRecords[$Element]['lvl'] : null; - } - elseif($Element >= 101 AND $Element <= 199) - { - // Technology - $UserID = isset($TechRecords[$Element]['user']) ? $TechRecords[$Element]['user'] : null; - $ElementCount = isset($TechRecords[$Element]['lvl']) ? $TechRecords[$Element]['lvl'] : null; - } - elseif($Element >= 201 AND $Element <= 399) - { - // Fleets - $UserID = isset($FleetRecords[$Element]['user']) ? $FleetRecords[$Element]['user'] : null; - $ElementCount = isset($FleetRecords[$Element]['lvl']) ? $FleetRecords[$Element]['lvl'] : null; - } - elseif($Element >= 401 AND $Element <= 599 AND $Element != 407 AND $Element != 408 AND $Element != 409) - { - // Defences (Excluded: Shields) - $UserID = isset($DefenseRecords[$Element]['user']) ? $DefenseRecords[$Element]['user'] : null; - $ElementCount = isset($DefenseRecords[$Element]['lvl']) ? $DefenseRecords[$Element]['lvl'] : null; - } - else - { - $Allow = false; - } - - if($Allow) - { - if($UserID == 0) - { - $UserID = '0'; - $ElementCount = '0'; - } - if($ElementCount == 0) - { - $ElementCount = '0'; - $UserID = '0'; - } - $records[] = array('element' => $Element, 'user' => $UserID, 'count' => $ElementCount); - } - } - } - - if(count($records) > 0) - { - $QryInsertRecords = "INSERT INTO {{table}} (`id`, `id_owner`, `element`, `count`) VALUES "; - foreach($records as $val) - { - $QryInsertRecordsArr[] = "(NULL, {$val['user']}, {$val['element']}, {$val['count']})"; - } - $QryInsertRecords .= implode(', ', $QryInsertRecordsArr).';'; - - doquery($QryInsertRecords, 'records'); - unset($QryInsertRecordsArr); - unset($QryInsertRecords); - } - $Bench->simpleCountStop(); - // ------------------------------------------------------------------------------------------- - $CounterNames[] = 'Deleting Users'; - $Bench->simpleCountStart(); - - // Delete all NonActivated Users which are in DataBase for at least 7 days - $SelectNonActivatedUsers = doquery("SELECT `id` FROM {{table}} WHERE `activation_code` != '' AND `register_time` < ({$StatDate} - (".NONACTIVE_DELETETIME."));", 'users'); - while($NonActivated = mysql_fetch_array($SelectNonActivatedUsers, MYSQL_ASSOC)) - { - $UsersToDelete[] = $NonActivated['id']; - } - - if(!empty($UsersToDelete)) - { - include($_EnginePath.'includes/functions/DeleteSelectedUser.php'); - include($_EnginePath.'includes/functions/FleetControl_Retreat.php'); - DeleteSelectedUser($UsersToDelete); - } - - $Bench->simpleCountStop(); - $CounterNames[] = 'Removing VacationModes & Updating Banned PPL'; - $Bench->simpleCountStart(); - - if(!empty($UsersToRemoveVacations)) - { - $UsersToRemoveVacations = implode(', ', $UsersToRemoveVacations); - doquery("UPDATE {{table}} SET `is_onvacation` = '0', `vacation_starttime` = '0', `vacation_endtime` = '0', `vacation_leavetime` = IF(`vacation_type` = 2, 0, {$StatDate}) WHERE `id` IN ({$UsersToRemoveVacations});", 'users'); - doquery("UPDATE {{table}} SET `last_update` = {$StatDate} WHERE `id_owner` IN ({$UsersToRemoveVacations});", 'planets'); - } - if(!empty($UsersToRemoveBan)) - { - $UsersToRemoveBan = implode(', ', $UsersToRemoveBan); - doquery("UPDATE {{table}} SET `is_banned` = 0, `ban_endtime` = 0 WHERE `id` IN ({$UsersToRemoveBan});", 'users'); - doquery("UPDATE {{table}} SET `Active` = 0, `Expired` = 1 WHERE `Active` = 1 AND `UserID` IN ({$UsersToRemoveBan});", 'bans'); - } - - $Bench->simpleCountStop(); - - $CounterNames[] = 'DataBase Optimization'; - $Bench->simpleCountStart(); - if(($StatDate - $_GameConfig['last_db_optimization']) > (2 * TIME_HOUR)) - { - $TableList = array - ( - 'acs', 'alliance', 'buddy', 'declarations', 'errors', 'fleets', - 'galaxy', 'ignoresystem', 'notes', 'planets', - 'records', 'statpoints', 'users' - ); - - foreach($TableList as $key => $val) - { - $TableList[$key] = '{{prefix}}'.$val; - } - - $TableList = implode(', ', $TableList); - - doquery("OPTIMIZE TABLE {$TableList}", ''); - doquery("UPDATE {{table}} SET `config_value` = {$StatDate} WHERE `config_name` = 'last_db_optimization';", 'config'); - $_GameConfig['last_db_optimization'] = $StatDate; - } - $Bench->simpleCountStop(); - $CounterNames[] = 'Final Updates'; - $Bench->simpleCountStart(); - doquery("UPDATE {{table}} SET `config_value` = {$StatDate} WHERE `config_name` = 'last_update';", 'config'); - $_GameConfig['last_update'] = $StatDate; - - // Create LastUpdate CacheFile (for Signature Generator) - file_put_contents('../cache/data/last_stats_update.php', ''); - - if($DailyStatsDiff > TIME_DAY) - { - doquery("UPDATE {{table}} SET `config_value` = {$StatDate} WHERE `config_name` = 'last_stats_daily';", 'config'); - $_GameConfig['last_stats_daily'] = $StatDate; - } - $_MemCache->GameConfig = $_GameConfig; - - $EndTime = microtime(true); - $Bench->simpleCountStop(); - $CountTime = $Bench->ReturnSimpleCountArray(); - - $TotalTime = sprintf('%0.6f', $EndTime - $StartTime); - - if($ShowOutput) - { - $Counted = '
'; - foreach($CountTime as $Key => $Data) - { - if(strstr($CounterNames[$Key], '>') == true) - { - $LastWasAssoc = true; - } - else - { - if(isset($LastWasAssoc) && $LastWasAssoc === true) - { - $Counted .= ''; - } - $LastWasAssoc = false; - } - $Counted .= ''; - } - $Counted .= '
'.$CounterNames[$Key].' '.sprintf('%0.20f', $Data['result']).'
'.$Data['endram'].'
'; - - AdminMessage(sprintf($_Lang['AutoStatBuilder_BuildInfo'], $TotalTime, pretty_time($DailyStatsDiff, true), $DailyStatsDiff, $Counted), $_Lang['AutoStatBuilder_Title']); - } - else - { - AdminMessage('OK', $_Lang['AutoStatBuilder_Title']); - } - -?> \ No newline at end of file +showSimpleCountSwitch(); +$Bench->echoTableSwitch(); + +// Load StatFunctions +include($_EnginePath.'admin/autostatbuilder_functions.php'); + +// Init Time +$StatDate = time(); +includeLang('admin'); +includeLang('admin/autostatbuilder'); + +if(!((isset($_User['id']) && $_User['id'] > 0 AND CheckAuth('programmer')) || ((!isset($_User['id']) || $_User['id'] <= 0) && md5($_GET['pass']) == AUTOTOOL_STATBUILDER_PASSWORDHASH))) +{ + AdminMessage($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); +} + +$CounterNames[] = 'Init & Delete old stats'; +$Bench->simpleCountStart(); + +// Initialization +$StartTime = microtime(true); + +$Users = array(); +$Allys = array(); + +$UsersBuilds = array(); +$UsersDefs = array(); +$UsersFleets = array(); +$UsersTech = array(); +$UsersTotal = array(); + +$AllysBuilds = array(); +$AllysDefs = array(); +$AllysFleets = array(); +$AllysTech = array(); +$AllysTotal = array(); +$DailyStatsDiff = $StatDate - $_GameConfig['last_stats_daily']; +$Loop = 0; + +$ForceDailyStats = (isset($_GET['force_yesterday']) && $_GET['force_yesterday'] == 'true' ? true : false); +$ShowOutput = (isset($_User['id']) && $_User['id'] > 0 ? true : false); +//END-OF-Initialization + +/////////// USERS /////////// + +// Techs needen fields +foreach($_Vars_ElementCategories['tech'] as $ID) +{ + if(!empty($_Vars_GameElements[$ID])) + { + $CreateTechFieldsList[] = "`user`.`{$_Vars_GameElements[$ID]}`"; + } +} +// Planet needen fields +$CreatePlanetFieldsList[] = 'id'; +$CreatePlanetFieldsList[] = 'id_owner'; +foreach($_Vars_ElementCategories as $ResType => $ResLists) +{ + if($ResType != 'build' AND $ResType != 'defense' AND $ResType != 'fleet') + { + continue; + } + foreach($ResLists as $ID) + { + $CreatePlanetFieldsList[] = "`{$_Vars_GameElements[$ID]}`"; + } +} + +// Needen fields +$CreateFleetFieldsList = "`fleet_owner`, `fleet_array`"; +$CreateStatFieldsList = "`id_owner`, `total_rank`, `tech_rank`, `build_rank`, `defs_rank`, `fleet_rank`, `tech_yesterday_rank`, `build_yesterday_rank`, `defs_yesterday_rank`, `fleet_yesterday_rank`, `total_yesterday_rank`"; +$CreateTechFieldsList = implode(', ', $CreateTechFieldsList); +$CreatePlanetFieldsList = implode(', ', $CreatePlanetFieldsList); +$UserNeedenFields = "`user`.`id`, `user`.`username`, `user`.`ally_id`, `is_ondeletion`, `deletion_endtime`, `pro_time`, `is_onvacation`, `vacation_endtime`, `is_banned`, `ban_endtime`, {$CreateTechFieldsList}"; + +$Bench->simpleCountStop(); +$CounterNames[] = 'User Stats Select'; +$Bench->simpleCountStart(); + +$CounterNames[] = '> Getting UsersData'; +$Bench->simpleCountStart(); +$GameUsers = doquery("SELECT {$UserNeedenFields} FROM {{table}} as `user` WHERE `user`.`authlevel` = 0 ORDER BY `user`.`id` ASC;", 'users'); +if(mysql_num_rows($GameUsers) <= 0) +{ + AdminMessage('No Users Found', 'StatBuilder'); +} + +$Bench->simpleCountStop(); +$CounterNames[] = '> Getting StatPoints'; +$Bench->simpleCountStart(); +$UsersStats = doquery("SELECT {$CreateStatFieldsList} FROM {{table}} WHERE `stat_type` = 1;", 'statpoints'); + +$Bench->simpleCountStop(); +$CounterNames[] = '> Getting PlanetsData'; +$Bench->simpleCountStart(); +$AllPlanets = doquery("SELECT {$CreatePlanetFieldsList} FROM {{table}};", 'planets'); + +$Bench->simpleCountStop(); +$CounterNames[] = '> Getting FleetsData'; +$Bench->simpleCountStart(); +$AllFleets= doquery("SELECT {$CreateFleetFieldsList} FROM {{table}};", 'fleets'); + +$Bench->simpleCountStop(); +$CounterNames[] = '> Parsing PlanetsData'; +$Bench->simpleCountStart(); +while($PlanetsData = mysql_fetch_array($AllPlanets, MYSQL_ASSOC)) +{ + $Planets[$PlanetsData['id_owner']][] = $PlanetsData; +} + +$Bench->simpleCountStop(); +$CounterNames[] = '> Parsing FleetsData'; +$Bench->simpleCountStart(); +while($FleetsData = mysql_fetch_array($AllFleets, MYSQL_ASSOC)) +{ + $Fleets[$FleetsData['fleet_owner']][] = $FleetsData; +} + +$Bench->simpleCountStop(); +$CounterNames[] = '> Parsing StatsData'; +$Bench->simpleCountStart(); +while($StatsData = mysql_fetch_array($UsersStats, MYSQL_ASSOC)) +{ + $Stats[$StatsData['id_owner']] = $StatsData; +} +$Bench->simpleCountStop(); + +$Bench->simpleCountStop(); +$CounterNames[] = 'User Stats Calculation'; +$Bench->simpleCountStart(); + +$OnlyOnce = true; + +while($CurUser = mysql_fetch_array($GameUsers, MYSQL_ASSOC)) +{ + // Delete User with DeletionRequest + if($CurUser['is_ondeletion'] == 1 AND $CurUser['deletion_endtime'] < $StatDate) + { + $UsersToDelete[] = $CurUser['id']; + continue; + } + if(!empty($CurUser['activation_code'])) + { + continue; + } + + // Remove "too long" Vacation Users + if(isOnVacation($CurUser) AND $CurUser['vacation_endtime'] != 0 AND $CurUser['vacation_endtime'] < $StatDate) + { + $UsersToRemoveVacations[] = $CurUser['id']; + } + + // Remove elapsed Bans + if($CurUser['is_banned'] == 1 AND $CurUser['ban_endtime'] < $StatDate) + { + $UsersToRemoveBan[] = $CurUser['id']; + } + + if($OnlyOnce) + { + $CounterNames[] = '> Set OldData'; + $Bench->simpleCountStart(); + } + $CurrentUserDefense = array(); + $CurrentUserFleet = array(); + + if(!isset($Stats[$CurUser['id']])) + { + $OldTotalRank = 0; + $OldTechRank = 0; + $OldBuildRank = 0; + $OldDefsRank = 0; + $OldFleetRank = 0; + } + else + { + $OldTotalRank = $Stats[$CurUser['id']]['total_rank']; + $OldTechRank = $Stats[$CurUser['id']]['tech_rank']; + $OldBuildRank = $Stats[$CurUser['id']]['build_rank']; + $OldDefsRank = $Stats[$CurUser['id']]['defs_rank']; + $OldFleetRank = $Stats[$CurUser['id']]['fleet_rank']; + } + + if($OnlyOnce) + { + $Bench->simpleCountStop(); + $CounterNames[] = '> Calc TechnoPoints'; + $Bench->simpleCountStart(); + } + + $Points = GetTechnoPoints($CurUser); + $TTechCount = $Points['TechCount']; + $TTechPoints = ($Points['TechPoint'] / $_GameConfig['stat_settings']); + + // Get Tech Records + if($Points['TechCount'] > 0) + { + foreach($Points['TechArr'] as $TechID => $Level) + { + if(!isset($TechRecords[$TechID]['lvl']) || $Level > $TechRecords[$TechID]['lvl']) + { + $TechRecords[$TechID] = array('lvl' => $Level, 'user' => $CurUser['id']); + } + } + } + + $TBuildCount = 0; + $TBuildPoints = 0; + $TDefsCount = 0; + $TDefsPoints = 0; + $TFleetCount = 0; + $TFleetPoints = 0; + $GCount = $TTechCount; + $GPoints = $TTechPoints; + + if($OnlyOnce) + { + $Bench->simpleCountStop(); + $CounterNames[] = '> Calc Planets Points'; + $Bench->simpleCountStart(); + } + + if(!empty($Planets[$CurUser['id']])) + { + foreach($Planets[$CurUser['id']] as $PlanetKey => $CurPlanet) + { + if($CurPlanet['id'] > 0) + { + // Calculate BuildingPoints + $Points = GetBuildPoints($CurPlanet); + $TBuildCount += $Points['BuildCount']; + $GCount += $Points['BuildCount']; + $PlanetPoints = ($Points['BuildPoint'] / $_GameConfig['stat_settings']); + $TBuildPoints += $PlanetPoints; + if($Points['BuildCount'] > 0) + { + foreach($Points['BuildArr'] as $ID => $Level) + { + if(!isset($BuildingRecords[$ID]['lvl']) || $Level > $BuildingRecords[$ID]['lvl']) + { + $BuildingRecords[$ID] = array('lvl' => $Level, 'user' => $CurUser['id']); + } + } + } + + // Calculate DefensePoints + $Points = GetDefensePoints($CurPlanet); + $TDefsCount += $Points['DefenseCount']; + $GCount += $Points['DefenseCount']; + $DefsPoints = ($Points['DefensePoint'] / $_GameConfig['stat_settings']); + $PlanetPoints += $DefsPoints; + $TDefsPoints += $DefsPoints; + if($Points['DefenseCount'] > 0) + { + foreach($Points['DefenseArr'] as $ID => $Count) + { + if(!isset($CurrentUserDefense[$ID])) + { + $CurrentUserDefense[$ID] = 0; + } + $CurrentUserDefense[$ID] += $Count; + } + } + + // Calculate FleetPoints (on Planet) + $Points = GetFleetPoints($CurPlanet); + $TFleetCount += $Points['FleetCount']; + $GCount += $Points['FleetCount']; + $FleetsPoints = ($Points['FleetPoint'] / $_GameConfig['stat_settings']); + $PlanetPoints += $FleetsPoints; + $TFleetPoints += $FleetsPoints; + if($Points['FleetCount'] > 0) + { + foreach($Points['FleetArr'] as $ID => $Count) + { + if(!isset($CurrentUserFleet[$ID])) + { + $CurrentUserFleet[$ID] = 0; + } + $CurrentUserFleet[$ID] += $Count; + } + } + $GPoints += $PlanetPoints; + + if($PlanetPoints == 0) + { + $PlanetPoints = '0'; + } + $PlanetsUpdate[] = '('.$CurPlanet['id'].', '.$PlanetPoints.')'; + } + unset($Planets[$CurUser['id']][$PlanetKey]); + } + + if(!empty($CurrentUserDefense)) + { + foreach($CurrentUserDefense as $ID => $Count) + { + if(!isset($DefenseRecords[$ID]['count']) || $Count > $DefenseRecords[$ID]['count']) + { + $DefenseRecords[$ID] = array('count' => $Count, 'user' => $CurUser['id']); + } + } + } + } + + if($OnlyOnce) + { + $Bench->simpleCountStop(); + $CounterNames[] = '> Calc FleetInFlight Points'; + $Bench->simpleCountStart(); + } + + if(!empty($Fleets[$CurUser['id']])) + { + foreach($Fleets[$CurUser['id']] as $FleetKey => $CurFleet) + { + $Points = GetFleetPointsOnTour($CurFleet['fleet_array']); + $TFleetCount += $Points['FleetCount']; + $GCount += $Points['FleetCount']; + $FleetsPoints = ($Points['FleetPoint'] / $_GameConfig['stat_settings']); + $TFleetPoints += $FleetsPoints; + $GPoints += $FleetsPoints; + if($Points['FleetCount'] > 0) + { + foreach($Points['FleetArr'] as $ID => $Count) + { + if(!isset($CurrentUserFleet[$ID])) + { + $CurrentUserFleet[$ID] = 0; + } + $CurrentUserFleet[$ID] += $Count; + } + } + + unset($Fleets[$CurUser['id']][$FleetKey]); + } + } + + if(!empty($CurrentUserFleet)) + { + foreach($CurrentUserFleet as $ID => $Count) + { + if(!isset($FleetRecords[$ID]['count']) || $Count > $FleetRecords[$ID]['count']) + { + $FleetRecords[$ID] = array('count' => $Count, 'user' => $CurUser['id']); + } + } + } + + if($OnlyOnce) + { + $Bench->simpleCountStop(); + $CounterNames[] = '> Set Data to Array'; + $Bench->simpleCountStart(); + } + + $Users[$Loop]['id'] = $CurUser['id']; + $Users[$Loop]['tech_points'] = $TTechPoints; + $Users[$Loop]['tech_count'] = $TTechCount; + $Users[$Loop]['tech_old_rank'] = $OldTechRank; + $Users[$Loop]['build_points'] = $TBuildPoints; + $Users[$Loop]['build_count'] = $TBuildCount; + $Users[$Loop]['build_old_rank'] = $OldBuildRank; + $Users[$Loop]['defs_points'] = $TDefsPoints; + $Users[$Loop]['defs_count'] = $TDefsCount; + $Users[$Loop]['defs_old_rank'] = $OldDefsRank; + $Users[$Loop]['fleet_points'] = $TFleetPoints; + $Users[$Loop]['fleet_count'] = $TFleetCount; + $Users[$Loop]['fleet_old_rank'] = $OldFleetRank; + $Users[$Loop]['total_points'] = $GPoints; + $Users[$Loop]['total_count'] = $GCount; + $Users[$Loop]['total_old_rank'] = $OldTotalRank; + if(!isset($Stats[$CurUser['id']])) + { + $Users[$Loop]['tech_yesterday_rank'] = 0; + $Users[$Loop]['build_yesterday_rank'] = 0; + $Users[$Loop]['defs_yesterday_rank'] = 0; + $Users[$Loop]['fleet_yesterday_rank'] = 0; + $Users[$Loop]['total_yesterday_rank'] = 0; + } + else + { + $Users[$Loop]['tech_yesterday_rank'] = $Stats[$CurUser['id']]['tech_yesterday_rank']; + $Users[$Loop]['build_yesterday_rank'] = $Stats[$CurUser['id']]['build_yesterday_rank']; + $Users[$Loop]['defs_yesterday_rank'] = $Stats[$CurUser['id']]['defs_yesterday_rank']; + $Users[$Loop]['fleet_yesterday_rank'] = $Stats[$CurUser['id']]['fleet_yesterday_rank']; + $Users[$Loop]['total_yesterday_rank'] = $Stats[$CurUser['id']]['total_yesterday_rank']; + } + + $UsersUpdate[] = "({$CurUser['id']}, ".(floor((($TTechPoints + $TBuildPoints) / 2) + $TFleetPoints + ($TDefsPoints * (3/4)))).")"; + + if($CurUser['ally_id'] > 0) + { + if(!isset($AllyStats[$CurUser['ally_id']])) + { + $AllyStats[$CurUser['ally_id']]['TechPoint'] = 0; + $AllyStats[$CurUser['ally_id']]['TechCount'] = 0; + $AllyStats[$CurUser['ally_id']]['BuildPoint'] = 0; + $AllyStats[$CurUser['ally_id']]['BuildCount'] = 0; + $AllyStats[$CurUser['ally_id']]['DefsPoint'] = 0; + $AllyStats[$CurUser['ally_id']]['DefsCount'] = 0; + $AllyStats[$CurUser['ally_id']]['FleetPoint'] = 0; + $AllyStats[$CurUser['ally_id']]['FleetCount'] = 0; + $AllyStats[$CurUser['ally_id']]['TotalPoint'] = 0; + $AllyStats[$CurUser['ally_id']]['TotalCount'] = 0; + } + $AllyStats[$CurUser['ally_id']]['TechPoint'] += $TTechPoints; + $AllyStats[$CurUser['ally_id']]['TechCount'] += $TTechCount; + $AllyStats[$CurUser['ally_id']]['BuildPoint'] += $TBuildPoints; + $AllyStats[$CurUser['ally_id']]['BuildCount'] += $TBuildCount; + $AllyStats[$CurUser['ally_id']]['DefsPoint'] += $TDefsPoints; + $AllyStats[$CurUser['ally_id']]['DefsCount'] += $TDefsCount; + $AllyStats[$CurUser['ally_id']]['FleetPoint'] += $TFleetPoints; + $AllyStats[$CurUser['ally_id']]['FleetCount'] += $TFleetCount; + $AllyStats[$CurUser['ally_id']]['TotalPoint'] += $GPoints; + $AllyStats[$CurUser['ally_id']]['TotalCount'] += $GCount; + } + + $UsersBuilds[$Loop] = $TBuildPoints; + $UsersTech[$Loop] = $TTechPoints; + $UsersDefs[$Loop] = $TDefsPoints; + $UsersFleets[$Loop] = $TFleetPoints; + $UsersTotal[$Loop] = $GPoints; + + $Loop += 1; + + if($OnlyOnce) + { + $Bench->simpleCountStop(); + $OnlyOnce = false; + } +} +$Bench->simpleCountStop(); +$CounterNames[] = 'User Stats Insertion'; +$Bench->simpleCountStart(); + +$CounterNames[] = '> Users Update'; +$Bench->simpleCountStart(); + +$Query_UpdateUsers = ''; +$Query_UpdateUsers .= "INSERT INTO {{table}} (`id`, `morale_points`) VALUES "; +$Query_UpdateUsers .= implode(',', $UsersUpdate); +$Query_UpdateUsers .= "ON DUPLICATE KEY UPDATE "; +$Query_UpdateUsers .= "`morale_points` = VALUES(`morale_points`);"; +doquery($Query_UpdateUsers, 'users'); +unset($UsersUpdate); +unset($Stats); + +$Bench->simpleCountStop(); + +$CounterNames[] = '> Planets Update'; +$Bench->simpleCountStart(); + +$QryPlanetsUpdate = "INSERT INTO {{table}} (`id`, `points`) VALUES "; +$QryPlanetsUpdate .= implode(', ', $PlanetsUpdate); +$QryPlanetsUpdate .= "ON DUPLICATE KEY UPDATE "; +$QryPlanetsUpdate .= "`points` = VALUES(`points`);"; +doquery($QryPlanetsUpdate, 'planets'); +unset($QryPlanetsUpdate); +unset($PlanetsUpdate); +unset($Planets); + +$Bench->simpleCountStop(); +$CounterNames[] = '> Sorting tables'; +$Bench->simpleCountStart(); + +arsort($UsersBuilds); +arsort($UsersTech); +arsort($UsersDefs); +arsort($UsersFleets); +arsort($UsersTotal); + +$Bench->simpleCountStop(); +$CounterNames[] = '> Creating rank numbers'; +$Bench->simpleCountStart(); +$Loop = 1; +foreach($UsersBuilds as $Key => $Val) +{ + $Users[$Key]['build_rank'] = $Loop; + $Loop += 1; +} +unset($UsersBuilds); +$Loop = 1; +foreach($UsersTech as $Key => $Val) +{ + $Users[$Key]['tech_rank'] = $Loop; + $Loop += 1; +} +unset($UsersTech); +$Loop = 1; +foreach($UsersDefs as $Key => $Val) +{ + $Users[$Key]['defs_rank'] = $Loop; + $Loop += 1; +} +unset($UsersDefs); +$Loop = 1; +foreach($UsersFleets as $Key => $Val) +{ + $Users[$Key]['fleets_rank'] = $Loop; + $Loop += 1; +} +unset($UsersFleets); +$Loop = 1; +foreach($UsersTotal as $Key => $Val) +{ + $Users[$Key]['total_rank'] = $Loop; + $Loop += 1; +} +unset($UsersTotal); + +$Bench->simpleCountStop(); +$CounterNames[] = '> Deleting old Stats'; +$Bench->simpleCountStart(); +doquery("DELETE FROM {{table}} WHERE `stat_type` = '1';", 'statpoints'); +$Bench->simpleCountStop(); + +if(count($Users) > 0) +{ + $CounterNames[] = '> Making Query'; + $Bench->simpleCountStart(); + + $QryInsertUserStats = 'INSERT INTO {{table}} (`id_owner`, `stat_type`, `tech_rank`, `tech_old_rank`, `tech_yesterday_rank`, `tech_points`, `tech_count`, `build_rank`, `build_old_rank`, `build_yesterday_rank`, `build_points`, `build_count`, `defs_rank`, `defs_old_rank`, `defs_yesterday_rank`, `defs_points`, `defs_count`, `fleet_rank`, `fleet_old_rank`, `fleet_yesterday_rank`, `fleet_points`, `fleet_count`, `total_rank`, `total_old_rank`, `total_yesterday_rank`, `total_points`, `total_count`) VALUES '; + foreach($Users as $Val) + { + if($Val['tech_old_rank'] <= 0) + { + $Val['tech_old_rank'] = $Val['tech_rank']; + } + if($Val['build_old_rank'] <= 0) + { + $Val['build_old_rank'] = $Val['build_rank']; + } + if($Val['defs_old_rank'] <= 0) + { + $Val['defs_old_rank'] = $Val['defs_rank']; + } + if($Val['fleet_old_rank'] <= 0) + { + $Val['fleet_old_rank'] = $Val['fleets_rank']; + } + if($Val['total_old_rank'] <= 0) + { + $Val['total_old_rank'] = $Val['total_rank']; + } + if($Val['tech_yesterday_rank'] <= 0) + { + $Val['tech_yesterday_rank'] = $Val['tech_old_rank']; + } + if($Val['build_yesterday_rank'] <= 0) + { + $Val['build_yesterday_rank'] = $Val['build_old_rank']; + } + if($Val['defs_yesterday_rank'] <= 0) + { + $Val['defs_yesterday_rank'] = $Val['defs_old_rank']; + } + if($Val['fleet_yesterday_rank'] <= 0) + { + $Val['fleet_yesterday_rank'] = $Val['fleet_old_rank']; + } + if($Val['total_yesterday_rank'] <= 0) + { + $Val['total_yesterday_rank'] = $Val['total_old_rank']; + } + + foreach($Val as $key => $value) + { + if(empty($value)) + { + $Val[$key] = '0'; + } + } + + if($DailyStatsDiff > TIME_DAY OR $ForceDailyStats) + { + $Val['tech_yesterday_rank'] = $Val['tech_old_rank']; + $Val['build_yesterday_rank']= $Val['build_old_rank']; + $Val['defs_yesterday_rank'] = $Val['defs_old_rank']; + $Val['fleet_yesterday_rank']= $Val['fleet_old_rank']; + $Val['total_yesterday_rank']= $Val['total_old_rank']; + } + + $CreateQryRow = "({$Val['id']}, 1, "; + $CreateQryRow .= "{$Val['tech_rank']}, {$Val['tech_old_rank']}, {$Val['tech_yesterday_rank']}, {$Val['tech_points']}, {$Val['tech_count']}, "; + $CreateQryRow .= "{$Val['build_rank']}, {$Val['build_old_rank']}, {$Val['build_yesterday_rank']}, {$Val['build_points']}, {$Val['build_count']}, "; + $CreateQryRow .= "{$Val['defs_rank']}, {$Val['defs_old_rank']}, {$Val['defs_yesterday_rank']}, {$Val['defs_points']}, {$Val['defs_count']}, "; + $CreateQryRow .= "{$Val['fleets_rank']}, {$Val['fleet_old_rank']}, {$Val['fleet_yesterday_rank']}, {$Val['fleet_points']}, {$Val['fleet_count']}, "; + $CreateQryRow .= "{$Val['total_rank']}, {$Val['total_old_rank']}, {$Val['total_yesterday_rank']}, {$Val['total_points']}, {$Val['total_count']}"; + $CreateQryRow .= ")"; + + $QryInsertUserStatsArr[] = $CreateQryRow; + } + $QryInsertUserStats .= implode(', ', $QryInsertUserStatsArr).';'; + + $Bench->simpleCountStop(); + $CounterNames[] = '> Sending Query'; + $Bench->simpleCountStart(); + + doquery($QryInsertUserStats, 'statpoints'); + unset($QryInsertUserStatsArr); + unset($QryInsertUserStats); + unset($Users); + + $Bench->simpleCountStop(); +} +$Bench->simpleCountStop(); + +$CounterNames[] = 'Allys data Calculation and Insertion'; +$Bench->simpleCountStart(); + +///////////////////// ALLIANCES //////////////////// +$AllysNeedenFields = "{{prefix}}statpoints.total_rank, {{prefix}}statpoints.tech_rank, {{prefix}}statpoints.build_rank, {{prefix}}statpoints.defs_rank, {{prefix}}statpoints.fleet_rank, {{prefix}}statpoints.tech_yesterday_rank,{{prefix}}statpoints.build_yesterday_rank,{{prefix}}statpoints.defs_yesterday_rank,{{prefix}}statpoints.fleet_yesterday_rank,{{prefix}}statpoints.total_yesterday_rank"; +$GameAllys = doquery("SELECT {{table}}.*, {$AllysNeedenFields} FROM {{table}} LEFT JOIN {{prefix}}statpoints ON `stat_type` = 2 AND {{prefix}}statpoints.id_owner = {{table}}.id GROUP BY {{table}}.id", 'alliance'); + +$Loop = 0; +while($CurAlly = mysql_fetch_array($GameAllys, MYSQL_ASSOC)) +{ + $OldTotalRank = $CurAlly['total_rank']; + $OldTechRank = $CurAlly['tech_rank']; + $OldBuildRank = $CurAlly['build_rank']; + $OldDefsRank = $CurAlly['defs_rank']; + $OldFleetRank = $CurAlly['fleet_rank']; + + if(isset($AllyStats[$CurAlly['id']])) + { + $Points = $AllyStats[$CurAlly['id']]; + } + else + { + $Points = array( + 'TechCount' => 0, + 'TechPoint' => 0, + 'BuildCount' => 0, + 'BuildPoint' => 0, + 'DefsCount' => 0, + 'DefsPoint' => 0, + 'FleetCount' => 0, + 'FleetPoint' => 0, + 'TotalCount' => 0, + 'TotalPoint' => 0 + ); + } + + $TTechCount = $Points['TechCount']; + $TTechPoints = $Points['TechPoint']; + $TBuildCount = $Points['BuildCount']; + $TBuildPoints = $Points['BuildPoint']; + $TDefsCount = $Points['DefsCount']; + $TDefsPoints = $Points['DefsPoint']; + $TFleetCount = $Points['FleetCount']; + $TFleetPoints = $Points['FleetPoint']; + $GCount = $Points['TotalCount']; + $GPoints = $Points['TotalPoint']; + + $Allys[$Loop]['id'] = $CurAlly['id']; + $Allys[$Loop]['tech_points'] = $TTechPoints; + $Allys[$Loop]['tech_count'] = $TTechCount; + $Allys[$Loop]['tech_old_rank'] = $OldTechRank; + $Allys[$Loop]['build_points'] = $TBuildPoints; + $Allys[$Loop]['build_count'] = $TBuildCount; + $Allys[$Loop]['build_old_rank'] = $OldBuildRank; + $Allys[$Loop]['defs_points'] = $TDefsPoints; + $Allys[$Loop]['defs_count'] = $TDefsCount; + $Allys[$Loop]['defs_old_rank'] = $OldDefsRank; + $Allys[$Loop]['fleet_points'] = $TFleetPoints; + $Allys[$Loop]['fleet_count'] = $TFleetCount; + $Allys[$Loop]['fleet_old_rank'] = $OldFleetRank; + $Allys[$Loop]['total_points'] = $GPoints; + $Allys[$Loop]['total_count'] = $GCount; + $Allys[$Loop]['total_old_rank'] = $OldTotalRank; + $Allys[$Loop]['tech_yesterday_rank'] = $CurAlly['tech_yesterday_rank']; + $Allys[$Loop]['build_yesterday_rank'] = $CurAlly['build_yesterday_rank']; + $Allys[$Loop]['defs_yesterday_rank'] = $CurAlly['defs_yesterday_rank']; + $Allys[$Loop]['fleet_yesterday_rank'] = $CurAlly['fleet_yesterday_rank']; + $Allys[$Loop]['total_yesterday_rank'] = $CurAlly['total_yesterday_rank']; + + $AllysBuilds[$Loop] = $TBuildPoints; + $AllysTech[$Loop] = $TTechPoints; + $AllysDefs[$Loop] = $TDefsPoints; + $AllysFleets[$Loop] = $TFleetPoints; + $AllysTotal[$Loop] = $GPoints; + + $Loop += 1; +} + +arsort($AllysBuilds); +arsort($AllysTech); +arsort($AllysDefs); +arsort($AllysFleets); +arsort($AllysTotal); +$Loop = 1; +foreach($AllysBuilds as $Key => $Val) +{ + $Allys[$Key]['build_rank'] = $Loop; + $Loop += 1; +} +unset($AllysBuilds); +$Loop = 1; +foreach($AllysTech as $Key => $Val) +{ + $Allys[$Key]['tech_rank'] = $Loop; + $Loop += 1; +} +unset($AllysTech); +$Loop = 1; +foreach($AllysDefs as $Key => $Val) +{ + $Allys[$Key]['defs_rank'] = $Loop; + $Loop += 1; +} +unset($AllysDefs); +$Loop = 1; +foreach($AllysFleets as $Key => $Val) +{ + $Allys[$Key]['fleets_rank'] = $Loop; + $Loop += 1; +} +unset($AllysFleets); +$Loop = 1; +foreach($AllysTotal as $Key => $Val) +{ + $Allys[$Key]['total_rank'] = $Loop; + $Loop += 1; +} +unset($AllysTotal); + +doquery("DELETE FROM {{table}} WHERE `stat_type` = '2';", 'statpoints'); + +if(count($Allys) > 0) +{ + $QryInsertAllyStats = 'INSERT INTO {{table}} (`id_owner`, `stat_type`, `tech_rank`, `tech_old_rank`, `tech_yesterday_rank`, `tech_points`, `tech_count`, `build_rank`, `build_old_rank`, `build_yesterday_rank`, `build_points`, `build_count`, `defs_rank`, `defs_old_rank`, `defs_yesterday_rank`, `defs_points`, `defs_count`, `fleet_rank`, `fleet_old_rank`, `fleet_yesterday_rank`, `fleet_points`, `fleet_count`, `total_rank`, `total_old_rank`, `total_yesterday_rank`, `total_points`, `total_count`) VALUES '; + foreach($Allys as $Val) + { + if($Val['tech_old_rank'] <= 0) + { + $Val['tech_old_rank'] = $Val['tech_rank']; + } + if($Val['build_old_rank'] <= 0) + { + $Val['build_old_rank'] = $Val['build_rank']; + } + if($Val['defs_old_rank'] <= 0) + { + $Val['defs_old_rank'] = $Val['defs_rank']; + } + if($Val['fleet_old_rank'] <= 0) + { + $Val['fleet_old_rank'] = $Val['fleets_rank']; + } + if($Val['total_old_rank'] <= 0) + { + $Val['total_old_rank'] = $Val['total_rank']; + } + if($Val['tech_yesterday_rank'] <= 0) + { + $Val['tech_yesterday_rank'] = $Val['tech_old_rank']; + } + if($Val['build_yesterday_rank'] <= 0) + { + $Val['build_yesterday_rank'] = $Val['build_old_rank']; + } + if($Val['defs_yesterday_rank'] <= 0) + { + $Val['defs_yesterday_rank'] = $Val['defs_old_rank']; + } + if($Val['fleet_yesterday_rank'] <= 0) + { + $Val['fleet_yesterday_rank'] = $Val['fleet_old_rank']; + } + if($Val['total_yesterday_rank'] <= 0) + { + $Val['total_yesterday_rank'] = $Val['total_old_rank']; + } + + foreach($Val as $key => $value) + { + if(empty($value)) + { + $Val[$key] = '0'; + } + } + + if($DailyStatsDiff > TIME_DAY OR $ForceDailyStats) + { + $Val['tech_yesterday_rank'] = $Val['tech_old_rank']; + $Val['build_yesterday_rank'] = $Val['build_old_rank']; + $Val['defs_yesterday_rank'] = $Val['defs_old_rank']; + $Val['fleet_yesterday_rank'] = $Val['fleet_old_rank']; + $Val['total_yesterday_rank'] = $Val['total_old_rank']; + } + + $CreateQryRow = "({$Val['id']}, 2, "; + $CreateQryRow .= "{$Val['tech_rank']}, {$Val['tech_old_rank']}, {$Val['tech_yesterday_rank']}, {$Val['tech_points']}, {$Val['tech_count']}, "; + $CreateQryRow .= "{$Val['build_rank']}, {$Val['build_old_rank']}, {$Val['build_yesterday_rank']}, {$Val['build_points']}, {$Val['build_count']}, "; + $CreateQryRow .= "{$Val['defs_rank']}, {$Val['defs_old_rank']}, {$Val['defs_yesterday_rank']}, {$Val['defs_points']}, {$Val['defs_count']}, "; + $CreateQryRow .= "{$Val['fleets_rank']}, {$Val['fleet_old_rank']}, {$Val['fleet_yesterday_rank']}, {$Val['fleet_points']}, {$Val['fleet_count']}, "; + $CreateQryRow .= "{$Val['total_rank']}, {$Val['total_old_rank']}, {$Val['total_yesterday_rank']}, {$Val['total_points']}, {$Val['total_count']}"; + $CreateQryRow .= ")"; + + $QryInsertAllyStatsArr[] = $CreateQryRow; + } + $QryInsertAllyStats .= implode(', ', $QryInsertAllyStatsArr).';'; + + doquery($QryInsertAllyStats, 'statpoints'); + unset($QryInsertAllyStatsArr); + unset($QryInsertAllyStats); + unset($Allys); +} +$Bench->simpleCountStop(); +$CounterNames[] = 'Records Calculation and Insertion'; +$Bench->simpleCountStart(); + +//////////////// RECORDS ///////////////////// +doquery("DELETE FROM {{table}};", 'records'); +$records = array(); +$Loop = 0; + +foreach($_Vars_GameElements as $Element => $ElementName) +{ + if(!empty($ElementName)) + { + $UserID = 0; + $ElementCount = 0; + $Allow = true; + if(($Element >= 1 AND $Element <= 39) OR $Element == 44) + { + // Buildings + $UserID = isset($BuildingRecords[$Element]['user']) ? $BuildingRecords[$Element]['user'] : null; + $ElementCount = isset($BuildingRecords[$Element]['lvl']) ? $BuildingRecords[$Element]['lvl'] : null; + } + elseif($Element >= 41 AND $Element <= 99 AND $Element != 44 AND $Element != 50) + { + // Special buildings + $UserID = isset($BuildingRecords[$Element]['user']) ? $BuildingRecords[$Element]['user'] : null; + $ElementCount = isset($BuildingRecords[$Element]['lvl']) ? $BuildingRecords[$Element]['lvl'] : null; + } + elseif($Element >= 101 AND $Element <= 199) + { + // Technology + $UserID = isset($TechRecords[$Element]['user']) ? $TechRecords[$Element]['user'] : null; + $ElementCount = isset($TechRecords[$Element]['lvl']) ? $TechRecords[$Element]['lvl'] : null; + } + elseif($Element >= 201 AND $Element <= 399) + { + // Fleets + $UserID = isset($FleetRecords[$Element]['user']) ? $FleetRecords[$Element]['user'] : null; + $ElementCount = isset($FleetRecords[$Element]['lvl']) ? $FleetRecords[$Element]['lvl'] : null; + } + elseif($Element >= 401 AND $Element <= 599 AND $Element != 407 AND $Element != 408 AND $Element != 409) + { + // Defences (Excluded: Shields) + $UserID = isset($DefenseRecords[$Element]['user']) ? $DefenseRecords[$Element]['user'] : null; + $ElementCount = isset($DefenseRecords[$Element]['lvl']) ? $DefenseRecords[$Element]['lvl'] : null; + } + else + { + $Allow = false; + } + + if($Allow) + { + if($UserID == 0) + { + $UserID = '0'; + $ElementCount = '0'; + } + if($ElementCount == 0) + { + $ElementCount = '0'; + $UserID = '0'; + } + $records[] = array('element' => $Element, 'user' => $UserID, 'count' => $ElementCount); + } + } +} + +if(count($records) > 0) +{ + $QryInsertRecords = "INSERT INTO {{table}} (`id`, `id_owner`, `element`, `count`) VALUES "; + foreach($records as $val) + { + $QryInsertRecordsArr[] = "(NULL, {$val['user']}, {$val['element']}, {$val['count']})"; + } + $QryInsertRecords .= implode(', ', $QryInsertRecordsArr).';'; + + doquery($QryInsertRecords, 'records'); + unset($QryInsertRecordsArr); + unset($QryInsertRecords); +} +$Bench->simpleCountStop(); +// ------------------------------------------------------------------------------------------- +$CounterNames[] = 'Deleting Users'; +$Bench->simpleCountStart(); + +// Delete all NonActivated Users which are in DataBase for at least 7 days +$SelectNonActivatedUsers = doquery("SELECT `id` FROM {{table}} WHERE `activation_code` != '' AND `register_time` < ({$StatDate} - (".NONACTIVE_DELETETIME."));", 'users'); +while($NonActivated = mysql_fetch_array($SelectNonActivatedUsers, MYSQL_ASSOC)) +{ + $UsersToDelete[] = $NonActivated['id']; +} + +if(!empty($UsersToDelete)) +{ + include($_EnginePath.'includes/functions/DeleteSelectedUser.php'); + include($_EnginePath.'includes/functions/FleetControl_Retreat.php'); + DeleteSelectedUser($UsersToDelete); +} + +$Bench->simpleCountStop(); +$CounterNames[] = 'Removing VacationModes & Updating Banned PPL'; +$Bench->simpleCountStart(); + +if(!empty($UsersToRemoveVacations)) +{ + $UsersToRemoveVacations = implode(', ', $UsersToRemoveVacations); + doquery("UPDATE {{table}} SET `is_onvacation` = '0', `vacation_starttime` = '0', `vacation_endtime` = '0', `vacation_leavetime` = IF(`vacation_type` = 2, 0, {$StatDate}) WHERE `id` IN ({$UsersToRemoveVacations});", 'users'); + doquery("UPDATE {{table}} SET `last_update` = {$StatDate} WHERE `id_owner` IN ({$UsersToRemoveVacations});", 'planets'); +} +if(!empty($UsersToRemoveBan)) +{ + $UsersToRemoveBan = implode(', ', $UsersToRemoveBan); + doquery("UPDATE {{table}} SET `is_banned` = 0, `ban_endtime` = 0 WHERE `id` IN ({$UsersToRemoveBan});", 'users'); + doquery("UPDATE {{table}} SET `Active` = 0, `Expired` = 1 WHERE `Active` = 1 AND `UserID` IN ({$UsersToRemoveBan});", 'bans'); +} + +$Bench->simpleCountStop(); + +$CounterNames[] = 'DataBase Optimization'; +$Bench->simpleCountStart(); +if(($StatDate - $_GameConfig['last_db_optimization']) > (2 * TIME_HOUR)) +{ + $TableList = array + ( + 'acs', 'alliance', 'buddy', 'declarations', 'errors', 'fleets', + 'galaxy', 'ignoresystem', 'notes', 'planets', + 'records', 'statpoints', 'users' + ); + + foreach($TableList as $key => $val) + { + $TableList[$key] = '{{prefix}}'.$val; + } + + $TableList = implode(', ', $TableList); + + doquery("OPTIMIZE TABLE {$TableList}", ''); + doquery("UPDATE {{table}} SET `config_value` = {$StatDate} WHERE `config_name` = 'last_db_optimization';", 'config'); + $_GameConfig['last_db_optimization'] = $StatDate; +} +$Bench->simpleCountStop(); +$CounterNames[] = 'Final Updates'; +$Bench->simpleCountStart(); +doquery("UPDATE {{table}} SET `config_value` = {$StatDate} WHERE `config_name` = 'last_update';", 'config'); +$_GameConfig['last_update'] = $StatDate; + +// Create LastUpdate CacheFile (for Signature Generator) +file_put_contents('../cache/data/last_stats_update.php', ''); + +if($DailyStatsDiff > TIME_DAY) +{ + doquery("UPDATE {{table}} SET `config_value` = {$StatDate} WHERE `config_name` = 'last_stats_daily';", 'config'); + $_GameConfig['last_stats_daily'] = $StatDate; +} +$_MemCache->GameConfig = $_GameConfig; + +$EndTime = microtime(true); +$Bench->simpleCountStop(); +$CountTime = $Bench->ReturnSimpleCountArray(); + +$TotalTime = sprintf('%0.6f', $EndTime - $StartTime); + +if($ShowOutput) +{ + $Counted = '
'; + foreach($CountTime as $Key => $Data) + { + if(strstr($CounterNames[$Key], '>') == true) + { + $LastWasAssoc = true; + } + else + { + if(isset($LastWasAssoc) && $LastWasAssoc === true) + { + $Counted .= ''; + } + $LastWasAssoc = false; + } + $Counted .= ''; + } + $Counted .= '
'.$CounterNames[$Key].' '.sprintf('%0.20f', $Data['result']).'
'.$Data['endram'].'
'; + + AdminMessage(sprintf($_Lang['AutoStatBuilder_BuildInfo'], $TotalTime, pretty_time($DailyStatsDiff, true), $DailyStatsDiff, $Counted), $_Lang['AutoStatBuilder_Title']); +} +else +{ + AdminMessage('OK', $_Lang['AutoStatBuilder_Title']); +} + +?> diff --git a/admin/autostatbuilder_functions.php b/admin/autostatbuilder_functions.php index 125dc69dc..9e6521316 100644 --- a/admin/autostatbuilder_functions.php +++ b/admin/autostatbuilder_functions.php @@ -1,219 +1,219 @@ - 0) - { - $FactorSum = 0; - $TechCounts += $ThisLevel; - $TechArr[$Techno] = $ThisLevel; - $CacheEmpty = false; - - if(isset($Cached[$Techno][$ThisLevel])) - { - // This Technology was already calculated on that level - get points from Cache - $TechPoints += $Cached[$Techno][$ThisLevel]; - continue; - } - else if(isset($Cached[$Techno]) && count($Cached[$Techno]) > 1) - { - // This Technology was calculated, but on lower level - get points from that level - $StartingLevel = count($Cached[$Techno]); - } - else - { - // This Technology was never seen before - $StartingLevel = 1; - $CacheEmpty = true; - } - - if(isset($ResourcesCost[$Techno])) - { - $Units = $ResourcesCost[$Techno]; - } - else - { - $Units = $_Vars_Prices[$Techno]['metal'] + $_Vars_Prices[$Techno]['crystal'] + $_Vars_Prices[$Techno]['deuterium']; - $ResourcesCost[$Techno] = $Units; - } - if($CacheEmpty) - { - $Cached[$Techno][1] = $Units; - } - else - { - $FactorSum += $CachedFactors[$Techno][$StartingLevel]; - } - - for($Level = $StartingLevel; $Level < $ThisLevel; $Level += 1) - { - $FactorSum += pow($_Vars_Prices[$Techno]['factor'], $Level); - $CachedFactors[$Techno][($Level + 1)] = $FactorSum; - $Cached[$Techno][($Level + 1)] = $Units * ($FactorSum + 1); - } - $TechPoints += $Cached[$Techno][$ThisLevel]; - } - } - $RetValue['TechCount'] = $TechCounts; - $RetValue['TechPoint'] = $TechPoints; - $RetValue['TechArr'] = $TechArr; - - return $RetValue; -} - -function GetBuildPoints($CurrentPlanet) -{ - global $_Vars_GameElements, $_Vars_Prices, $_Vars_ElementCategories; - static $ResourcesCost, $Cached, $CachedFactors; - - $BuildCounts = 0; - $BuildPoints = 0; - $BuildArr = null; - foreach($_Vars_ElementCategories['build'] AS $Building) - { - $ThisLevel = $CurrentPlanet[$_Vars_GameElements[$Building]]; - if($ThisLevel > 0) - { - $FactorSum = 0; - $BuildCounts += $ThisLevel; - $BuildArr[$Building] = $ThisLevel; - $CacheEmpty = false; - - if(isset($Cached[$Building][$ThisLevel])) - { - // This Building was already calculated on that level - get points from Cache - $BuildPoints += $Cached[$Building][$ThisLevel]; - continue; - } - else if(isset($Cached[$Building]) && count($Cached[$Building]) > 1) - { - // This Building was calculated, but on lower level - get points from that level - $StartingLevel = count($Cached[$Building]); - } - else - { - // This Building was never seen before - $StartingLevel = 1; - $CacheEmpty = true; - } - - if(isset($ResourcesCost[$Building])) - { - $Units = $ResourcesCost[$Building]; - } - else - { - $Units = $_Vars_Prices[$Building]['metal'] + $_Vars_Prices[$Building]['crystal'] + $_Vars_Prices[$Building]['deuterium']; - $ResourcesCost[$Building] = $Units; - } - if($CacheEmpty) - { - $Cached[$Building][1] = $Units; - } - else - { - $FactorSum += $CachedFactors[$Building][$StartingLevel]; - } - - for($Level = $StartingLevel; $Level < $ThisLevel; $Level += 1) - { - $FactorSum += pow($_Vars_Prices[$Building]['factor'], $Level); - $CachedFactors[$Building][($Level + 1)] = $FactorSum; - $Cached[$Building][($Level + 1)] = $Units * ($FactorSum + 1); - } - $BuildPoints += $Cached[$Building][$ThisLevel]; - } - } - $RetValue['BuildCount'] = $BuildCounts; - $RetValue['BuildPoint'] = $BuildPoints; - $RetValue['BuildArr'] = $BuildArr; - - return $RetValue; -} - -function GetDefensePoints($CurrentPlanet) -{ - global $_Vars_GameElements, $_Vars_Prices, $_Vars_ElementCategories; - - $DefenseCounts = 0; - $DefensePoints = 0; - $DefenseArr = null; - foreach($_Vars_ElementCategories['defense'] as $Defense) - { - if($CurrentPlanet[$_Vars_GameElements[$Defense]] > 0) - { - $Units = $_Vars_Prices[$Defense]['metal'] + $_Vars_Prices[$Defense]['crystal'] + $_Vars_Prices[$Defense]['deuterium']; - $DefensePoints += ($Units * $CurrentPlanet[$_Vars_GameElements[$Defense]]); - $DefenseCounts += $CurrentPlanet[$_Vars_GameElements[$Defense]]; - $DefenseArr[$Defense] = $CurrentPlanet[$_Vars_GameElements[$Defense]]; - } - } - $RetValue['DefenseCount'] = $DefenseCounts; - $RetValue['DefensePoint'] = $DefensePoints; - $RetValue['DefenseArr'] = $DefenseArr; - - return $RetValue; -} - -function GetFleetPoints($CurrentPlanet) -{ - global $_Vars_GameElements, $_Vars_Prices, $_Vars_ElementCategories; - - $FleetCounts = 0; - $FleetPoints = 0; - $FleetArr = null; - foreach($_Vars_ElementCategories['fleet'] as $Fleet) - { - if($CurrentPlanet[$_Vars_GameElements[$Fleet]] > 0) - { - $Units = $_Vars_Prices[$Fleet]['metal'] + $_Vars_Prices[$Fleet]['crystal'] + $_Vars_Prices[$Fleet]['deuterium']; - $FleetPoints += ($Units * $CurrentPlanet[$_Vars_GameElements[$Fleet]]); - $FleetCounts += $CurrentPlanet[$_Vars_GameElements[$Fleet]]; - $FleetArr[$Fleet] = $CurrentPlanet[$_Vars_GameElements[$Fleet]]; - } - } - $RetValue['FleetCount'] = $FleetCounts; - $RetValue['FleetPoint'] = $FleetPoints; - $RetValue['FleetArr'] = $FleetArr; - - return $RetValue; -} - -function GetFleetPointsOnTour($CurrentFleet) -{ - global $_Vars_Prices; - - $FleetCounts = 0; - $FleetPoints = 0; - $FleetArr = null; - - $Fleet = explode(';', $CurrentFleet); - foreach($Fleet as $Data) - { - if(!empty($Data)) - { - $Data = explode(',', $Data); - $Price = $_Vars_Prices[$Data[0]]['metal'] + $_Vars_Prices[$Data[0]]['crystal'] + $_Vars_Prices[$Data[0]]['deuterium']; - $FleetPoints += $Price * $Data[1]; - $FleetCounts += $Data[1]; - $FleetArr[$Data[0]] = $Data[1]; - } - } - - $RetValue['FleetCount'] = $FleetCounts; - $RetValue['FleetPoint'] = $FleetPoints; - $RetValue['FleetArr'] = $FleetArr; - - return $RetValue; -} - -?> \ No newline at end of file + 0) + { + $FactorSum = 0; + $TechCounts += $ThisLevel; + $TechArr[$Techno] = $ThisLevel; + $CacheEmpty = false; + + if(isset($Cached[$Techno][$ThisLevel])) + { + // This Technology was already calculated on that level - get points from Cache + $TechPoints += $Cached[$Techno][$ThisLevel]; + continue; + } + else if(isset($Cached[$Techno]) && count($Cached[$Techno]) > 1) + { + // This Technology was calculated, but on lower level - get points from that level + $StartingLevel = count($Cached[$Techno]); + } + else + { + // This Technology was never seen before + $StartingLevel = 1; + $CacheEmpty = true; + } + + if(isset($ResourcesCost[$Techno])) + { + $Units = $ResourcesCost[$Techno]; + } + else + { + $Units = $_Vars_Prices[$Techno]['metal'] + $_Vars_Prices[$Techno]['crystal'] + $_Vars_Prices[$Techno]['deuterium']; + $ResourcesCost[$Techno] = $Units; + } + if($CacheEmpty) + { + $Cached[$Techno][1] = $Units; + } + else + { + $FactorSum += $CachedFactors[$Techno][$StartingLevel]; + } + + for($Level = $StartingLevel; $Level < $ThisLevel; $Level += 1) + { + $FactorSum += pow($_Vars_Prices[$Techno]['factor'], $Level); + $CachedFactors[$Techno][($Level + 1)] = $FactorSum; + $Cached[$Techno][($Level + 1)] = $Units * ($FactorSum + 1); + } + $TechPoints += $Cached[$Techno][$ThisLevel]; + } + } + $RetValue['TechCount'] = $TechCounts; + $RetValue['TechPoint'] = $TechPoints; + $RetValue['TechArr'] = $TechArr; + + return $RetValue; +} + +function GetBuildPoints($CurrentPlanet) +{ + global $_Vars_GameElements, $_Vars_Prices, $_Vars_ElementCategories; + static $ResourcesCost, $Cached, $CachedFactors; + + $BuildCounts = 0; + $BuildPoints = 0; + $BuildArr = null; + foreach($_Vars_ElementCategories['build'] AS $Building) + { + $ThisLevel = $CurrentPlanet[$_Vars_GameElements[$Building]]; + if($ThisLevel > 0) + { + $FactorSum = 0; + $BuildCounts += $ThisLevel; + $BuildArr[$Building] = $ThisLevel; + $CacheEmpty = false; + + if(isset($Cached[$Building][$ThisLevel])) + { + // This Building was already calculated on that level - get points from Cache + $BuildPoints += $Cached[$Building][$ThisLevel]; + continue; + } + else if(isset($Cached[$Building]) && count($Cached[$Building]) > 1) + { + // This Building was calculated, but on lower level - get points from that level + $StartingLevel = count($Cached[$Building]); + } + else + { + // This Building was never seen before + $StartingLevel = 1; + $CacheEmpty = true; + } + + if(isset($ResourcesCost[$Building])) + { + $Units = $ResourcesCost[$Building]; + } + else + { + $Units = $_Vars_Prices[$Building]['metal'] + $_Vars_Prices[$Building]['crystal'] + $_Vars_Prices[$Building]['deuterium']; + $ResourcesCost[$Building] = $Units; + } + if($CacheEmpty) + { + $Cached[$Building][1] = $Units; + } + else + { + $FactorSum += $CachedFactors[$Building][$StartingLevel]; + } + + for($Level = $StartingLevel; $Level < $ThisLevel; $Level += 1) + { + $FactorSum += pow($_Vars_Prices[$Building]['factor'], $Level); + $CachedFactors[$Building][($Level + 1)] = $FactorSum; + $Cached[$Building][($Level + 1)] = $Units * ($FactorSum + 1); + } + $BuildPoints += $Cached[$Building][$ThisLevel]; + } + } + $RetValue['BuildCount'] = $BuildCounts; + $RetValue['BuildPoint'] = $BuildPoints; + $RetValue['BuildArr'] = $BuildArr; + + return $RetValue; +} + +function GetDefensePoints($CurrentPlanet) +{ + global $_Vars_GameElements, $_Vars_Prices, $_Vars_ElementCategories; + + $DefenseCounts = 0; + $DefensePoints = 0; + $DefenseArr = null; + foreach($_Vars_ElementCategories['defense'] as $Defense) + { + if($CurrentPlanet[$_Vars_GameElements[$Defense]] > 0) + { + $Units = $_Vars_Prices[$Defense]['metal'] + $_Vars_Prices[$Defense]['crystal'] + $_Vars_Prices[$Defense]['deuterium']; + $DefensePoints += ($Units * $CurrentPlanet[$_Vars_GameElements[$Defense]]); + $DefenseCounts += $CurrentPlanet[$_Vars_GameElements[$Defense]]; + $DefenseArr[$Defense] = $CurrentPlanet[$_Vars_GameElements[$Defense]]; + } + } + $RetValue['DefenseCount'] = $DefenseCounts; + $RetValue['DefensePoint'] = $DefensePoints; + $RetValue['DefenseArr'] = $DefenseArr; + + return $RetValue; +} + +function GetFleetPoints($CurrentPlanet) +{ + global $_Vars_GameElements, $_Vars_Prices, $_Vars_ElementCategories; + + $FleetCounts = 0; + $FleetPoints = 0; + $FleetArr = null; + foreach($_Vars_ElementCategories['fleet'] as $Fleet) + { + if($CurrentPlanet[$_Vars_GameElements[$Fleet]] > 0) + { + $Units = $_Vars_Prices[$Fleet]['metal'] + $_Vars_Prices[$Fleet]['crystal'] + $_Vars_Prices[$Fleet]['deuterium']; + $FleetPoints += ($Units * $CurrentPlanet[$_Vars_GameElements[$Fleet]]); + $FleetCounts += $CurrentPlanet[$_Vars_GameElements[$Fleet]]; + $FleetArr[$Fleet] = $CurrentPlanet[$_Vars_GameElements[$Fleet]]; + } + } + $RetValue['FleetCount'] = $FleetCounts; + $RetValue['FleetPoint'] = $FleetPoints; + $RetValue['FleetArr'] = $FleetArr; + + return $RetValue; +} + +function GetFleetPointsOnTour($CurrentFleet) +{ + global $_Vars_Prices; + + $FleetCounts = 0; + $FleetPoints = 0; + $FleetArr = null; + + $Fleet = explode(';', $CurrentFleet); + foreach($Fleet as $Data) + { + if(!empty($Data)) + { + $Data = explode(',', $Data); + $Price = $_Vars_Prices[$Data[0]]['metal'] + $_Vars_Prices[$Data[0]]['crystal'] + $_Vars_Prices[$Data[0]]['deuterium']; + $FleetPoints += $Price * $Data[1]; + $FleetCounts += $Data[1]; + $FleetArr[$Data[0]] = $Data[1]; + } + } + + $RetValue['FleetCount'] = $FleetCounts; + $RetValue['FleetPoint'] = $FleetPoints; + $RetValue['FleetArr'] = $FleetArr; + + return $RetValue; +} + +?> diff --git a/admin/banslist.php b/admin/banslist.php index c13efba87..31dea6590 100644 --- a/admin/banslist.php +++ b/admin/banslist.php @@ -1,305 +1,305 @@ - 0) - { - while($Data = mysql_fetch_assoc($CheckUsers)) - { - $Filters['UserID'][] = $Data['id']; - } - } - } - if(!empty($Filters['UserID'])) - { - $Filters['UserID'] = implode(',', $Filters['UserID']); - $Filters['UserID'] = "`UserID` IN ({$Filters['UserID']})"; - } - if(!empty($_Lang['Insert_Input_Users'])) - { - $_Lang['Insert_Input_Users'] = implode(',', $_Lang['Insert_Input_Users']); - } - } - - if(!empty($_POST['date_from'])) - { - $TempDate = strtotime($_POST['date_from']); - if($TempDate >= 0) - { - $FilterDateFrom = $TempDate; - $Filters[] = "`StartTime` >= {$TempDate}"; - $_Lang['Insert_Input_DateFrom'] = $_POST['date_from']; - } - } - - if(!empty($_POST['date_to'])) - { - $TempDate = strtotime($_POST['date_to']); - if($TempDate > 0 AND $TempDate > $FilterDateFrom) - { - $Filters[] = "((`Removed` = 1 AND `RemoveDate` <= {$TempDate}) OR (`Removed` = 0 AND `EndTime` <= {$TempDate}))"; - $_Lang['Insert_Input_DateTo'] = $_POST['date_to']; - } - } - } - - $_Page = isset($_POST['page']) ? intval($_POST['page']) : 0; - if($_Page < 1) - { - $_Page = 1; - } - $Select_Start = ($_Page - 1) * $_PerPage; - - if(!empty($Filters)) - { - $SelectIDs = "SELECT `ID` FROM {{table}} "; - foreach($Filters as $FilterData) - { - $QueryArr[] = $FilterData; - } - $SelectIDs .= "WHERE ".implode(' AND ', $QueryArr); - - $SelectedIDs = doquery($SelectIDs, 'bans'); - if(mysql_num_rows($SelectedIDs) > 0) - { - while($ThisRow = mysql_fetch_assoc($SelectedIDs)) - { - $FilterIDs[] = $ThisRow['ID']; - } - $TotalCount = count($FilterIDs); - $SelectWhere = " WHERE `ID` IN (".implode(', ', $FilterIDs).") "; - $RunQuery = true; - } - else - { - $TotalCount = 0; - } - } - else - { - $SelectTotalCount = doquery("SELECT COUNT(*) AS `Count` FROM {{table}};", 'bans', true); - $TotalCount = $SelectTotalCount['Count']; - if($TotalCount > 0) - { - $RunQuery = true; - } - } - if(isset($RunQuery)) - { - if($Select_Start >= $TotalCount) - { - $_Page = 1; - $Select_Start = 0; - } - - $SelectQuery = "SELECT * FROM {{table}} "; - $SelectQuery .= isset($SelectWhere) ? $SelectWhere : ''; - $SelectQuery .= "ORDER BY `Active` DESC, `EndTime` DESC LIMIT {$Select_Start}, {$_PerPage};"; - $SelectResult = doquery($SelectQuery, 'bans'); - } - else - { - $SelectResult = false; - } - - if($SelectResult !== false) - { - $GetUsernames = array(); - $TPL_Row = gettemplate('admin/banslist_row'); - - while($Row = mysql_fetch_assoc($SelectResult)) - { - if($Row['Active'] == 1) - { - if($Row['EndTime'] > $Now) - { - if($_JSChronoAppletIncluded === false) - { - $_JSChronoAppletIncluded = true; - include($_EnginePath.'includes/functions/InsertJavaScriptChronoApplet.php'); - } - $_Lang['Insert_Scripts'] .= InsertJavaScriptChronoApplet($Row['ID'], '', $Row['EndTime'], true); - $Row['Status'] = "{$_Lang['Row_Active']}
".pretty_time($Row['EndTime'] - $Now, true, 'D').""; - } - else - { - $Row['Status'] = $_Lang['Row_Expired']; - } - } - else - { - if($Row['Expired'] == 1) - { - $Row['Status'] = $_Lang['Row_Expired']; - } - else - { - $Row['Status'] = "{$_Lang['Row_Removed']}
".prettyDate('d m Y H:i:s', $Row['RemoveDate'], 1); - } - } - - if($Row['With_Vacation'] == 1) - { - $Row['Indicators'][] = $_Lang['Row_WithVacation']; - } - else - { - $Row['Indicators'][] = $_Lang['Row_WithoutVacation']; - } - if($Row['Fleets_Retreated_Own'] == 1 AND $Row['Fleets_Retreated_Others']) - { - $Row['Indicators'][] = $_Lang['Row_AllFleetsRetreaded']; - } - elseif($Row['Fleets_Retreated_Own'] == 1) - { - $Row['Indicators'][] = $_Lang['Row_OwnFleetsRetreaded']; - } - elseif($Row['Fleets_Retreated_Others'] == 1) - { - $Row['Indicators'][] = $_Lang['Row_OthersFleetsRetreaded']; - } - else - { - $Row['Indicators'][] = $_Lang['Row_NoFleetsRetreaded']; - } - if($Row['BlockadeOn_CookieStyle'] == 1) - { - $Row['Indicators'][] = $_Lang['Row_BlockadeOnCookieStyle']; - } - if(!empty($Row['Indicators'])) - { - $Row['Indicators'] = implode('
', $Row['Indicators']); - } - else - { - $Row['Indicators'] = ''; - } - - $ParsedRow = array - ( - 'ID' => $Row['ID'], - 'UserID' => $Row['UserID'], - 'StartTimeParsed' => prettyDate('d m Y H:i:s', $Row['StartTime'], 1), - 'Duration' => str_replace('00:00:00', '', pretty_time($Row['EndTime'] - $Row['StartTime'], true, 'D')), - 'EndTimeParsed' => prettyDate('d m Y H:i:s', $Row['EndTime'], 1), - 'Status' => $Row['Status'], - 'Reason' => (!empty($Row['Reason']) ? $Row['Reason'] : $_Lang['Row_ReasonEmpty']), - 'GiverID' => $Row['GiverID'], - 'Indicators' => $Row['Indicators'] - ); - - if(!in_array($Row['UserID'], $GetUsernames)) - { - $GetUsernames[] = $Row['UserID']; - } - if(!in_array($Row['GiverID'], $GetUsernames)) - { - $GetUsernames[] = $Row['GiverID']; - } - - $InsertRows[] = $ParsedRow; - } - - if(!empty($GetUsernames)) - { - $ResultUsernames = doquery("SELECT `id`, `username` FROM {{table}} WHERE `id` IN (".implode(', ', $GetUsernames).");", 'users'); - if($ResultUsernames != false) - { - while($UserData = mysql_fetch_assoc($ResultUsernames)) - { - $UsernamesArray[$UserData['id']] = $UserData['username']; - } - } - } - - foreach($InsertRows as $RowData) - { - $RowData['UserParsed'] = "{$UsernamesArray[$RowData['UserID']]} (#{$RowData['UserID']})"; - $RowData['GiverParsed'] = "{$UsernamesArray[$RowData['GiverID']]} (#{$RowData['GiverID']})"; - - $_Lang['Insert_Rows'][] = parsetemplate($TPL_Row, $RowData); - } - $_Lang['Insert_Rows'] = implode('', $_Lang['Insert_Rows']); - - if($TotalCount > $_PerPage) - { - include($_EnginePath.'includes/functions/Pagination.php'); - $Pagin = CreatePaginationArray($TotalCount, $_PerPage, $_Page, 7); - $PaginationTPL = "{\$ShowValue}"; - $PaginationViewOpt = array('CurrentPage_Classes' => 'orange', 'Breaker_View' => '...'); - $CreatePagination = implode(' ', ParsePaginationArray($Pagin, $_Page, $PaginationTPL, $PaginationViewOpt)); - $_Lang['Insert_Pagination'] = ''.$CreatePagination.''; - } - } - else - { - $_Lang['Insert_Rows'] = parsetemplate(gettemplate('_singleRow'), array('Colspan' => $_Colspan, 'Classes' => 'pad5 orange', 'Text' => $_Lang['Error_NoRows'])); - } - - $_Lang['Colspan'] = $_Colspan; - display(parsetemplate(gettemplate('admin/banslist_body'), $_Lang), $_Lang['Page_Title'], false, true); - -?> \ No newline at end of file + 0) + { + while($Data = mysql_fetch_assoc($CheckUsers)) + { + $Filters['UserID'][] = $Data['id']; + } + } + } + if(!empty($Filters['UserID'])) + { + $Filters['UserID'] = implode(',', $Filters['UserID']); + $Filters['UserID'] = "`UserID` IN ({$Filters['UserID']})"; + } + if(!empty($_Lang['Insert_Input_Users'])) + { + $_Lang['Insert_Input_Users'] = implode(',', $_Lang['Insert_Input_Users']); + } + } + + if(!empty($_POST['date_from'])) + { + $TempDate = strtotime($_POST['date_from']); + if($TempDate >= 0) + { + $FilterDateFrom = $TempDate; + $Filters[] = "`StartTime` >= {$TempDate}"; + $_Lang['Insert_Input_DateFrom'] = $_POST['date_from']; + } + } + + if(!empty($_POST['date_to'])) + { + $TempDate = strtotime($_POST['date_to']); + if($TempDate > 0 AND $TempDate > $FilterDateFrom) + { + $Filters[] = "((`Removed` = 1 AND `RemoveDate` <= {$TempDate}) OR (`Removed` = 0 AND `EndTime` <= {$TempDate}))"; + $_Lang['Insert_Input_DateTo'] = $_POST['date_to']; + } + } +} + +$_Page = isset($_POST['page']) ? intval($_POST['page']) : 0; +if($_Page < 1) +{ + $_Page = 1; +} +$Select_Start = ($_Page - 1) * $_PerPage; + +if(!empty($Filters)) +{ + $SelectIDs = "SELECT `ID` FROM {{table}} "; + foreach($Filters as $FilterData) + { + $QueryArr[] = $FilterData; + } + $SelectIDs .= "WHERE ".implode(' AND ', $QueryArr); + + $SelectedIDs = doquery($SelectIDs, 'bans'); + if(mysql_num_rows($SelectedIDs) > 0) + { + while($ThisRow = mysql_fetch_assoc($SelectedIDs)) + { + $FilterIDs[] = $ThisRow['ID']; + } + $TotalCount = count($FilterIDs); + $SelectWhere = " WHERE `ID` IN (".implode(', ', $FilterIDs).") "; + $RunQuery = true; + } + else + { + $TotalCount = 0; + } +} +else +{ + $SelectTotalCount = doquery("SELECT COUNT(*) AS `Count` FROM {{table}};", 'bans', true); + $TotalCount = $SelectTotalCount['Count']; + if($TotalCount > 0) + { + $RunQuery = true; + } +} +if(isset($RunQuery)) +{ + if($Select_Start >= $TotalCount) + { + $_Page = 1; + $Select_Start = 0; + } + + $SelectQuery = "SELECT * FROM {{table}} "; + $SelectQuery .= isset($SelectWhere) ? $SelectWhere : ''; + $SelectQuery .= "ORDER BY `Active` DESC, `EndTime` DESC LIMIT {$Select_Start}, {$_PerPage};"; + $SelectResult = doquery($SelectQuery, 'bans'); +} +else +{ + $SelectResult = false; +} + +if($SelectResult !== false) +{ + $GetUsernames = array(); + $TPL_Row = gettemplate('admin/banslist_row'); + + while($Row = mysql_fetch_assoc($SelectResult)) + { + if($Row['Active'] == 1) + { + if($Row['EndTime'] > $Now) + { + if($_JSChronoAppletIncluded === false) + { + $_JSChronoAppletIncluded = true; + include($_EnginePath.'includes/functions/InsertJavaScriptChronoApplet.php'); + } + $_Lang['Insert_Scripts'] .= InsertJavaScriptChronoApplet($Row['ID'], '', $Row['EndTime'], true); + $Row['Status'] = "{$_Lang['Row_Active']}
".pretty_time($Row['EndTime'] - $Now, true, 'D').""; + } + else + { + $Row['Status'] = $_Lang['Row_Expired']; + } + } + else + { + if($Row['Expired'] == 1) + { + $Row['Status'] = $_Lang['Row_Expired']; + } + else + { + $Row['Status'] = "{$_Lang['Row_Removed']}
".prettyDate('d m Y H:i:s', $Row['RemoveDate'], 1); + } + } + + if($Row['With_Vacation'] == 1) + { + $Row['Indicators'][] = $_Lang['Row_WithVacation']; + } + else + { + $Row['Indicators'][] = $_Lang['Row_WithoutVacation']; + } + if($Row['Fleets_Retreated_Own'] == 1 AND $Row['Fleets_Retreated_Others']) + { + $Row['Indicators'][] = $_Lang['Row_AllFleetsRetreaded']; + } + elseif($Row['Fleets_Retreated_Own'] == 1) + { + $Row['Indicators'][] = $_Lang['Row_OwnFleetsRetreaded']; + } + elseif($Row['Fleets_Retreated_Others'] == 1) + { + $Row['Indicators'][] = $_Lang['Row_OthersFleetsRetreaded']; + } + else + { + $Row['Indicators'][] = $_Lang['Row_NoFleetsRetreaded']; + } + if($Row['BlockadeOn_CookieStyle'] == 1) + { + $Row['Indicators'][] = $_Lang['Row_BlockadeOnCookieStyle']; + } + if(!empty($Row['Indicators'])) + { + $Row['Indicators'] = implode('
', $Row['Indicators']); + } + else + { + $Row['Indicators'] = ''; + } + + $ParsedRow = array + ( + 'ID' => $Row['ID'], + 'UserID' => $Row['UserID'], + 'StartTimeParsed' => prettyDate('d m Y H:i:s', $Row['StartTime'], 1), + 'Duration' => str_replace('00:00:00', '', pretty_time($Row['EndTime'] - $Row['StartTime'], true, 'D')), + 'EndTimeParsed' => prettyDate('d m Y H:i:s', $Row['EndTime'], 1), + 'Status' => $Row['Status'], + 'Reason' => (!empty($Row['Reason']) ? $Row['Reason'] : $_Lang['Row_ReasonEmpty']), + 'GiverID' => $Row['GiverID'], + 'Indicators' => $Row['Indicators'] + ); + + if(!in_array($Row['UserID'], $GetUsernames)) + { + $GetUsernames[] = $Row['UserID']; + } + if(!in_array($Row['GiverID'], $GetUsernames)) + { + $GetUsernames[] = $Row['GiverID']; + } + + $InsertRows[] = $ParsedRow; + } + + if(!empty($GetUsernames)) + { + $ResultUsernames = doquery("SELECT `id`, `username` FROM {{table}} WHERE `id` IN (".implode(', ', $GetUsernames).");", 'users'); + if($ResultUsernames != false) + { + while($UserData = mysql_fetch_assoc($ResultUsernames)) + { + $UsernamesArray[$UserData['id']] = $UserData['username']; + } + } + } + + foreach($InsertRows as $RowData) + { + $RowData['UserParsed'] = "{$UsernamesArray[$RowData['UserID']]} (#{$RowData['UserID']})"; + $RowData['GiverParsed'] = "{$UsernamesArray[$RowData['GiverID']]} (#{$RowData['GiverID']})"; + + $_Lang['Insert_Rows'][] = parsetemplate($TPL_Row, $RowData); + } + $_Lang['Insert_Rows'] = implode('', $_Lang['Insert_Rows']); + + if($TotalCount > $_PerPage) + { + include($_EnginePath.'includes/functions/Pagination.php'); + $Pagin = CreatePaginationArray($TotalCount, $_PerPage, $_Page, 7); + $PaginationTPL = "{\$ShowValue}"; + $PaginationViewOpt = array('CurrentPage_Classes' => 'orange', 'Breaker_View' => '...'); + $CreatePagination = implode(' ', ParsePaginationArray($Pagin, $_Page, $PaginationTPL, $PaginationViewOpt)); + $_Lang['Insert_Pagination'] = ''.$CreatePagination.''; + } +} +else +{ + $_Lang['Insert_Rows'] = parsetemplate(gettemplate('_singleRow'), array('Colspan' => $_Colspan, 'Classes' => 'pad5 orange', 'Text' => $_Lang['Error_NoRows'])); +} + +$_Lang['Colspan'] = $_Colspan; +display(parsetemplate(gettemplate('admin/banslist_body'), $_Lang), $_Lang['Page_Title'], false, true); + +?> diff --git a/admin/banuser.php b/admin/banuser.php index 4ebf8eae4..a458cbdda 100644 --- a/admin/banuser.php +++ b/admin/banuser.php @@ -1,294 +1,294 @@ - 0) - { - while($Data = mysql_fetch_assoc($CheckUsers)) - { - $BanUsers[$Data['id']] = $Data; - if($Data['ban_endtime'] > $Now) - { - $GetBanRows[] = $Data['id']; - } - } - } - if(!empty($BanUsers)) - { - $CalcPeriod = intval($_POST['period_days']) * TIME_DAY; - $CalcPeriod += intval($_POST['period_hours']) * TIME_HOUR; - $CalcPeriod += intval($_POST['period_mins']) * 60; - $CalcPeriod += intval($_POST['period_secs']); - - if($CalcPeriod > 0) - { - // Do Ban - $BanEnd = $Now + $CalcPeriod; - $UserIDs = implode(', ', array_keys($BanUsers)); - - if($Opt_OnVacation) - { - $VacationMaxTime = MAXVACATIONS_REG * TIME_DAY; - $UpdateUsers[] = '`is_onvacation` = 1'; - $UpdateUsers[] = "`vacation_starttime` = IF(`vacation_starttime` = 0, {$Now}, `vacation_starttime`)"; - if($Opt_ExtendBan) - { - $UpdateUsers[] = "`vacation_endtime` = IF((`is_onvacation` = 1 AND `vacation_type` = 1 AND `ban_endtime` > {$Now}), `ban_endtime` + {$CalcPeriod} + {$VacationMaxTime}, {$BanEnd} + {$VacationMaxTime})"; - } - else - { - $UpdateUsers[] = "`vacation_endtime` = {$BanEnd} + {$VacationMaxTime}"; - } - $UpdateUsers[] = '`vacation_type` = 1'; - $WithVacation = '1'; - } - else - { - if($Opt_ExtendBan) - { - $UpdateUsers[] = "`vacation_endtime` = IF((`is_onvacation` = 1 AND `vacation_type` = 1 AND `ban_endtime` > {$Now}), `vacation_endtime` + {$CalcPeriod}, `vacation_endtime`)"; - } - $WithVacation = '0'; - } - if($Opt_BanCookies) - { - $UpdateUsers[] = '`block_cookies` = 1'; - $WithBlockade_CookieStyle = '1'; - } - else - { - $WithBlockade_CookieStyle = '0'; - } - - $UpdateUsers[] = '`is_banned` = 1'; - if($Opt_ExtendBan) - { - $UpdateUsers[] = "`ban_endtime` = IF(`ban_endtime` > {$Now}, `ban_endtime` + {$CalcPeriod}, {$BanEnd})"; - } - else - { - $UpdateUsers[] = "`ban_endtime` = {$BanEnd}"; - } - - if($Opt_FleetRetreat_Own) - { - $RetreatOwn = '1'; - $RetreatSearch[] = "`fleet_owner` IN ({$UserIDs})"; - } - else - { - $RetreatOwn = '0'; - } - if($Opt_FleetRetreat_All) - { - $RetreatOthers = '1'; - $RetreatSearch[] = "`fleet_target_owner` IN ({$UserIDs})"; - } - else - { - $RetreatOthers = '0'; - } - - $_POST['reason'] = trim(strip_tags(stripslashes($_POST['reason'])), '

'); - if(!empty($_POST['reason'])) - { - $Reason = mysql_real_escape_string($_POST['reason']); - } - else - { - $Reason = ''; - } - - $UserLinkTPL = gettemplate('admin/banuser_userlink'); - foreach($BanUsers as $UserID => $UserData) - { - $UserLinks[] = parsetemplate($UserLinkTPL, array('ID' => $UserID, 'Username' => $UserData['username'])); - if($Opt_ExtendBan AND in_array($UserID, $GetBanRows)) - { - continue; - } - $InsertBans[] = "(NULL, {$UserID}, {$Now}, {$BanEnd}, '{$Reason}', {$_User['id']}, {$WithVacation}, 1, 0, 0, 0, {$RetreatOwn}, {$RetreatOthers}, {$WithBlockade_CookieStyle})"; - } - $BannedUsers = count($UserLinks); - $UserLinks = implode(', ', $UserLinks); - - doquery("UPDATE {{table}} SET ".implode(', ', $UpdateUsers)." WHERE `id` IN ({$UserIDs});", 'users'); - if($Opt_ExtendBan) - { - if(!empty($GetBanRows)) - { - $GetBanRows = implode(', ', $GetBanRows); - $SelectBanRows = "SELECT `ID` FROM {{table}} WHERE "; - $SelectBanRows .= "`Active` = 1 AND `EndTime` > {$Now} AND `UserID` IN ({$GetBanRows}) "; - $SelectBanRows .= "ORDER BY `EndTime` DESC;"; - - $SelectBanRows = doquery($SelectBanRows, 'bans'); - if(mysql_num_rows($SelectBanRows) > 0) - { - while($BanRow = mysql_fetch_assoc($SelectBanRows)) - { - $InsertBans[] = "({$BanRow['ID']}, 0, 0, 0, '', 0, 0, 0, 0, 0, 0, 0, 0, 0)"; - } - } - } - $UpdateQuery = "INSERT INTO {{table}} VALUES ".implode(', ', $InsertBans)." ON DUPLICATE KEY UPDATE "; - $UpdateQueryArr[] = "`EndTime` = `EndTime` + {$CalcPeriod}"; - if($Opt_OnVacation) - { - $UpdateQueryArr[] = "`With_Vacation` = 1"; - } - if($Opt_FleetRetreat_Own) - { - $UpdateQueryArr[] = "`Fleets_Retreated_Own` = 1"; - } - if($Opt_FleetRetreat_All) - { - $UpdateQueryArr[] = "`Fleets_Retreated_Others` = 1"; - } - if($Opt_BanCookies) - { - $UpdateQueryArr[] = "`BlockadeOn_CookieStyle` = 1"; - } - if(!empty($Reason)) - { - $UpdateQueryArr[] = "`Reason` = IF(`Reason` != '', CONCAT(`Reason`, '
', '{$Reason}'), '{$Reason}')"; - } - $UpdateQuery .= implode(', ', $UpdateQueryArr); - doquery($UpdateQuery, 'bans'); - } - else - { - doquery("UPDATE {{table}} SET `Active` = 0, `Removed` = 1, `RemoveDate` = {$Now} WHERE `Active` = 1 AND `EndTime` > {$Now} AND `UserID` IN ({$UserIDs});", 'bans'); - doquery("INSERT INTO {{table}} VALUES ".implode(', ', $InsertBans).";", 'bans'); - } - if(!empty($RetreatSearch)) - { - include($_EnginePath.'includes/functions/FleetControl_Retreat.php'); - $Result = FleetControl_Retreat(implode(' OR ', $RetreatSearch)); - $_Lang['InsertInfoBoxText'] = sprintf(($BannedUsers > 1 ? $_Lang['Msg_BanMOK_wFleets'] : $_Lang['Msg_Ban1OK_wFleets']), $UserLinks, (isset($Result['Updates']['Fleets']) ? prettyNumber($Result['Updates']['Fleets']) : 0)); - } - else - { - $_Lang['InsertInfoBoxText'] = sprintf(($BannedUsers > 1 ? $_Lang['Msg_BanMOK'] : $_Lang['Msg_Ban1OK']), $UserLinks); - } - $_Lang['InsertInfoBoxColor'] = 'lime'; - $_Lang['Insert_SearchBox'] = ''; - } - else - { - $_Lang['InsertInfoBoxText'] = $_Lang['Msg_PeriodBad']; - } - } - else - { - $_Lang['InsertInfoBoxText'] = $_Lang['Msg_UsersNotFound']; - } - } - else - { - $_Lang['InsertInfoBoxText'] = $_Lang['Msg_BadUserDataGiven']; - } - } - else - { - $_Lang['InsertInfoBoxText'] = $_Lang['Msg_EmptyUserInput']; - } - } - - if(!empty($_GET['ids'])) - { - $InsertIDs = explode(',', $_GET['ids']); - foreach($InsertIDs as $ThisID) - { - $_Lang['InsertUsernames'][] = "[{$ThisID}]"; - } - $_Lang['InsertUsernames'] = implode(',', $_Lang['InsertUsernames']); - } - else if(!empty($_GET['user'])) - { - $_Lang['InsertUsernames'] = $_GET['user']; - } - - $Page = parsetemplate($TPL, $_Lang); - display($Page, $_Lang['PageTitle'], false, true); - -?> \ No newline at end of file + 0) + { + while($Data = mysql_fetch_assoc($CheckUsers)) + { + $BanUsers[$Data['id']] = $Data; + if($Data['ban_endtime'] > $Now) + { + $GetBanRows[] = $Data['id']; + } + } + } + if(!empty($BanUsers)) + { + $CalcPeriod = intval($_POST['period_days']) * TIME_DAY; + $CalcPeriod += intval($_POST['period_hours']) * TIME_HOUR; + $CalcPeriod += intval($_POST['period_mins']) * 60; + $CalcPeriod += intval($_POST['period_secs']); + + if($CalcPeriod > 0) + { + // Do Ban + $BanEnd = $Now + $CalcPeriod; + $UserIDs = implode(', ', array_keys($BanUsers)); + + if($Opt_OnVacation) + { + $VacationMaxTime = MAXVACATIONS_REG * TIME_DAY; + $UpdateUsers[] = '`is_onvacation` = 1'; + $UpdateUsers[] = "`vacation_starttime` = IF(`vacation_starttime` = 0, {$Now}, `vacation_starttime`)"; + if($Opt_ExtendBan) + { + $UpdateUsers[] = "`vacation_endtime` = IF((`is_onvacation` = 1 AND `vacation_type` = 1 AND `ban_endtime` > {$Now}), `ban_endtime` + {$CalcPeriod} + {$VacationMaxTime}, {$BanEnd} + {$VacationMaxTime})"; + } + else + { + $UpdateUsers[] = "`vacation_endtime` = {$BanEnd} + {$VacationMaxTime}"; + } + $UpdateUsers[] = '`vacation_type` = 1'; + $WithVacation = '1'; + } + else + { + if($Opt_ExtendBan) + { + $UpdateUsers[] = "`vacation_endtime` = IF((`is_onvacation` = 1 AND `vacation_type` = 1 AND `ban_endtime` > {$Now}), `vacation_endtime` + {$CalcPeriod}, `vacation_endtime`)"; + } + $WithVacation = '0'; + } + if($Opt_BanCookies) + { + $UpdateUsers[] = '`block_cookies` = 1'; + $WithBlockade_CookieStyle = '1'; + } + else + { + $WithBlockade_CookieStyle = '0'; + } + + $UpdateUsers[] = '`is_banned` = 1'; + if($Opt_ExtendBan) + { + $UpdateUsers[] = "`ban_endtime` = IF(`ban_endtime` > {$Now}, `ban_endtime` + {$CalcPeriod}, {$BanEnd})"; + } + else + { + $UpdateUsers[] = "`ban_endtime` = {$BanEnd}"; + } + + if($Opt_FleetRetreat_Own) + { + $RetreatOwn = '1'; + $RetreatSearch[] = "`fleet_owner` IN ({$UserIDs})"; + } + else + { + $RetreatOwn = '0'; + } + if($Opt_FleetRetreat_All) + { + $RetreatOthers = '1'; + $RetreatSearch[] = "`fleet_target_owner` IN ({$UserIDs})"; + } + else + { + $RetreatOthers = '0'; + } + + $_POST['reason'] = trim(strip_tags(stripslashes($_POST['reason'])), '

'); + if(!empty($_POST['reason'])) + { + $Reason = mysql_real_escape_string($_POST['reason']); + } + else + { + $Reason = ''; + } + + $UserLinkTPL = gettemplate('admin/banuser_userlink'); + foreach($BanUsers as $UserID => $UserData) + { + $UserLinks[] = parsetemplate($UserLinkTPL, array('ID' => $UserID, 'Username' => $UserData['username'])); + if($Opt_ExtendBan AND in_array($UserID, $GetBanRows)) + { + continue; + } + $InsertBans[] = "(NULL, {$UserID}, {$Now}, {$BanEnd}, '{$Reason}', {$_User['id']}, {$WithVacation}, 1, 0, 0, 0, {$RetreatOwn}, {$RetreatOthers}, {$WithBlockade_CookieStyle})"; + } + $BannedUsers = count($UserLinks); + $UserLinks = implode(', ', $UserLinks); + + doquery("UPDATE {{table}} SET ".implode(', ', $UpdateUsers)." WHERE `id` IN ({$UserIDs});", 'users'); + if($Opt_ExtendBan) + { + if(!empty($GetBanRows)) + { + $GetBanRows = implode(', ', $GetBanRows); + $SelectBanRows = "SELECT `ID` FROM {{table}} WHERE "; + $SelectBanRows .= "`Active` = 1 AND `EndTime` > {$Now} AND `UserID` IN ({$GetBanRows}) "; + $SelectBanRows .= "ORDER BY `EndTime` DESC;"; + + $SelectBanRows = doquery($SelectBanRows, 'bans'); + if(mysql_num_rows($SelectBanRows) > 0) + { + while($BanRow = mysql_fetch_assoc($SelectBanRows)) + { + $InsertBans[] = "({$BanRow['ID']}, 0, 0, 0, '', 0, 0, 0, 0, 0, 0, 0, 0, 0)"; + } + } + } + $UpdateQuery = "INSERT INTO {{table}} VALUES ".implode(', ', $InsertBans)." ON DUPLICATE KEY UPDATE "; + $UpdateQueryArr[] = "`EndTime` = `EndTime` + {$CalcPeriod}"; + if($Opt_OnVacation) + { + $UpdateQueryArr[] = "`With_Vacation` = 1"; + } + if($Opt_FleetRetreat_Own) + { + $UpdateQueryArr[] = "`Fleets_Retreated_Own` = 1"; + } + if($Opt_FleetRetreat_All) + { + $UpdateQueryArr[] = "`Fleets_Retreated_Others` = 1"; + } + if($Opt_BanCookies) + { + $UpdateQueryArr[] = "`BlockadeOn_CookieStyle` = 1"; + } + if(!empty($Reason)) + { + $UpdateQueryArr[] = "`Reason` = IF(`Reason` != '', CONCAT(`Reason`, '
', '{$Reason}'), '{$Reason}')"; + } + $UpdateQuery .= implode(', ', $UpdateQueryArr); + doquery($UpdateQuery, 'bans'); + } + else + { + doquery("UPDATE {{table}} SET `Active` = 0, `Removed` = 1, `RemoveDate` = {$Now} WHERE `Active` = 1 AND `EndTime` > {$Now} AND `UserID` IN ({$UserIDs});", 'bans'); + doquery("INSERT INTO {{table}} VALUES ".implode(', ', $InsertBans).";", 'bans'); + } + if(!empty($RetreatSearch)) + { + include($_EnginePath.'includes/functions/FleetControl_Retreat.php'); + $Result = FleetControl_Retreat(implode(' OR ', $RetreatSearch)); + $_Lang['InsertInfoBoxText'] = sprintf(($BannedUsers > 1 ? $_Lang['Msg_BanMOK_wFleets'] : $_Lang['Msg_Ban1OK_wFleets']), $UserLinks, (isset($Result['Updates']['Fleets']) ? prettyNumber($Result['Updates']['Fleets']) : 0)); + } + else + { + $_Lang['InsertInfoBoxText'] = sprintf(($BannedUsers > 1 ? $_Lang['Msg_BanMOK'] : $_Lang['Msg_Ban1OK']), $UserLinks); + } + $_Lang['InsertInfoBoxColor'] = 'lime'; + $_Lang['Insert_SearchBox'] = ''; + } + else + { + $_Lang['InsertInfoBoxText'] = $_Lang['Msg_PeriodBad']; + } + } + else + { + $_Lang['InsertInfoBoxText'] = $_Lang['Msg_UsersNotFound']; + } + } + else + { + $_Lang['InsertInfoBoxText'] = $_Lang['Msg_BadUserDataGiven']; + } + } + else + { + $_Lang['InsertInfoBoxText'] = $_Lang['Msg_EmptyUserInput']; + } +} + +if(!empty($_GET['ids'])) +{ + $InsertIDs = explode(',', $_GET['ids']); + foreach($InsertIDs as $ThisID) + { + $_Lang['InsertUsernames'][] = "[{$ThisID}]"; + } + $_Lang['InsertUsernames'] = implode(',', $_Lang['InsertUsernames']); +} +else if(!empty($_GET['user'])) +{ + $_Lang['InsertUsernames'] = $_GET['user']; +} + +$Page = parsetemplate($TPL, $_Lang); +display($Page, $_Lang['PageTitle'], false, true); + +?> diff --git a/admin/bashDetector.php b/admin/bashDetector.php index 700138e37..9db3a14d7 100644 --- a/admin/bashDetector.php +++ b/admin/bashDetector.php @@ -1,300 +1,300 @@ - 0) - { - $Query_Where['Fleet_Owner'] = "`Fleet_Owner` = {$Filter['sender']}"; - $_Lang['Insert_srch_sender'] = "[{$Filter['sender']}]"; - $GetUsernames[] = $Filter['sender']; - $Set['SenderID'] = $Filter['sender']; - } - } - else if(preg_match(REGEXP_USERNAME_ABSOLUTE, $Filter['sender'])) - { - $Query_GetUser = doquery("SELECT `id`, `username` FROM {{table}} WHERE `username` = '{$Filter['sender']}' LIMIT 1;", 'users', true); - if($Query_GetUser['id'] > 0) - { - $Query_Where['Fleet_Owner'] = "`Fleet_Owner` = {$Query_GetUser['id']}"; - $_Lang['Insert_srch_sender'] = $Query_GetUser['username']; - $Usernames[$Query_GetUser['id']] = $Query_GetUser['username']; - $Set['SenderID'] = $Query_GetUser['id']; - } - else - { - $_Lang['Insert_BashOverallResult'][] = $_Lang['Analysis_BadSenderName']; - } - } - } - if(!empty($Filter['owner'])) - { - if(strstr($Filter['owner'], '[') !== false) - { - $Filter['owner'] = intval(str_replace(array('[', ']'), '', $Filter['owner'])); - if($Filter['owner'] > 0) - { - $Query_Where['Fleet_End_Owner'] = "`Fleet_End_Owner` = {$Filter['owner']}"; - $_Lang['Insert_srch_owner'] = "[{$Filter['owner']}]"; - $GetUsernames[] = $Filter['owner']; - $Set['OwnerID'] = $Filter['owner']; - } - } - else if(preg_match(REGEXP_USERNAME_ABSOLUTE, $Filter['owner'])) - { - $Query_GetUser = doquery("SELECT `id`, `username` FROM {{table}} WHERE `username` = '{$Filter['owner']}' LIMIT 1;", 'users', true); - if($Query_GetUser['id'] > 0) - { - $Query_Where['Fleet_End_Owner'] = "`Fleet_End_Owner` = {$Query_GetUser['id']}"; - $_Lang['Insert_srch_owner'] = $Query_GetUser['username']; - $Usernames[$Query_GetUser['id']] = $Query_GetUser['username']; - $Set['OwnerID'] = $Query_GetUser['id']; - } - else - { - $_Lang['Insert_BashOverallResult'][] = $_Lang['Analysis_BadOwnerName']; - } - } - } - if(!empty($Filter['date'])) - { - $Filter['timestamp'] = strtotime($Filter['date']); - if($Filter['timestamp'] != false AND $Filter['timestamp'] < $Now) - { - $Filter['timestampEnd'] = $Filter['timestamp'] + TIME_DAY; - $Query_Where['Fleet_Time_Start'] = "(`Fleet_Time_Start` + `Fleet_Time_ACSAdd`) BETWEEN {$Filter['timestamp']} AND {$Filter['timestampEnd']}"; - $_Lang['Insert_srch_date'] = $Filter['date']; - $Set['Date'] = $Filter['timestamp']; - } - } - - if(!empty($Query_Where['Fleet_Owner']) AND !empty($Query_Where['Fleet_End_Owner']) AND !empty($Query_Where['Fleet_Time_Start'])) - { - if(!empty($GetUsernames)) - { - $GetUsernamesCount = count($GetUsernames); - $GetUsernames = implode(',', $GetUsernames); - $Query_GetUsernames = "SELECT `id`, `username` FROM {{table}} WHERE `id` IN ({$GetUsernames}) LIMIT {$GetUsernamesCount};"; - $Result_GetUsernames = doquery($Query_GetUsernames, 'users'); - if(mysql_num_rows($Result_GetUsernames) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_GetUsernames)) - { - $Usernames[$FetchData['id']] = $FetchData['username']; - } - } - } - if(empty($Usernames[$Set['SenderID']])) - { - $Usernames[$Set['SenderID']] = $_Lang['UserRow_Deleted']; - } - if(empty($Usernames[$Set['OwnerID']])) - { - $Usernames[$Set['OwnerID']] = $_Lang['UserRow_Deleted']; - } - - $ThisArray = array($Usernames[$Set['SenderID']], $Set['SenderID'], $Set['SenderID'], $Usernames[$Set['OwnerID']], $Set['OwnerID'], $Set['OwnerID'], prettyDate('d m Y', $Set['Date'], 1)); - $_Lang['Insert_BashOverallResult'][] = vsprintf($_Lang['Analysis_Info'], $ThisArray); - - $Query_Where[] = "`Fleet_Mission` IN (1, 2, 9)"; - $Query_Where[] = "`Fleet_End_Owner_IdleHours` < 168"; - $Query_Where[] = "`Fleet_ReportID` > 0"; - $Query_Where[] = "`Fleet_Destroyed_Reason` NOT IN (1, 4, 11)"; - - $Query_GetFleets = ''; - $Query_GetFleets .= "SELECT `Fleet_ID`, `Fleet_Mission`, `Fleet_Time_Start`, `Fleet_End_ID`, `Fleet_ReportID` "; - $Query_GetFleets .= "FROM {{table}} WHERE "; - $Query_GetFleets .= implode(' AND ', $Query_Where); - - $Result_GetFleets = doquery($Query_GetFleets, 'fleet_archive'); - if(mysql_num_rows($Result_GetFleets) > 0) - { - $TPL_FleetRow = gettemplate('admin/bashDetector_fleetrow'); - $GetTargets = array(); - $BashCountersUser = 0; - $BashCountersPlanet = array(); - $FoundBash = false; - - while($FetchRow = mysql_fetch_assoc($Result_GetFleets)) - { - $BashCountersUser += 1; - if(!isset($BashCountersPlanet[$FetchRow['Fleet_End_ID']])) - { - $BashCountersPlanet[$FetchRow['Fleet_End_ID']] = 0; - } - $BashCountersPlanet[$FetchRow['Fleet_End_ID']] += 1; - - if($BashCountersUser > $_BashLimit_PerUser) - { - $FoundBash = true; - } - else if($BashCountersPlanet[$FetchRow['Fleet_End_ID']] > $_BashLimit_PerPlanet) - { - $FoundBash = true; - } - - $FetchRow['Fleet_Date'] = prettyDate('d m Y, H:i:s', $FetchRow['Fleet_Time_Start'], 1); - $FetchRow['Fleet_Mission'] = $_Lang['type_mission'][$FetchRow['Fleet_Mission']]; - - if(!in_array($FetchRow['Fleet_End_ID'], $GetTargets)) - { - $GetTargets[] = $FetchRow['Fleet_End_ID']; - } - - $FleetRow[] = $FetchRow; - } - if(!empty($GetTargets)) - { - $GetTargetsCount = count($GetTargets); - $GetTargets = implode(',', $GetTargets); - $Query_GetTargets = ''; - $Query_GetTargets .= "SELECT `id`, `name`, `galaxy`, `system`, `planet`, `planet_type` FROM {{table}} "; - $Query_GetTargets .= "WHERE `id` IN ({$GetTargets}) LIMIT {$GetTargetsCount};"; - - $Result_GetTargets = doquery($Query_GetTargets, 'planets'); - if(mysql_num_rows($Result_GetTargets) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_GetTargets)) - { - $Targets[$FetchData['id']] = $FetchData; - } - } - } - - if($FoundBash === true) - { - $_Lang['Insert_BashOverallResult'][] = sprintf($_Lang['Analysis_BashFound'], $Set['SenderID']); - - if($BashCountersUser > $_BashLimit_PerUser) - { - $BashedUser = true; - $_Lang['Insert_BashList'][] = sprintf($_Lang['Analysis_List_UserBash'], $BashCountersUser, $_BashLimit_PerUser); - } - foreach($BashCountersPlanet as $PlanetID => $Count) - { - if($Count > $_BashLimit_PerPlanet) - { - $BashedPlanets[$PlanetID] = true; - - if(!empty($Targets[$PlanetID]['name'])) - { - $ThisArray = array($Targets[$PlanetID]['name'], $Targets[$PlanetID]['galaxy'], $Targets[$PlanetID]['system'], $Targets[$PlanetID]['planet'], $_Lang['FleetRow_PlanetTypes'][$Targets[$PlanetID]['planet_type']], $PlanetID); - } - else - { - $ThisArray = array($_Lang['FleetRow_PlanetDeleted'], '0', '0', '0', '-', $PlanetID); - } - $ThisArray[] = $Count; - $ThisArray[] = $_BashLimit_PerPlanet; - $_Lang['Insert_BashList'][] = vsprintf($_Lang['Analysis_List_PlanetBash'], $ThisArray); - } - } - if(!empty($_Lang['Insert_BashList'])) - { - $_Lang['Insert_BashList'] = '
'.implode('
', $_Lang['Insert_BashList']); - } - } - else - { - $_Lang['Insert_BashOverallResult'][] = $_Lang['Analysis_BashNotFound']; - } - - foreach($FleetRow as $FleetData) - { - if(!empty($Targets[$FleetData['Fleet_End_ID']]['name'])) - { - $FleetData['Fleet_TargetName'] = $Targets[$FleetData['Fleet_End_ID']]['name']; - $FleetData['Fleet_TargetGalaxy'] = $Targets[$FleetData['Fleet_End_ID']]['galaxy']; - $FleetData['Fleet_TargetSystem'] = $Targets[$FleetData['Fleet_End_ID']]['system']; - $FleetData['Fleet_TargetPlanet'] = $Targets[$FleetData['Fleet_End_ID']]['planet']; - $FleetData['Fleet_TargetType'] = $_Lang['FleetRow_PlanetTypes'][$Targets[$FleetData['Fleet_End_ID']]['planet_type']]; - } - else - { - $FleetData['Fleet_TargetName'] = $_Lang['FleetRow_PlanetDeleted']; - $FleetData['Fleet_TargetGalaxy'] = '0'; - $FleetData['Fleet_TargetSystem'] = '0'; - $FleetData['Fleet_TargetPlanet'] = '0'; - $FleetData['Fleet_TargetType'] = '-'; - } - if(!isset($BashedUser) && isset($BashedPlanets[$FleetData['Fleet_End_ID']])) - { - $FleetData['BashClass'] = 'red'; - } - - $_Lang['Insert_FleetRows'][] = parsetemplate($TPL_FleetRow, $FleetData); - } - } - else - { - $_Lang['Insert_BashOverallResult'][] = $_Lang['Analysis_BashNotFound']; - $_Lang['Insert_FleetRows'][] = parsetemplate(gettemplate('_singleRow'), array('Classes' => 'orange pad5', 'Colspan' => $_Colspan, 'Text' => $_Lang['Info_NoFleetRows'])); - } - } - else - { - $_Lang['Insert_BashOverallResult'][] = $_Lang['Analysis_BadInput']; - $_Lang['Insert_HideFleetRows'] = 'display: none;'; - } - } - if(!empty($_Lang['Insert_BashOverallResult'])) - { - $_Lang['Insert_BashOverallResult'] = implode('
', $_Lang['Insert_BashOverallResult']); - } - if(!empty($_Lang['Insert_FleetRows'])) - { - $_Lang['Insert_FleetRows'] = implode('', $_Lang['Insert_FleetRows']); - } - - if(empty($_Lang['Insert_srch_date'])) - { - $_Lang['Insert_srch_date'] = date('Y-m-d'); - } - - display(parsetemplate($TPL_Body, $_Lang), $_Lang['Page_Title'], false, true); - -?> \ No newline at end of file + 0) + { + $Query_Where['Fleet_Owner'] = "`Fleet_Owner` = {$Filter['sender']}"; + $_Lang['Insert_srch_sender'] = "[{$Filter['sender']}]"; + $GetUsernames[] = $Filter['sender']; + $Set['SenderID'] = $Filter['sender']; + } + } + else if(preg_match(REGEXP_USERNAME_ABSOLUTE, $Filter['sender'])) + { + $Query_GetUser = doquery("SELECT `id`, `username` FROM {{table}} WHERE `username` = '{$Filter['sender']}' LIMIT 1;", 'users', true); + if($Query_GetUser['id'] > 0) + { + $Query_Where['Fleet_Owner'] = "`Fleet_Owner` = {$Query_GetUser['id']}"; + $_Lang['Insert_srch_sender'] = $Query_GetUser['username']; + $Usernames[$Query_GetUser['id']] = $Query_GetUser['username']; + $Set['SenderID'] = $Query_GetUser['id']; + } + else + { + $_Lang['Insert_BashOverallResult'][] = $_Lang['Analysis_BadSenderName']; + } + } + } + if(!empty($Filter['owner'])) + { + if(strstr($Filter['owner'], '[') !== false) + { + $Filter['owner'] = intval(str_replace(array('[', ']'), '', $Filter['owner'])); + if($Filter['owner'] > 0) + { + $Query_Where['Fleet_End_Owner'] = "`Fleet_End_Owner` = {$Filter['owner']}"; + $_Lang['Insert_srch_owner'] = "[{$Filter['owner']}]"; + $GetUsernames[] = $Filter['owner']; + $Set['OwnerID'] = $Filter['owner']; + } + } + else if(preg_match(REGEXP_USERNAME_ABSOLUTE, $Filter['owner'])) + { + $Query_GetUser = doquery("SELECT `id`, `username` FROM {{table}} WHERE `username` = '{$Filter['owner']}' LIMIT 1;", 'users', true); + if($Query_GetUser['id'] > 0) + { + $Query_Where['Fleet_End_Owner'] = "`Fleet_End_Owner` = {$Query_GetUser['id']}"; + $_Lang['Insert_srch_owner'] = $Query_GetUser['username']; + $Usernames[$Query_GetUser['id']] = $Query_GetUser['username']; + $Set['OwnerID'] = $Query_GetUser['id']; + } + else + { + $_Lang['Insert_BashOverallResult'][] = $_Lang['Analysis_BadOwnerName']; + } + } + } + if(!empty($Filter['date'])) + { + $Filter['timestamp'] = strtotime($Filter['date']); + if($Filter['timestamp'] != false AND $Filter['timestamp'] < $Now) + { + $Filter['timestampEnd'] = $Filter['timestamp'] + TIME_DAY; + $Query_Where['Fleet_Time_Start'] = "(`Fleet_Time_Start` + `Fleet_Time_ACSAdd`) BETWEEN {$Filter['timestamp']} AND {$Filter['timestampEnd']}"; + $_Lang['Insert_srch_date'] = $Filter['date']; + $Set['Date'] = $Filter['timestamp']; + } + } + + if(!empty($Query_Where['Fleet_Owner']) AND !empty($Query_Where['Fleet_End_Owner']) AND !empty($Query_Where['Fleet_Time_Start'])) + { + if(!empty($GetUsernames)) + { + $GetUsernamesCount = count($GetUsernames); + $GetUsernames = implode(',', $GetUsernames); + $Query_GetUsernames = "SELECT `id`, `username` FROM {{table}} WHERE `id` IN ({$GetUsernames}) LIMIT {$GetUsernamesCount};"; + $Result_GetUsernames = doquery($Query_GetUsernames, 'users'); + if(mysql_num_rows($Result_GetUsernames) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_GetUsernames)) + { + $Usernames[$FetchData['id']] = $FetchData['username']; + } + } + } + if(empty($Usernames[$Set['SenderID']])) + { + $Usernames[$Set['SenderID']] = $_Lang['UserRow_Deleted']; + } + if(empty($Usernames[$Set['OwnerID']])) + { + $Usernames[$Set['OwnerID']] = $_Lang['UserRow_Deleted']; + } + + $ThisArray = array($Usernames[$Set['SenderID']], $Set['SenderID'], $Set['SenderID'], $Usernames[$Set['OwnerID']], $Set['OwnerID'], $Set['OwnerID'], prettyDate('d m Y', $Set['Date'], 1)); + $_Lang['Insert_BashOverallResult'][] = vsprintf($_Lang['Analysis_Info'], $ThisArray); + + $Query_Where[] = "`Fleet_Mission` IN (1, 2, 9)"; + $Query_Where[] = "`Fleet_End_Owner_IdleHours` < 168"; + $Query_Where[] = "`Fleet_ReportID` > 0"; + $Query_Where[] = "`Fleet_Destroyed_Reason` NOT IN (1, 4, 11)"; + + $Query_GetFleets = ''; + $Query_GetFleets .= "SELECT `Fleet_ID`, `Fleet_Mission`, `Fleet_Time_Start`, `Fleet_End_ID`, `Fleet_ReportID` "; + $Query_GetFleets .= "FROM {{table}} WHERE "; + $Query_GetFleets .= implode(' AND ', $Query_Where); + + $Result_GetFleets = doquery($Query_GetFleets, 'fleet_archive'); + if(mysql_num_rows($Result_GetFleets) > 0) + { + $TPL_FleetRow = gettemplate('admin/bashDetector_fleetrow'); + $GetTargets = array(); + $BashCountersUser = 0; + $BashCountersPlanet = array(); + $FoundBash = false; + + while($FetchRow = mysql_fetch_assoc($Result_GetFleets)) + { + $BashCountersUser += 1; + if(!isset($BashCountersPlanet[$FetchRow['Fleet_End_ID']])) + { + $BashCountersPlanet[$FetchRow['Fleet_End_ID']] = 0; + } + $BashCountersPlanet[$FetchRow['Fleet_End_ID']] += 1; + + if($BashCountersUser > $_BashLimit_PerUser) + { + $FoundBash = true; + } + else if($BashCountersPlanet[$FetchRow['Fleet_End_ID']] > $_BashLimit_PerPlanet) + { + $FoundBash = true; + } + + $FetchRow['Fleet_Date'] = prettyDate('d m Y, H:i:s', $FetchRow['Fleet_Time_Start'], 1); + $FetchRow['Fleet_Mission'] = $_Lang['type_mission'][$FetchRow['Fleet_Mission']]; + + if(!in_array($FetchRow['Fleet_End_ID'], $GetTargets)) + { + $GetTargets[] = $FetchRow['Fleet_End_ID']; + } + + $FleetRow[] = $FetchRow; + } + if(!empty($GetTargets)) + { + $GetTargetsCount = count($GetTargets); + $GetTargets = implode(',', $GetTargets); + $Query_GetTargets = ''; + $Query_GetTargets .= "SELECT `id`, `name`, `galaxy`, `system`, `planet`, `planet_type` FROM {{table}} "; + $Query_GetTargets .= "WHERE `id` IN ({$GetTargets}) LIMIT {$GetTargetsCount};"; + + $Result_GetTargets = doquery($Query_GetTargets, 'planets'); + if(mysql_num_rows($Result_GetTargets) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_GetTargets)) + { + $Targets[$FetchData['id']] = $FetchData; + } + } + } + + if($FoundBash === true) + { + $_Lang['Insert_BashOverallResult'][] = sprintf($_Lang['Analysis_BashFound'], $Set['SenderID']); + + if($BashCountersUser > $_BashLimit_PerUser) + { + $BashedUser = true; + $_Lang['Insert_BashList'][] = sprintf($_Lang['Analysis_List_UserBash'], $BashCountersUser, $_BashLimit_PerUser); + } + foreach($BashCountersPlanet as $PlanetID => $Count) + { + if($Count > $_BashLimit_PerPlanet) + { + $BashedPlanets[$PlanetID] = true; + + if(!empty($Targets[$PlanetID]['name'])) + { + $ThisArray = array($Targets[$PlanetID]['name'], $Targets[$PlanetID]['galaxy'], $Targets[$PlanetID]['system'], $Targets[$PlanetID]['planet'], $_Lang['FleetRow_PlanetTypes'][$Targets[$PlanetID]['planet_type']], $PlanetID); + } + else + { + $ThisArray = array($_Lang['FleetRow_PlanetDeleted'], '0', '0', '0', '-', $PlanetID); + } + $ThisArray[] = $Count; + $ThisArray[] = $_BashLimit_PerPlanet; + $_Lang['Insert_BashList'][] = vsprintf($_Lang['Analysis_List_PlanetBash'], $ThisArray); + } + } + if(!empty($_Lang['Insert_BashList'])) + { + $_Lang['Insert_BashList'] = '
'.implode('
', $_Lang['Insert_BashList']); + } + } + else + { + $_Lang['Insert_BashOverallResult'][] = $_Lang['Analysis_BashNotFound']; + } + + foreach($FleetRow as $FleetData) + { + if(!empty($Targets[$FleetData['Fleet_End_ID']]['name'])) + { + $FleetData['Fleet_TargetName'] = $Targets[$FleetData['Fleet_End_ID']]['name']; + $FleetData['Fleet_TargetGalaxy'] = $Targets[$FleetData['Fleet_End_ID']]['galaxy']; + $FleetData['Fleet_TargetSystem'] = $Targets[$FleetData['Fleet_End_ID']]['system']; + $FleetData['Fleet_TargetPlanet'] = $Targets[$FleetData['Fleet_End_ID']]['planet']; + $FleetData['Fleet_TargetType'] = $_Lang['FleetRow_PlanetTypes'][$Targets[$FleetData['Fleet_End_ID']]['planet_type']]; + } + else + { + $FleetData['Fleet_TargetName'] = $_Lang['FleetRow_PlanetDeleted']; + $FleetData['Fleet_TargetGalaxy'] = '0'; + $FleetData['Fleet_TargetSystem'] = '0'; + $FleetData['Fleet_TargetPlanet'] = '0'; + $FleetData['Fleet_TargetType'] = '-'; + } + if(!isset($BashedUser) && isset($BashedPlanets[$FleetData['Fleet_End_ID']])) + { + $FleetData['BashClass'] = 'red'; + } + + $_Lang['Insert_FleetRows'][] = parsetemplate($TPL_FleetRow, $FleetData); + } + } + else + { + $_Lang['Insert_BashOverallResult'][] = $_Lang['Analysis_BashNotFound']; + $_Lang['Insert_FleetRows'][] = parsetemplate(gettemplate('_singleRow'), array('Classes' => 'orange pad5', 'Colspan' => $_Colspan, 'Text' => $_Lang['Info_NoFleetRows'])); + } + } + else + { + $_Lang['Insert_BashOverallResult'][] = $_Lang['Analysis_BadInput']; + $_Lang['Insert_HideFleetRows'] = 'display: none;'; + } +} +if(!empty($_Lang['Insert_BashOverallResult'])) +{ + $_Lang['Insert_BashOverallResult'] = implode('
', $_Lang['Insert_BashOverallResult']); +} +if(!empty($_Lang['Insert_FleetRows'])) +{ + $_Lang['Insert_FleetRows'] = implode('', $_Lang['Insert_FleetRows']); +} + +if(empty($_Lang['Insert_srch_date'])) +{ + $_Lang['Insert_srch_date'] = date('Y-m-d'); +} + +display(parsetemplate($TPL_Body, $_Lang), $_Lang['Page_Title'], false, true); + +?> diff --git a/admin/browse_actionlogs.php b/admin/browse_actionlogs.php index 17a0b9c14..7abfab14d 100644 --- a/admin/browse_actionlogs.php +++ b/admin/browse_actionlogs.php @@ -1,1246 +1,1246 @@ - 1048576) - { - $Unit = 1048576; - $UnitName = 'MB'; - } - else if($Mem > 1024) - { - $Unit = 1024; - $UnitName = 'KB'; - } - else - { - $Unit = 1; - $UnitName = 'B'; - return $Mem.' '.$UnitName; - } - return sprintf('%0.4f', ($Mem/$Unit)).' '.$UnitName; - } - - function PostParser($Array, $ReturnState = false) - { - global $PostParsed; - static $Depth, $DeepParse, $State; - if($Depth <= 0) - { - $Depth = 0; - } - if($ReturnState) - { - $State = array('arr' => false, 'cou' => 0); - } - - foreach($Array as $Key => $Data) - { - if((array)$Data === $Data) - { - if($ReturnState) - { - $State['arr'] = true; - } - $State['cou'] += 1; - $Depth += 1; - PostParser($Data); - if(is_string($Key)) - { - $Key = "'{$Key}'"; - } - $Start = "
{$Key}[]{"; - $End = "}"; - if($Depth == 1) - { - $PostParsed[] = $Start.implode(' & ', $DeepParse[$Depth]).$End; - unset($DeepParse[$Depth]); - } - else - { - $DeepParse[($Depth-1)][] = $Start.implode(' & ', $DeepParse[$Depth]).$End; - unset($DeepParse[$Depth]); - } - $Depth -= 1; - } - else - { - $State['cou'] += 1; - if(is_string($Key)) - { - $Key = "'{$Key}'"; - } - if(is_string($Data)) - { - $Data = "'{$Data}'"; - } - $ParseIt = "{$Key}=".valueParser($Data).""; - if($Depth > 0) - { - $DeepParse[$Depth][] = $ParseIt; - } - else - { - $PostParsed[] = $ParseIt; - } - } - } - - if($ReturnState) - { - $DeepParse = false; - return $State; - } - } - - function valueParser($Value) - { - $Length = strlen($Value); - if($Length > 40) - { - $Part1 = substr($Value, 0, 10); - $Part2 = substr($Value, 10, $Length - 20); - $Part3 = substr($Value, -10); - return "{$Part1}(...){$Part2}{$Part3}"; - } - return $Value; - } - - function walkPostArray($Array) - { - static $Return = array(), $CurrentPath = '', $CurrentLevel = 1; - - $PreviousPath = $CurrentPath; - foreach($Array as $Key => $Value) - { - if($CurrentLevel > 1) - { - $CurrentPath = "{$PreviousPath}[{$Key}]"; - } - else - { - $CurrentPath = $Key; - } - if((array)$Value === $Value) - { - $CurrentLevel += 1; - walkPostArray($Value); - $CurrentLevel -= 1; - } - else - { - $Return[] = array('name' => $CurrentPath, 'value' => $Value); - } - } - $CurrentPath = $PreviousPath; - - if($CurrentLevel <= 1) - { - $TempReturn = $Return; - $Return = array(); - $CurrentPath = ''; - $CurrentLevel = 1; - return $TempReturn; - } - } - - function parseTimestamp($Timestamp) - { - $Temp['H'] = floor($Timestamp / 3600); - $Timestamp -= $Temp['H'] * 3600; - $Temp['M'] = floor($Timestamp / 60); - $Timestamp -= $Temp['M'] * 60; - $Temp['S'] = $Timestamp; - - return str_pad($Temp['H'], 2, '0', STR_PAD_LEFT).':'.str_pad($Temp['M'], 2, '0', STR_PAD_LEFT).':'.str_pad($Temp['S'], 2, '0', STR_PAD_LEFT); - } - // ------------------------------------------------------------------------------------------------------------------------------------------ - // ------------------------------------------------------------------------------------------------------------------------------------------ - - includeLang('admin/browse_actionlogs'); - - $Error = $_Lang['PageTitle']; - $ThisPage = 'browse_actionlogs.php'; - $Parse = $_Lang; - $MainTPL = gettemplate('admin/browse_actionlogs_body'); - $RowListTPL = gettemplate('admin/browse_actionlogs_list_row'); - $HeadListTPL = gettemplate('admin/browse_actionlogs_list_header'); - $Row3LogTPL = gettemplate('admin/browse_actionlogs_log_row_3'); - $Row2LogTPL = gettemplate('admin/browse_actionlogs_log_row_2'); - $Row1LogTPL = gettemplate('admin/browse_actionlogs_log_row_1'); - $RowMLogTPL = gettemplate('admin/browse_actionlogs_log_row_multi'); - $HeadLogTPL = gettemplate('admin/browse_actionlogs_log_header'); - $ResendTPL = gettemplate('admin/browse_actionlogs_resendrequest'); - - if(!empty($_POST)) - { - if(isset($_POST['autoExpandArr']) && $_POST['autoExpandArr'] == 'on') - { - $AutoExpandArray = 'true'; - $SetArrCookie = 'on'; - } - else - { - $AutoExpandArray = 'false'; - $SetArrCookie = 'off'; - } - if(isset($_POST['autoExpandAmp']) && $_POST['autoExpandAmp'] == 'on') - { - $AutoExpandAmper = 'true'; - $SetAmpCookie = 'on'; - } - else - { - $AutoExpandAmper = 'false'; - $SetAmpCookie = 'off'; - } - setcookie('autoExpandArr', $SetArrCookie, time() + 31536000); - setcookie('autoExpandAmp', $SetAmpCookie, time() + 31536000); - } - else - { - if($_COOKIE['autoExpandArr'] == 'on') - { - $AutoExpandArray = 'true'; - } - else if($_COOKIE['autoExpandArr'] == 'off' OR empty($_COOKIE['autoExpandArr'])) - { - $AutoExpandArray = 'false'; - } - if($_COOKIE['autoExpandAmp'] == 'on') - { - $AutoExpandAmper = 'true'; - } - else if($_COOKIE['autoExpandAmp'] == 'off' OR empty($_COOKIE['autoExpandAmp'])) - { - $AutoExpandAmper = 'false'; - } - } - if($AutoExpandArray == 'true') - { - $_Lang['aEArrCheck'] = 'checked'; - } - if($AutoExpandAmper == 'true') - { - $_Lang['aEAmpCheck'] = 'checked'; - } - - $Parse['AutoExpandArray'] = $AutoExpandArray; - $Parse['AutoExpandAmp'] = $AutoExpandAmper; - - $UID = intval($_GET['uid']); - - if($UID <= 0) - { - message($_Lang['Error_BadUID'], $Error); - } - $ThisPage = "{$ThisPage}?uid={$UID}"; - $Parse['UID'] = $UID; - $_Lang['UID'] = $UID; - $UIDMarker = str_pad($UID, 6, '0', STR_PAD_LEFT); - $Date = isset($_GET['date']) ? $_GET['date'] : null; - - $LogExists = false; - - if(!empty($Date)) - { - if(preg_match('/^[0-9\_]{10}$/D', $Date)) - { - $Packed = ''; - if(isset($_GET['packed']) && $_GET['packed'] === 'true') - { - $FilePath = "./../action_logs/logs_{$Date}/Log_U_{$UIDMarker}_D_{$Date}.php.gz"; - $Packed = '&packed=true'; - $GZiped = true; - } - else - { - $FilePath = "./../action_logs/{$UIDMarker}/Log_U_{$UIDMarker}_D_{$Date}.php"; - $GZiped = false; - } - - if(file_exists($FilePath)) - { - $ThisPage = "{$ThisPage}&date={$Date}{$Packed}"; - - $Parse['TableColspan'] = 4; - $LogExists = true; - - $UserData = doquery("SELECT `username` FROM {{table}} WHERE `id` = {$UID} LIMIT 1;", 'users', true); - $Parse['UserName'] = $UserData['username']; - - $EDate = explode('_', $Date); - - if($GZiped) - { - $LogFile = gzfile($FilePath); - } - else - { - $LogFile = file($FilePath); - } - unset($LogFile[(count($LogFile) - 1)]); - unset($LogFile[0]); - - if(!empty($_GET['resendline'])) - { - $ResendLineNo = round($_GET['resendline']); - if($ResendLineNo >= 0) - { - if(!empty($LogFile[$ResendLineNo])) - { - if(preg_match('/^([0-9]{1,5}|[0-9]{2}\:[0-9]{2}\:[0-9]{2})\|([a-zA-Z0-9\.\?\=\;\&\_\/\-\ ]{1,})(\|){0,1}(.*?)$/D', trim($LogFile[$ResendLineNo]), $LogFile[$ResendLineNo])) - { - $ResendFile = false; - $ResendPost = false; - - if($LogFile[$ResendLineNo][2] == 'R' OR $LogFile[$ResendLineNo][2] == 'reload') - { - if(empty($LogFile[$ResendLineNo][4])) - { - $PostReload = true; - } - else - { - $ResendPost = $LogFile[$ResendLineNo][4]; - } - - $ReverseScanIndex = $ResendLineNo - 1; - while(!empty($LogFile[$ReverseScanIndex])) - { - if(!preg_match('/^([0-9]{1,5}|[0-9]{2}\:[0-9]{2}\:[0-9]{2})\|([a-zA-Z0-9\.\?\=\;\&\_\/\-\ ]{1,})(\|){0,1}(.*?)$/D', trim($LogFile[$ReverseScanIndex]), $LogFile[$ReverseScanIndex])) - { - $ReverseScanIndex -= 1; - continue; - } - if($PostReload === true AND !empty($LogFile[$ReverseScanIndex][4])) - { - $ResendPost = $LogFile[$ReverseScanIndex][4]; - } - if($LogFile[$ReverseScanIndex][2] == 'R' OR $LogFile[$ReverseScanIndex][2] == 'reload') - { - $ReverseScanIndex -= 1; - } - else - { - $ResendFile = $LogFile[$ReverseScanIndex][2]; - break; - } - } - - if(empty($ResendFile)) - { - AdminMessage($_Lang['Error_ResendLineBadRevScan'], $_Lang['PageTitle']); - } - } - else - { - $ResendFile = $LogFile[$ResendLineNo][2]; - $ResendPost = $LogFile[$ResendLineNo][4]; - } - - $GenerateForm['UserInfo'] = $_Lang['Info_RequestProceeding']; - $GenerateForm['FilePath'] = $_EnginePath.$ResendFile; - if(!empty($ResendPost) AND $ResendPost != 'N') - { - $ResendPost = json_decode($ResendPost, true); - $GenerateForm['GenerateInputs'] = walkPostArray($ResendPost); - foreach($GenerateForm['GenerateInputs'] as $InputData) - { - $InputData['value'] = stripslashes($InputData['value']); - $GenerateForm['GenerateInputsArray'][] = ""; - } - $GenerateForm['GenerateInputs'] = implode('', $GenerateForm['GenerateInputsArray']); - } - $Page = parsetemplate($ResendTPL, $GenerateForm); - $_DontShowMenus = true; - display($Page, $_Lang['PageTitle'], false, true); - } - else - { - AdminMessage($_Lang['Error_ResendLineBadFormat'], $_Lang['PageTitle']); - } - } - else - { - AdminMessage($_Lang['Error_ResendLineEmpty'], $_Lang['PageTitle']); - } - } - else - { - AdminMessage($_Lang['Error_ResendBadLine'], $_Lang['PageTitle']); - } - } - - // ------------------------------ - // Log Parser ------------------- - // ------------------------------ - $LogBreak = 100; - - // First Time - if(substr($LogFile[1], 0, 1) === '[') - { - $ExplodeFirst = $LogFile[2]; - } - else - { - $ExplodeFirst = $LogFile[1]; - } - $ExplodeFirst = explode('|', $ExplodeFirst); - if(strlen($ExplodeFirst[0]) == 8) - { - $ExplodeFirst[0] = explode(':', $ExplodeFirst[0]); - $_Lang['FromHour'] = $ExplodeFirst[0][0]; - $_Lang['FromMin'] = $ExplodeFirst[0][1]; - $_Lang['FromSec'] = $ExplodeFirst[0][2]; - } - else - { - $TempSec = $ExplodeFirst[0]; - $TempH = floor($TempSec/3600); - $TempSec -= $TempH * 3600; - $TempM = floor($TempSec/60); - $TempSec -= $TempM * 60; - $_Lang['FromHour'] = $TempH; - $_Lang['FromMin'] = $TempM; - $_Lang['FromSec'] = $TempSec; - } - // Last Time - $LogKeys = array_keys($LogFile); - $ExplodeLast = $LogFile[max($LogKeys)]; - $ExplodeLast = explode('|', $ExplodeLast); - if(strlen($ExplodeLast[0]) == 8) - { - $ExplodeLast[0] = explode(':', $ExplodeLast[0]); - $_Lang['ToHour'] = $ExplodeLast[0][0]; - $_Lang['ToMin'] = $ExplodeLast[0][1]; - $_Lang['ToSec'] = $ExplodeLast[0][2]; - } - else - { - $TempSec = $ExplodeLast[0]; - $TempH = floor($TempSec/3600); - $TempSec -= $TempH * 3600; - $TempM = floor($TempSec/60); - $TempSec -= $TempM * 60; - $_Lang['ToHour'] = $TempH; - $_Lang['ToMin'] = $TempM; - $_Lang['ToSec'] = $TempSec; - } - $FromMinimal = ($_Lang['FromHour'] * 3600) + ($_Lang['FromMin'] * 60) + $_Lang['FromSec']; - $ToMaximal = ($_Lang['ToHour'] * 3600) + ($_Lang['ToMin'] * 60) + $_Lang['ToSec']; - $_Lang['FromHour'] = str_pad($_Lang['FromHour'], 2, '0', STR_PAD_LEFT); - $_Lang['ToHour'] = str_pad($_Lang['ToHour'], 2, '0', STR_PAD_LEFT); - $_Lang['FromMin'] = str_pad($_Lang['FromMin'], 2, '0', STR_PAD_LEFT); - $_Lang['ToMin'] = str_pad($_Lang['ToMin'], 2, '0', STR_PAD_LEFT); - $_Lang['FromSec'] = str_pad($_Lang['FromSec'], 2, '0', STR_PAD_LEFT); - $_Lang['ToSec'] = str_pad($_Lang['ToSec'], 2, '0', STR_PAD_LEFT); - - // POST Filtering - $FilterOn = false; - $OneFilterOn = false; - if(isset($_POST['filter_time']) && $_POST['filter_time'] == 'on') - { - $OneFilterOn = true; - $JoinFrom = ($_POST['from_hour'] * 3600) + ($_POST['from_min'] * 60) + $_POST['from_sec']; - if($JoinFrom > $FromMinimal) - { - $_Lang['FromHour'] = str_pad($_POST['from_hour'], 2, '0', STR_PAD_LEFT); - $_Lang['FromMin'] = str_pad($_POST['from_min'], 2, '0', STR_PAD_LEFT); - $_Lang['FromSec'] = str_pad($_POST['from_sec'], 2, '0', STR_PAD_LEFT); - $EnableFromFilter = $JoinFrom; - $FilterOn = true; - } - else - { - $EnableFromFilter = 0; - } - $JoinTo = ($_POST['to_hour'] * 3600) + ($_POST['to_min'] * 60) + $_POST['to_sec']; - if($JoinTo < $ToMaximal) - { - $_Lang['ToHour'] = str_pad($_POST['to_hour'], 2, '0', STR_PAD_LEFT); - $_Lang['ToMin'] = str_pad($_POST['to_min'], 2, '0', STR_PAD_LEFT); - $_Lang['ToSec'] = str_pad($_POST['to_sec'], 2, '0', STR_PAD_LEFT); - $EnableToFilter = $JoinTo; - $FilterOn = true; - } - else - { - $EnableToFilter = 86400; - } - $_Lang['Set_filter_time_checked'] = 'checked'; - } - else - { - $EnableFromFilter = 0; - $EnableToFilter = 86400; - } - $FilterPlaceOn = false; - if(isset($_POST['filter_place']) && $_POST['filter_place'] == 'on') - { - if(!empty($_POST['filter_place_query'])) - { - if(in_array($_POST['filter_place_type'], array(1, 2, 3))) - { - $OneFilterOn = true; - $FilterPlaceOn = true; - $FilterPlaceType = $_POST['filter_place_type']; - $Query = $_POST['filter_place_query']; - if($FilterPlaceType == 1) - { - $FilterPlaceFunc = function($String) use($Query) - { - if($String == $Query) - { - return true; - } - return false; - }; - } - else if($FilterPlaceType == 2) - { - $FilterPlaceFunc = function($String) use($Query) - { - if($String != $Query) - { - return true; - } - return false; - }; - } - else if($FilterPlaceType == 3) - { - $FilterPlaceFunc = function($String) use($Query) - { - return (bool)@preg_match($Query, $String); - }; - } - $_Lang['Set_filter_place_type_'.$_POST['filter_place_type'].'_checked'] = 'checked'; - } - $_Lang['Set_filter_place_query'] = $_POST['filter_place_query']; - } - $_Lang['Set_filter_place_checked'] = 'checked'; - } - - // Pagination - $CurrentPage = isset($_GET['page']) ? intval($_GET['page']) : 0; - if($CurrentPage > 1) - { - $AfterFilter = false; - $EnablePageFilter = (($CurrentPage - 1) * $LogBreak) + 1; - } - else - { - $CurrentPage = 1; - $AfterFilter = true; - $EnablePageFilter = 1; - } - - if($OneFilterOn === false) - { - $Parse['FilteringDisplay'] = ' display: none;'; - } - - $Counters_LogsShowed = 0; - $Counters_LogsTotalCount = 0; - $Counters_LogsFilteredCount = 0; - $Counters_IPShowed = 0; - $Counters_BrowserShowed = 0; - $Counters_ScreenInfoShowed = 0; - $Counters_BadFormatLines = 0; - - $Switch_LastIPShowed = false; - $Switch_LastBrowserShowed = false; - $Switch_LastScreenInfoShowed = false; - $Switch_LastFormatErrorShowed = false; - $Switch_CanBeMerged = false; - $Switch_FullReload = false; - $Switch_BlockErrors = false; - $Switch_LastLineHadFormatError = false; - - $Indicator_LeftmostLimitTouched = false; - $Indicator_RightmostLimitReached = false; - $Indicator_PageLimitTouched = false; - $Indicator_OnScreenLimitReached = false; - $Indicator_LastSkippedByPlaceFilter = false; - - $Data_LastIP = false; - $Data_LastBrowser = false; - $Data_LastScreenInfo = false; - $Data_LastPage = false; - $Data_LastPOST = false; - $Data_LastIPChangeTime = false; - $Data_LastBrowserChangeTime = false; - $Data_LastScreenInfoChangeTime = false; - $Data_LastFormatErrorTime = false; - $Data_ParseRows = array(); - $Data_LastParsedRowsIndex = 0; - foreach($LogFile as $LineNo => $LineData) - { - $_This = array(); - $Data_ThisParsedRowsIndex = $Data_LastParsedRowsIndex + 1; - if(substr($LineData, 0, 1) === '[') - { - // This is IP/Browser Line - if(!$Indicator_RightmostLimitReached) - { - $LineData = explode('|', str_replace(array('[', ']'), '', $LineData)); - foreach($LineData as $LineDataSplit) - { - $FirstLetter = substr($LineDataSplit, 0, 1); - if($FirstLetter === 'B') - { - // This is Browser Data (Marked as "B") - $Data_LastBrowser = stripslashes(substr($LineDataSplit, 1)); - $Data_LastBrowserChangeTime = false; - $Switch_LastBrowserShowed = false; - } - else if($FirstLetter === 'S') - { - // This is ScreenResolution Data (Marked as "S") - $Data_LastScreenInfo = str_replace('_', 'x', substr($LineDataSplit, 1)); - $Data_LastScreenInfoChangeTime = false; - $Switch_LastScreenInfoShowed = false; - } - else - { - // This is IP Data (Marked as "A" or "other") - if($FirstLetter === 'A') - { - $Data_LastIP = substr($LineDataSplit, 1); - } - else - { - $Data_LastIP = $LineDataSplit; - } - $Data_LastIPChangeTime = false; - $Switch_LastIPShowed = false; - } - } - } - } - else - { - // This is Action Line - - // Check if Lineformat is correct - $LineData = trim($LineData); - if(!preg_match('/^([0-9]{1,5}|[0-9]{2}\:[0-9]{2}\:[0-9]{2})\|([a-zA-Z0-9\.\?\=\;\&\_\/\-\ ]{1,})(\|){0,1}(.*?)$/D', $LineData, $LineData)) - { - if(!$Switch_LastLineHadFormatError) - { - $Counters_BadFormatLines = 1; - } - else - { - $Counters_BadFormatLines += 1; - } - $Data_LastFormatErrorTime = false; - $Switch_LastFormatErrorShowed = false; - $Switch_LastLineHadFormatError = true; - continue; - } - $Counters_LogsTotalCount += 1; - if(!$Indicator_RightmostLimitReached) - { - // Parse Time - if(strstr($LineData[1], ':')) - { - $LineData[1] = explode(':', $LineData[1]); - $_This['Time'] = ($LineData[1][0] * 3600) + ($LineData[1][1] * 60) + $LineData[1][2]; - } - else - { - $_This['Time'] = $LineData[1]; - } - - // Filter Time - Rightmost Limit (ToTime Limit) - if($EnableToFilter < $_This['Time']) - { - $Indicator_RightmostLimitReached = true; - if(!$Switch_BlockErrors) - { - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'] = sprintf($_Lang['Log_ReachedFilter'], $_Lang['ToHour'], $_Lang['ToMin'], $_Lang['ToSec']); - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Type'] = '1'; - $Switch_BlockErrors = true; - } - $Switch_LastLineHadFormatError = false; - continue; - } - if(!$Switch_LastFormatErrorShowed AND $Data_LastFormatErrorTime === false) - { - $Data_LastFormatErrorTime = $_This['Time']; - } - if(!$Switch_LastIPShowed AND $Data_LastIPChangeTime === false) - { - $Data_LastIPChangeTime = $_This['Time']; - } - if(!$Switch_LastBrowserShowed AND $Data_LastBrowserChangeTime === false) - { - $Data_LastBrowserChangeTime = $_This['Time']; - } - if(!$Switch_LastScreenInfoShowed AND $Data_LastScreenInfoChangeTime === false) - { - $Data_LastScreenInfoChangeTime = $_This['Time']; - } - - // Parse File - $_This['File'] = $LineData[2]; - $Switch_FullReload = false; - if($_This['File'] == 'reload' OR $_This['File'] == 'R') - { - $_This['File'] = $Data_LastPage; - if(empty($LineData[3])) - { - $Switch_FullReload = true; - } - if($Counters_BadFormatLines == 0 AND $Switch_LastBrowserShowed === true AND $Switch_LastIPShowed === true AND $Switch_LastScreenInfoShowed === true) - { - $Switch_CanBeMerged = true; - } - if($Indicator_LastSkippedByPlaceFilter) - { - $Switch_LastLineHadFormatError = false; - continue; - } - } - else - { - $Data_LastPage = $_This['File']; - $Switch_CanBeMerged = false; - } - // Filter Place - if($FilterPlaceOn === true AND $FilterPlaceFunc($_This['File']) === false) - { - $Indicator_LastSkippedByPlaceFilter = true; - $Switch_LastLineHadFormatError = false; - continue; - } - $Indicator_LastSkippedByPlaceFilter = false; - - // Filter Time - Leftmost Limit (FromTime Limit) - if(!$Indicator_LeftmostLimitTouched) - { - if($_This['Time'] < $EnableFromFilter) - { - $Switch_LastLineHadFormatError = false; - continue; - } - $Indicator_LeftmostLimitTouched = true; - } - - $Counters_LogsFilteredCount += 1; - // Filter Page Limit - if(!$Indicator_PageLimitTouched) - { - if($Counters_LogsFilteredCount < $EnablePageFilter) - { - $Switch_LastLineHadFormatError = false; - continue; - } - $Indicator_PageLimitTouched = true; - } - - // Filter OnScreen Limit - if(!$Indicator_OnScreenLimitReached) - { - if($Counters_LogsShowed >= $LogBreak) - { - $Indicator_OnScreenLimitReached = true; - if(!$Switch_BlockErrors) - { - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'] = sprintf($_Lang['Log_TooManyLines'], prettyNumber($LogBreak)); - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Type'] = '1'; - $Switch_BlockErrors = true; - } - $Switch_LastLineHadFormatError = false; - continue; - } - } - else - { - $Switch_LastLineHadFormatError = false; - continue; - } - - // Now process the Line (all filters passed) - $_This['Args_POST'] = $LineData[4]; - if($Switch_CanBeMerged AND ($_This['Args_POST'] !== $Data_LastPOST AND !$Switch_FullReload)) - { - $Switch_CanBeMerged = false; - } - - if(!$Switch_CanBeMerged) - { - $_This['FileExplode'] = explode('?', $_This['File']); - $_This['File'] = $_This['FileExplode'][0]; - $_This['Args_GET'] = isset($_This['FileExplode'][1]) ? $_This['FileExplode'][1] : null; - $Data_LastPOST = $LineData[4]; - if($_This['Args_POST'] == 'N') - { - $_This['Args_POST'] = null; - } - - if($Counters_BadFormatLines > 0 OR !$Switch_LastIPShowed OR !$Switch_LastBrowserShowed OR !$Switch_LastScreenInfoShowed) - { - // Show InfoRows - $_InfoRowsData = array(); - - if(!$Switch_LastIPShowed) - { - if($Counters_IPShowed == 0) - { - $ThisMessage = sprintf($_Lang['Log_IPisCurentlyX'], $Data_LastIP); - } - else - { - $ThisMessage = sprintf($_Lang['Log_IPChangedToX'], $Data_LastIP); - } - $_InfoRowsData[$Data_LastIPChangeTime][] = $ThisMessage; - $Counters_IPShowed += 1; - } - if(!$Switch_LastBrowserShowed) - { - if($Counters_BrowserShowed == 0) - { - $ThisMessage = sprintf($_Lang['Log_BrowserCurrent'], $Data_LastBrowser); - } - else - { - $ThisMessage = sprintf($_Lang['Log_BrowserChange'], $Data_LastBrowser); - } - $_InfoRowsData[$Data_LastBrowserChangeTime][] = $ThisMessage; - $Counters_IPShowed += 1; - } - if(!$Switch_LastScreenInfoShowed) - { - if($Counters_ScreenInfoShowed == 0) - { - $ThisMessage = sprintf($_Lang['Log_ScreenCurrent'], $Data_LastScreenInfo); - } - else - { - $ThisMessage = sprintf($_Lang['Log_ScreenChange'], $Data_LastScreenInfo); - } - $_InfoRowsData[$Data_LastScreenInfoChangeTime][] = $ThisMessage; - $Counters_ScreenInfoShowed += 1; - } - if($Counters_BadFormatLines > 0 AND $Switch_LastLineHadFormatError) - { - $_InfoRowsData[$Data_LastFormatErrorTime][] = sprintf($_Lang['Log_BadFormatLines'], prettyNumber($Counters_BadFormatLines)); - } - - $_InfoRowsCount = count($_InfoRowsData); - reset($_InfoRowsData); - if($_InfoRowsCount > 1 OR key($_InfoRowsData) != $_This['Time']) - { - ksort($_InfoRowsData); - - foreach($_InfoRowsData as $Timestamp => $InfoRowData) - { - if($Timestamp == $_This['Time']) - { - continue; - } - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Type'] = '2'; - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Time'][] = parseTimestamp($Timestamp); - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'] = $InfoRowData; - $Data_ThisParsedRowsIndex += 1; - $Data_LastParsedRowsIndex += 1; - unset($_InfoRowsData[$Timestamp]); - } - } - if(!empty($_InfoRowsData)) - { - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Type'] = 'M'; - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Infos'] = implode('
', $_InfoRowsData[$_This['Time']]); - } - else - { - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Type'] = '3'; - } - - $Data_LastIPChangeTime = false; - $Data_LastBrowserChangeTime = false; - $Data_LastScreenInfoChangeTime = false; - $Data_LastFormatErrorTime = false; - } - else - { - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Type'] = '3'; - } - - // GET & POST Parser - if(!empty($_This['Args_GET']) OR !empty($_This['Args_POST'])){ - if(!empty($_This['Args_GET'])){ - $_This['Args_GET'] = explode('&', $_This['Args_GET']); - foreach($_This['Args_GET'] as &$GetParser){ - $GetParser = explode('=', $GetParser); - $GetParser = "{$GetParser[0]}=".valueParser($GetParser[1]).""; - } - $_This['Args_GET'] = implode(' & ', $_This['Args_GET']); - - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'][] = "{$_Lang['Log_GETData']}: {$_This['Args_GET']}"; - } - if(!empty($_This['Args_POST'])){ - $_This['Args_POST'] = json_decode($_This['Args_POST'], true); - - if(!empty($_This['Args_POST']) AND (array)$_This['Args_POST'] === $_This['Args_POST']){ - $PostParsed = false; - $GetState = PostParser($_This['Args_POST'], true); - if($GetState['arr'] === true){ - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Actions'][] = "{$_Lang['ExpandArrays']}"; - } - if($GetState['cou'] > 1){ - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Actions'][] = "{$_Lang['ExpandAmps']}"; - } - - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'][] = "{$_Lang['Log_POSTData']}: ".implode(' & ', $PostParsed); - } else { - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'][] = "{$_Lang['Log_POSTData']}: {$_Lang['Log_POST_UnserializeError']}"; - } - } - - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Actions'][] = "{$_Lang['ResendRequest']}"; - if(!empty($Data_ParseRows[$Data_ThisParsedRowsIndex]['Actions'])){ - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Actions'] = implode('
', $Data_ParseRows[$Data_ThisParsedRowsIndex]['Actions']); - } - - if(!empty($Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'])){ - $Data_ParseRows[$Data_ThisParsedRowsIndex]['LeftAlignClass'] = 'lal'; - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'] = implode('
', $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data']); - } - } else { - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'] = $_Lang['Log_No_GET_POST']; - } - if(empty($Data_ParseRows[$Data_ThisParsedRowsIndex]['Actions'])){ - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Actions'] = ' '; - } - - // Finish for this Row - $Data_ParseRows[$Data_ThisParsedRowsIndex]['File'] = $_This['File']; - $Data_ParseRows[$Data_ThisParsedRowsIndex]['FileShow'] = str_replace('/', '/
', $_This['File']); - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Path'] = $_EnginePath; - $Data_LastParsedRowsIndex += 1; - - $Counters_BadFormatLines = 0; - $Switch_LastIPShowed = true; - $Switch_LastBrowserShowed = true; - $Switch_LastScreenInfoShowed = true; - $Switch_LastFormatErrorShowed = true; - } - else - { - $Data_ThisParsedRowsIndex -= 1; - } - $Data_ParseRows[$Data_ThisParsedRowsIndex]['Time'][] = parseTimestamp($_This['Time']); - - $Counters_LogsShowed += 1; - $Switch_CanBeMerged = false; - } - } - } - - foreach($Data_ParseRows as $RowData) - { - if($RowData['Type'] == '1') - { - $ThisTemplate = &$Row1LogTPL; - } - else if($RowData['Type'] == '2') - { - $ThisTemplate = &$Row2LogTPL; - } - else if($RowData['Type'] == '3') - { - $ThisTemplate = &$Row3LogTPL; - } - else if($RowData['Type'] == 'M') - { - $ThisTemplate = &$RowMLogTPL; - } - if(!empty($RowData['Time'])) - { - $RowData['Time'] = implode('
', $RowData['Time']); - } - if((array)$RowData['Data'] === $RowData['Data']) - { - $RowData['Data'] = implode('
', $RowData['Data']); - } - $Rows[] = parsetemplate($ThisTemplate, $RowData); - } - - if($Counters_LogsShowed < $Counters_LogsFilteredCount) - { - $CurrentPage = ($CurrentPage > 1 ? $CurrentPage : 1); - include_once($_EnginePath.'includes/functions/Pagination.php'); - - $Pagin = CreatePaginationArray($Counters_LogsFilteredCount, $LogBreak, $CurrentPage, 7); - $PaginationTPL = gettemplate('admin/browse_actionlogs_pagination'); - $PaginationViewOpt = array('CurrentPage_Classes' => 'orange fatB', 'Breaker_View' => '...'); - $CreatePagination = ParsePaginationArray($Pagin, $CurrentPage, $PaginationTPL, $PaginationViewOpt); - $_Lang['Pagination'] = $Parse['Pagination'] = ''.implode(' ', $CreatePagination).''; - } - - $_Lang['ShowingXofYRows'] = sprintf($_Lang['ShowingXofYRows'], $Counters_LogsShowed, $Counters_LogsFilteredCount, $Counters_LogsTotalCount); - - $Parse['Headers']= parsetemplate($HeadLogTPL, $_Lang); - if(!empty($Rows)) - { - $Parse['Content'] = implode('', $Rows); - } - else - { - $Parse['Content'] = parsetemplate($Row1LogTPL, array('Data' => $_Lang['Info_NoLogsFilter'])); - } - - $Parse['CurrentBrowsingDate'] = " » {$EDate[2]}.{$EDate[1]}.{$EDate[0]}"; - } - else - { - message($_Lang['Error_LogNoExists'], $Error, $ThisPage, 3); - } - } - else - { - message($_Lang['Error_BadDateFormat'], $Error, $ThisPage, 3); - } - } - - if(!$LogExists) - { - // If Log not selected - // ---- Show List ---- - $Parse['TableColspan'] = 2; - - $UserData = doquery("SELECT `username`, `register_time` FROM {{table}} WHERE `id` = {$UID} LIMIT 1;", 'users', true); - $Parse['UserName'] = $UserData['username']; - - // - Sorting - - $Sort = 'date'; - $Order = 'desc'; - $_Lang['DateSort'] = 'desc'; - $_Lang['SizeSort'] = 'desc'; - - if(!empty($_GET['sort'])) - { - if($_GET['sort'] === 'date' OR $_GET['sort'] === 'size') - { - $Sort = $_GET['sort']; - if($_GET['order'] == 'desc' OR $_GET['order'] == 'asc') - { - $Order = $_GET['order']; - } - } - } - - if($Sort === 'date') - { - if($Order === 'desc') - { - $_Lang['DateSort'] = 'asc'; - } - else - { - $_Lang['DateSort'] = 'desc'; - } - } - else if($Sort === 'size') - { - if($Order === 'desc') - { - $_Lang['SizeSort'] = 'asc'; - } - else - { - $_Lang['SizeSort'] = 'desc'; - } - } - // --------------- - // - Date Filter - - $FilterOn = false; - $FromDate = str_pad(isset($_POST['from_yea']) ? $_POST['from_yea'] : null, 4, '0', STR_PAD_LEFT) - .'_'.str_pad(isset($_POST['from_mon']) ? $_POST['from_mon'] : null, 2, '0', STR_PAD_LEFT) - .'_'.str_pad(isset($_POST['from_day']) ? $_POST['from_day'] : null, 2, '0', STR_PAD_LEFT); - $ToDate = str_pad(isset($_POST['to_yea']) ? $_POST['to_yea'] : null, 4, '0', STR_PAD_LEFT) - .'_'.str_pad(isset($_POST['to_mon']) ? $_POST['to_mon'] : null, 2, '0', STR_PAD_LEFT) - .'_'.str_pad(isset($_POST['to_day']) ? $_POST['to_day'] : null, 2, '0', STR_PAD_LEFT); - if(!preg_match('/^[0-9]{4}\_[0-9]{2}\_[0-9]{2}$/D', $FromDate) OR strstr($FromDate, '0000_') OR strstr($FromDate, '_00')) - { - $RegdayExp = explode('.', date('d.m.Y', $UserData['register_time'])); - $FromDate = $RegdayExp[2].'_'.$RegdayExp[1].'_'.$RegdayExp[0]; - } - else - { - $RegdayExp = array_reverse(explode('_', $FromDate)); - $FilterOn = true; - } - if(!preg_match('/^[0-9]{4}\_[0-9]{2}\_[0-9]{2}$/D', $ToDate) OR strstr($ToDate, '0000_') OR strstr($ToDate, '_00')) - { - $TodayExp = explode('.', date('d.m.Y')); - $ToDate = $TodayExp[2].'_'.$TodayExp[1].'_'.$TodayExp[0]; - } - else - { - $TodayExp = array_reverse(explode('_', $ToDate)); - $FilterOn = true; - } - if($FromDate < date('Y_m_d', $UserData['register_time'])) - { - $RegdayExp = explode('.', date('d.m.Y', $UserData['register_time'])); - $FromDate = $RegdayExp[2].'_'.$RegdayExp[1].'_'.$RegdayExp[0]; - } - if($ToDate < $FromDate) - { - $TodayExp = $RegdayExp; - $ToDate = $TodayExp[2].'_'.$TodayExp[1].'_'.$TodayExp[0]; - } - else if($ToDate > date('Y_m_d')) - { - $TodayExp = explode('.', date('d.m.Y')); - $ToDate = $TodayExp[2].'_'.$TodayExp[1].'_'.$TodayExp[0]; - } - - $DirPath= './../action_logs/'.$UIDMarker; - $ScanDir= scandir($DirPath); - foreach($ScanDir as $Filename) - { - if(preg_match("/^Log\_U\_{$UIDMarker}\_D\_([0-9]{4}\_[0-9]{2}\_[0-9]{2})\.php$/D", $Filename, $Matches)) - { - if($Matches[1] >= $FromDate AND $Matches[1] <= $ToDate) - { - $Logs[$Matches[1]] = 'N'; - $FileSizes[$Matches[1]] = (string) filesize($DirPath.'/'.$Filename); - } - } - } - - if(isset($_POST['filter']) && $_POST['filter'] != 'on') - { - $Parse['FilteringDisplay'] = ' display: none;'; - } - - $ScanDir = scandir('./../action_logs'); - foreach($ScanDir as $DirName) - { - if(strstr($DirName, 'logs')) - { - $GetDate = substr($DirName, 5); - if($GetDate >= $FromDate AND $GetDate <= $ToDate) - { - $File = "./../action_logs/{$DirName}/Log_U_{$UIDMarker}_D_{$GetDate}.php.gz"; - if(file_exists($File)) - { - $Logs[$GetDate.'_P'] = 'P'; - $FileSizes[$GetDate.'_P'] = (string) filesize($File); - } - } - } - } - - $LogsCount = count($Logs); - if($LogsCount == 0) - { - $_Lang['NoHeader'] = 'display: none;'; - if($FilterOn) - { - $Rows = ''.$_Lang['Info_NoLogsForThatPeriod'].''; - } - else - { - $Rows = ''.$_Lang['Info_NoLogs'].''; - } - } - else - { - if($Sort === 'date' AND $Order === 'desc') - { - krsort($Logs); - } - else if($Sort === 'date' AND $Order === 'asc') - { - ksort($Logs); - } - else if($Sort === 'size' AND $Order === 'desc') - { - arsort($FileSizes); - foreach($FileSizes as $Key => $Val) - { - $NewLogs[$Key] = $Logs[$Key]; - } - $Logs = $NewLogs; - } - else if($Sort === 'size' AND $Order === 'asc') - { - asort($FileSizes); - foreach($FileSizes as $Key => $Val) - { - $NewLogs[$Key] = $Logs[$Key]; - } - $Logs = $NewLogs; - } - - $Rows = ''; - foreach($Logs as $Key => $Name) - { - $Row = false; - $Row['UID'] = $UID; - if(strstr($Key, '_P')) - { - $Row['Date'] = str_replace('_P', '', $Key); - $Row['Packed'] = '&packed=true'; - $Packed = true; - } - else - { - $Row['Date'] = $Key; - $Packed = false; - } - $Row['Date_Formated'] = explode('_', $Key); - $Row['Date_Formated'] = "{$Row['Date_Formated'][2]}.{$Row['Date_Formated'][1]}.{$Row['Date_Formated'][0]}"; - $Row['Size'] = humanSize($FileSizes[$Key]); - if($Packed) - { - $Row['Size'] = "{$Row['Size']}"; - } - - $Rows .= parsetemplate($RowListTPL, $Row); - } - } - - $_Lang['FromDay'] = $RegdayExp[0]; - $_Lang['FromMon'] = $RegdayExp[1]; - $_Lang['FromYea'] = $RegdayExp[2]; - $_Lang['ToDay'] = $TodayExp[0]; - $_Lang['ToMon'] = $TodayExp[1]; - $_Lang['ToYea'] = $TodayExp[2]; - $_Lang['LogsCount'] = $LogsCount; - $Parse['Headers'] = parsetemplate($HeadListTPL, $_Lang); - $Parse['Content'] = $Rows; - } - - $Parse['SetFiltering'] = isset($_POST['filter']) ? $_POST['filter'] : null; - $Parse['ThisPage'] = $ThisPage; - $Page = parsetemplate($MainTPL, $Parse); - display($Page, $_Lang['PageTitle'], false, true); - } - else - { - AdminMessage($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); - } - -?> \ No newline at end of file + 1048576) + { + $Unit = 1048576; + $UnitName = 'MB'; + } + else if($Mem > 1024) + { + $Unit = 1024; + $UnitName = 'KB'; + } + else + { + $Unit = 1; + $UnitName = 'B'; + return $Mem.' '.$UnitName; + } + return sprintf('%0.4f', ($Mem/$Unit)).' '.$UnitName; + } + + function PostParser($Array, $ReturnState = false) + { + global $PostParsed; + static $Depth, $DeepParse, $State; + if($Depth <= 0) + { + $Depth = 0; + } + if($ReturnState) + { + $State = array('arr' => false, 'cou' => 0); + } + + foreach($Array as $Key => $Data) + { + if((array)$Data === $Data) + { + if($ReturnState) + { + $State['arr'] = true; + } + $State['cou'] += 1; + $Depth += 1; + PostParser($Data); + if(is_string($Key)) + { + $Key = "'{$Key}'"; + } + $Start = "
{$Key}[]{"; + $End = "}"; + if($Depth == 1) + { + $PostParsed[] = $Start.implode(' & ', $DeepParse[$Depth]).$End; + unset($DeepParse[$Depth]); + } + else + { + $DeepParse[($Depth-1)][] = $Start.implode(' & ', $DeepParse[$Depth]).$End; + unset($DeepParse[$Depth]); + } + $Depth -= 1; + } + else + { + $State['cou'] += 1; + if(is_string($Key)) + { + $Key = "'{$Key}'"; + } + if(is_string($Data)) + { + $Data = "'{$Data}'"; + } + $ParseIt = "{$Key}=".valueParser($Data).""; + if($Depth > 0) + { + $DeepParse[$Depth][] = $ParseIt; + } + else + { + $PostParsed[] = $ParseIt; + } + } + } + + if($ReturnState) + { + $DeepParse = false; + return $State; + } + } + + function valueParser($Value) + { + $Length = strlen($Value); + if($Length > 40) + { + $Part1 = substr($Value, 0, 10); + $Part2 = substr($Value, 10, $Length - 20); + $Part3 = substr($Value, -10); + return "{$Part1}(...){$Part2}{$Part3}"; + } + return $Value; + } + + function walkPostArray($Array) + { + static $Return = array(), $CurrentPath = '', $CurrentLevel = 1; + + $PreviousPath = $CurrentPath; + foreach($Array as $Key => $Value) + { + if($CurrentLevel > 1) + { + $CurrentPath = "{$PreviousPath}[{$Key}]"; + } + else + { + $CurrentPath = $Key; + } + if((array)$Value === $Value) + { + $CurrentLevel += 1; + walkPostArray($Value); + $CurrentLevel -= 1; + } + else + { + $Return[] = array('name' => $CurrentPath, 'value' => $Value); + } + } + $CurrentPath = $PreviousPath; + + if($CurrentLevel <= 1) + { + $TempReturn = $Return; + $Return = array(); + $CurrentPath = ''; + $CurrentLevel = 1; + return $TempReturn; + } + } + + function parseTimestamp($Timestamp) + { + $Temp['H'] = floor($Timestamp / 3600); + $Timestamp -= $Temp['H'] * 3600; + $Temp['M'] = floor($Timestamp / 60); + $Timestamp -= $Temp['M'] * 60; + $Temp['S'] = $Timestamp; + + return str_pad($Temp['H'], 2, '0', STR_PAD_LEFT).':'.str_pad($Temp['M'], 2, '0', STR_PAD_LEFT).':'.str_pad($Temp['S'], 2, '0', STR_PAD_LEFT); + } + // ------------------------------------------------------------------------------------------------------------------------------------------ + // ------------------------------------------------------------------------------------------------------------------------------------------ + + includeLang('admin/browse_actionlogs'); + + $Error = $_Lang['PageTitle']; + $ThisPage = 'browse_actionlogs.php'; + $Parse = $_Lang; + $MainTPL = gettemplate('admin/browse_actionlogs_body'); + $RowListTPL = gettemplate('admin/browse_actionlogs_list_row'); + $HeadListTPL = gettemplate('admin/browse_actionlogs_list_header'); + $Row3LogTPL = gettemplate('admin/browse_actionlogs_log_row_3'); + $Row2LogTPL = gettemplate('admin/browse_actionlogs_log_row_2'); + $Row1LogTPL = gettemplate('admin/browse_actionlogs_log_row_1'); + $RowMLogTPL = gettemplate('admin/browse_actionlogs_log_row_multi'); + $HeadLogTPL = gettemplate('admin/browse_actionlogs_log_header'); + $ResendTPL = gettemplate('admin/browse_actionlogs_resendrequest'); + + if(!empty($_POST)) + { + if(isset($_POST['autoExpandArr']) && $_POST['autoExpandArr'] == 'on') + { + $AutoExpandArray = 'true'; + $SetArrCookie = 'on'; + } + else + { + $AutoExpandArray = 'false'; + $SetArrCookie = 'off'; + } + if(isset($_POST['autoExpandAmp']) && $_POST['autoExpandAmp'] == 'on') + { + $AutoExpandAmper = 'true'; + $SetAmpCookie = 'on'; + } + else + { + $AutoExpandAmper = 'false'; + $SetAmpCookie = 'off'; + } + setcookie('autoExpandArr', $SetArrCookie, time() + 31536000); + setcookie('autoExpandAmp', $SetAmpCookie, time() + 31536000); + } + else + { + if($_COOKIE['autoExpandArr'] == 'on') + { + $AutoExpandArray = 'true'; + } + else if($_COOKIE['autoExpandArr'] == 'off' OR empty($_COOKIE['autoExpandArr'])) + { + $AutoExpandArray = 'false'; + } + if($_COOKIE['autoExpandAmp'] == 'on') + { + $AutoExpandAmper = 'true'; + } + else if($_COOKIE['autoExpandAmp'] == 'off' OR empty($_COOKIE['autoExpandAmp'])) + { + $AutoExpandAmper = 'false'; + } + } + if($AutoExpandArray == 'true') + { + $_Lang['aEArrCheck'] = 'checked'; + } + if($AutoExpandAmper == 'true') + { + $_Lang['aEAmpCheck'] = 'checked'; + } + + $Parse['AutoExpandArray'] = $AutoExpandArray; + $Parse['AutoExpandAmp'] = $AutoExpandAmper; + + $UID = intval($_GET['uid']); + + if($UID <= 0) + { + message($_Lang['Error_BadUID'], $Error); + } + $ThisPage = "{$ThisPage}?uid={$UID}"; + $Parse['UID'] = $UID; + $_Lang['UID'] = $UID; + $UIDMarker = str_pad($UID, 6, '0', STR_PAD_LEFT); + $Date = isset($_GET['date']) ? $_GET['date'] : null; + + $LogExists = false; + + if(!empty($Date)) + { + if(preg_match('/^[0-9\_]{10}$/D', $Date)) + { + $Packed = ''; + if(isset($_GET['packed']) && $_GET['packed'] === 'true') + { + $FilePath = "./../action_logs/logs_{$Date}/Log_U_{$UIDMarker}_D_{$Date}.php.gz"; + $Packed = '&packed=true'; + $GZiped = true; + } + else + { + $FilePath = "./../action_logs/{$UIDMarker}/Log_U_{$UIDMarker}_D_{$Date}.php"; + $GZiped = false; + } + + if(file_exists($FilePath)) + { + $ThisPage = "{$ThisPage}&date={$Date}{$Packed}"; + + $Parse['TableColspan'] = 4; + $LogExists = true; + + $UserData = doquery("SELECT `username` FROM {{table}} WHERE `id` = {$UID} LIMIT 1;", 'users', true); + $Parse['UserName'] = $UserData['username']; + + $EDate = explode('_', $Date); + + if($GZiped) + { + $LogFile = gzfile($FilePath); + } + else + { + $LogFile = file($FilePath); + } + unset($LogFile[(count($LogFile) - 1)]); + unset($LogFile[0]); + + if(!empty($_GET['resendline'])) + { + $ResendLineNo = round($_GET['resendline']); + if($ResendLineNo >= 0) + { + if(!empty($LogFile[$ResendLineNo])) + { + if(preg_match('/^([0-9]{1,5}|[0-9]{2}\:[0-9]{2}\:[0-9]{2})\|([a-zA-Z0-9\.\?\=\;\&\_\/\-\ ]{1,})(\|){0,1}(.*?)$/D', trim($LogFile[$ResendLineNo]), $LogFile[$ResendLineNo])) + { + $ResendFile = false; + $ResendPost = false; + + if($LogFile[$ResendLineNo][2] == 'R' OR $LogFile[$ResendLineNo][2] == 'reload') + { + if(empty($LogFile[$ResendLineNo][4])) + { + $PostReload = true; + } + else + { + $ResendPost = $LogFile[$ResendLineNo][4]; + } + + $ReverseScanIndex = $ResendLineNo - 1; + while(!empty($LogFile[$ReverseScanIndex])) + { + if(!preg_match('/^([0-9]{1,5}|[0-9]{2}\:[0-9]{2}\:[0-9]{2})\|([a-zA-Z0-9\.\?\=\;\&\_\/\-\ ]{1,})(\|){0,1}(.*?)$/D', trim($LogFile[$ReverseScanIndex]), $LogFile[$ReverseScanIndex])) + { + $ReverseScanIndex -= 1; + continue; + } + if($PostReload === true AND !empty($LogFile[$ReverseScanIndex][4])) + { + $ResendPost = $LogFile[$ReverseScanIndex][4]; + } + if($LogFile[$ReverseScanIndex][2] == 'R' OR $LogFile[$ReverseScanIndex][2] == 'reload') + { + $ReverseScanIndex -= 1; + } + else + { + $ResendFile = $LogFile[$ReverseScanIndex][2]; + break; + } + } + + if(empty($ResendFile)) + { + AdminMessage($_Lang['Error_ResendLineBadRevScan'], $_Lang['PageTitle']); + } + } + else + { + $ResendFile = $LogFile[$ResendLineNo][2]; + $ResendPost = $LogFile[$ResendLineNo][4]; + } + + $GenerateForm['UserInfo'] = $_Lang['Info_RequestProceeding']; + $GenerateForm['FilePath'] = $_EnginePath.$ResendFile; + if(!empty($ResendPost) AND $ResendPost != 'N') + { + $ResendPost = json_decode($ResendPost, true); + $GenerateForm['GenerateInputs'] = walkPostArray($ResendPost); + foreach($GenerateForm['GenerateInputs'] as $InputData) + { + $InputData['value'] = stripslashes($InputData['value']); + $GenerateForm['GenerateInputsArray'][] = ""; + } + $GenerateForm['GenerateInputs'] = implode('', $GenerateForm['GenerateInputsArray']); + } + $Page = parsetemplate($ResendTPL, $GenerateForm); + $_DontShowMenus = true; + display($Page, $_Lang['PageTitle'], false, true); + } + else + { + AdminMessage($_Lang['Error_ResendLineBadFormat'], $_Lang['PageTitle']); + } + } + else + { + AdminMessage($_Lang['Error_ResendLineEmpty'], $_Lang['PageTitle']); + } + } + else + { + AdminMessage($_Lang['Error_ResendBadLine'], $_Lang['PageTitle']); + } + } + + // ------------------------------ + // Log Parser ------------------- + // ------------------------------ + $LogBreak = 100; + + // First Time + if(substr($LogFile[1], 0, 1) === '[') + { + $ExplodeFirst = $LogFile[2]; + } + else + { + $ExplodeFirst = $LogFile[1]; + } + $ExplodeFirst = explode('|', $ExplodeFirst); + if(strlen($ExplodeFirst[0]) == 8) + { + $ExplodeFirst[0] = explode(':', $ExplodeFirst[0]); + $_Lang['FromHour'] = $ExplodeFirst[0][0]; + $_Lang['FromMin'] = $ExplodeFirst[0][1]; + $_Lang['FromSec'] = $ExplodeFirst[0][2]; + } + else + { + $TempSec = $ExplodeFirst[0]; + $TempH = floor($TempSec/3600); + $TempSec -= $TempH * 3600; + $TempM = floor($TempSec/60); + $TempSec -= $TempM * 60; + $_Lang['FromHour'] = $TempH; + $_Lang['FromMin'] = $TempM; + $_Lang['FromSec'] = $TempSec; + } + // Last Time + $LogKeys = array_keys($LogFile); + $ExplodeLast = $LogFile[max($LogKeys)]; + $ExplodeLast = explode('|', $ExplodeLast); + if(strlen($ExplodeLast[0]) == 8) + { + $ExplodeLast[0] = explode(':', $ExplodeLast[0]); + $_Lang['ToHour'] = $ExplodeLast[0][0]; + $_Lang['ToMin'] = $ExplodeLast[0][1]; + $_Lang['ToSec'] = $ExplodeLast[0][2]; + } + else + { + $TempSec = $ExplodeLast[0]; + $TempH = floor($TempSec/3600); + $TempSec -= $TempH * 3600; + $TempM = floor($TempSec/60); + $TempSec -= $TempM * 60; + $_Lang['ToHour'] = $TempH; + $_Lang['ToMin'] = $TempM; + $_Lang['ToSec'] = $TempSec; + } + $FromMinimal = ($_Lang['FromHour'] * 3600) + ($_Lang['FromMin'] * 60) + $_Lang['FromSec']; + $ToMaximal = ($_Lang['ToHour'] * 3600) + ($_Lang['ToMin'] * 60) + $_Lang['ToSec']; + $_Lang['FromHour'] = str_pad($_Lang['FromHour'], 2, '0', STR_PAD_LEFT); + $_Lang['ToHour'] = str_pad($_Lang['ToHour'], 2, '0', STR_PAD_LEFT); + $_Lang['FromMin'] = str_pad($_Lang['FromMin'], 2, '0', STR_PAD_LEFT); + $_Lang['ToMin'] = str_pad($_Lang['ToMin'], 2, '0', STR_PAD_LEFT); + $_Lang['FromSec'] = str_pad($_Lang['FromSec'], 2, '0', STR_PAD_LEFT); + $_Lang['ToSec'] = str_pad($_Lang['ToSec'], 2, '0', STR_PAD_LEFT); + + // POST Filtering + $FilterOn = false; + $OneFilterOn = false; + if(isset($_POST['filter_time']) && $_POST['filter_time'] == 'on') + { + $OneFilterOn = true; + $JoinFrom = ($_POST['from_hour'] * 3600) + ($_POST['from_min'] * 60) + $_POST['from_sec']; + if($JoinFrom > $FromMinimal) + { + $_Lang['FromHour'] = str_pad($_POST['from_hour'], 2, '0', STR_PAD_LEFT); + $_Lang['FromMin'] = str_pad($_POST['from_min'], 2, '0', STR_PAD_LEFT); + $_Lang['FromSec'] = str_pad($_POST['from_sec'], 2, '0', STR_PAD_LEFT); + $EnableFromFilter = $JoinFrom; + $FilterOn = true; + } + else + { + $EnableFromFilter = 0; + } + $JoinTo = ($_POST['to_hour'] * 3600) + ($_POST['to_min'] * 60) + $_POST['to_sec']; + if($JoinTo < $ToMaximal) + { + $_Lang['ToHour'] = str_pad($_POST['to_hour'], 2, '0', STR_PAD_LEFT); + $_Lang['ToMin'] = str_pad($_POST['to_min'], 2, '0', STR_PAD_LEFT); + $_Lang['ToSec'] = str_pad($_POST['to_sec'], 2, '0', STR_PAD_LEFT); + $EnableToFilter = $JoinTo; + $FilterOn = true; + } + else + { + $EnableToFilter = 86400; + } + $_Lang['Set_filter_time_checked'] = 'checked'; + } + else + { + $EnableFromFilter = 0; + $EnableToFilter = 86400; + } + $FilterPlaceOn = false; + if(isset($_POST['filter_place']) && $_POST['filter_place'] == 'on') + { + if(!empty($_POST['filter_place_query'])) + { + if(in_array($_POST['filter_place_type'], array(1, 2, 3))) + { + $OneFilterOn = true; + $FilterPlaceOn = true; + $FilterPlaceType = $_POST['filter_place_type']; + $Query = $_POST['filter_place_query']; + if($FilterPlaceType == 1) + { + $FilterPlaceFunc = function($String) use($Query) + { + if($String == $Query) + { + return true; + } + return false; + }; + } + else if($FilterPlaceType == 2) + { + $FilterPlaceFunc = function($String) use($Query) + { + if($String != $Query) + { + return true; + } + return false; + }; + } + else if($FilterPlaceType == 3) + { + $FilterPlaceFunc = function($String) use($Query) + { + return (bool)@preg_match($Query, $String); + }; + } + $_Lang['Set_filter_place_type_'.$_POST['filter_place_type'].'_checked'] = 'checked'; + } + $_Lang['Set_filter_place_query'] = $_POST['filter_place_query']; + } + $_Lang['Set_filter_place_checked'] = 'checked'; + } + + // Pagination + $CurrentPage = isset($_GET['page']) ? intval($_GET['page']) : 0; + if($CurrentPage > 1) + { + $AfterFilter = false; + $EnablePageFilter = (($CurrentPage - 1) * $LogBreak) + 1; + } + else + { + $CurrentPage = 1; + $AfterFilter = true; + $EnablePageFilter = 1; + } + + if($OneFilterOn === false) + { + $Parse['FilteringDisplay'] = ' display: none;'; + } + + $Counters_LogsShowed = 0; + $Counters_LogsTotalCount = 0; + $Counters_LogsFilteredCount = 0; + $Counters_IPShowed = 0; + $Counters_BrowserShowed = 0; + $Counters_ScreenInfoShowed = 0; + $Counters_BadFormatLines = 0; + + $Switch_LastIPShowed = false; + $Switch_LastBrowserShowed = false; + $Switch_LastScreenInfoShowed = false; + $Switch_LastFormatErrorShowed = false; + $Switch_CanBeMerged = false; + $Switch_FullReload = false; + $Switch_BlockErrors = false; + $Switch_LastLineHadFormatError = false; + + $Indicator_LeftmostLimitTouched = false; + $Indicator_RightmostLimitReached = false; + $Indicator_PageLimitTouched = false; + $Indicator_OnScreenLimitReached = false; + $Indicator_LastSkippedByPlaceFilter = false; + + $Data_LastIP = false; + $Data_LastBrowser = false; + $Data_LastScreenInfo = false; + $Data_LastPage = false; + $Data_LastPOST = false; + $Data_LastIPChangeTime = false; + $Data_LastBrowserChangeTime = false; + $Data_LastScreenInfoChangeTime = false; + $Data_LastFormatErrorTime = false; + $Data_ParseRows = array(); + $Data_LastParsedRowsIndex = 0; + foreach($LogFile as $LineNo => $LineData) + { + $_This = array(); + $Data_ThisParsedRowsIndex = $Data_LastParsedRowsIndex + 1; + if(substr($LineData, 0, 1) === '[') + { + // This is IP/Browser Line + if(!$Indicator_RightmostLimitReached) + { + $LineData = explode('|', str_replace(array('[', ']'), '', $LineData)); + foreach($LineData as $LineDataSplit) + { + $FirstLetter = substr($LineDataSplit, 0, 1); + if($FirstLetter === 'B') + { + // This is Browser Data (Marked as "B") + $Data_LastBrowser = stripslashes(substr($LineDataSplit, 1)); + $Data_LastBrowserChangeTime = false; + $Switch_LastBrowserShowed = false; + } + else if($FirstLetter === 'S') + { + // This is ScreenResolution Data (Marked as "S") + $Data_LastScreenInfo = str_replace('_', 'x', substr($LineDataSplit, 1)); + $Data_LastScreenInfoChangeTime = false; + $Switch_LastScreenInfoShowed = false; + } + else + { + // This is IP Data (Marked as "A" or "other") + if($FirstLetter === 'A') + { + $Data_LastIP = substr($LineDataSplit, 1); + } + else + { + $Data_LastIP = $LineDataSplit; + } + $Data_LastIPChangeTime = false; + $Switch_LastIPShowed = false; + } + } + } + } + else + { + // This is Action Line + + // Check if Lineformat is correct + $LineData = trim($LineData); + if(!preg_match('/^([0-9]{1,5}|[0-9]{2}\:[0-9]{2}\:[0-9]{2})\|([a-zA-Z0-9\.\?\=\;\&\_\/\-\ ]{1,})(\|){0,1}(.*?)$/D', $LineData, $LineData)) + { + if(!$Switch_LastLineHadFormatError) + { + $Counters_BadFormatLines = 1; + } + else + { + $Counters_BadFormatLines += 1; + } + $Data_LastFormatErrorTime = false; + $Switch_LastFormatErrorShowed = false; + $Switch_LastLineHadFormatError = true; + continue; + } + $Counters_LogsTotalCount += 1; + if(!$Indicator_RightmostLimitReached) + { + // Parse Time + if(strstr($LineData[1], ':')) + { + $LineData[1] = explode(':', $LineData[1]); + $_This['Time'] = ($LineData[1][0] * 3600) + ($LineData[1][1] * 60) + $LineData[1][2]; + } + else + { + $_This['Time'] = $LineData[1]; + } + + // Filter Time - Rightmost Limit (ToTime Limit) + if($EnableToFilter < $_This['Time']) + { + $Indicator_RightmostLimitReached = true; + if(!$Switch_BlockErrors) + { + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'] = sprintf($_Lang['Log_ReachedFilter'], $_Lang['ToHour'], $_Lang['ToMin'], $_Lang['ToSec']); + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Type'] = '1'; + $Switch_BlockErrors = true; + } + $Switch_LastLineHadFormatError = false; + continue; + } + if(!$Switch_LastFormatErrorShowed AND $Data_LastFormatErrorTime === false) + { + $Data_LastFormatErrorTime = $_This['Time']; + } + if(!$Switch_LastIPShowed AND $Data_LastIPChangeTime === false) + { + $Data_LastIPChangeTime = $_This['Time']; + } + if(!$Switch_LastBrowserShowed AND $Data_LastBrowserChangeTime === false) + { + $Data_LastBrowserChangeTime = $_This['Time']; + } + if(!$Switch_LastScreenInfoShowed AND $Data_LastScreenInfoChangeTime === false) + { + $Data_LastScreenInfoChangeTime = $_This['Time']; + } + + // Parse File + $_This['File'] = $LineData[2]; + $Switch_FullReload = false; + if($_This['File'] == 'reload' OR $_This['File'] == 'R') + { + $_This['File'] = $Data_LastPage; + if(empty($LineData[3])) + { + $Switch_FullReload = true; + } + if($Counters_BadFormatLines == 0 AND $Switch_LastBrowserShowed === true AND $Switch_LastIPShowed === true AND $Switch_LastScreenInfoShowed === true) + { + $Switch_CanBeMerged = true; + } + if($Indicator_LastSkippedByPlaceFilter) + { + $Switch_LastLineHadFormatError = false; + continue; + } + } + else + { + $Data_LastPage = $_This['File']; + $Switch_CanBeMerged = false; + } + // Filter Place + if($FilterPlaceOn === true AND $FilterPlaceFunc($_This['File']) === false) + { + $Indicator_LastSkippedByPlaceFilter = true; + $Switch_LastLineHadFormatError = false; + continue; + } + $Indicator_LastSkippedByPlaceFilter = false; + + // Filter Time - Leftmost Limit (FromTime Limit) + if(!$Indicator_LeftmostLimitTouched) + { + if($_This['Time'] < $EnableFromFilter) + { + $Switch_LastLineHadFormatError = false; + continue; + } + $Indicator_LeftmostLimitTouched = true; + } + + $Counters_LogsFilteredCount += 1; + // Filter Page Limit + if(!$Indicator_PageLimitTouched) + { + if($Counters_LogsFilteredCount < $EnablePageFilter) + { + $Switch_LastLineHadFormatError = false; + continue; + } + $Indicator_PageLimitTouched = true; + } + + // Filter OnScreen Limit + if(!$Indicator_OnScreenLimitReached) + { + if($Counters_LogsShowed >= $LogBreak) + { + $Indicator_OnScreenLimitReached = true; + if(!$Switch_BlockErrors) + { + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'] = sprintf($_Lang['Log_TooManyLines'], prettyNumber($LogBreak)); + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Type'] = '1'; + $Switch_BlockErrors = true; + } + $Switch_LastLineHadFormatError = false; + continue; + } + } + else + { + $Switch_LastLineHadFormatError = false; + continue; + } + + // Now process the Line (all filters passed) + $_This['Args_POST'] = $LineData[4]; + if($Switch_CanBeMerged AND ($_This['Args_POST'] !== $Data_LastPOST AND !$Switch_FullReload)) + { + $Switch_CanBeMerged = false; + } + + if(!$Switch_CanBeMerged) + { + $_This['FileExplode'] = explode('?', $_This['File']); + $_This['File'] = $_This['FileExplode'][0]; + $_This['Args_GET'] = isset($_This['FileExplode'][1]) ? $_This['FileExplode'][1] : null; + $Data_LastPOST = $LineData[4]; + if($_This['Args_POST'] == 'N') + { + $_This['Args_POST'] = null; + } + + if($Counters_BadFormatLines > 0 OR !$Switch_LastIPShowed OR !$Switch_LastBrowserShowed OR !$Switch_LastScreenInfoShowed) + { + // Show InfoRows + $_InfoRowsData = array(); + + if(!$Switch_LastIPShowed) + { + if($Counters_IPShowed == 0) + { + $ThisMessage = sprintf($_Lang['Log_IPisCurentlyX'], $Data_LastIP); + } + else + { + $ThisMessage = sprintf($_Lang['Log_IPChangedToX'], $Data_LastIP); + } + $_InfoRowsData[$Data_LastIPChangeTime][] = $ThisMessage; + $Counters_IPShowed += 1; + } + if(!$Switch_LastBrowserShowed) + { + if($Counters_BrowserShowed == 0) + { + $ThisMessage = sprintf($_Lang['Log_BrowserCurrent'], $Data_LastBrowser); + } + else + { + $ThisMessage = sprintf($_Lang['Log_BrowserChange'], $Data_LastBrowser); + } + $_InfoRowsData[$Data_LastBrowserChangeTime][] = $ThisMessage; + $Counters_IPShowed += 1; + } + if(!$Switch_LastScreenInfoShowed) + { + if($Counters_ScreenInfoShowed == 0) + { + $ThisMessage = sprintf($_Lang['Log_ScreenCurrent'], $Data_LastScreenInfo); + } + else + { + $ThisMessage = sprintf($_Lang['Log_ScreenChange'], $Data_LastScreenInfo); + } + $_InfoRowsData[$Data_LastScreenInfoChangeTime][] = $ThisMessage; + $Counters_ScreenInfoShowed += 1; + } + if($Counters_BadFormatLines > 0 AND $Switch_LastLineHadFormatError) + { + $_InfoRowsData[$Data_LastFormatErrorTime][] = sprintf($_Lang['Log_BadFormatLines'], prettyNumber($Counters_BadFormatLines)); + } + + $_InfoRowsCount = count($_InfoRowsData); + reset($_InfoRowsData); + if($_InfoRowsCount > 1 OR key($_InfoRowsData) != $_This['Time']) + { + ksort($_InfoRowsData); + + foreach($_InfoRowsData as $Timestamp => $InfoRowData) + { + if($Timestamp == $_This['Time']) + { + continue; + } + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Type'] = '2'; + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Time'][] = parseTimestamp($Timestamp); + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'] = $InfoRowData; + $Data_ThisParsedRowsIndex += 1; + $Data_LastParsedRowsIndex += 1; + unset($_InfoRowsData[$Timestamp]); + } + } + if(!empty($_InfoRowsData)) + { + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Type'] = 'M'; + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Infos'] = implode('
', $_InfoRowsData[$_This['Time']]); + } + else + { + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Type'] = '3'; + } + + $Data_LastIPChangeTime = false; + $Data_LastBrowserChangeTime = false; + $Data_LastScreenInfoChangeTime = false; + $Data_LastFormatErrorTime = false; + } + else + { + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Type'] = '3'; + } + + // GET & POST Parser + if(!empty($_This['Args_GET']) OR !empty($_This['Args_POST'])){ + if(!empty($_This['Args_GET'])){ + $_This['Args_GET'] = explode('&', $_This['Args_GET']); + foreach($_This['Args_GET'] as &$GetParser){ + $GetParser = explode('=', $GetParser); + $GetParser = "{$GetParser[0]}=".valueParser($GetParser[1]).""; + } + $_This['Args_GET'] = implode(' & ', $_This['Args_GET']); + + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'][] = "{$_Lang['Log_GETData']}: {$_This['Args_GET']}"; + } + if(!empty($_This['Args_POST'])){ + $_This['Args_POST'] = json_decode($_This['Args_POST'], true); + + if(!empty($_This['Args_POST']) AND (array)$_This['Args_POST'] === $_This['Args_POST']){ + $PostParsed = false; + $GetState = PostParser($_This['Args_POST'], true); + if($GetState['arr'] === true){ + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Actions'][] = "{$_Lang['ExpandArrays']}"; + } + if($GetState['cou'] > 1){ + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Actions'][] = "{$_Lang['ExpandAmps']}"; + } + + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'][] = "{$_Lang['Log_POSTData']}: ".implode(' & ', $PostParsed); + } else { + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'][] = "{$_Lang['Log_POSTData']}: {$_Lang['Log_POST_UnserializeError']}"; + } + } + + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Actions'][] = "{$_Lang['ResendRequest']}"; + if(!empty($Data_ParseRows[$Data_ThisParsedRowsIndex]['Actions'])){ + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Actions'] = implode('
', $Data_ParseRows[$Data_ThisParsedRowsIndex]['Actions']); + } + + if(!empty($Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'])){ + $Data_ParseRows[$Data_ThisParsedRowsIndex]['LeftAlignClass'] = 'lal'; + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'] = implode('
', $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data']); + } + } else { + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Data'] = $_Lang['Log_No_GET_POST']; + } + if(empty($Data_ParseRows[$Data_ThisParsedRowsIndex]['Actions'])){ + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Actions'] = ' '; + } + + // Finish for this Row + $Data_ParseRows[$Data_ThisParsedRowsIndex]['File'] = $_This['File']; + $Data_ParseRows[$Data_ThisParsedRowsIndex]['FileShow'] = str_replace('/', '/
', $_This['File']); + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Path'] = $_EnginePath; + $Data_LastParsedRowsIndex += 1; + + $Counters_BadFormatLines = 0; + $Switch_LastIPShowed = true; + $Switch_LastBrowserShowed = true; + $Switch_LastScreenInfoShowed = true; + $Switch_LastFormatErrorShowed = true; + } + else + { + $Data_ThisParsedRowsIndex -= 1; + } + $Data_ParseRows[$Data_ThisParsedRowsIndex]['Time'][] = parseTimestamp($_This['Time']); + + $Counters_LogsShowed += 1; + $Switch_CanBeMerged = false; + } + } + } + + foreach($Data_ParseRows as $RowData) + { + if($RowData['Type'] == '1') + { + $ThisTemplate = &$Row1LogTPL; + } + else if($RowData['Type'] == '2') + { + $ThisTemplate = &$Row2LogTPL; + } + else if($RowData['Type'] == '3') + { + $ThisTemplate = &$Row3LogTPL; + } + else if($RowData['Type'] == 'M') + { + $ThisTemplate = &$RowMLogTPL; + } + if(!empty($RowData['Time'])) + { + $RowData['Time'] = implode('
', $RowData['Time']); + } + if((array)$RowData['Data'] === $RowData['Data']) + { + $RowData['Data'] = implode('
', $RowData['Data']); + } + $Rows[] = parsetemplate($ThisTemplate, $RowData); + } + + if($Counters_LogsShowed < $Counters_LogsFilteredCount) + { + $CurrentPage = ($CurrentPage > 1 ? $CurrentPage : 1); + include_once($_EnginePath.'includes/functions/Pagination.php'); + + $Pagin = CreatePaginationArray($Counters_LogsFilteredCount, $LogBreak, $CurrentPage, 7); + $PaginationTPL = gettemplate('admin/browse_actionlogs_pagination'); + $PaginationViewOpt = array('CurrentPage_Classes' => 'orange fatB', 'Breaker_View' => '...'); + $CreatePagination = ParsePaginationArray($Pagin, $CurrentPage, $PaginationTPL, $PaginationViewOpt); + $_Lang['Pagination'] = $Parse['Pagination'] = ''.implode(' ', $CreatePagination).''; + } + + $_Lang['ShowingXofYRows'] = sprintf($_Lang['ShowingXofYRows'], $Counters_LogsShowed, $Counters_LogsFilteredCount, $Counters_LogsTotalCount); + + $Parse['Headers']= parsetemplate($HeadLogTPL, $_Lang); + if(!empty($Rows)) + { + $Parse['Content'] = implode('', $Rows); + } + else + { + $Parse['Content'] = parsetemplate($Row1LogTPL, array('Data' => $_Lang['Info_NoLogsFilter'])); + } + + $Parse['CurrentBrowsingDate'] = " » {$EDate[2]}.{$EDate[1]}.{$EDate[0]}"; + } + else + { + message($_Lang['Error_LogNoExists'], $Error, $ThisPage, 3); + } + } + else + { + message($_Lang['Error_BadDateFormat'], $Error, $ThisPage, 3); + } + } + + if(!$LogExists) + { + // If Log not selected + // ---- Show List ---- + $Parse['TableColspan'] = 2; + + $UserData = doquery("SELECT `username`, `register_time` FROM {{table}} WHERE `id` = {$UID} LIMIT 1;", 'users', true); + $Parse['UserName'] = $UserData['username']; + + // - Sorting - + $Sort = 'date'; + $Order = 'desc'; + $_Lang['DateSort'] = 'desc'; + $_Lang['SizeSort'] = 'desc'; + + if(!empty($_GET['sort'])) + { + if($_GET['sort'] === 'date' OR $_GET['sort'] === 'size') + { + $Sort = $_GET['sort']; + if($_GET['order'] == 'desc' OR $_GET['order'] == 'asc') + { + $Order = $_GET['order']; + } + } + } + + if($Sort === 'date') + { + if($Order === 'desc') + { + $_Lang['DateSort'] = 'asc'; + } + else + { + $_Lang['DateSort'] = 'desc'; + } + } + else if($Sort === 'size') + { + if($Order === 'desc') + { + $_Lang['SizeSort'] = 'asc'; + } + else + { + $_Lang['SizeSort'] = 'desc'; + } + } + // --------------- + // - Date Filter - + $FilterOn = false; + $FromDate = str_pad(isset($_POST['from_yea']) ? $_POST['from_yea'] : null, 4, '0', STR_PAD_LEFT) + .'_'.str_pad(isset($_POST['from_mon']) ? $_POST['from_mon'] : null, 2, '0', STR_PAD_LEFT) + .'_'.str_pad(isset($_POST['from_day']) ? $_POST['from_day'] : null, 2, '0', STR_PAD_LEFT); + $ToDate = str_pad(isset($_POST['to_yea']) ? $_POST['to_yea'] : null, 4, '0', STR_PAD_LEFT) + .'_'.str_pad(isset($_POST['to_mon']) ? $_POST['to_mon'] : null, 2, '0', STR_PAD_LEFT) + .'_'.str_pad(isset($_POST['to_day']) ? $_POST['to_day'] : null, 2, '0', STR_PAD_LEFT); + if(!preg_match('/^[0-9]{4}\_[0-9]{2}\_[0-9]{2}$/D', $FromDate) OR strstr($FromDate, '0000_') OR strstr($FromDate, '_00')) + { + $RegdayExp = explode('.', date('d.m.Y', $UserData['register_time'])); + $FromDate = $RegdayExp[2].'_'.$RegdayExp[1].'_'.$RegdayExp[0]; + } + else + { + $RegdayExp = array_reverse(explode('_', $FromDate)); + $FilterOn = true; + } + if(!preg_match('/^[0-9]{4}\_[0-9]{2}\_[0-9]{2}$/D', $ToDate) OR strstr($ToDate, '0000_') OR strstr($ToDate, '_00')) + { + $TodayExp = explode('.', date('d.m.Y')); + $ToDate = $TodayExp[2].'_'.$TodayExp[1].'_'.$TodayExp[0]; + } + else + { + $TodayExp = array_reverse(explode('_', $ToDate)); + $FilterOn = true; + } + if($FromDate < date('Y_m_d', $UserData['register_time'])) + { + $RegdayExp = explode('.', date('d.m.Y', $UserData['register_time'])); + $FromDate = $RegdayExp[2].'_'.$RegdayExp[1].'_'.$RegdayExp[0]; + } + if($ToDate < $FromDate) + { + $TodayExp = $RegdayExp; + $ToDate = $TodayExp[2].'_'.$TodayExp[1].'_'.$TodayExp[0]; + } + else if($ToDate > date('Y_m_d')) + { + $TodayExp = explode('.', date('d.m.Y')); + $ToDate = $TodayExp[2].'_'.$TodayExp[1].'_'.$TodayExp[0]; + } + + $DirPath= './../action_logs/'.$UIDMarker; + $ScanDir= scandir($DirPath); + foreach($ScanDir as $Filename) + { + if(preg_match("/^Log\_U\_{$UIDMarker}\_D\_([0-9]{4}\_[0-9]{2}\_[0-9]{2})\.php$/D", $Filename, $Matches)) + { + if($Matches[1] >= $FromDate AND $Matches[1] <= $ToDate) + { + $Logs[$Matches[1]] = 'N'; + $FileSizes[$Matches[1]] = (string) filesize($DirPath.'/'.$Filename); + } + } + } + + if(isset($_POST['filter']) && $_POST['filter'] != 'on') + { + $Parse['FilteringDisplay'] = ' display: none;'; + } + + $ScanDir = scandir('./../action_logs'); + foreach($ScanDir as $DirName) + { + if(strstr($DirName, 'logs')) + { + $GetDate = substr($DirName, 5); + if($GetDate >= $FromDate AND $GetDate <= $ToDate) + { + $File = "./../action_logs/{$DirName}/Log_U_{$UIDMarker}_D_{$GetDate}.php.gz"; + if(file_exists($File)) + { + $Logs[$GetDate.'_P'] = 'P'; + $FileSizes[$GetDate.'_P'] = (string) filesize($File); + } + } + } + } + + $LogsCount = count($Logs); + if($LogsCount == 0) + { + $_Lang['NoHeader'] = 'display: none;'; + if($FilterOn) + { + $Rows = ''.$_Lang['Info_NoLogsForThatPeriod'].''; + } + else + { + $Rows = ''.$_Lang['Info_NoLogs'].''; + } + } + else + { + if($Sort === 'date' AND $Order === 'desc') + { + krsort($Logs); + } + else if($Sort === 'date' AND $Order === 'asc') + { + ksort($Logs); + } + else if($Sort === 'size' AND $Order === 'desc') + { + arsort($FileSizes); + foreach($FileSizes as $Key => $Val) + { + $NewLogs[$Key] = $Logs[$Key]; + } + $Logs = $NewLogs; + } + else if($Sort === 'size' AND $Order === 'asc') + { + asort($FileSizes); + foreach($FileSizes as $Key => $Val) + { + $NewLogs[$Key] = $Logs[$Key]; + } + $Logs = $NewLogs; + } + + $Rows = ''; + foreach($Logs as $Key => $Name) + { + $Row = false; + $Row['UID'] = $UID; + if(strstr($Key, '_P')) + { + $Row['Date'] = str_replace('_P', '', $Key); + $Row['Packed'] = '&packed=true'; + $Packed = true; + } + else + { + $Row['Date'] = $Key; + $Packed = false; + } + $Row['Date_Formated'] = explode('_', $Key); + $Row['Date_Formated'] = "{$Row['Date_Formated'][2]}.{$Row['Date_Formated'][1]}.{$Row['Date_Formated'][0]}"; + $Row['Size'] = humanSize($FileSizes[$Key]); + if($Packed) + { + $Row['Size'] = "{$Row['Size']}"; + } + + $Rows .= parsetemplate($RowListTPL, $Row); + } + } + + $_Lang['FromDay'] = $RegdayExp[0]; + $_Lang['FromMon'] = $RegdayExp[1]; + $_Lang['FromYea'] = $RegdayExp[2]; + $_Lang['ToDay'] = $TodayExp[0]; + $_Lang['ToMon'] = $TodayExp[1]; + $_Lang['ToYea'] = $TodayExp[2]; + $_Lang['LogsCount'] = $LogsCount; + $Parse['Headers'] = parsetemplate($HeadListTPL, $_Lang); + $Parse['Content'] = $Rows; + } + + $Parse['SetFiltering'] = isset($_POST['filter']) ? $_POST['filter'] : null; + $Parse['ThisPage'] = $ThisPage; + $Page = parsetemplate($MainTPL, $Parse); + display($Page, $_Lang['PageTitle'], false, true); +} +else +{ + AdminMessage($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); +} + +?> diff --git a/admin/chatbrowser.php b/admin/chatbrowser.php index 2a7db809b..f4826b554 100644 --- a/admin/chatbrowser.php +++ b/admin/chatbrowser.php @@ -1,322 +1,322 @@ - $ThisValue) - { - if($ThisValue == 'on') - { - $ThisID = round($ThisID); - if($ThisID > 0) - { - $DeleteMsgs[] = $ThisID; - } - } - } - - if(!empty($DeleteMsgs)) - { - $Query_DeleteMsgs = "DELETE FROM {{table}} WHERE `ID` IN (".implode(',', $DeleteMsgs).") LIMIT ".count($DeleteMsgs).";"; - doquery($Query_DeleteMsgs, 'chat_messages'); - - $DeletedCount = mysql_affected_rows(); - if($DeletedCount > 0) - { - $_MsgBox = array('Color' => 'lime', 'Text' => sprintf($_Lang['CMDInfo_Delete_DeletedOK'], prettyNumber($DeletedCount))); - } - else - { - $_MsgBox = array('Color' => 'red', 'Text' => $_Lang['CMDInfo_Delete_NothingDeleted']); - } - } - else - { - $_MsgBox = array('Color' => 'red', 'Text' => $_Lang['CMDInfo_Delete_NothingToDelete']); - } - } - } - else - { - $_MsgBox = array('Color' => 'red', 'Text' => $_Lang['CMDInfo_BadCMD']); - } - } - - if(!empty($_GET['fID'])) - { - $FirstID = round($_GET['fID']); - if($FirstID > 0) - { - $_Pos_DefaultPos = false; - $_Pos_RemoveLeftSide = true; - $_Pos_Where = " AND `chat`.`ID` > {$FirstID} "; - $_Pos_LeftIDWhere = " > {$FirstID}"; - $_Pos_Order = 'ASC'; - $_Pos_ArraySort = true; - } - } - else if(!empty($_GET['lID'])) - { - $LastID = round($_GET['lID']); - if($LastID > 0) - { - $_Pos_DefaultPos = false; - $_Pos_AddLeftSide = true; - if(isset($_GET['this']) && $_GET['this'] == '1') - { - $_Highlight = $LastID; - $_Pos_Where = " AND `chat`.`ID` <= {$LastID} "; - $_Pos_LeftIDWhere = " > {$LastID}"; - } - else - { - $_Pos_Where = " AND `chat`.`ID` < {$LastID} "; - $_Pos_LeftIDWhere = " >= {$LastID}"; - } - $_Pos_Order = 'DESC'; - } - } - else if(!empty($_GET['page'])) - { - $ThisPage = round($_GET['page']); - if($ThisPage > 0) - { - $_Pos_AddLeftSide = true; - $_Pos_Order = 'DESC'; - $PosOffset = ($ThisPage - 1) * $_Limit_PerPage; - } - } - - if(!empty($_GET['highlight'])) - { - $Highlight = round($_GET['highlight']); - if($Highlight > 0) - { - $_Highlight = $Highlight; - } - } - - $PosOffset = 0; - if($_Pos_DefaultPos === false) - { - $PosOffset = isset($_GET['off']) ? round($_GET['off']) : 0; - if($PosOffset < 0) - { - $PosOffset += 1; - } - else if($PosOffset > 0) - { - $PosOffset -= 1; - } - if($PosOffset < 0) - { - $PosOffset *= -1; - } - $PosOffset *= $_Limit_PerPage; - } - if($PosOffset > 0) - { - $_Limit_Offset = $PosOffset; - } - else - { - $_Limit_Offset = 0; - } - - $Query_GetTotalCount = "SELECT COUNT(*) AS `Count` FROM {{table}} WHERE `RID` = {$_RoomID};"; - $Result_GetTotalCount = doquery($Query_GetTotalCount, 'chat_messages', true); - $_Pagination_TotalCount = $Result_GetTotalCount['Count']; - - if($_Pagination_TotalCount > 0) - { - if(!empty($_Pos_LeftIDWhere)) - { - $Query_GetLeftSideCount = ''; - $Query_GetLeftSideCount .= "SELECT COUNT(*) AS `Count` FROM {{table}} WHERE "; - $Query_GetLeftSideCount .= "`RID` = {$_RoomID} AND `ID` {$_Pos_LeftIDWhere};"; - $Result_GetLeftSideCount = doquery($Query_GetLeftSideCount, 'chat_messages', true); - $_Pagination_LeftSideCount = $Result_GetLeftSideCount['Count']; - } - else - { - $_Pagination_LeftSideCount = 0; - } - if(isset($_Pos_RemoveLeftSide)) - { - $_Pagination_LeftSideCount -= ($_Limit_Offset + $_Limit_PerPage); - } - if(isset($_Pos_AddLeftSide)) - { - $_Pagination_LeftSideCount += ($_Limit_Offset); - } - if($_Pagination_LeftSideCount <= 0) - { - $_Pos_DefaultPos = true; - $_Pos_Where = ''; - $_Pos_Order = 'DESC'; - $_Limit_Offset = 0; - $_Pagination_LeftSideCount = 0; - } - else if(($_Pagination_TotalCount - $_Pagination_LeftSideCount) <= 0) - { - $_Pos_DefaultPos = true; - $_Pos_Where = ''; - $_Pos_Order = 'DESC'; - $_Limit_Offset = $_Pagination_TotalCount - ($_Pagination_TotalCount % $_Limit_PerPage); - $_Pagination_LeftSideCount = $_Limit_Offset; - } - - $Query_GetMessages = ''; - $Query_GetMessages .= "SELECT `chat`.*, `user`.`username`, `user`.`authlevel` FROM {{table}} AS `chat` "; - $Query_GetMessages .= "LEFT JOIN `{{prefix}}users` AS `user` ON `chat`.`UID` = `user`.`id` "; - $Query_GetMessages .= "WHERE "; - $Query_GetMessages .= "`chat`.`RID` = {$_RoomID} "; - $Query_GetMessages .= $_Pos_Where; - $Query_GetMessages .= "ORDER BY `chat`.`ID` {$_Pos_Order} "; - $Query_GetMessages .= "LIMIT {$_Limit_Offset}, {$_Limit_PerPage};"; - $Result_GetMessages = doquery($Query_GetMessages, 'chat_messages'); - } - - $Result_GetMessages_Count = 0; - if(isset($Result_GetMessages)) - { - $Result_GetMessages_Count = mysql_num_rows($Result_GetMessages); - } - if(isset($Result_GetMessages) && $Result_GetMessages_Count > 0) - { - include($_EnginePath.'includes/functions/BBcodeFunction.php'); - include_once($_EnginePath.'includes/functions/Pagination.php'); - - while($FetchData = mysql_fetch_assoc($Result_GetMessages)) - { - $MessageRows[$FetchData['ID']] = $FetchData; - } - - if($Result_GetMessages_Count <= 10) - { - $_Lang['Insert_HideOnFewMessages'] = 'class="hide"'; - } - - if($_Pos_ArraySort === true) - { - krsort($MessageRows); - } - - $TempIDGetter = array_keys($MessageRows); - $LastSeenID = array_pop($TempIDGetter); - $FirstSeenID = array_shift($TempIDGetter); - - $CurrentPage = floor($_Pagination_LeftSideCount / $_Limit_PerPage) + 1; - $TheoreticalLeftSideCount = (($CurrentPage - 1) * $_Limit_PerPage); - if($_Pagination_LeftSideCount > $TheoreticalLeftSideCount) - { - $_Pagination_TotalCount -= ($_Pagination_LeftSideCount - $TheoreticalLeftSideCount); - } - $Pagin = CreatePaginationArray($_Pagination_TotalCount, $_Limit_PerPage, $CurrentPage, 7); - $PaginationTPL = '{$ShowValue}'; - $PaginationViewOpt = array('CurrentPage_Classes' => 'fatB orange', 'Breaker_View' => '...', 'OffsetValues' => true); - $CreatePagination = ParsePaginationArray($Pagin, $CurrentPage, $PaginationTPL, $PaginationViewOpt); - foreach($CreatePagination as &$Value) - { - if(strstr($Value, '{InsertID}') !== false) - { - if(strstr($Value, 'off=0') !== false) - { - $Value = str_replace('{InsertID}', 'lID='.($FirstSeenID + 1), $Value); - } - else if(strstr($Value, 'off=-') !== false) - { - $Value = str_replace('{InsertID}', 'fID='.$FirstSeenID, $Value); - } - else - { - $Value = str_replace('{InsertID}', 'lID='.$LastSeenID, $Value); - } - } - } - if($_Pagination_LeftSideCount > $TheoreticalLeftSideCount) - { - array_unshift($CreatePagination, str_replace(array('{InsertID}&off={$Value}', '{$Classes}', '{$ShowValue}'), array('page='.$CurrentPage.($_Highlight > 0 ? '&highlight='.$_Highlight : ''), 'red mr_20', $_Lang['Pagination_Reload']), $PaginationTPL)); - } - $_Lang['Insert_Pagination'] = implode(' ', $CreatePagination); - - foreach($MessageRows as $MessageData) - { - if($MessageData['ID'] == $_Highlight) - { - $MessageData['Hightligh'] = 'class="msgHighlight"'; - } - $MessageData['UserAuthLevel'] = GetAuthLabel($MessageData); - $MessageData['ParseDate'] = prettyDate('d m Y, H:i:s', $MessageData['TimeStamp_Add'], 1); - - $MessageData['ParseMessage'] = bbcodeChat($MessageData['Text']); - - $_Lang['Insert_ChatRows'][] = parsetemplate($TPL_MsgRow, $MessageData); - } - $_Lang['Insert_ChatRows'] = implode('', $_Lang['Insert_ChatRows']); - } - else - { - $_Lang['Insert_ChatRows'] = parsetemplate(gettemplate('_singleRow'), array('Colspan' => 5, 'Classes' => 'pad5 orange', 'Text' => $_Lang['Notice_NoMessages'])); - $_Lang['Insert_Pagination'] = ' '; - $_Lang['Insert_HideOnNoMessages'] = 'class="hide"'; - } - - $_Lang['Insert_RoomID'] = $_RoomID; - if(isset($CurrentPage) && $CurrentPage > 0) - { - $_Lang['Insert_ThisPage'] = $CurrentPage; - } - else - { - $_Lang['Insert_ThisPage'] = 0; - } - - if(!empty($_MsgBox)) - { - $_Lang['Insert_MsgBox'] = parsetemplate(gettemplate('_singleRow'), array('Classes' => 'pad2 '.$_MsgBox['Color'], 'Colspan' => 5, 'Text' => $_MsgBox['Text'])); - } - - display(parsetemplate($TPL_Body, $_Lang), $_Lang['Page_Title'], false, true); - -?> \ No newline at end of file + $ThisValue) + { + if($ThisValue == 'on') + { + $ThisID = round($ThisID); + if($ThisID > 0) + { + $DeleteMsgs[] = $ThisID; + } + } + } + + if(!empty($DeleteMsgs)) + { + $Query_DeleteMsgs = "DELETE FROM {{table}} WHERE `ID` IN (".implode(',', $DeleteMsgs).") LIMIT ".count($DeleteMsgs).";"; + doquery($Query_DeleteMsgs, 'chat_messages'); + + $DeletedCount = mysql_affected_rows(); + if($DeletedCount > 0) + { + $_MsgBox = array('Color' => 'lime', 'Text' => sprintf($_Lang['CMDInfo_Delete_DeletedOK'], prettyNumber($DeletedCount))); + } + else + { + $_MsgBox = array('Color' => 'red', 'Text' => $_Lang['CMDInfo_Delete_NothingDeleted']); + } + } + else + { + $_MsgBox = array('Color' => 'red', 'Text' => $_Lang['CMDInfo_Delete_NothingToDelete']); + } + } + } + else + { + $_MsgBox = array('Color' => 'red', 'Text' => $_Lang['CMDInfo_BadCMD']); + } +} + +if(!empty($_GET['fID'])) +{ + $FirstID = round($_GET['fID']); + if($FirstID > 0) + { + $_Pos_DefaultPos = false; + $_Pos_RemoveLeftSide = true; + $_Pos_Where = " AND `chat`.`ID` > {$FirstID} "; + $_Pos_LeftIDWhere = " > {$FirstID}"; + $_Pos_Order = 'ASC'; + $_Pos_ArraySort = true; + } +} +else if(!empty($_GET['lID'])) +{ + $LastID = round($_GET['lID']); + if($LastID > 0) + { + $_Pos_DefaultPos = false; + $_Pos_AddLeftSide = true; + if(isset($_GET['this']) && $_GET['this'] == '1') + { + $_Highlight = $LastID; + $_Pos_Where = " AND `chat`.`ID` <= {$LastID} "; + $_Pos_LeftIDWhere = " > {$LastID}"; + } + else + { + $_Pos_Where = " AND `chat`.`ID` < {$LastID} "; + $_Pos_LeftIDWhere = " >= {$LastID}"; + } + $_Pos_Order = 'DESC'; + } +} +else if(!empty($_GET['page'])) +{ + $ThisPage = round($_GET['page']); + if($ThisPage > 0) + { + $_Pos_AddLeftSide = true; + $_Pos_Order = 'DESC'; + $PosOffset = ($ThisPage - 1) * $_Limit_PerPage; + } +} + +if(!empty($_GET['highlight'])) +{ + $Highlight = round($_GET['highlight']); + if($Highlight > 0) + { + $_Highlight = $Highlight; + } +} + +$PosOffset = 0; +if($_Pos_DefaultPos === false) +{ + $PosOffset = isset($_GET['off']) ? round($_GET['off']) : 0; + if($PosOffset < 0) + { + $PosOffset += 1; + } + else if($PosOffset > 0) + { + $PosOffset -= 1; + } + if($PosOffset < 0) + { + $PosOffset *= -1; + } + $PosOffset *= $_Limit_PerPage; +} +if($PosOffset > 0) +{ + $_Limit_Offset = $PosOffset; +} +else +{ + $_Limit_Offset = 0; +} + +$Query_GetTotalCount = "SELECT COUNT(*) AS `Count` FROM {{table}} WHERE `RID` = {$_RoomID};"; +$Result_GetTotalCount = doquery($Query_GetTotalCount, 'chat_messages', true); +$_Pagination_TotalCount = $Result_GetTotalCount['Count']; + +if($_Pagination_TotalCount > 0) +{ + if(!empty($_Pos_LeftIDWhere)) + { + $Query_GetLeftSideCount = ''; + $Query_GetLeftSideCount .= "SELECT COUNT(*) AS `Count` FROM {{table}} WHERE "; + $Query_GetLeftSideCount .= "`RID` = {$_RoomID} AND `ID` {$_Pos_LeftIDWhere};"; + $Result_GetLeftSideCount = doquery($Query_GetLeftSideCount, 'chat_messages', true); + $_Pagination_LeftSideCount = $Result_GetLeftSideCount['Count']; + } + else + { + $_Pagination_LeftSideCount = 0; + } + if(isset($_Pos_RemoveLeftSide)) + { + $_Pagination_LeftSideCount -= ($_Limit_Offset + $_Limit_PerPage); + } + if(isset($_Pos_AddLeftSide)) + { + $_Pagination_LeftSideCount += ($_Limit_Offset); + } + if($_Pagination_LeftSideCount <= 0) + { + $_Pos_DefaultPos = true; + $_Pos_Where = ''; + $_Pos_Order = 'DESC'; + $_Limit_Offset = 0; + $_Pagination_LeftSideCount = 0; + } + else if(($_Pagination_TotalCount - $_Pagination_LeftSideCount) <= 0) + { + $_Pos_DefaultPos = true; + $_Pos_Where = ''; + $_Pos_Order = 'DESC'; + $_Limit_Offset = $_Pagination_TotalCount - ($_Pagination_TotalCount % $_Limit_PerPage); + $_Pagination_LeftSideCount = $_Limit_Offset; + } + + $Query_GetMessages = ''; + $Query_GetMessages .= "SELECT `chat`.*, `user`.`username`, `user`.`authlevel` FROM {{table}} AS `chat` "; + $Query_GetMessages .= "LEFT JOIN `{{prefix}}users` AS `user` ON `chat`.`UID` = `user`.`id` "; + $Query_GetMessages .= "WHERE "; + $Query_GetMessages .= "`chat`.`RID` = {$_RoomID} "; + $Query_GetMessages .= $_Pos_Where; + $Query_GetMessages .= "ORDER BY `chat`.`ID` {$_Pos_Order} "; + $Query_GetMessages .= "LIMIT {$_Limit_Offset}, {$_Limit_PerPage};"; + $Result_GetMessages = doquery($Query_GetMessages, 'chat_messages'); +} + +$Result_GetMessages_Count = 0; +if(isset($Result_GetMessages)) +{ + $Result_GetMessages_Count = mysql_num_rows($Result_GetMessages); +} +if(isset($Result_GetMessages) && $Result_GetMessages_Count > 0) +{ + include($_EnginePath.'includes/functions/BBcodeFunction.php'); + include_once($_EnginePath.'includes/functions/Pagination.php'); + + while($FetchData = mysql_fetch_assoc($Result_GetMessages)) + { + $MessageRows[$FetchData['ID']] = $FetchData; + } + + if($Result_GetMessages_Count <= 10) + { + $_Lang['Insert_HideOnFewMessages'] = 'class="hide"'; + } + + if($_Pos_ArraySort === true) + { + krsort($MessageRows); + } + + $TempIDGetter = array_keys($MessageRows); + $LastSeenID = array_pop($TempIDGetter); + $FirstSeenID = array_shift($TempIDGetter); + + $CurrentPage = floor($_Pagination_LeftSideCount / $_Limit_PerPage) + 1; + $TheoreticalLeftSideCount = (($CurrentPage - 1) * $_Limit_PerPage); + if($_Pagination_LeftSideCount > $TheoreticalLeftSideCount) + { + $_Pagination_TotalCount -= ($_Pagination_LeftSideCount - $TheoreticalLeftSideCount); + } + $Pagin = CreatePaginationArray($_Pagination_TotalCount, $_Limit_PerPage, $CurrentPage, 7); + $PaginationTPL = '{$ShowValue}'; + $PaginationViewOpt = array('CurrentPage_Classes' => 'fatB orange', 'Breaker_View' => '...', 'OffsetValues' => true); + $CreatePagination = ParsePaginationArray($Pagin, $CurrentPage, $PaginationTPL, $PaginationViewOpt); + foreach($CreatePagination as &$Value) + { + if(strstr($Value, '{InsertID}') !== false) + { + if(strstr($Value, 'off=0') !== false) + { + $Value = str_replace('{InsertID}', 'lID='.($FirstSeenID + 1), $Value); + } + else if(strstr($Value, 'off=-') !== false) + { + $Value = str_replace('{InsertID}', 'fID='.$FirstSeenID, $Value); + } + else + { + $Value = str_replace('{InsertID}', 'lID='.$LastSeenID, $Value); + } + } + } + if($_Pagination_LeftSideCount > $TheoreticalLeftSideCount) + { + array_unshift($CreatePagination, str_replace(array('{InsertID}&off={$Value}', '{$Classes}', '{$ShowValue}'), array('page='.$CurrentPage.($_Highlight > 0 ? '&highlight='.$_Highlight : ''), 'red mr_20', $_Lang['Pagination_Reload']), $PaginationTPL)); + } + $_Lang['Insert_Pagination'] = implode(' ', $CreatePagination); + + foreach($MessageRows as $MessageData) + { + if($MessageData['ID'] == $_Highlight) + { + $MessageData['Hightligh'] = 'class="msgHighlight"'; + } + $MessageData['UserAuthLevel'] = GetAuthLabel($MessageData); + $MessageData['ParseDate'] = prettyDate('d m Y, H:i:s', $MessageData['TimeStamp_Add'], 1); + + $MessageData['ParseMessage'] = bbcodeChat($MessageData['Text']); + + $_Lang['Insert_ChatRows'][] = parsetemplate($TPL_MsgRow, $MessageData); + } + $_Lang['Insert_ChatRows'] = implode('', $_Lang['Insert_ChatRows']); +} +else +{ + $_Lang['Insert_ChatRows'] = parsetemplate(gettemplate('_singleRow'), array('Colspan' => 5, 'Classes' => 'pad5 orange', 'Text' => $_Lang['Notice_NoMessages'])); + $_Lang['Insert_Pagination'] = ' '; + $_Lang['Insert_HideOnNoMessages'] = 'class="hide"'; +} + +$_Lang['Insert_RoomID'] = $_RoomID; +if(isset($CurrentPage) && $CurrentPage > 0) +{ + $_Lang['Insert_ThisPage'] = $CurrentPage; +} +else +{ + $_Lang['Insert_ThisPage'] = 0; +} + +if(!empty($_MsgBox)) +{ + $_Lang['Insert_MsgBox'] = parsetemplate(gettemplate('_singleRow'), array('Classes' => 'pad2 '.$_MsgBox['Color'], 'Colspan' => 5, 'Text' => $_MsgBox['Text'])); +} + +display(parsetemplate($TPL_Body, $_Lang), $_Lang['Page_Title'], false, true); + +?> diff --git a/admin/cron_GarbageCollector.php b/admin/cron_GarbageCollector.php index 9c1763c80..9ac8057ff 100644 --- a/admin/cron_GarbageCollector.php +++ b/admin/cron_GarbageCollector.php @@ -1,286 +1,287 @@ -showSimpleCountSwitch(); - $Bench->echoTableSwitch(); - - $StartTime = microtime(true); - includeLang('admin/cron_GarbageCollector'); - - if(!((isset($_User['id']) && $_User['id'] > 0 AND CheckAuth('programmer')) || ((!isset($_User['id']) || $_User['id'] <= 0) && md5($_GET['pass']) == AUTOTOOL_GARBAGECOLLECTOR_PASSWORDHASH))) - { - AdminMessage($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); - } - - $ShowOutput = (isset($_User['id']) && $_User['id'] > 0 ? true : false); - - // Settings - $Now = time(); - - $DelLimit = 500; - $DelTime['spymsg'] = TIME_DAY; - $DelTime['sysmsg_deleted'] = TIME_DAY * 7; - $DelTime['sysmsg_nondeleted'] = TIME_DAY * 14; - $DelTime['usrmsg_deleted'] = TIME_DAY * 14; - $DelTime['usrmsg_nondeleted'] = TIME_DAY * 30; - $DelTime['simreport'] = 3600; - $DelTime['allyinvite_all'] = TIME_DAY * 14; - $DelTime['allyinvite_changed'] = TIME_DAY * 7; - $DelTime['loginprotection'] = LOGINPROTECTION_LOCKTIME; - $DelTime['planet_abandontime'] = PLANET_ABANDONTIME; - - $Opt_Interval = TIME_HOUR; - // End of Settings - - foreach($DelTime as &$Value) - { - $Value = $Now - $Value; - } - - $Query_SelectMessages = "SELECT `id`, `Thread_ID` FROM {{table}} WHERE "; - $Query_SelectMessages .= "(`type` = 0 AND `time` < {$DelTime['spymsg']}) OR "; - $Query_SelectMessages .= "(`type` IN (4, 5, 15, 50, 70) AND ((`deleted` = 1 AND `time` < {$DelTime['sysmsg_deleted']}) OR `time` < {$DelTime['sysmsg_nondeleted']})) OR "; - $Query_SelectMessages .= "(`type` IN (1, 2, 3, 80) AND ((`deleted` = 1 AND `time` < {$DelTime['usrmsg_deleted']}) OR `time` < {$DelTime['usrmsg_nondeleted']})) "; - $Query_SelectMessages .= "LIMIT {$DelLimit};"; - - $Query_SelectThreaded = "SELECT MAX(`id`) AS `id` FROM {{table}} WHERE `Thread_ID` IN ({_InsertIDs_}) AND `deleted` = false GROUP BY `Thread_ID`, `id_owner`;"; - - $Query_SelectPlanets = "SELECT `id` FROM {{table}} WHERE `abandon_time` > 0 AND `abandon_time` < {$DelTime['planet_abandontime']} AND `planet_type` = 1;"; - $Query_SelectMoons = "SELECT `id_moon` FROM {{table}} WHERE `id_planet` IN ({_InsertIDs_}) LIMIT {_InsertCount_};"; - - $Query_DeleteMessages = "DELETE FROM {{table}} WHERE `id` IN ({_InsertIDs_}) LIMIT {_InsertCount_};"; - $Query_DeleteSimReports = "DELETE FROM {{table}} WHERE `time` < {$DelTime['simreport']} LIMIT {$DelLimit};"; - $Query_DeleteAllyInvites = "DELETE FROM {{table}} WHERE `Date` < {$DelTime['allyinvite_all']} OR (`State` != 0 AND `Date` < {$DelTime['allyinvite_changed']});"; - $Query_DeleteLoginProtectionRows = "DELETE FROM {{table}} WHERE `Date` < {$DelTime['loginprotection']};"; - $Query_DeletePlanets = "DELETE FROM {{table}} WHERE `id` IN ({_InsertIDs_}) LIMIT {_InsertCount_};"; - $Query_DeletePlanetsOnGalaxy = "DELETE FROM {{table}} WHERE `id_planet` IN ({_InsertIDs_}) LIMIT {_InsertCount_};"; - - $Query_UpdateThreads = "UPDATE {{table}} SET `Thread_IsLast` = 1 WHERE `id` IN ({_InsertIDs_});"; - - // Preparations begin - $CounterNames[] = 'Preparing'; - $Bench->simpleCountStart(); - - $CounterNames[] = '> Messages'; - $Bench->simpleCountStart(); - $SelectMessages = doquery($Query_SelectMessages, 'messages'); - $Update_Threads = array(); - if(mysql_num_rows($SelectMessages) > 0) - { - while($FetchData = mysql_fetch_assoc($SelectMessages)) - { - $Delete_Messages[] = $FetchData['id']; - if($FetchData['Thread_ID'] > 0) - { - if(!in_array($FetchData['Thread_ID'], $Update_Threads)) - { - $Update_Threads[] = $FetchData['Thread_ID']; - } - } - } - } - $Bench->simpleCountStop(); - $CounterNames[] = '> Planets'; - $Bench->simpleCountStart(); - $SelectPlanets = doquery($Query_SelectPlanets, 'planets'); - if(mysql_num_rows($SelectPlanets) > 0) - { - while($FetchData = mysql_fetch_assoc($SelectPlanets)) - { - if($FetchData['id'] > 0) - { - $Delete_Planets[] = $FetchData['id']; - $Delete_PlanetsFromGalaxy[] = $FetchData['id']; - } - } - $Query_SelectMoons = str_replace(array('{_InsertIDs_}', '{_InsertCount_}'), array(implode(', ', $Delete_Planets), count($Delete_Planets)), $Query_SelectMoons); - $SelectMoons = doquery($Query_SelectMoons, 'galaxy'); - if(mysql_num_rows($SelectMoons) > 0) - { - while($FetchData = mysql_fetch_assoc($SelectMoons)) - { - if($FetchData['id_moon'] > 0) - { - $Delete_Planets[] = $FetchData['id_moon']; - } - } - } - } - $Bench->simpleCountStop(); - - $Bench->simpleCountStop(); - // Preparations end - - // Deletion begins - $CounterNames[] = 'Deleting'; - $Bench->simpleCountStart(); - - $CounterNames[] = '> Messages'; - $Bench->simpleCountStart(); - if(!empty($Delete_Messages)) - { - $Query_DeleteMessages = str_replace(array('{_InsertIDs_}', '{_InsertCount_}'), array(implode(', ', $Delete_Messages), count($Delete_Messages)), $Query_DeleteMessages); - doquery($Query_DeleteMessages, 'messages'); - $Stats['del']['msg'] = mysql_affected_rows(); - } - else - { - $Stats['del']['msg'] = 0; - } - $Bench->simpleCountStop(); - - $CounterNames[] = '> SimReports'; - $Bench->simpleCountStart(); - doquery($Query_DeleteSimReports, 'sim_battle_reports'); - $Stats['del']['simrep'] = mysql_affected_rows(); - $Bench->simpleCountStop(); - - $CounterNames[] = '> Ally Invites'; - $Bench->simpleCountStart(); - doquery($Query_DeleteAllyInvites, 'ally_invites'); - $Stats['del']['allyinvite'] = mysql_affected_rows(); - $Bench->simpleCountStop(); - - $CounterNames[] = '> LoginProtection Rows'; - $Bench->simpleCountStart(); - doquery($Query_DeleteLoginProtectionRows, 'login_protection'); - $Stats['del']['loginprotection'] = mysql_affected_rows(); - $Bench->simpleCountStop(); - - $CounterNames[] = '> Planets'; - $Bench->simpleCountStart(); - if(!empty($Delete_Planets)) - { - $Query_DeletePlanets = str_replace(array('{_InsertIDs_}', '{_InsertCount_}'), array(implode(', ', $Delete_Planets), count($Delete_Planets)), $Query_DeletePlanets); - $Query_DeletePlanetsOnGalaxy = str_replace(array('{_InsertIDs_}', '{_InsertCount_}'), array(implode(', ', $Delete_PlanetsFromGalaxy), count($Delete_PlanetsFromGalaxy)), $Query_DeletePlanetsOnGalaxy); - doquery($Query_DeletePlanets, 'planets'); - $Stats['del']['planets'] = mysql_affected_rows(); - doquery($Query_DeletePlanetsOnGalaxy, 'galaxy'); - } - else - { - $Stats['del']['planets'] = 0; - } - $Bench->simpleCountStop(); - - $Bench->simpleCountStop(); - // Deletion ends - - // Updating begins - $CounterNames[] = 'Updating'; - $Bench->simpleCountStart(); - - if(!empty($Update_Threads)) - { - $CounterNames[] = '> Messages'; - $Bench->simpleCountStart(); - $Query_SelectThreaded = str_replace('{_InsertIDs_}', implode(',', $Update_Threads), $Query_SelectThreaded); - $SelectMessages = doquery($Query_SelectThreaded, 'messages'); - if(mysql_num_rows($SelectMessages) > 0) - { - $Update_Threads = array(); - while($FetchData = mysql_fetch_assoc($SelectMessages)) - { - $Update_Threads[] = $FetchData['id']; - } - $Query_UpdateThreads = str_replace('{_InsertIDs_}', implode(',', $Update_Threads), $Query_UpdateThreads); - doquery($Query_UpdateThreads, 'messages'); - } - $Bench->simpleCountStop(); - } - - if(!empty($Delete_Planets)) - { - $CounterNames[] = '> Planets (Fleets Retreat)'; - $Bench->simpleCountStart(); - $Delete_Planets_Implode = implode(',', $Delete_Planets); - include($_EnginePath.'includes/functions/FleetControl_Retreat.php'); - FleetControl_Retreat("`fleet_start_id` IN ({$Delete_Planets_Implode}) OR `fleet_end_id` IN ({$Delete_Planets_Implode})", false); - $Bench->simpleCountStop(); - } - - $Bench->simpleCountStop(); - // Updating ends - - // Optimization begins - if($_GameConfig['cron_GC_LastOptimize'] < ($Now - $Opt_Interval)) - { - $Tables2Optimize = array('messages', 'sim_battle_reports', 'ally_invites', 'login_protection'); - - $Query_OptimizeTables = "OPTIMIZE TABLE "; - foreach($Tables2Optimize as &$Table) - { - $Table = "`{{prefix}}{$Table}`"; - } - $Query_OptimizeTables .= implode(', ', $Tables2Optimize); - - $CounterNames[] = 'Optimizing'; - $Bench->simpleCountStart(); - - $CounterNames[] = '> Doin "OPTIMIZE TABLE"'; - $Bench->simpleCountStart(); - doquery($Query_OptimizeTables, ''); - $Bench->simpleCountStop(); - - $CounterNames[] = '> Updating GameConfig'; - $Bench->simpleCountStart(); - doquery("INSERT INTO {{table}} VALUES ('cron_GC_LastOptimize', {$Now}) ON DUPLICATE KEY UPDATE `config_value` = VALUES(`config_value`);", 'config'); - $_GameConfig['cron_GC_LastOptimize'] = $Now; - $_MemCache->GameConfig = $_GameConfig; - $Bench->simpleCountStop(); - - $Bench->simpleCountStop(); - } - - $EndTime = microtime(true); - $TotalTime = sprintf('%0.6f', $EndTime - $StartTime); - $CountTime = $Bench->ReturnSimpleCountArray(); - - if($ShowOutput) - { - $Counted = '
'; - foreach($CountTime as $Key => $Data) - { - if(strstr($CounterNames[$Key], '>') == true) - { - $LastWasAssoc = true; - } - else - { - if(isset($LastWasAssoc) && $LastWasAssoc === true) - { - $Counted .= ''; - } - $LastWasAssoc = false; - } - $Counted .= ''; - } - $Counted .= '
'.$CounterNames[$Key].' '.sprintf('%0.20f', $Data['result']).'
'.$Data['endram'].'
'; - - foreach($Stats['del'] as &$Value) - { - $Value = prettyNumber($Value); - } - - $ResultsArray = array($TotalTime, $Stats['del']['msg'], $Stats['del']['simrep'], $Stats['del']['allyinvite'], $Stats['del']['loginprotection'], $Stats['del']['planets'], $Counted); - AdminMessage(vsprintf($_Lang['Result_Parse'], $ResultsArray), $_Lang['Title']); - } - else - { - AdminMessage('OK', $_Lang['Title']); - } - -?> \ No newline at end of file +showSimpleCountSwitch(); +$Bench->echoTableSwitch(); + +$StartTime = microtime(true); +includeLang('admin/cron_GarbageCollector'); + +if(!((isset($_User['id']) && $_User['id'] > 0 AND CheckAuth('programmer')) || ((!isset($_User['id']) || $_User['id'] <= 0) && md5($_GET['pass']) == AUTOTOOL_GARBAGECOLLECTOR_PASSWORDHASH))) +{ + AdminMessage($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); +} + +$ShowOutput = (isset($_User['id']) && $_User['id'] > 0 ? true : false); + +// Settings +$Now = time(); + +$DelLimit = 500; +$DelTime['spymsg'] = TIME_DAY; +$DelTime['sysmsg_deleted'] = TIME_DAY * 7; +$DelTime['sysmsg_nondeleted'] = TIME_DAY * 14; +$DelTime['usrmsg_deleted'] = TIME_DAY * 14; +$DelTime['usrmsg_nondeleted'] = TIME_DAY * 30; +$DelTime['simreport'] = 3600; +$DelTime['allyinvite_all'] = TIME_DAY * 14; +$DelTime['allyinvite_changed'] = TIME_DAY * 7; +$DelTime['loginprotection'] = LOGINPROTECTION_LOCKTIME; +$DelTime['planet_abandontime'] = PLANET_ABANDONTIME; + +$Opt_Interval = TIME_HOUR; +// End of Settings + +foreach($DelTime as &$Value) +{ + $Value = $Now - $Value; +} + +$Query_SelectMessages = "SELECT `id`, `Thread_ID` FROM {{table}} WHERE "; +$Query_SelectMessages .= "(`type` = 0 AND `time` < {$DelTime['spymsg']}) OR "; +$Query_SelectMessages .= "(`type` IN (4, 5, 15, 50, 70) AND ((`deleted` = 1 AND `time` < {$DelTime['sysmsg_deleted']}) OR `time` < {$DelTime['sysmsg_nondeleted']})) OR "; +$Query_SelectMessages .= "(`type` IN (1, 2, 3, 80) AND ((`deleted` = 1 AND `time` < {$DelTime['usrmsg_deleted']}) OR `time` < {$DelTime['usrmsg_nondeleted']})) "; +$Query_SelectMessages .= "LIMIT {$DelLimit};"; + +$Query_SelectThreaded = "SELECT MAX(`id`) AS `id` FROM {{table}} WHERE `Thread_ID` IN ({_InsertIDs_}) AND `deleted` = false GROUP BY `Thread_ID`, `id_owner`;"; + +$Query_SelectPlanets = "SELECT `id` FROM {{table}} WHERE `abandon_time` > 0 AND `abandon_time` < {$DelTime['planet_abandontime']} AND `planet_type` = 1;"; +$Query_SelectMoons = "SELECT `id_moon` FROM {{table}} WHERE `id_planet` IN ({_InsertIDs_}) LIMIT {_InsertCount_};"; + +$Query_DeleteMessages = "DELETE FROM {{table}} WHERE `id` IN ({_InsertIDs_}) LIMIT {_InsertCount_};"; +$Query_DeleteSimReports = "DELETE FROM {{table}} WHERE `time` < {$DelTime['simreport']} LIMIT {$DelLimit};"; +$Query_DeleteAllyInvites = "DELETE FROM {{table}} WHERE `Date` < {$DelTime['allyinvite_all']} OR (`State` != 0 AND `Date` < {$DelTime['allyinvite_changed']});"; +$Query_DeleteLoginProtectionRows = "DELETE FROM {{table}} WHERE `Date` < {$DelTime['loginprotection']};"; +$Query_DeletePlanets = "DELETE FROM {{table}} WHERE `id` IN ({_InsertIDs_}) LIMIT {_InsertCount_};"; +$Query_DeletePlanetsOnGalaxy = "DELETE FROM {{table}} WHERE `id_planet` IN ({_InsertIDs_}) LIMIT {_InsertCount_};"; + +$Query_UpdateThreads = "UPDATE {{table}} SET `Thread_IsLast` = 1 WHERE `id` IN ({_InsertIDs_});"; + +// Preparations begin +$CounterNames[] = 'Preparing'; +$Bench->simpleCountStart(); + +$CounterNames[] = '> Messages'; +$Bench->simpleCountStart(); +$SelectMessages = doquery($Query_SelectMessages, 'messages'); +$Update_Threads = array(); +if(mysql_num_rows($SelectMessages) > 0) +{ + while($FetchData = mysql_fetch_assoc($SelectMessages)) + { + $Delete_Messages[] = $FetchData['id']; + if($FetchData['Thread_ID'] > 0) + { + if(!in_array($FetchData['Thread_ID'], $Update_Threads)) + { + $Update_Threads[] = $FetchData['Thread_ID']; + } + } + } +} +$Bench->simpleCountStop(); +$CounterNames[] = '> Planets'; +$Bench->simpleCountStart(); +$SelectPlanets = doquery($Query_SelectPlanets, 'planets'); +if(mysql_num_rows($SelectPlanets) > 0) +{ + while($FetchData = mysql_fetch_assoc($SelectPlanets)) + { + if($FetchData['id'] > 0) + { + $Delete_Planets[] = $FetchData['id']; + $Delete_PlanetsFromGalaxy[] = $FetchData['id']; + } + } + $Query_SelectMoons = str_replace(array('{_InsertIDs_}', '{_InsertCount_}'), array(implode(', ', $Delete_Planets), count($Delete_Planets)), $Query_SelectMoons); + $SelectMoons = doquery($Query_SelectMoons, 'galaxy'); + if(mysql_num_rows($SelectMoons) > 0) + { + while($FetchData = mysql_fetch_assoc($SelectMoons)) + { + if($FetchData['id_moon'] > 0) + { + $Delete_Planets[] = $FetchData['id_moon']; + } + } + } +} +$Bench->simpleCountStop(); + +$Bench->simpleCountStop(); +// Preparations end + +// Deletion begins +$CounterNames[] = 'Deleting'; +$Bench->simpleCountStart(); + +$CounterNames[] = '> Messages'; +$Bench->simpleCountStart(); +if(!empty($Delete_Messages)) +{ + $Query_DeleteMessages = str_replace(array('{_InsertIDs_}', '{_InsertCount_}'), array(implode(', ', $Delete_Messages), count($Delete_Messages)), $Query_DeleteMessages); + doquery($Query_DeleteMessages, 'messages'); + $Stats['del']['msg'] = mysql_affected_rows(); +} +else +{ + $Stats['del']['msg'] = 0; +} +$Bench->simpleCountStop(); + +$CounterNames[] = '> SimReports'; +$Bench->simpleCountStart(); +doquery($Query_DeleteSimReports, 'sim_battle_reports'); +$Stats['del']['simrep'] = mysql_affected_rows(); +$Bench->simpleCountStop(); + +$CounterNames[] = '> Ally Invites'; +$Bench->simpleCountStart(); +doquery($Query_DeleteAllyInvites, 'ally_invites'); +$Stats['del']['allyinvite'] = mysql_affected_rows(); +$Bench->simpleCountStop(); + +$CounterNames[] = '> LoginProtection Rows'; +$Bench->simpleCountStart(); +doquery($Query_DeleteLoginProtectionRows, 'login_protection'); +$Stats['del']['loginprotection'] = mysql_affected_rows(); +$Bench->simpleCountStop(); + +$CounterNames[] = '> Planets'; +$Bench->simpleCountStart(); +if(!empty($Delete_Planets)) +{ + $Query_DeletePlanets = str_replace(array('{_InsertIDs_}', '{_InsertCount_}'), array(implode(', ', $Delete_Planets), count($Delete_Planets)), $Query_DeletePlanets); + $Query_DeletePlanetsOnGalaxy = str_replace(array('{_InsertIDs_}', '{_InsertCount_}'), array(implode(', ', $Delete_PlanetsFromGalaxy), count($Delete_PlanetsFromGalaxy)), $Query_DeletePlanetsOnGalaxy); + doquery($Query_DeletePlanets, 'planets'); + $Stats['del']['planets'] = mysql_affected_rows(); + doquery($Query_DeletePlanetsOnGalaxy, 'galaxy'); +} +else +{ + $Stats['del']['planets'] = 0; +} +$Bench->simpleCountStop(); + +$Bench->simpleCountStop(); +// Deletion ends + +// Updating begins +$CounterNames[] = 'Updating'; +$Bench->simpleCountStart(); + +if(!empty($Update_Threads)) +{ + $CounterNames[] = '> Messages'; + $Bench->simpleCountStart(); + $Query_SelectThreaded = str_replace('{_InsertIDs_}', implode(',', $Update_Threads), $Query_SelectThreaded); + $SelectMessages = doquery($Query_SelectThreaded, 'messages'); + if(mysql_num_rows($SelectMessages) > 0) + { + $Update_Threads = array(); + while($FetchData = mysql_fetch_assoc($SelectMessages)) + { + $Update_Threads[] = $FetchData['id']; + } + $Query_UpdateThreads = str_replace('{_InsertIDs_}', implode(',', $Update_Threads), $Query_UpdateThreads); + doquery($Query_UpdateThreads, 'messages'); + } + $Bench->simpleCountStop(); +} + +if(!empty($Delete_Planets)) +{ + $CounterNames[] = '> Planets (Fleets Retreat)'; + $Bench->simpleCountStart(); + $Delete_Planets_Implode = implode(',', $Delete_Planets); + include($_EnginePath.'includes/functions/FleetControl_Retreat.php'); + FleetControl_Retreat("`fleet_start_id` IN ({$Delete_Planets_Implode}) OR `fleet_end_id` IN ({$Delete_Planets_Implode})", false); + $Bench->simpleCountStop(); +} + +$Bench->simpleCountStop(); +// Updating ends + +// Optimization begins +if($_GameConfig['cron_GC_LastOptimize'] < ($Now - $Opt_Interval)) +{ + $Tables2Optimize = array('messages', 'sim_battle_reports', 'ally_invites', 'login_protection'); + + $Query_OptimizeTables = "OPTIMIZE TABLE "; + foreach($Tables2Optimize as &$Table) + { + $Table = "`{{prefix}}{$Table}`"; + } + $Query_OptimizeTables .= implode(', ', $Tables2Optimize); + + $CounterNames[] = 'Optimizing'; + $Bench->simpleCountStart(); + + $CounterNames[] = '> Doin "OPTIMIZE TABLE"'; + $Bench->simpleCountStart(); + doquery($Query_OptimizeTables, ''); + $Bench->simpleCountStop(); + + $CounterNames[] = '> Updating GameConfig'; + $Bench->simpleCountStart(); + doquery("INSERT INTO {{table}} VALUES ('cron_GC_LastOptimize', {$Now}) ON DUPLICATE KEY UPDATE `config_value` = VALUES(`config_value`);", 'config'); + $_GameConfig['cron_GC_LastOptimize'] = $Now; + $_MemCache->GameConfig = $_GameConfig; + $Bench->simpleCountStop(); + + $Bench->simpleCountStop(); +} + +$EndTime = microtime(true); +$TotalTime = sprintf('%0.6f', $EndTime - $StartTime); +$CountTime = $Bench->ReturnSimpleCountArray(); + +if($ShowOutput) +{ + $Counted = '
'; + foreach($CountTime as $Key => $Data) + { + if(strstr($CounterNames[$Key], '>') == true) + { + $LastWasAssoc = true; + } + else + { + if(isset($LastWasAssoc) && $LastWasAssoc === true) + { + $Counted .= ''; + } + $LastWasAssoc = false; + } + $Counted .= ''; + } + $Counted .= '
'.$CounterNames[$Key].' '.sprintf('%0.20f', $Data['result']).'
'.$Data['endram'].'
'; + + foreach($Stats['del'] as &$Value) + { + $Value = prettyNumber($Value); + } + + $ResultsArray = array($TotalTime, $Stats['del']['msg'], $Stats['del']['simrep'], $Stats['del']['allyinvite'], $Stats['del']['loginprotection'], $Stats['del']['planets'], $Counted); + AdminMessage(vsprintf($_Lang['Result_Parse'], $ResultsArray), $_Lang['Title']); +} +else +{ + AdminMessage('OK', $_Lang['Title']); +} + +?> diff --git a/admin/declare_list.php b/admin/declare_list.php index 0b0249791..7f4ed60f1 100644 --- a/admin/declare_list.php +++ b/admin/declare_list.php @@ -1,227 +1,227 @@ - 0) - { - $GetDeclaration = doquery("SELECT `users`, `status` FROM {{table}} WHERE `id` = {$ID} LIMIT 1;", 'declarations', true); - if($GetDeclaration) - { - if($GetDeclaration['status'] != -2) - { - $Status = $GetDeclaration['status']; - if(!(($Status == 1 AND $_GET['action'] == 'accept') OR ($Status == -1 AND $_GET['action'] == 'refuse'))) - { - $Message = false; - - $UserIDs = str_replace('|', '', $GetDeclaration['users']); - switch($_GET['action']) - { - case 'delete': - $Message['msg_id'] = '080'; - doquery("UPDATE {{table}} SET `status` = -2 WHERE `id` = {$ID};", 'declarations'); - doquery("UPDATE {{table}} SET `multi_validated` = 0 WHERE `id` IN ({$UserIDs});", 'users'); - $MSG = $_Lang['declaration_deleted']; - break; - case 'accept': - $Message['msg_id'] = '077'; - doquery("UPDATE {{table}} SET `status` = 1 WHERE `id` = {$ID};", 'declarations'); - doquery("UPDATE {{table}} SET `multi_validated` = 1 WHERE `id` IN ({$UserIDs});", 'users'); - $MSG = $_Lang['declaration_accepted']; - break; - case 'refuse': - $Message['msg_id'] = '078'; - doquery("UPDATE {{table}} SET `status` = -1 WHERE `id` = {$ID};", 'declarations'); - doquery("UPDATE {{table}} SET `multi_validated` = -1 WHERE `id` IN ({$UserIDs});", 'users'); - $MSG = $_Lang['declaration_refused']; - break; - } - $ExplodeUsers = explode(',', $UserIDs); - foreach($ExplodeUsers as $UserID) - { - if($UserID > 0) - { - $SendArray[] = $UserID; - } - } - - $Message['args'] = array(); - $Message = json_encode($Message); - Cache_Message($SendArray, 0, time(), 70, '007', '020', $Message); - } - else - { - $MSG = $_Lang['declaration_noaffect']; - } - } - else - { - $MSG = $_Lang['declaration_deletedalready']; - } - } - else - { - $MSG = $_Lang['declaration_noexist']; - } - } - else - { - $MSG = $_Lang['No_id_given']; - } - } - - $AddWhere = ''; - if(!isset($_GET['cmd']) || $_GET['cmd'] != 'showall') - { - $AddWhere = ' WHERE `status` != -2 '; - $_Lang['AddShowAll'] = 'cmd=showall'; - } - else - { - $_Lang['Declarations_Header_ShowAll'] = $_Lang['Declarations_Header_HideDel']; - } - $query = doquery("SELECT * FROM {{table}} {$AddWhere} ORDER BY `time` DESC", 'declarations'); - - $parse = $_Lang; - $parse['adm_ul_table'] = ''; - if(!empty($MSG)) - { - $parse['system_msg'] = ''.$MSG.'
'; - } - $i = 0; - - if(mysql_num_rows($query) > 0) - { - while($u = mysql_fetch_assoc($query)) - { - $UserTemp = explode(',', $u['users']); - foreach($UserTemp as $Key) - { - $UserID = str_replace('|', '', $Key); - if($UserID > 0) - { - if(empty($UsersID) OR !in_array($UserID, $UsersID)) - { - $UsersID[] = $UserID; - } - $u['userlist'][] = $UserID; - } - } - if(!empty($u['all_present_users'])) - { - $UserTemp = explode(',', $u['all_present_users']); - if(!empty($UserTemp)) - { - foreach($UserTemp as $Key) - { - $UserID = str_replace('|', '', $Key); - if($UserID > 0) - { - if(empty($UsersID) OR !in_array($UserID, $UsersID)) - { - $UsersID[] = $UserID; - } - $u['allusers'][] = $UserID; - } - } - } - } - - $Data[] = $u; - } - - $SelectUsers = doquery("SELECT `id`, `username` FROM {{table}} WHERE `id` IN (".implode(',', $UsersID).")", 'users'); - - while($Users = mysql_fetch_assoc($SelectUsers)) - { - $UserNames[$Users['id']] = $Users['username']; - } - foreach($UsersID as $UserID) - { - if(empty($UserNames[$UserID])) - { - $UserNames[$UserID] = $_Lang['Declarations_EmptyUser']; - } - } - - foreach($Data as $Vars) - { - $Bloc = array(); - - $Bloc['UserID'] = $Vars['userlist'][0]; - $Bloc['Username'] = $UserNames[$Vars['userlist'][0]]; - foreach($Vars['userlist'] as $Index => $Values) - { - if($Index == 0) - { - continue; - } - $Bloc['CreateOtherPlayers'][] = "{$UserNames[$Values]} (#{$Values})"; - } - if(!empty($Bloc['CreateOtherPlayers'])) - { - $Bloc['CreateOtherPlayers'] = implode(', ', $Bloc['CreateOtherPlayers']); - } - else - { - $Bloc['CreateOtherPlayers'] = $_Lang['Declarations_NoUser']; - } - if(!empty($Vars['allusers'])) - { - foreach($Vars['allusers'] as $UserID) - { - if(!in_array($UserID, $Vars['userlist'])) - { - $Bloc['NotPresentUsers'][] = "{$UserNames[$UserID]} (#{$UserID})"; - } - } - } - if(!empty($Bloc['NotPresentUsers'])) - { - $Bloc['CreateOtherPlayers'] .= '
[ '.implode(', ', $Bloc['NotPresentUsers']).' ]'; - } - - $Bloc['UsersIDList'] = implode('|', $Vars['userlist']); - $Bloc['DeclarationDate'] = prettyDate('d m Y\<\b\r/>H:i:s', $Vars['time'], 1); - $Bloc['DeclarationReason'] = $_Lang['DeclarationReasons_'][$Vars['reason']]; - $Bloc['DeclarationStatus'] = $_Lang['DeclarationStatuses_'][(string)($Vars['status'] + 0)]; - $Bloc['declaration_id'] = $Vars['id']; - - $parse['adm_ul_table'] .= parsetemplate($RowsTPL, $Bloc); - $i += 1; - } - - $parse['adm_ul_count'] = $i; - } - else - { - $parse['adm_ul_table'] = ''.$_Lang['Declarations_NothingFound'].''; - } - - $page = parsetemplate( $PageTPL, $parse ); - display($page, $_Lang['declaration_title'], false, true); - } - else - { - message($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); - } - -?> \ No newline at end of file + 0) + { + $GetDeclaration = doquery("SELECT `users`, `status` FROM {{table}} WHERE `id` = {$ID} LIMIT 1;", 'declarations', true); + if($GetDeclaration) + { + if($GetDeclaration['status'] != -2) + { + $Status = $GetDeclaration['status']; + if(!(($Status == 1 AND $_GET['action'] == 'accept') OR ($Status == -1 AND $_GET['action'] == 'refuse'))) + { + $Message = false; + + $UserIDs = str_replace('|', '', $GetDeclaration['users']); + switch($_GET['action']) + { + case 'delete': + $Message['msg_id'] = '080'; + doquery("UPDATE {{table}} SET `status` = -2 WHERE `id` = {$ID};", 'declarations'); + doquery("UPDATE {{table}} SET `multi_validated` = 0 WHERE `id` IN ({$UserIDs});", 'users'); + $MSG = $_Lang['declaration_deleted']; + break; + case 'accept': + $Message['msg_id'] = '077'; + doquery("UPDATE {{table}} SET `status` = 1 WHERE `id` = {$ID};", 'declarations'); + doquery("UPDATE {{table}} SET `multi_validated` = 1 WHERE `id` IN ({$UserIDs});", 'users'); + $MSG = $_Lang['declaration_accepted']; + break; + case 'refuse': + $Message['msg_id'] = '078'; + doquery("UPDATE {{table}} SET `status` = -1 WHERE `id` = {$ID};", 'declarations'); + doquery("UPDATE {{table}} SET `multi_validated` = -1 WHERE `id` IN ({$UserIDs});", 'users'); + $MSG = $_Lang['declaration_refused']; + break; + } + $ExplodeUsers = explode(',', $UserIDs); + foreach($ExplodeUsers as $UserID) + { + if($UserID > 0) + { + $SendArray[] = $UserID; + } + } + + $Message['args'] = array(); + $Message = json_encode($Message); + Cache_Message($SendArray, 0, time(), 70, '007', '020', $Message); + } + else + { + $MSG = $_Lang['declaration_noaffect']; + } + } + else + { + $MSG = $_Lang['declaration_deletedalready']; + } + } + else + { + $MSG = $_Lang['declaration_noexist']; + } + } + else + { + $MSG = $_Lang['No_id_given']; + } + } + + $AddWhere = ''; + if(!isset($_GET['cmd']) || $_GET['cmd'] != 'showall') + { + $AddWhere = ' WHERE `status` != -2 '; + $_Lang['AddShowAll'] = 'cmd=showall'; + } + else + { + $_Lang['Declarations_Header_ShowAll'] = $_Lang['Declarations_Header_HideDel']; + } + $query = doquery("SELECT * FROM {{table}} {$AddWhere} ORDER BY `time` DESC", 'declarations'); + + $parse = $_Lang; + $parse['adm_ul_table'] = ''; + if(!empty($MSG)) + { + $parse['system_msg'] = ''.$MSG.'
'; + } + $i = 0; + + if(mysql_num_rows($query) > 0) + { + while($u = mysql_fetch_assoc($query)) + { + $UserTemp = explode(',', $u['users']); + foreach($UserTemp as $Key) + { + $UserID = str_replace('|', '', $Key); + if($UserID > 0) + { + if(empty($UsersID) OR !in_array($UserID, $UsersID)) + { + $UsersID[] = $UserID; + } + $u['userlist'][] = $UserID; + } + } + if(!empty($u['all_present_users'])) + { + $UserTemp = explode(',', $u['all_present_users']); + if(!empty($UserTemp)) + { + foreach($UserTemp as $Key) + { + $UserID = str_replace('|', '', $Key); + if($UserID > 0) + { + if(empty($UsersID) OR !in_array($UserID, $UsersID)) + { + $UsersID[] = $UserID; + } + $u['allusers'][] = $UserID; + } + } + } + } + + $Data[] = $u; + } + + $SelectUsers = doquery("SELECT `id`, `username` FROM {{table}} WHERE `id` IN (".implode(',', $UsersID).")", 'users'); + + while($Users = mysql_fetch_assoc($SelectUsers)) + { + $UserNames[$Users['id']] = $Users['username']; + } + foreach($UsersID as $UserID) + { + if(empty($UserNames[$UserID])) + { + $UserNames[$UserID] = $_Lang['Declarations_EmptyUser']; + } + } + + foreach($Data as $Vars) + { + $Bloc = array(); + + $Bloc['UserID'] = $Vars['userlist'][0]; + $Bloc['Username'] = $UserNames[$Vars['userlist'][0]]; + foreach($Vars['userlist'] as $Index => $Values) + { + if($Index == 0) + { + continue; + } + $Bloc['CreateOtherPlayers'][] = "{$UserNames[$Values]} (#{$Values})"; + } + if(!empty($Bloc['CreateOtherPlayers'])) + { + $Bloc['CreateOtherPlayers'] = implode(', ', $Bloc['CreateOtherPlayers']); + } + else + { + $Bloc['CreateOtherPlayers'] = $_Lang['Declarations_NoUser']; + } + if(!empty($Vars['allusers'])) + { + foreach($Vars['allusers'] as $UserID) + { + if(!in_array($UserID, $Vars['userlist'])) + { + $Bloc['NotPresentUsers'][] = "{$UserNames[$UserID]} (#{$UserID})"; + } + } + } + if(!empty($Bloc['NotPresentUsers'])) + { + $Bloc['CreateOtherPlayers'] .= '
[ '.implode(', ', $Bloc['NotPresentUsers']).' ]'; + } + + $Bloc['UsersIDList'] = implode('|', $Vars['userlist']); + $Bloc['DeclarationDate'] = prettyDate('d m Y\<\b\r/>H:i:s', $Vars['time'], 1); + $Bloc['DeclarationReason'] = $_Lang['DeclarationReasons_'][$Vars['reason']]; + $Bloc['DeclarationStatus'] = $_Lang['DeclarationStatuses_'][(string)($Vars['status'] + 0)]; + $Bloc['declaration_id'] = $Vars['id']; + + $parse['adm_ul_table'] .= parsetemplate($RowsTPL, $Bloc); + $i += 1; + } + + $parse['adm_ul_count'] = $i; + } + else + { + $parse['adm_ul_table'] = ''.$_Lang['Declarations_NothingFound'].''; + } + + $page = parsetemplate( $PageTPL, $parse ); + display($page, $_Lang['declaration_title'], false, true); +} +else +{ + message($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); +} + +?> diff --git a/admin/errors.php b/admin/errors.php index 0e0317142..871bbcd5e 100644 --- a/admin/errors.php +++ b/admin/errors.php @@ -1,61 +1,61 @@ - 0) - { - doquery("DELETE FROM {{table}} WHERE `error_id` = {$DeleteID} LIMIT 1;", 'errors'); - } - else if($DoDeleteAll) - { - doquery("TRUNCATE TABLE {{table}}", 'errors'); - } - - $Query_GetErrors = doquery("SELECT * FROM {{table}} LIMIT 100;", 'errors'); - $i = 0; - - $parse['errors_list'] = ''; - while($ErrorData = mysql_fetch_assoc($Query_GetErrors)) - { - ++$i; - $parse['errors_list'] .= parsetemplate($TPL_Row, array - ( - 'ID' => $ErrorData['error_id'], - 'Date' => date('d.m.Y H:i:s', $ErrorData['error_time']), - 'Text' => nl2br($ErrorData['error_text']) - )); - } - - $Query_GetCount = doquery("SELECT COUNT(`error_id`) AS `count` FROM {{table}};", 'errors', true); - $i = $Query_GetCount['count']; - if($i >= 100) - { - $parse['errors_list'] .= "{$_Lang['ErrorsList_TooManyErrors']}"; - break; - } - - $parse['errors_list'] .= "{$_Lang['ErrorsList_Count']}: {$i}"; - - display(parsetemplate(gettemplate('admin/errors_body'), $parse), $_Lang['ErrorsList_Title'], false, true); -?> + 0) +{ + doquery("DELETE FROM {{table}} WHERE `error_id` = {$DeleteID} LIMIT 1;", 'errors'); +} +else if($DoDeleteAll) +{ + doquery("TRUNCATE TABLE {{table}}", 'errors'); +} + +$Query_GetErrors = doquery("SELECT * FROM {{table}} LIMIT 100;", 'errors'); +$i = 0; + +$parse['errors_list'] = ''; +while($ErrorData = mysql_fetch_assoc($Query_GetErrors)) +{ + ++$i; + $parse['errors_list'] .= parsetemplate($TPL_Row, array + ( + 'ID' => $ErrorData['error_id'], + 'Date' => date('d.m.Y H:i:s', $ErrorData['error_time']), + 'Text' => nl2br($ErrorData['error_text']) + )); +} + +$Query_GetCount = doquery("SELECT COUNT(`error_id`) AS `count` FROM {{table}};", 'errors', true); +$i = $Query_GetCount['count']; +if($i >= 100) +{ + $parse['errors_list'] .= "{$_Lang['ErrorsList_TooManyErrors']}"; + break; +} + +$parse['errors_list'] .= "{$_Lang['ErrorsList_Count']}: {$i}"; + +display(parsetemplate(gettemplate('admin/errors_body'), $parse), $_Lang['ErrorsList_Title'], false, true); +?> diff --git a/admin/images/index.php b/admin/images/index.php index 2c5d40047..bc99142d1 100644 --- a/admin/images/index.php +++ b/admin/images/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/admin/index.php b/admin/index.php index 2c5d40047..bc99142d1 100644 --- a/admin/index.php +++ b/admin/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/admin/iplog.php b/admin/iplog.php index 563b49710..6df8fe5a8 100644 --- a/admin/iplog.php +++ b/admin/iplog.php @@ -1,659 +1,659 @@ - 0) - { - $Query_GetIP = ''; - $Query_GetIP .= "SELECT `ID`, `isProxy` FROM {{table}} "; - $Query_GetIP .= "WHERE `ID` = {$Proxy_IPID} AND `Type` = 'ip' LIMIT 1;"; - $Result_GetIP = doquery($Query_GetIP, 'used_ip_and_ua', true); - if($Result_GetIP['ID'] == $Proxy_IPID) - { - $Query_UpdateIP = ''; - $Query_UpdateIP .= "UPDATE {{table}} SET "; - $Query_UpdateIP .= "`isProxy` = ".($Result_GetIP['isProxy'] == 1 ? 'false' : 'true')." "; - $Query_UpdateIP .= "WHERE `ID` = {$Proxy_IPID} LIMIT 1;"; - doquery($Query_UpdateIP, 'used_ip_and_ua'); - - $_Lang['InfoBox_Msg'] = "{$_Lang['Info_ProxySet_OK_'.($Result_GetIP['isProxy'] == 0 ? 'Set' : 'Unset')]}"; - } - else - { - $_Lang['InfoBox_Msg'] = "{$_Lang['Info_ProxySet_NoIP']}"; - } - } - else - { - $_Lang['InfoBox_Msg'] = "{$_Lang['Info_ProxySet_BadID']}"; - } - } - - if(!empty($_POST['search'])) - { - if(!empty($_POST['uid'])) - { - $_GET['uid'] = $_POST['uid']; - } - if(!empty($_POST['ipid'])) - { - $_GET['ipid'] = $_POST['ipid']; - } - - if(empty($_GET['uid']) && empty($_GET['ipid'])) - { - // Do Search and then Redirect to result page (if found) - $Search = explode('|', $_POST['search']); - $Search = array_map(function($val){return trim($val);}, $Search); - - if(isset($_POST['strict']) && $_POST['strict'] == '1') - { - $UseStrict = true; - } - else - { - $UseStrict = false; - } - - if(in_array($_POST['type'], array('uname', 'uid', 'ipstr', 'ipid'))) - { - // If searchType is supported: - // Create search data for each searchType - if($_POST['type'] == 'uname') - { - $Query[0]['table'] = 'users'; - $Query[0]['select'] = 'id'; - $Query[0]['select_field'] = 'id'; - $Query[0]['result'] = 'uid'; - $Query[0]['fields'][0] = 'username'; - $Query[0]['search'][0] = 'REGEXP'; - if(!$UseStrict) - { - $CheckFunction = function($Value) - { - if(preg_match(REGEXP_USERNAME, $Value)) - { - return true; - } - return false; - }; - } - else - { - $CheckFunction = function($Value) - { - if(preg_match(REGEXP_USERNAME_ABSOLUTE, $Value)) - { - return true; - } - return false; - }; - } - } - else if($_POST['type'] == 'uid') - { - $Query[0]['table'] = 'users'; - $Query[0]['select'] = 'id'; - $Query[0]['select_field'] = 'id'; - $Query[0]['result'] = 'uid'; - $Query[0]['fields'][0] = 'id'; - $Query[0]['search'][0] = 'IN'; - $CheckFunction = function(&$Value) - { - $Value = intval($Value); - if($Value > 0) - { - return true; - } - return false; - }; - } - else if($_POST['type'] == 'ipstr') - { - $Query[0]['table'] = 'used_ip_and_ua'; - $Query[0]['select'] = 'ID'; - $Query[0]['select_field'] = 'ID'; - $Query[0]['result'] = 'ipid'; - if($UseStrict) - { - $Query[0]['fields'][0] = 'ValueHash'; - $Query[0]['search'][0] = 'IN'; - $Query[0]['valadd'][0] = '\'{$VAL}\''; - } - else - { - $Query[0]['fields'][0] = 'Value'; - $Query[0]['search'][0] = 'REGEXP'; - } - $CheckFunction = function($Value) - { - if(preg_match(REGEXP_IP, $Value)) - { - return true; - } - return false; - }; - } - else if($_POST['type'] == 'ipid') - { - $Query[0]['table'] = 'user_enterlog'; - $Query[0]['select'] = 'DISTINCT IP_ID'; - $Query[0]['select_field'] = 'IP_ID'; - $Query[0]['result'] = 'ipid'; - $Query[0]['fields'][0] = 'IP_ID'; - $Query[0]['search'][0] = 'IN'; - $CheckFunction = function(&$Value) - { - $Value = round($Value); - if($Value > 0) - { - return true; - } - return false; - }; - } - - // Pass all values through CheckFunction - foreach($Search as $Value) - { - if($CheckFunction($Value)) - { - $QryData[] = $Value; - } - } - - if(!empty($QryData)) - { - // Do Search - foreach($Query as $QueryID => $QueryData) - { - $LastQueryID = $QueryID; - - $ComposeQuery = "SELECT {$QueryData['select']} FROM {{table}} WHERE {Fields};"; - $Fields = array(); - foreach($QueryData['fields'] as $FieldID => $Field) - { - if(empty($QueryData['values'][$FieldID])) - { - $Temp = $QryData; - if(!empty($QueryData['valadd'][$FieldID])) - { - $Temp = array_map(function($val){global $QueryData; return str_replace('{$VAL}', $val, $QueryData['valadd'][$FieldID]);}, $Temp); - } - if($QueryData['search'][$FieldID] == 'REGEXP') - { - $Values = '\''.implode('|', $Temp).'\''; - } - else if($QueryData['search'][$FieldID] == 'IN') - { - $Values = '('.implode(', ', $Temp).')'; - } - } - else - { - $Values = $QueryData['values'][$FieldID]; - } - $Fields[] = "`{$Field}` {$QueryData['search'][$FieldID]} {$Values}"; - } - if(!empty($QueryData['joins'])) - { - foreach($QueryData['joins'] as $JoinID => $JoinType) - { - $Fields[$JoinID] .= " {$JoinType} "; - } - } - $ComposeQuery = str_replace('{Fields}', implode('', $Fields), $ComposeQuery); - $Result = doquery($ComposeQuery, $QueryData['table']); - if(mysql_num_rows($Result) > 0) - { - while($Data = mysql_fetch_assoc($Result)) - { - $Query[$QueryID]['results'][] = $Data; - } - } - else - { - break; - } - } - - if(!empty($Query[$LastQueryID]['results'])) - { - $Data = array_map(function($val){global $Query, $LastQueryID; return $val[$Query[$LastQueryID]['select_field']];}, $Query[$LastQueryID]['results']); - if(!empty($FoundData[$Query[$LastQueryID]['result']])) - { - $FoundData[$Query[$LastQueryID]['result']] = array_merge($FoundData[$Query[$LastQueryID]['result']], $Data); - } - else - { - $FoundData[$Query[$LastQueryID]['result']] = $Data; - } - } - else - { - $Error['txt'] = $_Lang['Error_Search_NoRowsFound']; - } - } - } - else - { - // Bad Type - throw Error - $Error['txt'] = $_Lang['Error_Search_BadType']; - } - - if(!empty($FoundData['uid'])) - { - $_GET['uid'] = implode('|', $FoundData['uid']); - } - else if(!empty($FoundData['ipid'])) - { - $_GET['ipid'] = implode('|', $FoundData['ipid']); - } - } - - $ThisUrl['search'] = $_POST['search']; - $ThisUrl['type'] = $_POST['type']; - } - - if(!empty($_GET['search'])) - { - $ThisUrl['search'] = $_GET['search']; - } - if(!empty($_GET['type'])) - { - $ThisUrl['type'] = $_GET['type']; - } - if(!empty($_POST['sort'])) - { - if(in_array($_POST['sort'], array('uid', 'ipid', 'logcount', 'logdate'))) - { - $SortType = $_POST['sort']; - if($_POST['mode'] == 'asc' OR $_POST['mode'] == 'desc') - { - $SortMode = $_POST['mode']; - } - else - { - $SortMode = 'asc'; - } - } - if(!empty($SortType)) - { - if($SortType == 'uid') - { - $Sortings['user']['uid'] = " ORDER BY `id` {$SortMode}"; - $Sortings['ip']['uid'] = " ORDER BY `User_ID` {$SortMode}"; - $_Lang['SortUIDMode'] = '&mode='.($SortMode == 'asc' ? 'desc' : 'asc'); - $_Lang['SortUIDModeClass'] = $SortMode; - } - else if($SortType == 'ipid') - { - $Sortings['user']['ipid'] = true; - $Sortings['ip']['ipid'] = " ORDER BY `IP_ID` {$SortMode}"; - $_Lang['SortIPIDMode'] = '&mode='.($SortMode == 'asc' ? 'desc' : 'asc'); - $_Lang['SortIPIDModeClass'] = $SortMode; - } - else if($SortType == 'logcount') - { - $Sortings['user']['logcount'] = true; - $Sortings['ip']['logcount'] = true; - $_Lang['SortLogCountMode'] = '&mode='.($SortMode == 'asc' ? 'desc' : 'asc'); - $_Lang['SortLogCountModeClass'] = $SortMode; - } - else if($SortType == 'logdate') - { - $Sortings['user']['logdate'] = true; - $Sortings['ip']['logdate'] = true; - $_Lang['SortLogDateMode'] = '&mode='.($SortMode == 'asc' ? 'desc' : 'asc'); - $_Lang['SortLogDateModeClass'] = $SortMode; - } - $_Lang['Insert_SortType'] = $SortType; - $_Lang['Insert_SortMode'] = $SortMode; - } - } - - if(!empty($Error)) - { - $_Lang['InfoBox_Msg'] = "{$Error['txt']}"; - } - - // If data given, create Where statement - if(!empty($_GET['uid'])) - { - $_Lang['Insert_Found_UID'] = $_GET['uid']; - $_GET['uid'] = explode('|', $_GET['uid']); - foreach($_GET['uid'] as $Value) - { - $Value = round($Value); - if($Value > 0) - { - $GetData['value'][] = $Value; - } - } - if(!empty($GetData['value'])) - { - $GetData['type'] = 'user'; - $GetData['query'] = "SELECT `id`, `username`, `ip_at_reg`, `user_lastip` FROM {{table}} WHERE `id` IN (".implode(', ', $GetData['value']).")".(isset($Sortings['user']['uid']) ? $Sortings['user']['uid'] : null).";"; - $GetData['table'] = 'users'; - $GetData['tpl'] = 'user'; - } - } - if(!empty($_GET['ipid'])) - { - $_Lang['Insert_Found_IPID'] = $_GET['ipid']; - $_GET['ipid'] = explode('|', $_GET['ipid']); - foreach($_GET['ipid'] as $Value) - { - $Value = round($Value); - if($Value > 0) - { - $GetData['value'][] = $Value; - } - } - if(!empty($GetData['value'])) - { - $GetData['type'] = 'ip'; - $GetData['query'] = "SELECT DISTINCT `logs`.`User_ID`, `logs`.`IP_ID`, `logs`.`Count`, `logs`.`LastTime`, `values`.`Value`, `values`.`isProxy`, `users`.`username` FROM {{table}} AS `logs` LEFT JOIN `{{prefix}}used_ip_and_ua` AS `values` ON `values`.`ID` = `logs`.`IP_ID` LEFT JOIN `{{prefix}}users` AS `users` ON `users`.`id` = `logs`.`User_ID` WHERE `IP_ID` IN (".implode(', ', $GetData['value']).")".(isset($Sortings['ip']['uid']) ? $Sortings['ip']['uid'] : null).(isset($Sortings['ip']['ipid']) ? $Sortings['ip']['ipid'] : null).";"; - $GetData['table'] = 'user_enterlog'; - $GetData['tpl'] = 'ip'; - } - } - - $_Lang['Insert_Search_Value'] = (isset($ThisUrl['search']) ? $ThisUrl['search'] : ''); - if(isset($ThisUrl['type'])) - { - $_Lang['Insert_Search_OptSel_'.$ThisUrl['type']] = 'selected'; - } - - if(!empty($GetData)) - { - if(empty($_Lang['Insert_Search_Value'])) - { - $_Lang['Insert_Search_Value'] = implode('|', $GetData['value']); - $_Lang['Insert_Search_OptSel_'.($GetData['type'] == 'user' ? 'uid' : 'ipid')] = 'selected'; - } - - $LoadData = doquery($GetData['query'], $GetData['table']); - if(mysql_num_rows($LoadData) > 0) - { - // Parse main data and then grab secondary data - $HeaderTPL = gettemplate('admin/iplog_result_header_'.$GetData['tpl']); - $BreakTPL = gettemplate('admin/iplog_result_header_breakline'); - $RowTPL = gettemplate('admin/iplog_result_mainrow_'.$GetData['tpl']); - $SubRowTPL = gettemplate('admin/iplog_result_subrow_'.$GetData['tpl']); - - while($Data = mysql_fetch_assoc($LoadData)) - { - if($GetData['type'] == 'user') - { - $Rows[] = $Data; - } - else if($GetData['type'] == 'ip') - { - if(empty($Data['username'])) - { - $Data['username'] = ''.$_Lang['SubRow_IP_NoData'].''; - } - if(empty($Rows[$Data['User_ID']])) - { - $Rows[$Data['User_ID']] = $Data; - } - if(empty($Rows[$Data['User_ID']][$Data['IP_ID']])) - { - $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['IP_ID'] = $Data['IP_ID']; - $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['Value'] = $Data['Value']; - $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['isProxy'] = ($Data['isProxy'] ? 'isProxy' : 'noProxy'); - $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['isProxyColor'] = ($Data['isProxy'] ? 'orange' : ''); - } - if(!isset($Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['Count'])) - { - $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['Count'] = 0; - } - $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['Count'] += $Data['Count']; - if(!isset($Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['LastDateRaw']) || $Data['LastTime'] > $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['LastDateRaw']) - { - $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['LastDateRaw'] = $Data['LastTime']; - $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['LastDate'] = prettyDate('d m Y, H:i:s', $Data['LastTime'] + SERVER_MAINOPEN_TSTAMP, 1); - } - } - } - - if($GetData['type'] == 'user') - { - foreach($Rows as $RowData) - { - $LoadWhere[] = $RowData['id']; - } - $LoadWhere = implode(', ', $LoadWhere); - $LoadData = doquery("SELECT `logs`.`IP_ID`, `logs`.`User_ID`, `logs`.`Count`, `logs`.`LastTime`, `values`.`Value`, `values`.`isProxy` FROM {{table}} AS `logs` LEFT JOIN `{{prefix}}used_ip_and_ua` AS `values` ON `logs`.`IP_ID` = `values`.`ID` WHERE `User_ID` IN ({$LoadWhere});", 'user_enterlog'); - $MainKey = 'id'; - if(mysql_num_rows($LoadData) > 0) - { - while($Data = mysql_fetch_assoc($LoadData)) - { - if(empty($SubRows[$Data['User_ID']][$Data['IP_ID']])) - { - $SubRows[$Data['User_ID']][$Data['IP_ID']] = $Data; - $SubRows[$Data['User_ID']][$Data['IP_ID']]['isProxy'] = ($Data['isProxy'] ? 'isProxy' : 'noProxy'); - $SubRows[$Data['User_ID']][$Data['IP_ID']]['isProxyColor'] = ($Data['isProxy'] ? 'orange' : ''); - if(!isset($IPTable[$Data['IP_ID']])) - { - $IPTable[$Data['IP_ID']] = 0; - } - $IPTable[$Data['IP_ID']] += 1; - $IPReverse[$Data['IP_ID']] = $Data['Value']; - } - else - { - $SubRows[$Data['User_ID']][$Data['IP_ID']]['Count'] += $Data['Count']; - } - if(!isset($SubRows[$Data['User_ID']][$Data['IP_ID']]['LastDateRaw']) || $Data['LastTime'] > $SubRows[$Data['User_ID']][$Data['IP_ID']]['LastDateRaw']) - { - $SubRows[$Data['User_ID']][$Data['IP_ID']]['LastDateRaw'] = $Data['LastTime']; - $SubRows[$Data['User_ID']][$Data['IP_ID']]['LastDate'] = prettyDate('d m Y, H:i:s', $Data['LastTime'] + SERVER_MAINOPEN_TSTAMP, 1); - } - } - if(isset($Sortings['user']['logcount']) && $Sortings['user']['logcount'] === true) - { - if($SortMode == 'desc') - { - $SortMode = SORT_DESC; - } - else - { - $SortMode = SORT_ASC; - } - foreach($SubRows as $Key => $Array) - { - $SortArray = array(); - foreach($Array as $ID => $Array2) - { - $SortArray[$ID] = $Array2['Count']; - } - array_multisort($SortArray, $SortMode, $SubRows[$Key]); - } - } - else if(isset($Sortings['user']['logdate']) && $Sortings['user']['logdate'] === true) - { - if($SortMode == 'desc') - { - $SortMode = SORT_DESC; - } - else - { - $SortMode = SORT_ASC; - } - foreach($SubRows as $Key => $Array) - { - $SortArray = array(); - foreach($Array as $ID => $Array2) - { - $SortArray[$ID] = $Array2['LastDateRaw']; - } - array_multisort($SortArray, $SortMode, $SubRows[$Key]); - } - } - else if(isset($Sortings['user']['ipid']) && $Sortings['user']['ipid'] === true) - { - foreach($SubRows as $Key => $Data) - { - if($SortMode == 'desc') - { - krsort($SubRows[$Key]); - } - else - { - ksort($SubRows[$Key]); - } - } - } - } - } - else if($GetData['type'] == 'ip') - { - foreach($Rows as $UserID => $UserData) - { - $SubRows[$UserID] = $UserData['IP']; - foreach($UserData['IP'] as $ThisData) - { - if(!isset($IPTable[$ThisData['IP_ID']])) - { - $IPTable[$ThisData['IP_ID']] = 0; - } - $IPTable[$ThisData['IP_ID']] += 1; - $IPReverse[$ThisData['IP_ID']] = $ThisData['Value']; - } - } - $MainKey = 'User_ID'; - } - - $RowNoTable = array(); - foreach($Rows as $RowData) - { - if(!empty($SubRows[$RowData[$MainKey]])) - { - foreach($SubRows[$RowData[$MainKey]] as $SubRowData) - { - if($IPTable[$SubRowData['IP_ID']] > 1) - { - $ThisKey = $SubRowData['IP_ID']; - } - else - { - $ThisKey = 0; - } - if(empty($RowData['sub'][$ThisKey]['SubRowFirst'])) - { - $RowData['sub'][$ThisKey]['SubRowFirst'] = parsetemplate($SubRowTPL, $SubRowData); - $RowData['sub'][$ThisKey]['SubRowsCount'] = 1; - } - else - { - $RowData['sub'][$ThisKey]['SubRows'] .= ''.parsetemplate($SubRowTPL, $SubRowData).''; - $RowData['sub'][$ThisKey]['SubRowsCount'] += 1; - } - } - } - else - { - if($GetData['type'] == 'user') - { - $NoData_Text = $_Lang['SubRow_User_NoData']; - } - else - { - $NoData_Text = $_Lang['SubRow_IP_NoData']; - } - $RowData['sub'][0]['SubRowFirst'] = ''.$NoData_Text.''; - $RowData['sub'][0]['SubRowsCount'] = 1; - } - - $RowDataReduced = $RowData; - unset($RowDataReduced['sub']); - foreach($RowData['sub'] as $TableKey => $ThisData) - { - $ThisData = array_merge($RowDataReduced, $ThisData); - - if(!isset($RowNoTable[$TableKey])) - { - $RowNoTable[$TableKey] = 0; - } - $ThisData['RowNo'] = $RowNoTable[$TableKey] + 1; - $RowNoTable[$TableKey] += 1; - if($ThisData['RowNo'] % 2 == 0) - { - $ThisData['EvenOrOdd'] = 'even'; - } - else - { - $ThisData['EvenOrOdd'] = 'odd'; - } - - $ParsedRows[$TableKey] = parsetemplate($RowTPL, $ThisData); - } - } - - krsort($ParsedRows); - $ParsedRowsCount = count($ParsedRows); - foreach($ParsedRows as $ThisKey => $CombinedRows) - { - if($ThisKey > 0) - { - $BreakArray = array('BreakText' => sprintf($_Lang['BreakLine_Intersection'], $ThisKey, $IPReverse[$ThisKey], $ThisKey, $ThisKey)); - $_Lang['Results'][] = parsetemplate($BreakTPL, $BreakArray); - } - else - { - if($ParsedRowsCount > 1) - { - $BreakArray = array('BreakText' => $_Lang['BreakLine_NormalLogs']); - $_Lang['Results'][] = parsetemplate($BreakTPL, $BreakArray); - } - } - $_Lang['Results'][] = $CombinedRows; - } - - $_Lang['Results'] = implode('', $_Lang['Results']); - $_Lang['Headers'] = parsetemplate($HeaderTPL, $_Lang); - } - else - { - $_Lang['InfoBox_Msg'] = "{$_Lang['Error_Where_NoData']}"; - } - } - else - { - if(empty($Error)) - { - $_Lang['InfoBox_Msg'] = "{$_Lang['Info_InsertData']}"; - } - } - - if(empty($_Lang['InfoBox_Msg'])) - { - $_Lang['Insert_InfoBox_Hide'] = 'hide'; - } - - display(parsetemplate($PageTPL, $_Lang), $PageTitle, false, true); - -?> \ No newline at end of file + 0) + { + $Query_GetIP = ''; + $Query_GetIP .= "SELECT `ID`, `isProxy` FROM {{table}} "; + $Query_GetIP .= "WHERE `ID` = {$Proxy_IPID} AND `Type` = 'ip' LIMIT 1;"; + $Result_GetIP = doquery($Query_GetIP, 'used_ip_and_ua', true); + if($Result_GetIP['ID'] == $Proxy_IPID) + { + $Query_UpdateIP = ''; + $Query_UpdateIP .= "UPDATE {{table}} SET "; + $Query_UpdateIP .= "`isProxy` = ".($Result_GetIP['isProxy'] == 1 ? 'false' : 'true')." "; + $Query_UpdateIP .= "WHERE `ID` = {$Proxy_IPID} LIMIT 1;"; + doquery($Query_UpdateIP, 'used_ip_and_ua'); + + $_Lang['InfoBox_Msg'] = "{$_Lang['Info_ProxySet_OK_'.($Result_GetIP['isProxy'] == 0 ? 'Set' : 'Unset')]}"; + } + else + { + $_Lang['InfoBox_Msg'] = "{$_Lang['Info_ProxySet_NoIP']}"; + } + } + else + { + $_Lang['InfoBox_Msg'] = "{$_Lang['Info_ProxySet_BadID']}"; + } +} + +if(!empty($_POST['search'])) +{ + if(!empty($_POST['uid'])) + { + $_GET['uid'] = $_POST['uid']; + } + if(!empty($_POST['ipid'])) + { + $_GET['ipid'] = $_POST['ipid']; + } + + if(empty($_GET['uid']) && empty($_GET['ipid'])) + { + // Do Search and then Redirect to result page (if found) + $Search = explode('|', $_POST['search']); + $Search = array_map(function($val){return trim($val);}, $Search); + + if(isset($_POST['strict']) && $_POST['strict'] == '1') + { + $UseStrict = true; + } + else + { + $UseStrict = false; + } + + if(in_array($_POST['type'], array('uname', 'uid', 'ipstr', 'ipid'))) + { + // If searchType is supported: + // Create search data for each searchType + if($_POST['type'] == 'uname') + { + $Query[0]['table'] = 'users'; + $Query[0]['select'] = 'id'; + $Query[0]['select_field'] = 'id'; + $Query[0]['result'] = 'uid'; + $Query[0]['fields'][0] = 'username'; + $Query[0]['search'][0] = 'REGEXP'; + if(!$UseStrict) + { + $CheckFunction = function($Value) + { + if(preg_match(REGEXP_USERNAME, $Value)) + { + return true; + } + return false; + }; + } + else + { + $CheckFunction = function($Value) + { + if(preg_match(REGEXP_USERNAME_ABSOLUTE, $Value)) + { + return true; + } + return false; + }; + } + } + else if($_POST['type'] == 'uid') + { + $Query[0]['table'] = 'users'; + $Query[0]['select'] = 'id'; + $Query[0]['select_field'] = 'id'; + $Query[0]['result'] = 'uid'; + $Query[0]['fields'][0] = 'id'; + $Query[0]['search'][0] = 'IN'; + $CheckFunction = function(&$Value) + { + $Value = intval($Value); + if($Value > 0) + { + return true; + } + return false; + }; + } + else if($_POST['type'] == 'ipstr') + { + $Query[0]['table'] = 'used_ip_and_ua'; + $Query[0]['select'] = 'ID'; + $Query[0]['select_field'] = 'ID'; + $Query[0]['result'] = 'ipid'; + if($UseStrict) + { + $Query[0]['fields'][0] = 'ValueHash'; + $Query[0]['search'][0] = 'IN'; + $Query[0]['valadd'][0] = '\'{$VAL}\''; + } + else + { + $Query[0]['fields'][0] = 'Value'; + $Query[0]['search'][0] = 'REGEXP'; + } + $CheckFunction = function($Value) + { + if(preg_match(REGEXP_IP, $Value)) + { + return true; + } + return false; + }; + } + else if($_POST['type'] == 'ipid') + { + $Query[0]['table'] = 'user_enterlog'; + $Query[0]['select'] = 'DISTINCT IP_ID'; + $Query[0]['select_field'] = 'IP_ID'; + $Query[0]['result'] = 'ipid'; + $Query[0]['fields'][0] = 'IP_ID'; + $Query[0]['search'][0] = 'IN'; + $CheckFunction = function(&$Value) + { + $Value = round($Value); + if($Value > 0) + { + return true; + } + return false; + }; + } + + // Pass all values through CheckFunction + foreach($Search as $Value) + { + if($CheckFunction($Value)) + { + $QryData[] = $Value; + } + } + + if(!empty($QryData)) + { + // Do Search + foreach($Query as $QueryID => $QueryData) + { + $LastQueryID = $QueryID; + + $ComposeQuery = "SELECT {$QueryData['select']} FROM {{table}} WHERE {Fields};"; + $Fields = array(); + foreach($QueryData['fields'] as $FieldID => $Field) + { + if(empty($QueryData['values'][$FieldID])) + { + $Temp = $QryData; + if(!empty($QueryData['valadd'][$FieldID])) + { + $Temp = array_map(function($val){global $QueryData; return str_replace('{$VAL}', $val, $QueryData['valadd'][$FieldID]);}, $Temp); + } + if($QueryData['search'][$FieldID] == 'REGEXP') + { + $Values = '\''.implode('|', $Temp).'\''; + } + else if($QueryData['search'][$FieldID] == 'IN') + { + $Values = '('.implode(', ', $Temp).')'; + } + } + else + { + $Values = $QueryData['values'][$FieldID]; + } + $Fields[] = "`{$Field}` {$QueryData['search'][$FieldID]} {$Values}"; + } + if(!empty($QueryData['joins'])) + { + foreach($QueryData['joins'] as $JoinID => $JoinType) + { + $Fields[$JoinID] .= " {$JoinType} "; + } + } + $ComposeQuery = str_replace('{Fields}', implode('', $Fields), $ComposeQuery); + $Result = doquery($ComposeQuery, $QueryData['table']); + if(mysql_num_rows($Result) > 0) + { + while($Data = mysql_fetch_assoc($Result)) + { + $Query[$QueryID]['results'][] = $Data; + } + } + else + { + break; + } + } + + if(!empty($Query[$LastQueryID]['results'])) + { + $Data = array_map(function($val){global $Query, $LastQueryID; return $val[$Query[$LastQueryID]['select_field']];}, $Query[$LastQueryID]['results']); + if(!empty($FoundData[$Query[$LastQueryID]['result']])) + { + $FoundData[$Query[$LastQueryID]['result']] = array_merge($FoundData[$Query[$LastQueryID]['result']], $Data); + } + else + { + $FoundData[$Query[$LastQueryID]['result']] = $Data; + } + } + else + { + $Error['txt'] = $_Lang['Error_Search_NoRowsFound']; + } + } + } + else + { + // Bad Type - throw Error + $Error['txt'] = $_Lang['Error_Search_BadType']; + } + + if(!empty($FoundData['uid'])) + { + $_GET['uid'] = implode('|', $FoundData['uid']); + } + else if(!empty($FoundData['ipid'])) + { + $_GET['ipid'] = implode('|', $FoundData['ipid']); + } + } + + $ThisUrl['search'] = $_POST['search']; + $ThisUrl['type'] = $_POST['type']; +} + +if(!empty($_GET['search'])) +{ + $ThisUrl['search'] = $_GET['search']; +} +if(!empty($_GET['type'])) +{ + $ThisUrl['type'] = $_GET['type']; +} +if(!empty($_POST['sort'])) +{ + if(in_array($_POST['sort'], array('uid', 'ipid', 'logcount', 'logdate'))) + { + $SortType = $_POST['sort']; + if($_POST['mode'] == 'asc' OR $_POST['mode'] == 'desc') + { + $SortMode = $_POST['mode']; + } + else + { + $SortMode = 'asc'; + } + } + if(!empty($SortType)) + { + if($SortType == 'uid') + { + $Sortings['user']['uid'] = " ORDER BY `id` {$SortMode}"; + $Sortings['ip']['uid'] = " ORDER BY `User_ID` {$SortMode}"; + $_Lang['SortUIDMode'] = '&mode='.($SortMode == 'asc' ? 'desc' : 'asc'); + $_Lang['SortUIDModeClass'] = $SortMode; + } + else if($SortType == 'ipid') + { + $Sortings['user']['ipid'] = true; + $Sortings['ip']['ipid'] = " ORDER BY `IP_ID` {$SortMode}"; + $_Lang['SortIPIDMode'] = '&mode='.($SortMode == 'asc' ? 'desc' : 'asc'); + $_Lang['SortIPIDModeClass'] = $SortMode; + } + else if($SortType == 'logcount') + { + $Sortings['user']['logcount'] = true; + $Sortings['ip']['logcount'] = true; + $_Lang['SortLogCountMode'] = '&mode='.($SortMode == 'asc' ? 'desc' : 'asc'); + $_Lang['SortLogCountModeClass'] = $SortMode; + } + else if($SortType == 'logdate') + { + $Sortings['user']['logdate'] = true; + $Sortings['ip']['logdate'] = true; + $_Lang['SortLogDateMode'] = '&mode='.($SortMode == 'asc' ? 'desc' : 'asc'); + $_Lang['SortLogDateModeClass'] = $SortMode; + } + $_Lang['Insert_SortType'] = $SortType; + $_Lang['Insert_SortMode'] = $SortMode; + } +} + +if(!empty($Error)) +{ + $_Lang['InfoBox_Msg'] = "{$Error['txt']}"; +} + +// If data given, create Where statement +if(!empty($_GET['uid'])) +{ + $_Lang['Insert_Found_UID'] = $_GET['uid']; + $_GET['uid'] = explode('|', $_GET['uid']); + foreach($_GET['uid'] as $Value) + { + $Value = round($Value); + if($Value > 0) + { + $GetData['value'][] = $Value; + } + } + if(!empty($GetData['value'])) + { + $GetData['type'] = 'user'; + $GetData['query'] = "SELECT `id`, `username`, `ip_at_reg`, `user_lastip` FROM {{table}} WHERE `id` IN (".implode(', ', $GetData['value']).")".(isset($Sortings['user']['uid']) ? $Sortings['user']['uid'] : null).";"; + $GetData['table'] = 'users'; + $GetData['tpl'] = 'user'; + } +} +if(!empty($_GET['ipid'])) +{ + $_Lang['Insert_Found_IPID'] = $_GET['ipid']; + $_GET['ipid'] = explode('|', $_GET['ipid']); + foreach($_GET['ipid'] as $Value) + { + $Value = round($Value); + if($Value > 0) + { + $GetData['value'][] = $Value; + } + } + if(!empty($GetData['value'])) + { + $GetData['type'] = 'ip'; + $GetData['query'] = "SELECT DISTINCT `logs`.`User_ID`, `logs`.`IP_ID`, `logs`.`Count`, `logs`.`LastTime`, `values`.`Value`, `values`.`isProxy`, `users`.`username` FROM {{table}} AS `logs` LEFT JOIN `{{prefix}}used_ip_and_ua` AS `values` ON `values`.`ID` = `logs`.`IP_ID` LEFT JOIN `{{prefix}}users` AS `users` ON `users`.`id` = `logs`.`User_ID` WHERE `IP_ID` IN (".implode(', ', $GetData['value']).")".(isset($Sortings['ip']['uid']) ? $Sortings['ip']['uid'] : null).(isset($Sortings['ip']['ipid']) ? $Sortings['ip']['ipid'] : null).";"; + $GetData['table'] = 'user_enterlog'; + $GetData['tpl'] = 'ip'; + } +} + +$_Lang['Insert_Search_Value'] = (isset($ThisUrl['search']) ? $ThisUrl['search'] : ''); +if(isset($ThisUrl['type'])) +{ + $_Lang['Insert_Search_OptSel_'.$ThisUrl['type']] = 'selected'; +} + +if(!empty($GetData)) +{ + if(empty($_Lang['Insert_Search_Value'])) + { + $_Lang['Insert_Search_Value'] = implode('|', $GetData['value']); + $_Lang['Insert_Search_OptSel_'.($GetData['type'] == 'user' ? 'uid' : 'ipid')] = 'selected'; + } + + $LoadData = doquery($GetData['query'], $GetData['table']); + if(mysql_num_rows($LoadData) > 0) + { + // Parse main data and then grab secondary data + $HeaderTPL = gettemplate('admin/iplog_result_header_'.$GetData['tpl']); + $BreakTPL = gettemplate('admin/iplog_result_header_breakline'); + $RowTPL = gettemplate('admin/iplog_result_mainrow_'.$GetData['tpl']); + $SubRowTPL = gettemplate('admin/iplog_result_subrow_'.$GetData['tpl']); + + while($Data = mysql_fetch_assoc($LoadData)) + { + if($GetData['type'] == 'user') + { + $Rows[] = $Data; + } + else if($GetData['type'] == 'ip') + { + if(empty($Data['username'])) + { + $Data['username'] = ''.$_Lang['SubRow_IP_NoData'].''; + } + if(empty($Rows[$Data['User_ID']])) + { + $Rows[$Data['User_ID']] = $Data; + } + if(empty($Rows[$Data['User_ID']][$Data['IP_ID']])) + { + $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['IP_ID'] = $Data['IP_ID']; + $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['Value'] = $Data['Value']; + $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['isProxy'] = ($Data['isProxy'] ? 'isProxy' : 'noProxy'); + $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['isProxyColor'] = ($Data['isProxy'] ? 'orange' : ''); + } + if(!isset($Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['Count'])) + { + $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['Count'] = 0; + } + $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['Count'] += $Data['Count']; + if(!isset($Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['LastDateRaw']) || $Data['LastTime'] > $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['LastDateRaw']) + { + $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['LastDateRaw'] = $Data['LastTime']; + $Rows[$Data['User_ID']]['IP'][$Data['IP_ID']]['LastDate'] = prettyDate('d m Y, H:i:s', $Data['LastTime'] + SERVER_MAINOPEN_TSTAMP, 1); + } + } + } + + if($GetData['type'] == 'user') + { + foreach($Rows as $RowData) + { + $LoadWhere[] = $RowData['id']; + } + $LoadWhere = implode(', ', $LoadWhere); + $LoadData = doquery("SELECT `logs`.`IP_ID`, `logs`.`User_ID`, `logs`.`Count`, `logs`.`LastTime`, `values`.`Value`, `values`.`isProxy` FROM {{table}} AS `logs` LEFT JOIN `{{prefix}}used_ip_and_ua` AS `values` ON `logs`.`IP_ID` = `values`.`ID` WHERE `User_ID` IN ({$LoadWhere});", 'user_enterlog'); + $MainKey = 'id'; + if(mysql_num_rows($LoadData) > 0) + { + while($Data = mysql_fetch_assoc($LoadData)) + { + if(empty($SubRows[$Data['User_ID']][$Data['IP_ID']])) + { + $SubRows[$Data['User_ID']][$Data['IP_ID']] = $Data; + $SubRows[$Data['User_ID']][$Data['IP_ID']]['isProxy'] = ($Data['isProxy'] ? 'isProxy' : 'noProxy'); + $SubRows[$Data['User_ID']][$Data['IP_ID']]['isProxyColor'] = ($Data['isProxy'] ? 'orange' : ''); + if(!isset($IPTable[$Data['IP_ID']])) + { + $IPTable[$Data['IP_ID']] = 0; + } + $IPTable[$Data['IP_ID']] += 1; + $IPReverse[$Data['IP_ID']] = $Data['Value']; + } + else + { + $SubRows[$Data['User_ID']][$Data['IP_ID']]['Count'] += $Data['Count']; + } + if(!isset($SubRows[$Data['User_ID']][$Data['IP_ID']]['LastDateRaw']) || $Data['LastTime'] > $SubRows[$Data['User_ID']][$Data['IP_ID']]['LastDateRaw']) + { + $SubRows[$Data['User_ID']][$Data['IP_ID']]['LastDateRaw'] = $Data['LastTime']; + $SubRows[$Data['User_ID']][$Data['IP_ID']]['LastDate'] = prettyDate('d m Y, H:i:s', $Data['LastTime'] + SERVER_MAINOPEN_TSTAMP, 1); + } + } + if(isset($Sortings['user']['logcount']) && $Sortings['user']['logcount'] === true) + { + if($SortMode == 'desc') + { + $SortMode = SORT_DESC; + } + else + { + $SortMode = SORT_ASC; + } + foreach($SubRows as $Key => $Array) + { + $SortArray = array(); + foreach($Array as $ID => $Array2) + { + $SortArray[$ID] = $Array2['Count']; + } + array_multisort($SortArray, $SortMode, $SubRows[$Key]); + } + } + else if(isset($Sortings['user']['logdate']) && $Sortings['user']['logdate'] === true) + { + if($SortMode == 'desc') + { + $SortMode = SORT_DESC; + } + else + { + $SortMode = SORT_ASC; + } + foreach($SubRows as $Key => $Array) + { + $SortArray = array(); + foreach($Array as $ID => $Array2) + { + $SortArray[$ID] = $Array2['LastDateRaw']; + } + array_multisort($SortArray, $SortMode, $SubRows[$Key]); + } + } + else if(isset($Sortings['user']['ipid']) && $Sortings['user']['ipid'] === true) + { + foreach($SubRows as $Key => $Data) + { + if($SortMode == 'desc') + { + krsort($SubRows[$Key]); + } + else + { + ksort($SubRows[$Key]); + } + } + } + } + } + else if($GetData['type'] == 'ip') + { + foreach($Rows as $UserID => $UserData) + { + $SubRows[$UserID] = $UserData['IP']; + foreach($UserData['IP'] as $ThisData) + { + if(!isset($IPTable[$ThisData['IP_ID']])) + { + $IPTable[$ThisData['IP_ID']] = 0; + } + $IPTable[$ThisData['IP_ID']] += 1; + $IPReverse[$ThisData['IP_ID']] = $ThisData['Value']; + } + } + $MainKey = 'User_ID'; + } + + $RowNoTable = array(); + foreach($Rows as $RowData) + { + if(!empty($SubRows[$RowData[$MainKey]])) + { + foreach($SubRows[$RowData[$MainKey]] as $SubRowData) + { + if($IPTable[$SubRowData['IP_ID']] > 1) + { + $ThisKey = $SubRowData['IP_ID']; + } + else + { + $ThisKey = 0; + } + if(empty($RowData['sub'][$ThisKey]['SubRowFirst'])) + { + $RowData['sub'][$ThisKey]['SubRowFirst'] = parsetemplate($SubRowTPL, $SubRowData); + $RowData['sub'][$ThisKey]['SubRowsCount'] = 1; + } + else + { + $RowData['sub'][$ThisKey]['SubRows'] .= ''.parsetemplate($SubRowTPL, $SubRowData).''; + $RowData['sub'][$ThisKey]['SubRowsCount'] += 1; + } + } + } + else + { + if($GetData['type'] == 'user') + { + $NoData_Text = $_Lang['SubRow_User_NoData']; + } + else + { + $NoData_Text = $_Lang['SubRow_IP_NoData']; + } + $RowData['sub'][0]['SubRowFirst'] = ''.$NoData_Text.''; + $RowData['sub'][0]['SubRowsCount'] = 1; + } + + $RowDataReduced = $RowData; + unset($RowDataReduced['sub']); + foreach($RowData['sub'] as $TableKey => $ThisData) + { + $ThisData = array_merge($RowDataReduced, $ThisData); + + if(!isset($RowNoTable[$TableKey])) + { + $RowNoTable[$TableKey] = 0; + } + $ThisData['RowNo'] = $RowNoTable[$TableKey] + 1; + $RowNoTable[$TableKey] += 1; + if($ThisData['RowNo'] % 2 == 0) + { + $ThisData['EvenOrOdd'] = 'even'; + } + else + { + $ThisData['EvenOrOdd'] = 'odd'; + } + + $ParsedRows[$TableKey] = parsetemplate($RowTPL, $ThisData); + } + } + + krsort($ParsedRows); + $ParsedRowsCount = count($ParsedRows); + foreach($ParsedRows as $ThisKey => $CombinedRows) + { + if($ThisKey > 0) + { + $BreakArray = array('BreakText' => sprintf($_Lang['BreakLine_Intersection'], $ThisKey, $IPReverse[$ThisKey], $ThisKey, $ThisKey)); + $_Lang['Results'][] = parsetemplate($BreakTPL, $BreakArray); + } + else + { + if($ParsedRowsCount > 1) + { + $BreakArray = array('BreakText' => $_Lang['BreakLine_NormalLogs']); + $_Lang['Results'][] = parsetemplate($BreakTPL, $BreakArray); + } + } + $_Lang['Results'][] = $CombinedRows; + } + + $_Lang['Results'] = implode('', $_Lang['Results']); + $_Lang['Headers'] = parsetemplate($HeaderTPL, $_Lang); + } + else + { + $_Lang['InfoBox_Msg'] = "{$_Lang['Error_Where_NoData']}"; + } +} +else +{ + if(empty($Error)) + { + $_Lang['InfoBox_Msg'] = "{$_Lang['Info_InsertData']}"; + } +} + +if(empty($_Lang['InfoBox_Msg'])) +{ + $_Lang['Insert_InfoBox_Hide'] = 'hide'; +} + +display(parsetemplate($PageTPL, $_Lang), $PageTitle, false, true); + +?> diff --git a/admin/iplog_addproxy.php b/admin/iplog_addproxy.php index 685c3f921..716e53d47 100644 --- a/admin/iplog_addproxy.php +++ b/admin/iplog_addproxy.php @@ -1,69 +1,69 @@ - 'pad2 '.$_MsgBox['Class'], 'Colspan' => 2, 'Text' => $_MsgBox['Text'])); - - display(parsetemplate($TPL_Body, $_Lang), $_Lang['PageTitle'], false, true); - -?> \ No newline at end of file + 'pad2 '.$_MsgBox['Class'], 'Colspan' => 2, 'Text' => $_MsgBox['Text'])); + +display(parsetemplate($TPL_Body, $_Lang), $_Lang['PageTitle'], false, true); + +?> diff --git a/admin/massmessage.php b/admin/massmessage.php index 7696f30ed..406a68d6e 100644 --- a/admin/massmessage.php +++ b/admin/massmessage.php @@ -1,69 +1,70 @@ -'.sprintf($_Lang['MassMessage_Success'], count($UserList)).'', 'MassMessage'); - } - else - { - message($_Lang['MassMessage_NoSufficientData'], 'MassMessage'); - } - } - else - { - $parse = $_GameConfig; - $parse['skinpath'] = $_SkinPath; - $page = parsetemplate(gettemplate('admin/massmessage_body'), $parse); - display($page, 'MassMessage', false, true); - } - } - else - { - // User have no required access - message($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); - } -?> +'.sprintf($_Lang['MassMessage_Success'], count($UserList)).'', 'MassMessage'); + } + else + { + message($_Lang['MassMessage_NoSufficientData'], 'MassMessage'); + } + } + else + { + $parse = $_GameConfig; + $parse['skinpath'] = $_SkinPath; + $page = parsetemplate(gettemplate('admin/massmessage_body'), $parse); + display($page, 'MassMessage', false, true); + } +} +else +{ + // User have no required access + message($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); +} + +?> diff --git a/admin/messagelist.php b/admin/messagelist.php index 5583d4c99..4a11c76f6 100644 --- a/admin/messagelist.php +++ b/admin/messagelist.php @@ -1,502 +1,502 @@ - 0) - { - $MID = intval($_GET['mid']); - if($MID > 0) - { - $_POST['msg_id'] = $MID; - } - } - } - - if(isset($_POST['msg_id']) && $_POST['msg_id'] > 0) - { - $_POST['msg_id'] = intval($_POST['msg_id']); - if($_POST['msg_id'] <= 0) - { - $_POST['msg_id'] = 0; - } - } - if(!isset($_POST['msg_id']) || $_POST['msg_id'] == 0) - { - if(isset($_POST['user_id']) && $_POST['user_id'] > 0) - { - $_POST['user_id'] = intval($_POST['user_id']); - if($_POST['user_id'] <= 0) - { - $_POST['user_id'] = 0; - } - } - else - { - $_POST['user_id'] = 0; - } - if($_POST['user_id'] == 0) - { - if(isset($_GET['uid']) && $_GET['uid'] > 0) - { - $UID = intval($_GET['uid']); - if($UID > 0) - { - $_POST['user_id'] = $UID; - } - } - } - } - - // Do actions in here! - if($DelSelSoft === true || $DelSel === true || $SetRead === true || $SetNotRead === true) - { - if(CheckAuth('supportadmin')) - { - if(!empty($_POST['sele']) && (array)$_POST['sele'] === $_POST['sele']) - { - foreach($_POST['sele'] as $MessId => $Value) - { - if($Value == 'on') - { - $DeleteIDs[] = $MessId; - } - } - if(!empty($DeleteIDs)) - { - foreach($DeleteIDs as $CheckID) - { - $CheckCopyTexts[] = "'{COPY_MSG_#{$CheckID}}'"; - } - $CheckCopy = doquery("SELECT `id` FROM {{table}} WHERE `text` IN (".implode(', ', $CheckCopyTexts).");", 'messages'); - if(mysql_num_rows($CheckCopy) > 0) - { - while($AdditionalIDs = mysql_fetch_assoc($CheckCopy)) - { - if(!in_array($AdditionalIDs['id'], $DeleteIDs)) - { - $DeleteIDs[] = $AdditionalIDs['id']; - } - } - } - if(!empty($DeleteIDs)) - { - $DeleteIDs = implode(',', $DeleteIDs); - $SelectThreads = false; - if($DelSelSoft === true || $DelSel === true) - { - $SelectThreads = doquery("SELECT `Thread_ID` FROM {{table}} WHERE `Thread_ID` > 0 AND `id` IN ({$DeleteIDs});", 'messages'); - } - - if($DelSelSoft === true) - { - doquery("UPDATE {{table}} SET `deleted` = 1, `Thread_IsLast` = 0 WHERE `id` IN ({$DeleteIDs});", 'messages'); - } - else if($DelSel === true) - { - doquery("DELETE FROM {{table}} WHERE `id` IN ({$DeleteIDs});", 'messages'); - } - else if($SetRead === true) - { - doquery("UPDATE {{table}} SET `read` = 1 WHERE `id` IN ({$DeleteIDs});", 'messages'); - } - else if($SetNotRead === true) - { - doquery("UPDATE {{table}} SET `read` = 0 WHERE `id` IN ({$DeleteIDs});", 'messages'); - } - - if($SelectThreads != false) - { - if(mysql_num_rows($SelectThreads) > 0) - { - $UpdateThreads = array(); - while($FetchData = mysql_fetch_assoc($SelectThreads)) - { - if(!in_array($FetchData['Thread_ID'], $UpdateThreads)) - { - $UpdateThreads[] = $FetchData['Thread_ID']; - } - } - $IDs = implode(',', $UpdateThreads); - $SelectIDs = doquery("SELECT MAX(`id`) AS `id` FROM {{table}} WHERE `Thread_ID` IN ({$IDs}) AND `deleted` = false GROUP BY `Thread_ID`, `id_owner`;", 'messages'); - if(mysql_num_rows($SelectIDs) > 0) - { - $UpdateThreads = array(); - while($SelectData = mysql_fetch_assoc($SelectIDs)) - { - $UpdateThreads[] = $SelectData['id']; - } - $IDs = implode(',', $UpdateThreads); - doquery("UPDATE {{table}} SET `Thread_IsLast` = 1 WHERE `id` IN ({$IDs});", 'messages'); - } - } - } - } - } - } - } - } - // - End of Actions - - $ViewPage = 1; - if($Selected != $SelType) - { - $Selected = $SelType; - $ViewPage = 1; - } - else if($CurrPage != $SelPage) - { - $ViewPage = !empty($SelPage) ? $SelPage : 1; - } - - $ExcludedUsers = false; - if(CheckAuth('supportadmin')) - { - $Query = "SELECT `id` FROM {{table}} WHERE `authlevel` >= {$_User['authlevel']} AND `id` != {$_User['id']};"; - $Result = doquery($Query, 'users'); - if(mysql_num_rows($Result) > 0) - { - while($Data = mysql_fetch_assoc($Result)) - { - $ExcludedUsers[] = $Data['id']; - } - $DisallowTpl = gettemplate('admin/messagelist_table_rows_disallowed'); - } - } - - $WhereClausures = false; - if($Selected != 100) - { - $WhereClausures[] = "`type` = {$Selected}"; - } - // $_POST['user_id'] is SAFE for SQL - if($_POST['user_id'] > 0) - { - if($Selected != 2) - { - $WhereClausures[] = "(`id_owner` = {$_POST['user_id']} OR `id_sender` = {$_POST['user_id']})"; - } - else - { - $AdditionalSelect = doquery("SELECT `id` FROM {{table}} WHERE `ally_id` = {$_POST['user_id']};", 'users'); - if(mysql_num_rows($AdditionalSelect) > 0) - { - while($AdditionalData = mysql_fetch_assoc($AdditionalSelect)) - { - $AdditionalUsers[] = $AdditionalData['id']; - } - } - if(!empty($AdditionalUsers)) - { - $WhereClausures[] = "(`id_owner` IN (".implode(', ', $AdditionalUsers).") OR `id_sender` IN (".implode(', ', $AdditionalUsers)."))"; - } - else - { - $WhereClausures[] = "(1 = 2)"; - } - } - $DontBlockCopy = true; - } - // $_POST['msg_id'] is SAFE for SQL - if(isset($_POST['msg_id']) && $_POST['msg_id'] > 0) - { - $WhereClausures[] = "{{table}}.`id` = {$_POST['msg_id']}"; - $DontBlockCopy = true; - } - - if(!isset($DontBlockCopy)) - { - $WhereClausures[] = '`text` NOT LIKE \'{COPY_MSG_#%}\''; - } - - if(!empty($WhereClausures)) - { - $WhereClausures = ' WHERE '.implode(' AND ', $WhereClausures); - } - - $Mess = doquery("SELECT COUNT(`id`) AS `max` FROM {{table}}{$WhereClausures};", 'messages', true); - $MaxPage = ceil(($Mess['max'] / $_PerPage)); - - if(isset($_POST['stay']) && $_POST['stay'] == 'true') - { - $Selected = $SelType; - $ViewPage = (!empty($SelPage)) ? $SelPage : 1; - if($ViewPage > $MaxPage) - { - $ViewPage = $MaxPage; - } - } - - if($Prev == true) - { - $CurrPage -= 1; - if($CurrPage >= 1) - { - $ViewPage = $CurrPage; - } - else - { - $ViewPage = 1; - } - } - else if($Next == true) - { - $CurrPage += 1; - if($CurrPage <= $MaxPage) - { - $ViewPage = $CurrPage; - } - else - { - $ViewPage = $MaxPage; - } - } - - $parse = $_Lang; - $parse['mlst_data_rows'] = ''; - $parse['mlst_data_page'] = $ViewPage; - $parse['mlst_data_pagemax'] = $MaxPage; - $parse['mlst_data_sele'] = $Selected; - - $parse['mlst_data_types'] = '"; - $parse['mlst_data_types'] .= '"; - $parse['mlst_data_types'] .= '"; - $parse['mlst_data_types'] .= '"; - $parse['mlst_data_types'] .= '"; - $parse['mlst_data_types'] .= '"; - $parse['mlst_data_types'] .= '"; - $parse['mlst_data_types'] .= '"; - $parse['mlst_data_types'] .= '"; - $parse['mlst_data_types'] .= '"; - $parse['mlst_data_types'] .= '"; - - $parse['_PagesTotalCount'] = $MaxPage; - $parse['_PagesTotalCount_Pretty'] = prettyNumber($MaxPage); - $parse['_PagesCurrent_Pretty'] = prettyNumber($ViewPage); - - $parse['tbl_rows'] = ''; - $parse['mlst_title'] = $_Lang['mlst_title']; - - if($ViewPage < 1) - { - $ViewPage = 1; - } - - $StartRec = (($ViewPage - 1) * $_PerPage); - - $GetMessages = "SELECT {{table}}.*, `users`.`username`, `users`.`authlevel`, `users`.`galaxy`, `users`.`system`, `users`.`planet`, `users2`.`username` as `username2` FROM {{table}} "; - $GetMessages .= "LEFT JOIN {{prefix}}users AS `users2` ON `id_owner` = `users2`.`id` "; - $GetMessages .= "LEFT JOIN {{prefix}}users as `users` ON `id_sender` = `users`.`id` "; - $GetMessages .= $WhereClausures; - $GetMessages .= " ORDER BY {{table}}.`time` DESC, {{table}}.`id` DESC "; - $GetMessages .= "LIMIT {$StartRec}, {$_PerPage};"; - $Messages = doquery($GetMessages, 'messages'); - - if($_GameConfig['enable_bbcode'] == 1) - { - include($_EnginePath.'includes/functions/BBcodeFunction.php'); - } - - while($row = mysql_fetch_assoc($Messages)) - { - $bloc = array(); - - if(!empty($ExcludedUsers)) - { - if(in_array($row['id_sender'], $ExcludedUsers) OR in_array($row['id_owner'], $ExcludedUsers)) - { - $parse['mlst_data_rows'] .= parsetemplate($DisallowTpl , $_Lang); - continue; - } - } - - if($row['id_sender'] == 0) - { - $MsgArray = json_decode($row['text'], true); - $row['from'] = (!empty($row['from']) ? $_Lang['msg_const']['senders']['system'][$row['from']] : ' '); - $row['subject'] = (!empty($row['subject']) ? $_Lang['msg_const']['subjects'][$row['subject']] : ' '); - if(empty($MsgArray['msg_text'])) - { - if(!empty($MsgArray['msg_id'])) - { - $row['text'] = vsprintf($_Lang['msg_const']['msgs'][$MsgArray['msg_id']], $MsgArray['args']); - } - else - { - $row['text'] = sprintf($_Lang['msg_const']['msgs']['err2'], $row['id']); - } - } - else - { - if((array)$MsgArray['msg_text'] === $MsgArray['msg_text']) - { - $row['text'] = implode('', innerReplace(multidim2onedim($MsgArray['msg_text']), $_Lang)); - } - else - { - $row['text'] = sprintf($_Lang['msg_const']['msgs']['err'], $row['id']); - } - } - } - else - { - $AddFrom = ''; - if(!empty($row['from'])) - { - $AddFrom = ' '.$row['from']; - } - if(CheckAuth('user', AUTHCHECK_HIGHER, $row)) - { - $row['from'] = $_Lang['msg_const']['senders']['rangs'][GetAuthLabel($row)].' '.$row['username'].$AddFrom; - $row['subject'] = stripslashes($row['subject']); - } - else - { - $row['from'] = $row['username'].$AddFrom; - $row['subject'] = stripslashes($row['subject']); - } - $row['from'] .= '
[ID: '.$row['id_sender'].']'; - - if(preg_match('/^\{COPY\_MSG\_\#([0-9]{1,})\}$/D', $row['text'], $row['matched'])) - { - $GetMsgCopies[$row['matched'][1]][] = $row['id']; - $bloc['mlst_status'][] = ''; - $bloc['mlst_copyID'] = "
[{$row['matched'][1]}]"; - } - else - { - if($_GameConfig['enable_bbcode'] == 1) - { - $row['text'] = bbcode(image($row['text'])); - } - $row['text'] = nl2br($row['text']); - } - } - if($row['read'] != 0) - { - $bloc['mlst_status'][] = ''; - } - if($row['deleted'] != 0) - { - $bloc['mlst_status'][] = ''; - } - $bloc['mlst_id'] = $row['id']; - if(isset($_POST['msg_id']) && $_POST['msg_id'] == $row['id']) - { - $bloc['mlst_rowcolor'] = 'lime'; - } - $bloc['mlst_from'] = $row['from']; - $bloc['mlst_to'] = "{$row['username2']}
[ID: {$row['id_owner']}]"; - $bloc['mlst_text'] = $row['text']; - if(!empty($bloc['mlst_status'])) - { - $bloc['mlst_status'] = implode('
', $bloc['mlst_status']); - } - else - { - $bloc['mlst_status'] = ' '; - } - $bloc['mlst_time'] = date('d.m.Y', $row['time']).'
'.date('H:i:s', $row['time']); - $parse['mlst_data_rows'][$row['id']] = $bloc; - } - if(empty($parse['mlst_data_rows'])) - { - $parse['mlst_data_rows'] .= ''.$_Lang['Error_NoMsgFound'].'
('.$_Lang['Form_ResetFilters'].')'; - $parse['HideSelectedActionRow'] = ' style="display: none;"'; - } - else - { - if(!empty($GetMsgCopies)) - { - $GetMsgCopiesIDs = implode(', ', array_keys($GetMsgCopies)); - $GetMsgCopiesQuery = "SELECT `id`, `subject`, `text` FROM {{table}} WHERE `id` IN ({$GetMsgCopiesIDs});"; - $GetMsgCopiesResult = doquery($GetMsgCopiesQuery, 'messages'); - if(mysql_num_rows($GetMsgCopiesResult) > 0) - { - while($GetMsgCopiesRow = mysql_fetch_assoc($GetMsgCopiesResult)) - { - $GetMsgCopiesData[$GetMsgCopiesRow['id']] = $GetMsgCopiesRow; - } - } - - foreach($GetMsgCopies as $CopyID => $ReplaceIDs) - { - if(!empty($GetMsgCopiesData[$CopyID])) - { - if($_GameConfig['enable_bbcode'] == 1) - { - $GetMsgCopiesData[$CopyID]['text'] = bbcode(image($GetMsgCopiesData[$CopyID]['text'])); - } - $GetMsgCopiesData[$CopyID]['text'] = nl2br($GetMsgCopiesData[$CopyID]['text']); - foreach($ReplaceIDs as $ReplaceID) - { - $parse['mlst_data_rows'][$ReplaceID]['mlst_text'] = $GetMsgCopiesData[$CopyID]['text']; - $parse['mlst_data_rows'][$ReplaceID]['mlst_subject'] = $GetMsgCopiesData[$CopyID]['subject']; - } - } - else - { - foreach($ReplaceIDs as $ReplaceID) - { - $parse['mlst_data_rows'][$ReplaceID]['mlst_text'] = $_Lang['Err_CopyNotFound']; - $parse['mlst_data_rows'][$ReplaceID]['mlst_subject'] = '-'; - } - } - } - } - - $JoinMsgs = ''; - foreach($parse['mlst_data_rows'] as $RowData) - { - $JoinMsgs .= parsetemplate($RowsTpl, $RowData); - } - - $parse['mlst_data_rows'] = $JoinMsgs; - } - - $parse['selected_user_id'] = $_POST['user_id']; - $display = parsetemplate($BodyTpl , $parse); - - display ($display, $_Lang['mlst_title'], false, '', true); - -?> \ No newline at end of file + 0) + { + $MID = intval($_GET['mid']); + if($MID > 0) + { + $_POST['msg_id'] = $MID; + } + } +} + +if(isset($_POST['msg_id']) && $_POST['msg_id'] > 0) +{ + $_POST['msg_id'] = intval($_POST['msg_id']); + if($_POST['msg_id'] <= 0) + { + $_POST['msg_id'] = 0; + } +} +if(!isset($_POST['msg_id']) || $_POST['msg_id'] == 0) +{ + if(isset($_POST['user_id']) && $_POST['user_id'] > 0) + { + $_POST['user_id'] = intval($_POST['user_id']); + if($_POST['user_id'] <= 0) + { + $_POST['user_id'] = 0; + } + } + else + { + $_POST['user_id'] = 0; + } + if($_POST['user_id'] == 0) + { + if(isset($_GET['uid']) && $_GET['uid'] > 0) + { + $UID = intval($_GET['uid']); + if($UID > 0) + { + $_POST['user_id'] = $UID; + } + } + } +} + +// Do actions in here! +if($DelSelSoft === true || $DelSel === true || $SetRead === true || $SetNotRead === true) +{ + if(CheckAuth('supportadmin')) + { + if(!empty($_POST['sele']) && (array)$_POST['sele'] === $_POST['sele']) + { + foreach($_POST['sele'] as $MessId => $Value) + { + if($Value == 'on') + { + $DeleteIDs[] = $MessId; + } + } + if(!empty($DeleteIDs)) + { + foreach($DeleteIDs as $CheckID) + { + $CheckCopyTexts[] = "'{COPY_MSG_#{$CheckID}}'"; + } + $CheckCopy = doquery("SELECT `id` FROM {{table}} WHERE `text` IN (".implode(', ', $CheckCopyTexts).");", 'messages'); + if(mysql_num_rows($CheckCopy) > 0) + { + while($AdditionalIDs = mysql_fetch_assoc($CheckCopy)) + { + if(!in_array($AdditionalIDs['id'], $DeleteIDs)) + { + $DeleteIDs[] = $AdditionalIDs['id']; + } + } + } + if(!empty($DeleteIDs)) + { + $DeleteIDs = implode(',', $DeleteIDs); + $SelectThreads = false; + if($DelSelSoft === true || $DelSel === true) + { + $SelectThreads = doquery("SELECT `Thread_ID` FROM {{table}} WHERE `Thread_ID` > 0 AND `id` IN ({$DeleteIDs});", 'messages'); + } + + if($DelSelSoft === true) + { + doquery("UPDATE {{table}} SET `deleted` = 1, `Thread_IsLast` = 0 WHERE `id` IN ({$DeleteIDs});", 'messages'); + } + else if($DelSel === true) + { + doquery("DELETE FROM {{table}} WHERE `id` IN ({$DeleteIDs});", 'messages'); + } + else if($SetRead === true) + { + doquery("UPDATE {{table}} SET `read` = 1 WHERE `id` IN ({$DeleteIDs});", 'messages'); + } + else if($SetNotRead === true) + { + doquery("UPDATE {{table}} SET `read` = 0 WHERE `id` IN ({$DeleteIDs});", 'messages'); + } + + if($SelectThreads != false) + { + if(mysql_num_rows($SelectThreads) > 0) + { + $UpdateThreads = array(); + while($FetchData = mysql_fetch_assoc($SelectThreads)) + { + if(!in_array($FetchData['Thread_ID'], $UpdateThreads)) + { + $UpdateThreads[] = $FetchData['Thread_ID']; + } + } + $IDs = implode(',', $UpdateThreads); + $SelectIDs = doquery("SELECT MAX(`id`) AS `id` FROM {{table}} WHERE `Thread_ID` IN ({$IDs}) AND `deleted` = false GROUP BY `Thread_ID`, `id_owner`;", 'messages'); + if(mysql_num_rows($SelectIDs) > 0) + { + $UpdateThreads = array(); + while($SelectData = mysql_fetch_assoc($SelectIDs)) + { + $UpdateThreads[] = $SelectData['id']; + } + $IDs = implode(',', $UpdateThreads); + doquery("UPDATE {{table}} SET `Thread_IsLast` = 1 WHERE `id` IN ({$IDs});", 'messages'); + } + } + } + } + } + } + } +} +// - End of Actions + +$ViewPage = 1; +if($Selected != $SelType) +{ + $Selected = $SelType; + $ViewPage = 1; +} +else if($CurrPage != $SelPage) +{ + $ViewPage = !empty($SelPage) ? $SelPage : 1; +} + +$ExcludedUsers = false; +if(CheckAuth('supportadmin')) +{ + $Query = "SELECT `id` FROM {{table}} WHERE `authlevel` >= {$_User['authlevel']} AND `id` != {$_User['id']};"; + $Result = doquery($Query, 'users'); + if(mysql_num_rows($Result) > 0) + { + while($Data = mysql_fetch_assoc($Result)) + { + $ExcludedUsers[] = $Data['id']; + } + $DisallowTpl = gettemplate('admin/messagelist_table_rows_disallowed'); + } +} + +$WhereClausures = false; +if($Selected != 100) +{ + $WhereClausures[] = "`type` = {$Selected}"; +} +// $_POST['user_id'] is SAFE for SQL +if($_POST['user_id'] > 0) +{ + if($Selected != 2) + { + $WhereClausures[] = "(`id_owner` = {$_POST['user_id']} OR `id_sender` = {$_POST['user_id']})"; + } + else + { + $AdditionalSelect = doquery("SELECT `id` FROM {{table}} WHERE `ally_id` = {$_POST['user_id']};", 'users'); + if(mysql_num_rows($AdditionalSelect) > 0) + { + while($AdditionalData = mysql_fetch_assoc($AdditionalSelect)) + { + $AdditionalUsers[] = $AdditionalData['id']; + } + } + if(!empty($AdditionalUsers)) + { + $WhereClausures[] = "(`id_owner` IN (".implode(', ', $AdditionalUsers).") OR `id_sender` IN (".implode(', ', $AdditionalUsers)."))"; + } + else + { + $WhereClausures[] = "(1 = 2)"; + } + } + $DontBlockCopy = true; +} +// $_POST['msg_id'] is SAFE for SQL +if(isset($_POST['msg_id']) && $_POST['msg_id'] > 0) +{ + $WhereClausures[] = "{{table}}.`id` = {$_POST['msg_id']}"; + $DontBlockCopy = true; +} + +if(!isset($DontBlockCopy)) +{ + $WhereClausures[] = '`text` NOT LIKE \'{COPY_MSG_#%}\''; +} + +if(!empty($WhereClausures)) +{ + $WhereClausures = ' WHERE '.implode(' AND ', $WhereClausures); +} + +$Mess = doquery("SELECT COUNT(`id`) AS `max` FROM {{table}}{$WhereClausures};", 'messages', true); +$MaxPage = ceil(($Mess['max'] / $_PerPage)); + +if(isset($_POST['stay']) && $_POST['stay'] == 'true') +{ + $Selected = $SelType; + $ViewPage = (!empty($SelPage)) ? $SelPage : 1; + if($ViewPage > $MaxPage) + { + $ViewPage = $MaxPage; + } +} + +if($Prev == true) +{ + $CurrPage -= 1; + if($CurrPage >= 1) + { + $ViewPage = $CurrPage; + } + else + { + $ViewPage = 1; + } +} +else if($Next == true) +{ + $CurrPage += 1; + if($CurrPage <= $MaxPage) + { + $ViewPage = $CurrPage; + } + else + { + $ViewPage = $MaxPage; + } +} + +$parse = $_Lang; +$parse['mlst_data_rows'] = ''; +$parse['mlst_data_page'] = $ViewPage; +$parse['mlst_data_pagemax'] = $MaxPage; +$parse['mlst_data_sele'] = $Selected; + +$parse['mlst_data_types'] = '"; +$parse['mlst_data_types'] .= '"; +$parse['mlst_data_types'] .= '"; +$parse['mlst_data_types'] .= '"; +$parse['mlst_data_types'] .= '"; +$parse['mlst_data_types'] .= '"; +$parse['mlst_data_types'] .= '"; +$parse['mlst_data_types'] .= '"; +$parse['mlst_data_types'] .= '"; +$parse['mlst_data_types'] .= '"; +$parse['mlst_data_types'] .= '"; + +$parse['_PagesTotalCount'] = $MaxPage; +$parse['_PagesTotalCount_Pretty'] = prettyNumber($MaxPage); +$parse['_PagesCurrent_Pretty'] = prettyNumber($ViewPage); + +$parse['tbl_rows'] = ''; +$parse['mlst_title'] = $_Lang['mlst_title']; + +if($ViewPage < 1) +{ + $ViewPage = 1; +} + +$StartRec = (($ViewPage - 1) * $_PerPage); + +$GetMessages = "SELECT {{table}}.*, `users`.`username`, `users`.`authlevel`, `users`.`galaxy`, `users`.`system`, `users`.`planet`, `users2`.`username` as `username2` FROM {{table}} "; +$GetMessages .= "LEFT JOIN {{prefix}}users AS `users2` ON `id_owner` = `users2`.`id` "; +$GetMessages .= "LEFT JOIN {{prefix}}users as `users` ON `id_sender` = `users`.`id` "; +$GetMessages .= $WhereClausures; +$GetMessages .= " ORDER BY {{table}}.`time` DESC, {{table}}.`id` DESC "; +$GetMessages .= "LIMIT {$StartRec}, {$_PerPage};"; +$Messages = doquery($GetMessages, 'messages'); + +if($_GameConfig['enable_bbcode'] == 1) +{ + include($_EnginePath.'includes/functions/BBcodeFunction.php'); +} + +while($row = mysql_fetch_assoc($Messages)) +{ + $bloc = array(); + + if(!empty($ExcludedUsers)) + { + if(in_array($row['id_sender'], $ExcludedUsers) OR in_array($row['id_owner'], $ExcludedUsers)) + { + $parse['mlst_data_rows'] .= parsetemplate($DisallowTpl , $_Lang); + continue; + } + } + + if($row['id_sender'] == 0) + { + $MsgArray = json_decode($row['text'], true); + $row['from'] = (!empty($row['from']) ? $_Lang['msg_const']['senders']['system'][$row['from']] : ' '); + $row['subject'] = (!empty($row['subject']) ? $_Lang['msg_const']['subjects'][$row['subject']] : ' '); + if(empty($MsgArray['msg_text'])) + { + if(!empty($MsgArray['msg_id'])) + { + $row['text'] = vsprintf($_Lang['msg_const']['msgs'][$MsgArray['msg_id']], $MsgArray['args']); + } + else + { + $row['text'] = sprintf($_Lang['msg_const']['msgs']['err2'], $row['id']); + } + } + else + { + if((array)$MsgArray['msg_text'] === $MsgArray['msg_text']) + { + $row['text'] = implode('', innerReplace(multidim2onedim($MsgArray['msg_text']), $_Lang)); + } + else + { + $row['text'] = sprintf($_Lang['msg_const']['msgs']['err'], $row['id']); + } + } + } + else + { + $AddFrom = ''; + if(!empty($row['from'])) + { + $AddFrom = ' '.$row['from']; + } + if(CheckAuth('user', AUTHCHECK_HIGHER, $row)) + { + $row['from'] = $_Lang['msg_const']['senders']['rangs'][GetAuthLabel($row)].' '.$row['username'].$AddFrom; + $row['subject'] = stripslashes($row['subject']); + } + else + { + $row['from'] = $row['username'].$AddFrom; + $row['subject'] = stripslashes($row['subject']); + } + $row['from'] .= '
[ID: '.$row['id_sender'].']'; + + if(preg_match('/^\{COPY\_MSG\_\#([0-9]{1,})\}$/D', $row['text'], $row['matched'])) + { + $GetMsgCopies[$row['matched'][1]][] = $row['id']; + $bloc['mlst_status'][] = ''; + $bloc['mlst_copyID'] = "
[{$row['matched'][1]}]"; + } + else + { + if($_GameConfig['enable_bbcode'] == 1) + { + $row['text'] = bbcode(image($row['text'])); + } + $row['text'] = nl2br($row['text']); + } + } + if($row['read'] != 0) + { + $bloc['mlst_status'][] = ''; + } + if($row['deleted'] != 0) + { + $bloc['mlst_status'][] = ''; + } + $bloc['mlst_id'] = $row['id']; + if(isset($_POST['msg_id']) && $_POST['msg_id'] == $row['id']) + { + $bloc['mlst_rowcolor'] = 'lime'; + } + $bloc['mlst_from'] = $row['from']; + $bloc['mlst_to'] = "{$row['username2']}
[ID: {$row['id_owner']}]"; + $bloc['mlst_text'] = $row['text']; + if(!empty($bloc['mlst_status'])) + { + $bloc['mlst_status'] = implode('
', $bloc['mlst_status']); + } + else + { + $bloc['mlst_status'] = ' '; + } + $bloc['mlst_time'] = date('d.m.Y', $row['time']).'
'.date('H:i:s', $row['time']); + $parse['mlst_data_rows'][$row['id']] = $bloc; +} +if(empty($parse['mlst_data_rows'])) +{ + $parse['mlst_data_rows'] .= ''.$_Lang['Error_NoMsgFound'].'
('.$_Lang['Form_ResetFilters'].')'; + $parse['HideSelectedActionRow'] = ' style="display: none;"'; +} +else +{ + if(!empty($GetMsgCopies)) + { + $GetMsgCopiesIDs = implode(', ', array_keys($GetMsgCopies)); + $GetMsgCopiesQuery = "SELECT `id`, `subject`, `text` FROM {{table}} WHERE `id` IN ({$GetMsgCopiesIDs});"; + $GetMsgCopiesResult = doquery($GetMsgCopiesQuery, 'messages'); + if(mysql_num_rows($GetMsgCopiesResult) > 0) + { + while($GetMsgCopiesRow = mysql_fetch_assoc($GetMsgCopiesResult)) + { + $GetMsgCopiesData[$GetMsgCopiesRow['id']] = $GetMsgCopiesRow; + } + } + + foreach($GetMsgCopies as $CopyID => $ReplaceIDs) + { + if(!empty($GetMsgCopiesData[$CopyID])) + { + if($_GameConfig['enable_bbcode'] == 1) + { + $GetMsgCopiesData[$CopyID]['text'] = bbcode(image($GetMsgCopiesData[$CopyID]['text'])); + } + $GetMsgCopiesData[$CopyID]['text'] = nl2br($GetMsgCopiesData[$CopyID]['text']); + foreach($ReplaceIDs as $ReplaceID) + { + $parse['mlst_data_rows'][$ReplaceID]['mlst_text'] = $GetMsgCopiesData[$CopyID]['text']; + $parse['mlst_data_rows'][$ReplaceID]['mlst_subject'] = $GetMsgCopiesData[$CopyID]['subject']; + } + } + else + { + foreach($ReplaceIDs as $ReplaceID) + { + $parse['mlst_data_rows'][$ReplaceID]['mlst_text'] = $_Lang['Err_CopyNotFound']; + $parse['mlst_data_rows'][$ReplaceID]['mlst_subject'] = '-'; + } + } + } + } + + $JoinMsgs = ''; + foreach($parse['mlst_data_rows'] as $RowData) + { + $JoinMsgs .= parsetemplate($RowsTpl, $RowData); + } + + $parse['mlst_data_rows'] = $JoinMsgs; +} + +$parse['selected_user_id'] = $_POST['user_id']; +$display = parsetemplate($BodyTpl , $parse); + +display ($display, $_Lang['mlst_title'], false, '', true); + +?> diff --git a/admin/overview.php b/admin/overview.php index 9879db012..c4bb86b75 100644 --- a/admin/overview.php +++ b/admin/overview.php @@ -1,22 +1,22 @@ - \ No newline at end of file + diff --git a/admin/planets_resmanager.php b/admin/planets_resmanager.php index 2fc680792..e94ce47f9 100644 --- a/admin/planets_resmanager.php +++ b/admin/planets_resmanager.php @@ -1,274 +1,274 @@ - 'metal', 2 => 'crystal', 3 => 'deuterium'); - $Items_Resources_Keys = array_keys($Items_Resources); - $Items_Buildings = &$_Vars_ElementCategories['build']; - $Items_Fleet = &$_Vars_ElementCategories['fleet']; - $Items_Defense = &$_Vars_ElementCategories['defense']; - - $_ResLimit = 1000000000000000000000; - $Allowed_CMD = array('add', 'set', 'sub'); - $Allowed_Tabs = array - ( - 1 => &$Items_Resources_Keys, - 2 => &$Items_Buildings, - 3 => &$Items_Fleet, - 4 => &$Items_Defense - ); - - if(isset($_POST['sent']) && $_POST['sent'] == 1) - { - $PlanetID = round($_POST['planetID']); - $TabID = intval($_POST['tab']); - $ThisCMD = (isset($_POST['cmd']) ? $_POST['cmd'] : null); - - $_Lang['Insert_PreviousPlanetID'] = $PlanetID; - $_Lang['Insert_SelectCMD_'.$ThisCMD] = 'checked'; - $_Lang['Insert_DefaultTab'] = $TabID - 1; - - if($PlanetID > 0) - { - if(in_array($ThisCMD, $Allowed_CMD)) - { - if(in_array($TabID, array_keys($Allowed_Tabs))) - { - if(!empty($_POST['res'][$TabID])) - { - $Query_GetPlanet = ''; - $Query_GetPlanet .= "SELECT `pl`.`id`, `pl`.`name`, `pl`.`id_owner`, `user`.`username`, "; - $Query_GetPlanet .= "`pl`.`galaxy`, `pl`.`system`, `pl`.`planet`, `pl`.`planet_type` "; - $Query_GetPlanet .= "FROM {{table}} AS `pl` "; - $Query_GetPlanet .= "LEFT JOIN {{prefix}}users AS `user` ON `user`.`id` = `pl`.`id_owner` "; - $Query_GetPlanet .= "WHERE `pl`.`id` = {$PlanetID} LIMIT 1;"; - $Result_GetPlanet = doquery($Query_GetPlanet, 'planets', true); - if($Result_GetPlanet['id'] == $PlanetID) - { - foreach($_POST['res'][$TabID] as $ThisID => $ThisValue) - { - if(in_array($ThisID, $Allowed_Tabs[$TabID])) - { - if($ThisCMD == 'set' AND empty($ThisValue)) - { - continue; - } - if($TabID == 2 AND !in_array($ThisID, $_Vars_ElementCategories['buildOn'][$Result_GetPlanet['planet_type']])) - { - continue; - } - $ThisValue = round(str_replace('.', '', $ThisValue)); - if(($ThisCMD == 'set' AND $ThisValue >= 0) OR ($ThisCMD != 'set' AND $ThisValue > 0)) - { - if($ThisValue > $_ResLimit) - { - $ThisValue = $_ResLimit; - } - $Query_Update_Data[$ThisID] = $ThisValue; - } - } - } - - if(!empty($Query_Update_Data)) - { - if($ThisCMD == 'add') - { - $Query_Update = ''; - $Query_Update .= "UPDATE {{table}} SET "; - if($TabID == 1) - { - foreach($Query_Update_Data as $ThisID => $ThisValue) - { - $Query_Update_Array[] = "`{$Items_Resources[$ThisID]}` = `{$Items_Resources[$ThisID]}` + {$ThisValue}"; - } - } - else - { - foreach($Query_Update_Data as $ThisID => $ThisValue) - { - $Query_Update_Array[] = "`{$_Vars_GameElements[$ThisID]}` = `{$_Vars_GameElements[$ThisID]}` + {$ThisValue}"; - } - } - $Query_Update .= implode(',', $Query_Update_Array); - $Query_Update .= " WHERE `id` = {$PlanetID} LIMIT 1;"; - } - else if($ThisCMD == 'set') - { - $Query_Update = ''; - $Query_Update .= "UPDATE {{table}} SET "; - if($TabID == 1) - { - foreach($Query_Update_Data as $ThisID => $ThisValue) - { - $Query_Update_Array[] = "`{$Items_Resources[$ThisID]}` = {$ThisValue}"; - } - } - else - { - foreach($Query_Update_Data as $ThisID => $ThisValue) - { - $Query_Update_Array[] = "`{$_Vars_GameElements[$ThisID]}` = {$ThisValue}"; - } - } - $Query_Update .= implode(',', $Query_Update_Array); - $Query_Update .= " WHERE `id` = {$PlanetID} LIMIT 1;"; - } - else if($ThisCMD == 'sub') - { - if($TabID == 1) - { - foreach($Query_Update_Data as $ThisID => $ThisValue) - { - $Query_Update_Fields[] = "`{$Items_Resources[$ThisID]}`"; - $Query_Update_Values[] = $ThisValue; - $Query_Update_Set[] = "`{$Items_Resources[$ThisID]}` = IF(VALUES(`{$Items_Resources[$ThisID]}`) > `{$Items_Resources[$ThisID]}`, 0, `{$Items_Resources[$ThisID]}` - VALUES(`{$Items_Resources[$ThisID]}`))"; - } - } - else - { - foreach($Query_Update_Data as $ThisID => $ThisValue) - { - $Query_Update_Fields[] = "`{$_Vars_GameElements[$ThisID]}`"; - $Query_Update_Values[] = $ThisValue; - $Query_Update_Set[] = "`{$_Vars_GameElements[$ThisID]}` = IF(VALUES(`{$_Vars_GameElements[$ThisID]}`) > `{$_Vars_GameElements[$ThisID]}`, 0, `{$_Vars_GameElements[$ThisID]}` - VALUES(`{$_Vars_GameElements[$ThisID]}`))"; - } - } - $Query_Update = ''; - $Query_Update .= "INSERT INTO {{table}} (`id`, ".implode(', ', $Query_Update_Fields).") "; - $Query_Update .= "VALUES ({$PlanetID}, ".implode(', ', $Query_Update_Values).") "; - $Query_Update .= "ON DUPLICATE KEY UPDATE "; - $Query_Update .= implode(',', $Query_Update_Set); - } - doquery($Query_Update, 'planets'); - if(mysql_affected_rows() > 0) - { - $_MsgBox = array - ( - 'color' => 'lime', - 'text' => sprintf - ( - $_Lang['MsgBox_UpdateOK'], - ($Result_GetPlanet['planet_type'] == 1 ? $_Lang['MsgBox_UpdateOK_Planet'] : $_Lang['MsgBox_UpdateOK_Moon']), - $Result_GetPlanet['name'], $Result_GetPlanet['galaxy'], $Result_GetPlanet['system'], $Result_GetPlanet['planet'], - $Result_GetPlanet['id'], - $Result_GetPlanet['id_owner'], $Result_GetPlanet['username'], $Result_GetPlanet['id_owner'], - prettyNumber(count($Query_Update_Data)) - ) - ); - } - else - { - $_MsgBox = array - ( - 'color' => 'orange', - 'text' => sprintf - ( - $_Lang['MsgBox_UpdateNotAffected'], - ($Result_GetPlanet['planet_type'] == 1 ? $_Lang['MsgBox_UpdateOK_Planet'] : $_Lang['MsgBox_UpdateOK_Moon']), - $Result_GetPlanet['name'], $Result_GetPlanet['galaxy'], $Result_GetPlanet['system'], $Result_GetPlanet['planet'], - $Result_GetPlanet['id'], - $Result_GetPlanet['id_owner'], $Result_GetPlanet['username'], $Result_GetPlanet['id_owner'] - ) - ); - } - } - else - { - $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_BadInput']); - } - } - else - { - $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_PlanetDoesntExist']); - } - } - else - { - $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_EmptyInput']); - } - } - else - { - $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_BadTabID']); - } - } - else - { - $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_BadCMD']); - } - } - else - { - $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_BadPlanetID']); - } - } - - $_Lang['Insert_Rows_Res'] = ''; - foreach($Items_Resources as $ItemID => $ItemName) - { - $_Lang['Insert_Rows_Res'] .= parsetemplate($TPL_Row, array - ( - 'Name' => $_Lang[ucfirst($ItemName)], - 'TabNo' => 1, - 'ResID' => $ItemID - )); - } - $_Lang['Insert_Rows_Buildings'] = ''; - foreach($Items_Buildings as $ItemID) - { - $_Lang['Insert_Rows_Buildings'] .= parsetemplate($TPL_Row, array - ( - 'Name' => "{$_Lang['tech'][$ItemID]} [#{$ItemID}]", - 'TabNo' => 2, - 'ResID' => $ItemID - )); - } - $_Lang['Insert_Rows_Fleet'] = ''; - foreach($Items_Fleet as $ItemID) - { - $_Lang['Insert_Rows_Fleet'] .= parsetemplate($TPL_Row, array - ( - 'Name' => "{$_Lang['tech'][$ItemID]} [#{$ItemID}]", - 'TabNo' => 3, - 'ResID' => $ItemID - )); - } - $_Lang['Insert_Rows_Defense'] = ''; - foreach($Items_Defense as $ItemID) - { - $_Lang['Insert_Rows_Defense'] .= parsetemplate($TPL_Row, array - ( - 'Name' => "{$_Lang['tech'][$ItemID]} [#{$ItemID}]", - 'TabNo' => 4, - 'ResID' => $ItemID - )); - } - - if(!empty($_MsgBox)) - { - $_Lang['MsgBox_Text'] = $_MsgBox['text']; - $_Lang['MsgBox_Color'] = $_MsgBox['color']; - } - else - { - $_Lang['MsgBox_Text'] = ' '; - } - - display(parsetemplate($TPL_Body, $_Lang), $_Lang['PageTitle'], false, true); - -?> \ No newline at end of file + 'metal', 2 => 'crystal', 3 => 'deuterium'); +$Items_Resources_Keys = array_keys($Items_Resources); +$Items_Buildings = &$_Vars_ElementCategories['build']; +$Items_Fleet = &$_Vars_ElementCategories['fleet']; +$Items_Defense = &$_Vars_ElementCategories['defense']; + +$_ResLimit = 1000000000000000000000; +$Allowed_CMD = array('add', 'set', 'sub'); +$Allowed_Tabs = array +( + 1 => &$Items_Resources_Keys, + 2 => &$Items_Buildings, + 3 => &$Items_Fleet, + 4 => &$Items_Defense +); + +if(isset($_POST['sent']) && $_POST['sent'] == 1) +{ + $PlanetID = round($_POST['planetID']); + $TabID = intval($_POST['tab']); + $ThisCMD = (isset($_POST['cmd']) ? $_POST['cmd'] : null); + + $_Lang['Insert_PreviousPlanetID'] = $PlanetID; + $_Lang['Insert_SelectCMD_'.$ThisCMD] = 'checked'; + $_Lang['Insert_DefaultTab'] = $TabID - 1; + + if($PlanetID > 0) + { + if(in_array($ThisCMD, $Allowed_CMD)) + { + if(in_array($TabID, array_keys($Allowed_Tabs))) + { + if(!empty($_POST['res'][$TabID])) + { + $Query_GetPlanet = ''; + $Query_GetPlanet .= "SELECT `pl`.`id`, `pl`.`name`, `pl`.`id_owner`, `user`.`username`, "; + $Query_GetPlanet .= "`pl`.`galaxy`, `pl`.`system`, `pl`.`planet`, `pl`.`planet_type` "; + $Query_GetPlanet .= "FROM {{table}} AS `pl` "; + $Query_GetPlanet .= "LEFT JOIN {{prefix}}users AS `user` ON `user`.`id` = `pl`.`id_owner` "; + $Query_GetPlanet .= "WHERE `pl`.`id` = {$PlanetID} LIMIT 1;"; + $Result_GetPlanet = doquery($Query_GetPlanet, 'planets', true); + if($Result_GetPlanet['id'] == $PlanetID) + { + foreach($_POST['res'][$TabID] as $ThisID => $ThisValue) + { + if(in_array($ThisID, $Allowed_Tabs[$TabID])) + { + if($ThisCMD == 'set' AND empty($ThisValue)) + { + continue; + } + if($TabID == 2 AND !in_array($ThisID, $_Vars_ElementCategories['buildOn'][$Result_GetPlanet['planet_type']])) + { + continue; + } + $ThisValue = round(str_replace('.', '', $ThisValue)); + if(($ThisCMD == 'set' AND $ThisValue >= 0) OR ($ThisCMD != 'set' AND $ThisValue > 0)) + { + if($ThisValue > $_ResLimit) + { + $ThisValue = $_ResLimit; + } + $Query_Update_Data[$ThisID] = $ThisValue; + } + } + } + + if(!empty($Query_Update_Data)) + { + if($ThisCMD == 'add') + { + $Query_Update = ''; + $Query_Update .= "UPDATE {{table}} SET "; + if($TabID == 1) + { + foreach($Query_Update_Data as $ThisID => $ThisValue) + { + $Query_Update_Array[] = "`{$Items_Resources[$ThisID]}` = `{$Items_Resources[$ThisID]}` + {$ThisValue}"; + } + } + else + { + foreach($Query_Update_Data as $ThisID => $ThisValue) + { + $Query_Update_Array[] = "`{$_Vars_GameElements[$ThisID]}` = `{$_Vars_GameElements[$ThisID]}` + {$ThisValue}"; + } + } + $Query_Update .= implode(',', $Query_Update_Array); + $Query_Update .= " WHERE `id` = {$PlanetID} LIMIT 1;"; + } + else if($ThisCMD == 'set') + { + $Query_Update = ''; + $Query_Update .= "UPDATE {{table}} SET "; + if($TabID == 1) + { + foreach($Query_Update_Data as $ThisID => $ThisValue) + { + $Query_Update_Array[] = "`{$Items_Resources[$ThisID]}` = {$ThisValue}"; + } + } + else + { + foreach($Query_Update_Data as $ThisID => $ThisValue) + { + $Query_Update_Array[] = "`{$_Vars_GameElements[$ThisID]}` = {$ThisValue}"; + } + } + $Query_Update .= implode(',', $Query_Update_Array); + $Query_Update .= " WHERE `id` = {$PlanetID} LIMIT 1;"; + } + else if($ThisCMD == 'sub') + { + if($TabID == 1) + { + foreach($Query_Update_Data as $ThisID => $ThisValue) + { + $Query_Update_Fields[] = "`{$Items_Resources[$ThisID]}`"; + $Query_Update_Values[] = $ThisValue; + $Query_Update_Set[] = "`{$Items_Resources[$ThisID]}` = IF(VALUES(`{$Items_Resources[$ThisID]}`) > `{$Items_Resources[$ThisID]}`, 0, `{$Items_Resources[$ThisID]}` - VALUES(`{$Items_Resources[$ThisID]}`))"; + } + } + else + { + foreach($Query_Update_Data as $ThisID => $ThisValue) + { + $Query_Update_Fields[] = "`{$_Vars_GameElements[$ThisID]}`"; + $Query_Update_Values[] = $ThisValue; + $Query_Update_Set[] = "`{$_Vars_GameElements[$ThisID]}` = IF(VALUES(`{$_Vars_GameElements[$ThisID]}`) > `{$_Vars_GameElements[$ThisID]}`, 0, `{$_Vars_GameElements[$ThisID]}` - VALUES(`{$_Vars_GameElements[$ThisID]}`))"; + } + } + $Query_Update = ''; + $Query_Update .= "INSERT INTO {{table}} (`id`, ".implode(', ', $Query_Update_Fields).") "; + $Query_Update .= "VALUES ({$PlanetID}, ".implode(', ', $Query_Update_Values).") "; + $Query_Update .= "ON DUPLICATE KEY UPDATE "; + $Query_Update .= implode(',', $Query_Update_Set); + } + doquery($Query_Update, 'planets'); + if(mysql_affected_rows() > 0) + { + $_MsgBox = array + ( + 'color' => 'lime', + 'text' => sprintf + ( + $_Lang['MsgBox_UpdateOK'], + ($Result_GetPlanet['planet_type'] == 1 ? $_Lang['MsgBox_UpdateOK_Planet'] : $_Lang['MsgBox_UpdateOK_Moon']), + $Result_GetPlanet['name'], $Result_GetPlanet['galaxy'], $Result_GetPlanet['system'], $Result_GetPlanet['planet'], + $Result_GetPlanet['id'], + $Result_GetPlanet['id_owner'], $Result_GetPlanet['username'], $Result_GetPlanet['id_owner'], + prettyNumber(count($Query_Update_Data)) + ) + ); + } + else + { + $_MsgBox = array + ( + 'color' => 'orange', + 'text' => sprintf + ( + $_Lang['MsgBox_UpdateNotAffected'], + ($Result_GetPlanet['planet_type'] == 1 ? $_Lang['MsgBox_UpdateOK_Planet'] : $_Lang['MsgBox_UpdateOK_Moon']), + $Result_GetPlanet['name'], $Result_GetPlanet['galaxy'], $Result_GetPlanet['system'], $Result_GetPlanet['planet'], + $Result_GetPlanet['id'], + $Result_GetPlanet['id_owner'], $Result_GetPlanet['username'], $Result_GetPlanet['id_owner'] + ) + ); + } + } + else + { + $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_BadInput']); + } + } + else + { + $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_PlanetDoesntExist']); + } + } + else + { + $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_EmptyInput']); + } + } + else + { + $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_BadTabID']); + } + } + else + { + $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_BadCMD']); + } + } + else + { + $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_BadPlanetID']); + } +} + +$_Lang['Insert_Rows_Res'] = ''; +foreach($Items_Resources as $ItemID => $ItemName) +{ + $_Lang['Insert_Rows_Res'] .= parsetemplate($TPL_Row, array + ( + 'Name' => $_Lang[ucfirst($ItemName)], + 'TabNo' => 1, + 'ResID' => $ItemID + )); +} +$_Lang['Insert_Rows_Buildings'] = ''; +foreach($Items_Buildings as $ItemID) +{ + $_Lang['Insert_Rows_Buildings'] .= parsetemplate($TPL_Row, array + ( + 'Name' => "{$_Lang['tech'][$ItemID]} [#{$ItemID}]", + 'TabNo' => 2, + 'ResID' => $ItemID + )); +} +$_Lang['Insert_Rows_Fleet'] = ''; +foreach($Items_Fleet as $ItemID) +{ + $_Lang['Insert_Rows_Fleet'] .= parsetemplate($TPL_Row, array + ( + 'Name' => "{$_Lang['tech'][$ItemID]} [#{$ItemID}]", + 'TabNo' => 3, + 'ResID' => $ItemID + )); +} +$_Lang['Insert_Rows_Defense'] = ''; +foreach($Items_Defense as $ItemID) +{ + $_Lang['Insert_Rows_Defense'] .= parsetemplate($TPL_Row, array + ( + 'Name' => "{$_Lang['tech'][$ItemID]} [#{$ItemID}]", + 'TabNo' => 4, + 'ResID' => $ItemID + )); +} + +if(!empty($_MsgBox)) +{ + $_Lang['MsgBox_Text'] = $_MsgBox['text']; + $_Lang['MsgBox_Color'] = $_MsgBox['color']; +} +else +{ + $_Lang['MsgBox_Text'] = ' '; +} + +display(parsetemplate($TPL_Body, $_Lang), $_Lang['PageTitle'], false, true); + +?> diff --git a/admin/reduceban.php b/admin/reduceban.php index 69355e8a9..8077fc3e2 100644 --- a/admin/reduceban.php +++ b/admin/reduceban.php @@ -1,201 +1,201 @@ - $Now) - { - $DoSearch = true; - } - else - { - $_Lang['InsertInfoBoxText'] = $_Lang['Error_BadNewEndTime']; - } - } - else if($_POST['reduce_type'] == '02') - { - // Reduce by given period of time - $Opt_ReduceType = 2; - $Opt_Period = intval($_POST['period_days']) * TIME_DAY; - $Opt_Period += intval($_POST['period_hours']) * 3600; - $Opt_Period += intval($_POST['period_mins']) * 60; - $Opt_Period += intval($_POST['period_secs']); - - if($Opt_Period > 0) - { - $DoSearch = true; - } - else - { - $_Lang['InsertInfoBoxText'] = $_Lang['Error_BadPeriod']; - } - } - } - else - { - $_Lang['InsertInfoBoxText'] = $_Lang['Error_BadType']; - } - - if(isset($DoSearch)) - { - if(!empty($_POST['users'])) - { - $UserErrors['badID'] = 0; - $UserErrors['badNick'] = 0; - - $Users = explode(',', $_POST['users']); - foreach($Users as $UserData) - { - $UserData = trim($UserData); - if(strstr($UserData, '[') !== FALSE) - { - if(preg_match('/^\[[0-9]{1,20}\]$/D', $UserData)) - { - $GetUsers['id'][] = trim($UserData, '[]'); - } - else - { - $UserErrors['badID'] += 1; - } - } - else - { - if(preg_match(REGEXP_USERNAME_ABSOLUTE, $UserData)) - { - $GetUsers['name'][] = "'{$UserData}'"; - } - else - { - $UserErrors['badNick'] += 1; - } - } - } - if(!empty($GetUsers)) - { - if(!empty($GetUsers['id'])) - { - $Where[] = "`id` IN (".implode(', ', $GetUsers['id']).")"; - } - if(!empty($GetUsers['name'])) - { - $Where[] = "`username` IN (".implode(', ', $GetUsers['name']).")"; - } - - $CheckUsers = doquery("SELECT `id`, `username`, `is_banned`, `ban_endtime` FROM {{table}} WHERE ".implode(' OR ', $Where).";", 'users'); - $UpdateUsers = array(); - if(mysql_num_rows($CheckUsers) > 0) - { - while($Data = mysql_fetch_assoc($CheckUsers)) - { - if($Data['is_banned'] == 1 AND $Data['ban_endtime'] > $Now) - { - if($Opt_ReduceType == 1 AND $Opt_NewEndTime >= $Data['ban_endtime']) - { - continue; - } - else if($Opt_ReduceType == 2 AND ($Data['ban_endtime'] - $Opt_Period) <= $Now) - { - continue; - } - $UpdateUsers[$Data['id']] = $Data; - } - } - } - if(!empty($UpdateUsers)) - { - $UpdatedCount = count($UpdateUsers); - - if($Opt_ReduceType == 1) - { - $UpdateFields[] = "`vacation_endtime` = IF((`is_onvacation` = 1 AND `vacation_type` = 1), `vacation_endtime` - (`ban_endtime` - {$Opt_NewEndTime}), `vacation_endtime`)"; - $UpdateFields[] = "`ban_endtime` = {$Opt_NewEndTime}"; - $UpdateBanRows[] = "`EndTime` = {$Opt_NewEndTime}"; - } - elseif($Opt_ReduceType == 2) - { - $UpdateFields[] = "`vacation_endtime` = IF((`is_onvacation` = 1 AND `vacation_type` = 1), `vacation_endtime` - {$Opt_Period}, `vacation_endtime`)"; - $UpdateFields[] = "`ban_endtime` = `ban_endtime` - {$Opt_Period}"; - $UpdateBanRows[] = "`EndTime` = `EndTime` - {$Opt_Period}"; - } - - $UserIDs = implode(', ', array_keys($UpdateUsers)); - doquery("UPDATE {{table}} SET ".implode(', ', $UpdateFields)." WHERE `id` IN ({$UserIDs});", 'users'); - doquery("UPDATE {{table}} SET ".implode(', ', $UpdateBanRows)." WHERE `Active` = 1 AND `EndTime` > {$Now} AND `UserID` IN ({$UserIDs});", 'bans'); - - $UserLinkTPL = gettemplate('admin/banuser_userlink'); - foreach($UpdateUsers as $UserID => $UserData) - { - $UserLinks[] = parsetemplate($UserLinkTPL, array('ID' => $UserID, 'Username' => $UserData['username'])); - } - $UserLinks = implode(', ', $UserLinks); - $_Lang['InsertInfoBoxText'] = sprintf(($UpdatedCount > 1 ? $_Lang['Msg_UpdateMOK'] : $_Lang['Msg_Update1OK']), $UserLinks); - $_Lang['InsertInfoBoxColor'] = 'lime'; - $_Lang['Insert_SearchBox'] = ''; - } - else - { - $_Lang['InsertInfoBoxText'] = $_Lang['Error_NoOne2Update']; - } - } - else - { - $_Lang['InsertInfoBoxText'] = $_Lang['Error_BadSearch']; - } - } - else - { - $_Lang['InsertInfoBoxText'] = $_Lang['Error_EmptySearch']; - } - } - } - - if(!empty($_GET['ids'])) - { - $InsertIDs = explode(',', $_GET['ids']); - foreach($InsertIDs as $ThisID) - { - $_Lang['InsertUsernames'][] = "[{$ThisID}]"; - } - $_Lang['InsertUsernames'] = implode(',', $_Lang['InsertUsernames']); - } - else if(!empty($_GET['user'])) - { - $_Lang['InsertUsernames'] = $_GET['user']; - } - - $Page = parsetemplate($TPL, $_Lang); - display($Page, $_Lang['Page_Title'], false, true); - -?> \ No newline at end of file + $Now) + { + $DoSearch = true; + } + else + { + $_Lang['InsertInfoBoxText'] = $_Lang['Error_BadNewEndTime']; + } + } + else if($_POST['reduce_type'] == '02') + { + // Reduce by given period of time + $Opt_ReduceType = 2; + $Opt_Period = intval($_POST['period_days']) * TIME_DAY; + $Opt_Period += intval($_POST['period_hours']) * 3600; + $Opt_Period += intval($_POST['period_mins']) * 60; + $Opt_Period += intval($_POST['period_secs']); + + if($Opt_Period > 0) + { + $DoSearch = true; + } + else + { + $_Lang['InsertInfoBoxText'] = $_Lang['Error_BadPeriod']; + } + } + } + else + { + $_Lang['InsertInfoBoxText'] = $_Lang['Error_BadType']; + } + + if(isset($DoSearch)) + { + if(!empty($_POST['users'])) + { + $UserErrors['badID'] = 0; + $UserErrors['badNick'] = 0; + + $Users = explode(',', $_POST['users']); + foreach($Users as $UserData) + { + $UserData = trim($UserData); + if(strstr($UserData, '[') !== FALSE) + { + if(preg_match('/^\[[0-9]{1,20}\]$/D', $UserData)) + { + $GetUsers['id'][] = trim($UserData, '[]'); + } + else + { + $UserErrors['badID'] += 1; + } + } + else + { + if(preg_match(REGEXP_USERNAME_ABSOLUTE, $UserData)) + { + $GetUsers['name'][] = "'{$UserData}'"; + } + else + { + $UserErrors['badNick'] += 1; + } + } + } + if(!empty($GetUsers)) + { + if(!empty($GetUsers['id'])) + { + $Where[] = "`id` IN (".implode(', ', $GetUsers['id']).")"; + } + if(!empty($GetUsers['name'])) + { + $Where[] = "`username` IN (".implode(', ', $GetUsers['name']).")"; + } + + $CheckUsers = doquery("SELECT `id`, `username`, `is_banned`, `ban_endtime` FROM {{table}} WHERE ".implode(' OR ', $Where).";", 'users'); + $UpdateUsers = array(); + if(mysql_num_rows($CheckUsers) > 0) + { + while($Data = mysql_fetch_assoc($CheckUsers)) + { + if($Data['is_banned'] == 1 AND $Data['ban_endtime'] > $Now) + { + if($Opt_ReduceType == 1 AND $Opt_NewEndTime >= $Data['ban_endtime']) + { + continue; + } + else if($Opt_ReduceType == 2 AND ($Data['ban_endtime'] - $Opt_Period) <= $Now) + { + continue; + } + $UpdateUsers[$Data['id']] = $Data; + } + } + } + if(!empty($UpdateUsers)) + { + $UpdatedCount = count($UpdateUsers); + + if($Opt_ReduceType == 1) + { + $UpdateFields[] = "`vacation_endtime` = IF((`is_onvacation` = 1 AND `vacation_type` = 1), `vacation_endtime` - (`ban_endtime` - {$Opt_NewEndTime}), `vacation_endtime`)"; + $UpdateFields[] = "`ban_endtime` = {$Opt_NewEndTime}"; + $UpdateBanRows[] = "`EndTime` = {$Opt_NewEndTime}"; + } + elseif($Opt_ReduceType == 2) + { + $UpdateFields[] = "`vacation_endtime` = IF((`is_onvacation` = 1 AND `vacation_type` = 1), `vacation_endtime` - {$Opt_Period}, `vacation_endtime`)"; + $UpdateFields[] = "`ban_endtime` = `ban_endtime` - {$Opt_Period}"; + $UpdateBanRows[] = "`EndTime` = `EndTime` - {$Opt_Period}"; + } + + $UserIDs = implode(', ', array_keys($UpdateUsers)); + doquery("UPDATE {{table}} SET ".implode(', ', $UpdateFields)." WHERE `id` IN ({$UserIDs});", 'users'); + doquery("UPDATE {{table}} SET ".implode(', ', $UpdateBanRows)." WHERE `Active` = 1 AND `EndTime` > {$Now} AND `UserID` IN ({$UserIDs});", 'bans'); + + $UserLinkTPL = gettemplate('admin/banuser_userlink'); + foreach($UpdateUsers as $UserID => $UserData) + { + $UserLinks[] = parsetemplate($UserLinkTPL, array('ID' => $UserID, 'Username' => $UserData['username'])); + } + $UserLinks = implode(', ', $UserLinks); + $_Lang['InsertInfoBoxText'] = sprintf(($UpdatedCount > 1 ? $_Lang['Msg_UpdateMOK'] : $_Lang['Msg_Update1OK']), $UserLinks); + $_Lang['InsertInfoBoxColor'] = 'lime'; + $_Lang['Insert_SearchBox'] = ''; + } + else + { + $_Lang['InsertInfoBoxText'] = $_Lang['Error_NoOne2Update']; + } + } + else + { + $_Lang['InsertInfoBoxText'] = $_Lang['Error_BadSearch']; + } + } + else + { + $_Lang['InsertInfoBoxText'] = $_Lang['Error_EmptySearch']; + } + } +} + +if(!empty($_GET['ids'])) +{ + $InsertIDs = explode(',', $_GET['ids']); + foreach($InsertIDs as $ThisID) + { + $_Lang['InsertUsernames'][] = "[{$ThisID}]"; + } + $_Lang['InsertUsernames'] = implode(',', $_Lang['InsertUsernames']); +} +else if(!empty($_GET['user'])) +{ + $_Lang['InsertUsernames'] = $_GET['user']; +} + +$Page = parsetemplate($TPL, $_Lang); +display($Page, $_Lang['Page_Title'], false, true); + +?> diff --git a/admin/report_list.php b/admin/report_list.php index 66ec30faa..3798bb259 100644 --- a/admin/report_list.php +++ b/admin/report_list.php @@ -1,141 +1,141 @@ - 0) - { - $GetDeclaration = doquery("SELECT `id`, `status` FROM {{table}} WHERE `id` = {$ID} LIMIT 1;", 'reports'); - if(mysql_num_rows($GetDeclaration) == 1) - { - switch($_GET['action']) - { - case 'delete': - doquery("DELETE FROM {{table}} WHERE `id` = {$ID};", 'reports'); - $MSG = $_Lang['Report_deleted']; - $MSGColor = 'lime'; - break; - case 'change_status': - $Status = isset($_GET['set_status']) ? intval($_GET['set_status']) : -1; - if($Status < 0) - { - $MSG = $_Lang['Report_no_status_given']; - } - else - { - doquery("UPDATE {{table}} SET `status` = {$Status} WHERE `id` = {$ID};", 'reports'); - $MSG = $_Lang['Report_status_changed']; - $MSGColor = 'lime'; - } - break; - } - } - else - { - $MSG = $_Lang['Report_noexist']; - } - } - else - { - $MSG = $_Lang['No_id_given']; - } - } - - $ShowAllWhere = ''; - if($ShowAll == '0') - { - $ShowAllWhere = "WHERE `status` NOT IN (9,10)"; - } - $query = doquery("SELECT {{table}}.*, `users`.`username`, `users1`.`username` AS `reported_user` FROM {{table}} LEFT JOIN {{prefix}}users AS `users` ON `sender_id` = `users`.`id` LEFT JOIN {{prefix}}users AS `users1` ON `report_user` = `users1`.`id` {$ShowAllWhere} ORDER BY {{table}}.`date` DESC;", 'reports'); - - $parse = $_Lang; - $parse['adm_ul_table'] = ''; - if(!empty($MSG)) - { - $parse['system_msg'] = ''.$MSG.'
'; - } - - if(mysql_num_rows($query) > 0) - { - while($u = mysql_fetch_assoc($query)) - { - $Bloc['data_id'] = $u['id']; - $Bloc['data_date'] = date('d.m.Y', $u['date']).'
'.date('H:i:s', $u['date']).''; - $Bloc['data_sender'] = $u['username'].'
(#'.$u['sender_id'].')'; - $Bloc['sender_id'] = $u['sender_id']; - $Bloc['data_type'] = $TypeList[($u['report_type'] - 1)]; - $Bloc['data_element'] = (($u['report_element'] > 0) ? '#'.$u['report_element'] : ' - '); - if(in_array($u['report_type'], array(1, 5))) - { - $Bloc['data_element'] = ''.$Bloc['data_element'].''; - } - else if($u['report_type'] == 9) - { - $Bloc['data_element'] = ''.$Bloc['data_element'].''; - } - $Bloc['data_user'] = (($u['report_user'] > 0) ? $u['reported_user'].'
(#'.$u['report_user'].')' : ' - '); - $Bloc['report_user'] = $u['report_user']; - $Bloc['data_info'] = (!empty($u['user_info']) ? nl2br($u['user_info']) : '-'); - $Bloc['data_status'] = $StatusList[$u['status']]; - $Bloc['showall'] = $ShowAll; - $Bloc['msg_answer_subject'] = sprintf($_Lang['Report_reply_subject'], $u['id']); - $Bloc['msg_answer_input'] = $_Lang['Report_reply_input']; - if($u['report_type'] == 2) - { - $Bloc['data_datebash'] = date('Y-m-d', $u['date']); - } - else - { - $Bloc['Hide_NoBash'] = 'hide'; - } - - $parse['adm_ul_table'] .= parsetemplate($RowsTPL, $Bloc ); - } - } - else - { - $parse['adm_ul_table'] = ''.$_Lang['Report_noreports'].''; - } - - $page = parsetemplate($PageTPL, $parse); - display($page, $_Lang['Report_list_title'], false, true); - -?> \ No newline at end of file + 0) + { + $GetDeclaration = doquery("SELECT `id`, `status` FROM {{table}} WHERE `id` = {$ID} LIMIT 1;", 'reports'); + if(mysql_num_rows($GetDeclaration) == 1) + { + switch($_GET['action']) + { + case 'delete': + doquery("DELETE FROM {{table}} WHERE `id` = {$ID};", 'reports'); + $MSG = $_Lang['Report_deleted']; + $MSGColor = 'lime'; + break; + case 'change_status': + $Status = isset($_GET['set_status']) ? intval($_GET['set_status']) : -1; + if($Status < 0) + { + $MSG = $_Lang['Report_no_status_given']; + } + else + { + doquery("UPDATE {{table}} SET `status` = {$Status} WHERE `id` = {$ID};", 'reports'); + $MSG = $_Lang['Report_status_changed']; + $MSGColor = 'lime'; + } + break; + } + } + else + { + $MSG = $_Lang['Report_noexist']; + } + } + else + { + $MSG = $_Lang['No_id_given']; + } +} + +$ShowAllWhere = ''; +if($ShowAll == '0') +{ + $ShowAllWhere = "WHERE `status` NOT IN (9,10)"; +} +$query = doquery("SELECT {{table}}.*, `users`.`username`, `users1`.`username` AS `reported_user` FROM {{table}} LEFT JOIN {{prefix}}users AS `users` ON `sender_id` = `users`.`id` LEFT JOIN {{prefix}}users AS `users1` ON `report_user` = `users1`.`id` {$ShowAllWhere} ORDER BY {{table}}.`date` DESC;", 'reports'); + +$parse = $_Lang; +$parse['adm_ul_table'] = ''; +if(!empty($MSG)) +{ + $parse['system_msg'] = ''.$MSG.'
'; +} + +if(mysql_num_rows($query) > 0) +{ + while($u = mysql_fetch_assoc($query)) + { + $Bloc['data_id'] = $u['id']; + $Bloc['data_date'] = date('d.m.Y', $u['date']).'
'.date('H:i:s', $u['date']).''; + $Bloc['data_sender'] = $u['username'].'
(#'.$u['sender_id'].')'; + $Bloc['sender_id'] = $u['sender_id']; + $Bloc['data_type'] = $TypeList[($u['report_type'] - 1)]; + $Bloc['data_element'] = (($u['report_element'] > 0) ? '#'.$u['report_element'] : ' - '); + if(in_array($u['report_type'], array(1, 5))) + { + $Bloc['data_element'] = ''.$Bloc['data_element'].''; + } + else if($u['report_type'] == 9) + { + $Bloc['data_element'] = ''.$Bloc['data_element'].''; + } + $Bloc['data_user'] = (($u['report_user'] > 0) ? $u['reported_user'].'
(#'.$u['report_user'].')' : ' - '); + $Bloc['report_user'] = $u['report_user']; + $Bloc['data_info'] = (!empty($u['user_info']) ? nl2br($u['user_info']) : '-'); + $Bloc['data_status'] = $StatusList[$u['status']]; + $Bloc['showall'] = $ShowAll; + $Bloc['msg_answer_subject'] = sprintf($_Lang['Report_reply_subject'], $u['id']); + $Bloc['msg_answer_input'] = $_Lang['Report_reply_input']; + if($u['report_type'] == 2) + { + $Bloc['data_datebash'] = date('Y-m-d', $u['date']); + } + else + { + $Bloc['Hide_NoBash'] = 'hide'; + } + + $parse['adm_ul_table'] .= parsetemplate($RowsTPL, $Bloc ); + } +} +else +{ + $parse['adm_ul_table'] = ''.$_Lang['Report_noreports'].''; +} + +$page = parsetemplate($PageTPL, $parse); +display($page, $_Lang['Report_list_title'], false, true); + +?> diff --git a/admin/scripts/index.php b/admin/scripts/index.php index b0c9fceef..bc99142d1 100644 --- a/admin/scripts/index.php +++ b/admin/scripts/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/admin/scripts/script.createUserDevDump.php b/admin/scripts/script.createUserDevDump.php index d6d604bcb..d5bf7e61a 100644 --- a/admin/scripts/script.createUserDevDump.php +++ b/admin/scripts/script.createUserDevDump.php @@ -1,190 +1,190 @@ - 0) -{ - $WhereClausure1 = " WHERE `id` = {$SelectedUID}"; - $WhereClausure2 = " WHERE `id_owner` = {$SelectedUID}"; - $WhereClausure3 = " WHERE `fleet_owner` = {$SelectedUID}"; -} - -$GetUsers = doquery("SELECT * FROM {{table}}{$WhereClausure1};", 'users'); -$GetPlanets = doquery("SELECT * FROM {{table}}{$WhereClausure2};", 'planets'); -$GetFleets = doquery("SELECT * FROM {{table}}{$WhereClausure3};", 'fleets'); - -if(mysql_num_rows($GetUsers) > 0) -{ - while($UserData = mysql_fetch_assoc($GetUsers)) - { - $DevDump[$UserData['id']] = array('planets' => array(), 'techs' => array(), 'inflight' => array()); - $Point = &$DevDump[$UserData['id']]['techs']; - foreach($_Vars_ElementCategories['tech'] as $TechID) - { - if($UserData[$_Vars_GameElements[$TechID]] > 0) - { - $Point[$TechID] = $UserData[$_Vars_GameElements[$TechID]]; - } - } - } - - if(mysql_num_rows($GetPlanets) > 0) - { - while($PlanetData = mysql_fetch_assoc($GetPlanets)) - { - if($PlanetData['id_owner'] <= 0) - { - continue; - } - $Point = &$DevDump[$PlanetData['id_owner']]; - - $Point['planets'][$PlanetData['id']]['pt'] = $PlanetData['planet_type']; - $Point['planets'][$PlanetData['id']]['t'] = $PlanetData['temp_max']; - $Point['planets'][$PlanetData['id']]['lu'] = $PlanetData['last_update']; - $Point['planets'][$PlanetData['id']]['res'] = floor($PlanetData['metal']).','.floor($PlanetData['crystal']).','.floor($PlanetData['deuterium']); - - - foreach($_Vars_ElementCategories as $Key => $Array) - { - if(in_array($Key, array('tech', 'buildOn', 'units'))) - { - continue; - } - if($Key != 'build') - { - if($Key != 'prod') - { - foreach($Array as $ElementID) - { - if(isset($PlanetData[$_Vars_GameElements[$ElementID]]) && $PlanetData[$_Vars_GameElements[$ElementID]] > 0) - { - $Point['planets'][$PlanetData['id']]['f'][] = "{$ElementID},{$PlanetData[$_Vars_GameElements[$ElementID]]}"; - } - } - } - else - { - foreach($Array as $ElementID) - { - $Point['planets'][$PlanetData['id']]['p'][] = $ElementID.','.$PlanetData[$_Vars_GameElements[$ElementID].'_workpercent']; - } - } - } - else - { - foreach($Array as $BuildID) - { - if(isset($PlanetData[$_Vars_GameElements[$BuildID]]) && $PlanetData[$_Vars_GameElements[$BuildID]] > 0) - { - $Point['planets'][$PlanetData['id']]['b'][] = "{$BuildID},{$PlanetData[$_Vars_GameElements[$BuildID]]}"; - } - } - } - } - } - - if(mysql_num_rows($GetFleets) > 0) - { - while($FleetData = mysql_fetch_assoc($GetFleets)) - { - $Point = &$DevDump[$FleetData['fleet_owner']]['inflight'][$FleetData['fleet_id']]; - $Point = rtrim($FleetData['fleet_array'], ';'); - if($FleetData['fleet_resource_metal'] > 0) - { - $Point .= ';M,'.$FleetData['fleet_resource_metal']; - } - if($FleetData['fleet_resource_crystal'] > 0) - { - $Point .= ';C,'.$FleetData['fleet_resource_crystal']; - } - if($FleetData['fleet_resource_deuterium'] > 0) - { - $Point .= ';D,'.$FleetData['fleet_resource_deuterium']; - } - } - } - } - - if(isset($DevDump) && !empty($DevDump)) - { - if($SelectedUID > 0) - { - doquery("DELETE FROM {{table}} WHERE `UserID` = {$SelectedUID} LIMIT 1;", 'user_developmentdumps'); - doquery("DELETE FROM {{table}} WHERE `UserID` = {$SelectedUID};", 'user_developmentlog'); - } - else - { - doquery("TRUNCATE {{table}};", 'user_developmentdumps'); - doquery("TRUNCATE {{table}};", 'user_developmentlog'); - } - - $InsertQry = "INSERT INTO {{table}} VALUES "; - foreach($DevDump as $UserID => $DevData) - { - $TempElements = array(); - foreach($DevData['planets'] as $PlanetID => $Data) - { - if(isset($Data['b']) && !empty($Data['b'])) - { - $DevData['planets'][$PlanetID]['b'] = implode(';', $Data['b']); - } - if(isset($Data['p']) && !empty($Data['p'])) - { - $DevData['planets'][$PlanetID]['p'] = implode(';', $Data['p']); - } - if(isset($Data['f']) && !empty($Data['f'])) - { - $DevData['planets'][$PlanetID]['f'] = implode(';', $Data['f']); - } - } - $DevData['planets'] = json_encode($DevData['planets']); - foreach($DevData['techs'] as $ID => $Count) - { - $TempElements[] = "{$ID},{$Count}"; - } - $DevData['techs'] = implode(';', $TempElements); - - $DevData['inflight'] = json_encode($DevData['inflight']); - - $InsertQryArr[] = "({$UserID}, {$Now}, '{$DevData['planets']}', '{$DevData['techs']}', '{$DevData['inflight']}')"; - } - $InsertQry .= implode(', ', $InsertQryArr); - doquery($InsertQry, 'user_developmentdumps'); - - $EndTime = microtime(true); - - if(!isset($SkipDumpMsg) || $SkipDumpMsg !== true) - { - message('User Development Dump creation DONE
Generated in: '.sprintf('%0.10f', ($EndTime - $StartTime)), ''); - } - } - else - { - if(!isset($SkipDumpMsg) || $SkipDumpMsg !== true) - { - message('No Data to Insert!', ''); - } - } -} -else -{ - if(!isset($SkipDumpMsg) || $SkipDumpMsg !== true) - { - message('Users not Found!', ''); - } -} - -?> \ No newline at end of file + 0) +{ + $WhereClausure1 = " WHERE `id` = {$SelectedUID}"; + $WhereClausure2 = " WHERE `id_owner` = {$SelectedUID}"; + $WhereClausure3 = " WHERE `fleet_owner` = {$SelectedUID}"; +} + +$GetUsers = doquery("SELECT * FROM {{table}}{$WhereClausure1};", 'users'); +$GetPlanets = doquery("SELECT * FROM {{table}}{$WhereClausure2};", 'planets'); +$GetFleets = doquery("SELECT * FROM {{table}}{$WhereClausure3};", 'fleets'); + +if(mysql_num_rows($GetUsers) > 0) +{ + while($UserData = mysql_fetch_assoc($GetUsers)) + { + $DevDump[$UserData['id']] = array('planets' => array(), 'techs' => array(), 'inflight' => array()); + $Point = &$DevDump[$UserData['id']]['techs']; + foreach($_Vars_ElementCategories['tech'] as $TechID) + { + if($UserData[$_Vars_GameElements[$TechID]] > 0) + { + $Point[$TechID] = $UserData[$_Vars_GameElements[$TechID]]; + } + } + } + + if(mysql_num_rows($GetPlanets) > 0) + { + while($PlanetData = mysql_fetch_assoc($GetPlanets)) + { + if($PlanetData['id_owner'] <= 0) + { + continue; + } + $Point = &$DevDump[$PlanetData['id_owner']]; + + $Point['planets'][$PlanetData['id']]['pt'] = $PlanetData['planet_type']; + $Point['planets'][$PlanetData['id']]['t'] = $PlanetData['temp_max']; + $Point['planets'][$PlanetData['id']]['lu'] = $PlanetData['last_update']; + $Point['planets'][$PlanetData['id']]['res'] = floor($PlanetData['metal']).','.floor($PlanetData['crystal']).','.floor($PlanetData['deuterium']); + + + foreach($_Vars_ElementCategories as $Key => $Array) + { + if(in_array($Key, array('tech', 'buildOn', 'units'))) + { + continue; + } + if($Key != 'build') + { + if($Key != 'prod') + { + foreach($Array as $ElementID) + { + if(isset($PlanetData[$_Vars_GameElements[$ElementID]]) && $PlanetData[$_Vars_GameElements[$ElementID]] > 0) + { + $Point['planets'][$PlanetData['id']]['f'][] = "{$ElementID},{$PlanetData[$_Vars_GameElements[$ElementID]]}"; + } + } + } + else + { + foreach($Array as $ElementID) + { + $Point['planets'][$PlanetData['id']]['p'][] = $ElementID.','.$PlanetData[$_Vars_GameElements[$ElementID].'_workpercent']; + } + } + } + else + { + foreach($Array as $BuildID) + { + if(isset($PlanetData[$_Vars_GameElements[$BuildID]]) && $PlanetData[$_Vars_GameElements[$BuildID]] > 0) + { + $Point['planets'][$PlanetData['id']]['b'][] = "{$BuildID},{$PlanetData[$_Vars_GameElements[$BuildID]]}"; + } + } + } + } + } + + if(mysql_num_rows($GetFleets) > 0) + { + while($FleetData = mysql_fetch_assoc($GetFleets)) + { + $Point = &$DevDump[$FleetData['fleet_owner']]['inflight'][$FleetData['fleet_id']]; + $Point = rtrim($FleetData['fleet_array'], ';'); + if($FleetData['fleet_resource_metal'] > 0) + { + $Point .= ';M,'.$FleetData['fleet_resource_metal']; + } + if($FleetData['fleet_resource_crystal'] > 0) + { + $Point .= ';C,'.$FleetData['fleet_resource_crystal']; + } + if($FleetData['fleet_resource_deuterium'] > 0) + { + $Point .= ';D,'.$FleetData['fleet_resource_deuterium']; + } + } + } + } + + if(isset($DevDump) && !empty($DevDump)) + { + if($SelectedUID > 0) + { + doquery("DELETE FROM {{table}} WHERE `UserID` = {$SelectedUID} LIMIT 1;", 'user_developmentdumps'); + doquery("DELETE FROM {{table}} WHERE `UserID` = {$SelectedUID};", 'user_developmentlog'); + } + else + { + doquery("TRUNCATE {{table}};", 'user_developmentdumps'); + doquery("TRUNCATE {{table}};", 'user_developmentlog'); + } + + $InsertQry = "INSERT INTO {{table}} VALUES "; + foreach($DevDump as $UserID => $DevData) + { + $TempElements = array(); + foreach($DevData['planets'] as $PlanetID => $Data) + { + if(isset($Data['b']) && !empty($Data['b'])) + { + $DevData['planets'][$PlanetID]['b'] = implode(';', $Data['b']); + } + if(isset($Data['p']) && !empty($Data['p'])) + { + $DevData['planets'][$PlanetID]['p'] = implode(';', $Data['p']); + } + if(isset($Data['f']) && !empty($Data['f'])) + { + $DevData['planets'][$PlanetID]['f'] = implode(';', $Data['f']); + } + } + $DevData['planets'] = json_encode($DevData['planets']); + foreach($DevData['techs'] as $ID => $Count) + { + $TempElements[] = "{$ID},{$Count}"; + } + $DevData['techs'] = implode(';', $TempElements); + + $DevData['inflight'] = json_encode($DevData['inflight']); + + $InsertQryArr[] = "({$UserID}, {$Now}, '{$DevData['planets']}', '{$DevData['techs']}', '{$DevData['inflight']}')"; + } + $InsertQry .= implode(', ', $InsertQryArr); + doquery($InsertQry, 'user_developmentdumps'); + + $EndTime = microtime(true); + + if(!isset($SkipDumpMsg) || $SkipDumpMsg !== true) + { + message('User Development Dump creation DONE
Generated in: '.sprintf('%0.10f', ($EndTime - $StartTime)), ''); + } + } + else + { + if(!isset($SkipDumpMsg) || $SkipDumpMsg !== true) + { + message('No Data to Insert!', ''); + } + } +} +else +{ + if(!isset($SkipDumpMsg) || $SkipDumpMsg !== true) + { + message('Users not Found!', ''); + } +} + +?> diff --git a/admin/settings.php b/admin/settings.php index 3945fdc95..99b05e9c3 100644 --- a/admin/settings.php +++ b/admin/settings.php @@ -1,222 +1,222 @@ - function($Value){ if($Value == 'on'){ return '1'; } return '0'; }, - 'checkbox_reverse' => function($Value){ if($Value == 'on'){ return '0'; } return '1'; }, - 'sanitize_plusint' => function($Value){ $Value = intval($Value); if($Value <= 0){ return false; } return $Value; }, - 'sanitize_nonnegint' => function($Value){ $Value = intval($Value); if($Value < 0){ return false; } return $Value; }, - 'sanitize_percent' => function($Value){ $Value = round($Value, 2); if($Value < 0 OR $Value > 100){ return false; } return $Value; }, - 'sanitize_text' => function($Value){ return mysql_real_escape_string(stripslashes($Value)); }, - 'sanitize_check' => function($Value){ return mysql_real_escape_string($Value); }, - 'desanitize_text' => function($Value){ return stripslashes($Value); }, - 'dedesanitize_text' => function($Name, $Value){ return stripslashes($_POST[$Name]); }, - ); - - $_PreProcessor = array - ( - 'close_reason' => $_DefFunctions['sanitize_text'], - 'game_disable' => $_DefFunctions['checkbox'], - 'enforceRulesAcceptance' => $_DefFunctions['checkbox'], - 'last_rules_changes' => function($Value){ return strtotime($Value); }, - 'TelemetryEnabled' => $_DefFunctions['checkbox'], - 'enable_bbcode' => $_DefFunctions['checkbox'], - 'game_speed' => function($Value){ return $Value * 2500; }, - 'fleet_speed' => function($Value){ return $Value * 2500; }, - 'BuildLabWhileRun' => $_DefFunctions['checkbox_reverse'], - 'OverviewNewsText' => $_DefFunctions['sanitize_text'], - 'OverviewClickBanner' => $_DefFunctions['sanitize_text'], - 'OverviewNewsFrame' => $_DefFunctions['checkbox'], - 'OverviewBanner' => $_DefFunctions['checkbox'], - 'banned_ip_list' => function($Value){ $Value = explode("\n", $Value); $Value = array_map('trim', $Value); return implode('|', $Value); }, - 'BannedMailDomains' => function($Value){ $Value = explode("\n", $Value); $Value = array_map('trim', $Value); return implode('|', $Value); }, - ); - $_CheckSanitize = array - ( - 'close_reason' => $_DefFunctions['sanitize_check'], - 'OverviewNewsText' => $_DefFunctions['sanitize_check'], - 'OverviewClickBanner' => $_DefFunctions['sanitize_check'], - ); - - $_PostProcessor['2db'] = array - ( - - ); - $_PostProcessor['2var'] = array - ( - 'close_reason' => $_DefFunctions['dedesanitize_text'], - 'OverviewNewsText' => $_DefFunctions['dedesanitize_text'], - 'OverviewClickBanner' => $_DefFunctions['dedesanitize_text'], - ); - - $_Sanitizers = array - ( - 'EngineInfo_Version' => function($Value){ if(!preg_match('/^[0-9\.]{1,}$/D', $Value)){ return false; } return $Value; }, - 'EngineInfo_BuildNo' => function($Value){ $Value = intval($Value); if($Value < 0){ return false; } return $Value; }, - 'last_rules_changes' => function($Value){ if($Value < 0){ return false; } return $Value; }, - 'game_speed' => $_DefFunctions['sanitize_plusint'], - 'resource_multiplier' => $_DefFunctions['sanitize_plusint'], - 'fleet_speed' => $_DefFunctions['sanitize_plusint'], - 'Fleet_Cdr' => $_DefFunctions['sanitize_percent'], - 'Defs_Cdr' => $_DefFunctions['sanitize_percent'], - 'Debris_Def_Rocket' => $_DefFunctions['sanitize_percent'], - 'stat_settings' => $_DefFunctions['sanitize_plusint'], - 'initial_fields' => $_DefFunctions['sanitize_plusint'], - 'metal_basic_income' => $_DefFunctions['sanitize_nonnegint'], - 'crystal_basic_income' => $_DefFunctions['sanitize_nonnegint'], - 'deuterium_basic_income' => $_DefFunctions['sanitize_nonnegint'], - 'energy_basic_income' => $_DefFunctions['sanitize_nonnegint'], - 'banned_ip_list' => function($Value){ if(!preg_match('/^[0-9\.\|\:]{1,}$/D', $Value)){ return false; } return $Value; }, - 'BannedMailDomains' => function($Value){ if(!preg_match('/^[a-zA-Z0-9\.\_\-\|]{1,}$/D', $Value)){ return false; } return $Value; }, - ); - - if(isset($_GET['configcachereload']) && $_GET['configcachereload'] == 1) - { - $Query_GetGameConfig = "SELECT * FROM {{table}};"; - $Result_GetGameConfig = doquery($Query_GetGameConfig, 'config'); - while($FetchData = mysql_fetch_assoc($Result_GetGameConfig)) - { - $_GameConfig[$FetchData['config_name']] = $FetchData['config_value']; - } - $_MemCache->GameConfig = $_GameConfig; - - $_Lang['Msg_Color'] = 'lime'; - $_Lang['Msg_Text'] = $_Lang['Messages_ConfigCacheReloaded']; - } - else if(isset($_POST['opt_save']) && $_POST['opt_save'] == '1') - { - foreach($AllowedVars as $Name) - { - $Value = isset($_POST[$Name]) ? $_POST[$Name] : null; - if(in_array($Name, $AllowedVars)) - { - if(!empty($_PreProcessor[$Name])) - { - $Value = $_PreProcessor[$Name]($Value); - } - - $VarToCheck = $_GameConfig[$Name]; - if(!empty($_CheckSanitize[$Name])) - { - $VarToCheck = $_CheckSanitize[$Name]($VarToCheck); - } - if($Value != $VarToCheck) - { - if(isset($_Sanitizers[$Name])) - { - $Value = $_Sanitizers[$Name]($Value); - } - - if($Value !== false) - { - $ToUpdate[$Name] = $Value; - if(!empty($_PostProcessor['2db'][$Name])) - { - $ToUpdate[$Name] = $_PostProcessor['2db'][$Name]($Value); - } - if(!empty($_PostProcessor['2var'][$Name])) - { - $Value = $_PostProcessor['2var'][$Name]($Name, $Value); - } - $_GameConfig[$Name] = $Value; - } - } - } - } - - if(!empty($ToUpdate)) - { - $UpdateQuery = "INSERT INTO {{table}} (`config_name`, `config_value`) VALUES "; - foreach($ToUpdate as $FieldName => $Value) - { - $UpdateQueryArray[] = "('{$FieldName}', '{$Value}')"; - } - $UpdateQuery .= implode(', ', $UpdateQueryArray); - $UpdateQuery .= " ON DUPLICATE KEY UPDATE "; - $UpdateQuery .= "`config_value` = VALUES(`config_value`);"; - doquery($UpdateQuery, 'config'); - $_MemCache->GameConfig = $_GameConfig; - - $UpdatedRows = mysql_affected_rows(); - if($UpdatedRows > 0) - { - $_Lang['Msg_Color'] = 'lime'; - $_Lang['Msg_Text'] = sprintf($_Lang['Messages_UpdateSuccess'], prettyNumber($UpdatedRows / 2)); - } - else - { - $_Lang['Msg_Color'] = 'orange'; - $_Lang['Msg_Text'] = $_Lang['Messages_NoUpdateMade']; - } - } - else - { - $_Lang['Msg_Color'] = 'orange'; - $_Lang['Msg_Text'] = $_Lang['Messages_NothingToUpdate']; - } - } - - if(empty($_Lang['Msg_Text'])) - { - $_Lang['Msg_Hide'] = ' style="display: none;"'; - } - - $_Lang['PHP_EngineInfo_Version'] = $_GameConfig['EngineInfo_Version']; - $_Lang['PHP_EngineInfo_BuildNo'] = $_GameConfig['EngineInfo_BuildNo']; - $_Lang['PHP_game_disable'] = ($_GameConfig['game_disable'] ? $_Checked : ''); - $_Lang['PHP_close_reason'] = $_GameConfig['close_reason']; - $_Lang['PHP_enforceRulesAcceptance'] = ($_GameConfig['enforceRulesAcceptance'] ? $_Checked : ''); - $_Lang['PHP_last_rules_changes'] = date('Y-m-d H:i:s', $_GameConfig['last_rules_changes']); - $_Lang['PHP_TelemetryEnabled'] = ($_GameConfig['TelemetryEnabled'] ? $_Checked : ''); - $_Lang['PHP_enable_bbcode'] = ($_GameConfig['enable_bbcode'] ? $_Checked : ''); - $_Lang['PHP_game_speed'] = $_GameConfig['game_speed'] / 2500; - $_Lang['PHP_resource_multiplier'] = $_GameConfig['resource_multiplier']; - $_Lang['PHP_fleet_speed'] = $_GameConfig['fleet_speed'] / 2500; - $_Lang['PHP_Fleet_Cdr'] = $_GameConfig['Fleet_Cdr']; - $_Lang['PHP_Defs_Cdr'] = $_GameConfig['Defs_Cdr']; - $_Lang['PHP_Debris_Def_Rocket'] = $_GameConfig['Debris_Def_Rocket']; - $_Lang['PHP_stat_settings'] = $_GameConfig['stat_settings']; - $_Lang['PHP_initial_fields'] = $_GameConfig['initial_fields']; - $_Lang['PHP_BuildLabWhileRun'] = (!$_GameConfig['BuildLabWhileRun'] ? $_Checked : ''); - $_Lang['PHP_metal_basic_income'] = $_GameConfig['metal_basic_income']; - $_Lang['PHP_crystal_basic_income'] = $_GameConfig['crystal_basic_income']; - $_Lang['PHP_deuterium_basic_income'] = $_GameConfig['deuterium_basic_income']; - $_Lang['PHP_energy_basic_income'] = $_GameConfig['energy_basic_income']; - $_Lang['PHP_OverviewNewsFrame'] = ($_GameConfig['OverviewNewsFrame'] ? $_Checked : ''); - $_Lang['PHP_OverviewNewsText'] = $_GameConfig['OverviewNewsText']; - $_Lang['PHP_OverviewBanner'] = ($_GameConfig['OverviewBanner'] ? $_Checked : ''); - $_Lang['PHP_OverviewClickBanner'] = $_GameConfig['OverviewClickBanner']; - $_Lang['PHP_banned_ip_list'] = str_replace('|', "\n", $_GameConfig['banned_ip_list']); - $_Lang['PHP_BannedMailDomains'] = str_replace('|', "\n", $_GameConfig['BannedMailDomains']); - - $Page = parsetemplate(gettemplate('admin/settings_body'), $_Lang); - display($Page, $_Lang['Body_Title'], false, true); - -?> \ No newline at end of file + function($Value){ if($Value == 'on'){ return '1'; } return '0'; }, + 'checkbox_reverse' => function($Value){ if($Value == 'on'){ return '0'; } return '1'; }, + 'sanitize_plusint' => function($Value){ $Value = intval($Value); if($Value <= 0){ return false; } return $Value; }, + 'sanitize_nonnegint' => function($Value){ $Value = intval($Value); if($Value < 0){ return false; } return $Value; }, + 'sanitize_percent' => function($Value){ $Value = round($Value, 2); if($Value < 0 OR $Value > 100){ return false; } return $Value; }, + 'sanitize_text' => function($Value){ return mysql_real_escape_string(stripslashes($Value)); }, + 'sanitize_check' => function($Value){ return mysql_real_escape_string($Value); }, + 'desanitize_text' => function($Value){ return stripslashes($Value); }, + 'dedesanitize_text' => function($Name, $Value){ return stripslashes($_POST[$Name]); }, +); + +$_PreProcessor = array +( + 'close_reason' => $_DefFunctions['sanitize_text'], + 'game_disable' => $_DefFunctions['checkbox'], + 'enforceRulesAcceptance' => $_DefFunctions['checkbox'], + 'last_rules_changes' => function($Value){ return strtotime($Value); }, + 'TelemetryEnabled' => $_DefFunctions['checkbox'], + 'enable_bbcode' => $_DefFunctions['checkbox'], + 'game_speed' => function($Value){ return $Value * 2500; }, + 'fleet_speed' => function($Value){ return $Value * 2500; }, + 'BuildLabWhileRun' => $_DefFunctions['checkbox_reverse'], + 'OverviewNewsText' => $_DefFunctions['sanitize_text'], + 'OverviewClickBanner' => $_DefFunctions['sanitize_text'], + 'OverviewNewsFrame' => $_DefFunctions['checkbox'], + 'OverviewBanner' => $_DefFunctions['checkbox'], + 'banned_ip_list' => function($Value){ $Value = explode("\n", $Value); $Value = array_map('trim', $Value); return implode('|', $Value); }, + 'BannedMailDomains' => function($Value){ $Value = explode("\n", $Value); $Value = array_map('trim', $Value); return implode('|', $Value); }, +); +$_CheckSanitize = array +( + 'close_reason' => $_DefFunctions['sanitize_check'], + 'OverviewNewsText' => $_DefFunctions['sanitize_check'], + 'OverviewClickBanner' => $_DefFunctions['sanitize_check'], +); + +$_PostProcessor['2db'] = array +( + +); +$_PostProcessor['2var'] = array +( + 'close_reason' => $_DefFunctions['dedesanitize_text'], + 'OverviewNewsText' => $_DefFunctions['dedesanitize_text'], + 'OverviewClickBanner' => $_DefFunctions['dedesanitize_text'], +); + +$_Sanitizers = array +( + 'EngineInfo_Version' => function($Value){ if(!preg_match('/^[0-9\.]{1,}$/D', $Value)){ return false; } return $Value; }, + 'EngineInfo_BuildNo' => function($Value){ $Value = intval($Value); if($Value < 0){ return false; } return $Value; }, + 'last_rules_changes' => function($Value){ if($Value < 0){ return false; } return $Value; }, + 'game_speed' => $_DefFunctions['sanitize_plusint'], + 'resource_multiplier' => $_DefFunctions['sanitize_plusint'], + 'fleet_speed' => $_DefFunctions['sanitize_plusint'], + 'Fleet_Cdr' => $_DefFunctions['sanitize_percent'], + 'Defs_Cdr' => $_DefFunctions['sanitize_percent'], + 'Debris_Def_Rocket' => $_DefFunctions['sanitize_percent'], + 'stat_settings' => $_DefFunctions['sanitize_plusint'], + 'initial_fields' => $_DefFunctions['sanitize_plusint'], + 'metal_basic_income' => $_DefFunctions['sanitize_nonnegint'], + 'crystal_basic_income' => $_DefFunctions['sanitize_nonnegint'], + 'deuterium_basic_income' => $_DefFunctions['sanitize_nonnegint'], + 'energy_basic_income' => $_DefFunctions['sanitize_nonnegint'], + 'banned_ip_list' => function($Value){ if(!preg_match('/^[0-9\.\|\:]{1,}$/D', $Value)){ return false; } return $Value; }, + 'BannedMailDomains' => function($Value){ if(!preg_match('/^[a-zA-Z0-9\.\_\-\|]{1,}$/D', $Value)){ return false; } return $Value; }, +); + +if(isset($_GET['configcachereload']) && $_GET['configcachereload'] == 1) +{ + $Query_GetGameConfig = "SELECT * FROM {{table}};"; + $Result_GetGameConfig = doquery($Query_GetGameConfig, 'config'); + while($FetchData = mysql_fetch_assoc($Result_GetGameConfig)) + { + $_GameConfig[$FetchData['config_name']] = $FetchData['config_value']; + } + $_MemCache->GameConfig = $_GameConfig; + + $_Lang['Msg_Color'] = 'lime'; + $_Lang['Msg_Text'] = $_Lang['Messages_ConfigCacheReloaded']; +} +else if(isset($_POST['opt_save']) && $_POST['opt_save'] == '1') +{ + foreach($AllowedVars as $Name) + { + $Value = isset($_POST[$Name]) ? $_POST[$Name] : null; + if(in_array($Name, $AllowedVars)) + { + if(!empty($_PreProcessor[$Name])) + { + $Value = $_PreProcessor[$Name]($Value); + } + + $VarToCheck = $_GameConfig[$Name]; + if(!empty($_CheckSanitize[$Name])) + { + $VarToCheck = $_CheckSanitize[$Name]($VarToCheck); + } + if($Value != $VarToCheck) + { + if(isset($_Sanitizers[$Name])) + { + $Value = $_Sanitizers[$Name]($Value); + } + + if($Value !== false) + { + $ToUpdate[$Name] = $Value; + if(!empty($_PostProcessor['2db'][$Name])) + { + $ToUpdate[$Name] = $_PostProcessor['2db'][$Name]($Value); + } + if(!empty($_PostProcessor['2var'][$Name])) + { + $Value = $_PostProcessor['2var'][$Name]($Name, $Value); + } + $_GameConfig[$Name] = $Value; + } + } + } + } + + if(!empty($ToUpdate)) + { + $UpdateQuery = "INSERT INTO {{table}} (`config_name`, `config_value`) VALUES "; + foreach($ToUpdate as $FieldName => $Value) + { + $UpdateQueryArray[] = "('{$FieldName}', '{$Value}')"; + } + $UpdateQuery .= implode(', ', $UpdateQueryArray); + $UpdateQuery .= " ON DUPLICATE KEY UPDATE "; + $UpdateQuery .= "`config_value` = VALUES(`config_value`);"; + doquery($UpdateQuery, 'config'); + $_MemCache->GameConfig = $_GameConfig; + + $UpdatedRows = mysql_affected_rows(); + if($UpdatedRows > 0) + { + $_Lang['Msg_Color'] = 'lime'; + $_Lang['Msg_Text'] = sprintf($_Lang['Messages_UpdateSuccess'], prettyNumber($UpdatedRows / 2)); + } + else + { + $_Lang['Msg_Color'] = 'orange'; + $_Lang['Msg_Text'] = $_Lang['Messages_NoUpdateMade']; + } + } + else + { + $_Lang['Msg_Color'] = 'orange'; + $_Lang['Msg_Text'] = $_Lang['Messages_NothingToUpdate']; + } +} + +if(empty($_Lang['Msg_Text'])) +{ + $_Lang['Msg_Hide'] = ' style="display: none;"'; +} + +$_Lang['PHP_EngineInfo_Version'] = $_GameConfig['EngineInfo_Version']; +$_Lang['PHP_EngineInfo_BuildNo'] = $_GameConfig['EngineInfo_BuildNo']; +$_Lang['PHP_game_disable'] = ($_GameConfig['game_disable'] ? $_Checked : ''); +$_Lang['PHP_close_reason'] = $_GameConfig['close_reason']; +$_Lang['PHP_enforceRulesAcceptance'] = ($_GameConfig['enforceRulesAcceptance'] ? $_Checked : ''); +$_Lang['PHP_last_rules_changes'] = date('Y-m-d H:i:s', $_GameConfig['last_rules_changes']); +$_Lang['PHP_TelemetryEnabled'] = ($_GameConfig['TelemetryEnabled'] ? $_Checked : ''); +$_Lang['PHP_enable_bbcode'] = ($_GameConfig['enable_bbcode'] ? $_Checked : ''); +$_Lang['PHP_game_speed'] = $_GameConfig['game_speed'] / 2500; +$_Lang['PHP_resource_multiplier'] = $_GameConfig['resource_multiplier']; +$_Lang['PHP_fleet_speed'] = $_GameConfig['fleet_speed'] / 2500; +$_Lang['PHP_Fleet_Cdr'] = $_GameConfig['Fleet_Cdr']; +$_Lang['PHP_Defs_Cdr'] = $_GameConfig['Defs_Cdr']; +$_Lang['PHP_Debris_Def_Rocket'] = $_GameConfig['Debris_Def_Rocket']; +$_Lang['PHP_stat_settings'] = $_GameConfig['stat_settings']; +$_Lang['PHP_initial_fields'] = $_GameConfig['initial_fields']; +$_Lang['PHP_BuildLabWhileRun'] = (!$_GameConfig['BuildLabWhileRun'] ? $_Checked : ''); +$_Lang['PHP_metal_basic_income'] = $_GameConfig['metal_basic_income']; +$_Lang['PHP_crystal_basic_income'] = $_GameConfig['crystal_basic_income']; +$_Lang['PHP_deuterium_basic_income'] = $_GameConfig['deuterium_basic_income']; +$_Lang['PHP_energy_basic_income'] = $_GameConfig['energy_basic_income']; +$_Lang['PHP_OverviewNewsFrame'] = ($_GameConfig['OverviewNewsFrame'] ? $_Checked : ''); +$_Lang['PHP_OverviewNewsText'] = $_GameConfig['OverviewNewsText']; +$_Lang['PHP_OverviewBanner'] = ($_GameConfig['OverviewBanner'] ? $_Checked : ''); +$_Lang['PHP_OverviewClickBanner'] = $_GameConfig['OverviewClickBanner']; +$_Lang['PHP_banned_ip_list'] = str_replace('|', "\n", $_GameConfig['banned_ip_list']); +$_Lang['PHP_BannedMailDomains'] = str_replace('|', "\n", $_GameConfig['BannedMailDomains']); + +$Page = parsetemplate(gettemplate('admin/settings_body'), $_Lang); +display($Page, $_Lang['Body_Title'], false, true); + +?> diff --git a/admin/ship_calculations.php b/admin/ship_calculations.php index 97ceab424..a19162e8e 100644 --- a/admin/ship_calculations.php +++ b/admin/ship_calculations.php @@ -1,218 +1,218 @@ - 1, 'crystal' => 2, 'deuterium' => 4); - - if(CheckAuth('programmer')) - { - includeLang('admin/ship_calculations'); - $TPL = gettemplate('admin/ship_calculations_body'); - - $ShipID = 0; - $TargetID = 0; - - if(isset($_GET['ship']) && $_GET['ship'] > 0) - { - $ShipID = intval($_GET['ship']); - $TargetID = isset($_GET['ship2']) ? intval($_GET['ship2']) : 0; - if(!in_array($TargetID, $_Vars_ElementCategories['fleet'])) - { - $TargetID = 0; - } - - if(in_array($ShipID, $_Vars_ElementCategories['fleet'])) - { - // Do calculations in here! - $_Lang['Input_Table_Hide'] = 'hide'; - $TPL_Headers = gettemplate('admin/ship_calculations_headers'); - $TPL_Rows = gettemplate('admin/ship_calculations_rows'); - - $Ship['Price'] = (($_Vars_Prices[$ShipID]['metal'] * $MerchantRatio['metal']) + - ($_Vars_Prices[$ShipID]['crystal'] * $MerchantRatio['crystal']) + - ($_Vars_Prices[$ShipID]['deuterium'] * $MerchantRatio['deuterium'])); - $Ship['Hull'] = ($_Vars_Prices[$ShipID]['metal'] + $_Vars_Prices[$ShipID]['crystal']) / 10; - $Ship['Life'] = $Ship['Hull'] + $_Vars_CombatData[$ShipID]['shield']; - - if($TargetID > 0) - { - if($_Vars_CombatData[$ShipID]['attack'] > 0) - { - $_Lang['Input_EnableProfitabilitySort'] = 'true'; - $Ship2['Hull'] = ($_Vars_Prices[$TargetID]['metal'] + $_Vars_Prices[$TargetID]['crystal']) / 10; - $Ship2['Life'] = $Ship2['Hull'] + $_Vars_CombatData[$TargetID]['shield']; - - $Ship['Profitability'] = $_Vars_CombatData[$ShipID]['attack'] / $Ship2['Life']; - if($Ship['Profitability'] > 1) - { - $Ship['Profitability'] = 1; - } - if($_Vars_CombatData[$ShipID]['sd'][$TargetID] > 1) - { - $Ship['Profitability'] *= $_Vars_CombatData[$ShipID]['sd'][$TargetID]; - } - $Ship['Profitability'] = $Ship['Price'] / $Ship['Profitability']; - } - else - { - $TargetID = 0; - } - } - - $_Lang['Input_InsertRows'] = ''; - foreach($_Vars_ElementCategories['fleet'] as $ID) - { - $Row = array(); - if($ID == $ShipID OR $ID == $TargetID) - { - if($ID == $ShipID) - { - $Row['Input_CurrentColor'] = 'lime'; - } - else - { - $Row['Input_CurrentColor'] = 'orange'; - } - $Row['Input_IsCurrentShip'] = 'current'; - } - $Row['Input_ID'] = $ID; - $Row['Input_Name'] = $_Lang['tech'][$ID]; - if($_Vars_Prices[$ID]['metal'] > 0 AND $_Vars_Prices[$ShipID]['metal'] > 0) - { - $Row['Input_MetalRatio']= round($_Vars_Prices[$ID]['metal'] / $_Vars_Prices[$ShipID]['metal'], 4); - } - else - { - $Row['Input_MetalRatio']= '-'; - } - if($_Vars_Prices[$ID]['crystal'] > 0 AND $_Vars_Prices[$ShipID]['crystal'] > 0) - { - $Row['Input_CrystalRatio']= round($_Vars_Prices[$ID]['crystal'] / $_Vars_Prices[$ShipID]['crystal'], 4); - } - else - { - $Row['Input_CrystalRatio']= '-'; - } - if($_Vars_Prices[$ID]['deuterium'] > 0 AND $_Vars_Prices[$ShipID]['deuterium'] > 0) - { - $Row['Input_DeuteriumRatio']= round($_Vars_Prices[$ID]['deuterium'] / $_Vars_Prices[$ShipID]['deuterium'], 4); - } - else - { - $Row['Input_DeuteriumRatio']= '-'; - } - $Row['Price'] = - ($_Vars_Prices[$ID]['metal'] * $MerchantRatio['metal']) + - ($_Vars_Prices[$ID]['crystal'] * $MerchantRatio['crystal']) + - ($_Vars_Prices[$ID]['deuterium'] * $MerchantRatio['deuterium']); - - $Row['Input_TotalPriceRatio'] = round($Row['Price']/ $Ship['Price'], 4); - - if($_Vars_CombatData[$ID]['attack'] > 0 AND $_Vars_CombatData[$ShipID]['attack'] > 0) - { - $Row['Input_ForceRatio'] = round($_Vars_CombatData[$ID]['attack'] / $_Vars_CombatData[$ShipID]['attack'], 4); - } - else - { - $Row['Input_ForceRatio'] = '-'; - } - if($_Vars_CombatData[$ID]['shield'] > 0 AND $_Vars_CombatData[$ShipID]['shield'] > 0) - { - $Row['Input_ShieldRatio'] = round($_Vars_CombatData[$ID]['shield'] / $_Vars_CombatData[$ShipID]['shield'], 4); - } - else - { - $Row['Input_ShieldRatio'] = '-'; - } - $Row['Hull'] = ($_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal']) / 10; - $Row['Life'] = $Row['Hull'] + $_Vars_CombatData[$ID]['shield']; - - $Row['Input_HullRatio'] = round($Row['Hull'] / $Ship['Hull'], 4); - if($_Vars_CombatData[$ShipID]['attack'] > 0) - { - $Row['NeedToDestroyOne'] = $_Vars_CombatData[$ShipID]['attack'] / $Row['Life']; - if($Row['NeedToDestroyOne'] > 1) - { - $Row['NeedToDestroyOne'] = 1; - } - if($_Vars_CombatData[$ShipID]['sd'][$ID] > 1) - { - $Row['DestroyInOneTurn'] = $Row['NeedToDestroyOne'] * $_Vars_CombatData[$ShipID]['sd'][$ID]; - } - else - { - $Row['DestroyInOneTurn'] = $Row['NeedToDestroyOne']; - } - $Row['Input_DestroyInOneTurn'] = floor($Row['DestroyInOneTurn']); - if($Row['Input_DestroyInOneTurn'] < 1) - { - $Row['Input_DestroyInOneTurn'] = '('.ceil(1 / $Row['DestroyInOneTurn']).')'; - } - } - else - { - $Row['Input_DestroyInOneTurn']= '-'; - } - $Row['Input_RapidFireValue'] = $_Vars_CombatData[$ShipID]['sd'][$ID]; - - if($TargetID == 0) - { - $Row['Input_CompareProfitability'] = '0'; - } - else - { - if($_Vars_CombatData[$ID]['attack'] > 0) - { - $Row['Profitability'] = $_Vars_CombatData[$ID]['attack'] / $Ship2['Life']; - if($Row['Profitability'] > 1) - { - $Row['Profitability'] = 1; - } - if($_Vars_CombatData[$ID]['sd'][$TargetID] > 1) - { - $Row['Profitability'] *= $_Vars_CombatData[$ID]['sd'][$TargetID]; - } - $Row['Profitability'] = $Row['Price'] / $Row['Profitability']; - - $Row['Input_CompareProfitability'] = $Ship['Profitability'] / $Row['Profitability']; - } - else - { - $Row['Input_CompareProfitability'] = '0'; - } - } - - $_Lang['Input_InsertRows'] .= parsetemplate($TPL_Rows, $Row); - } - - $_Lang['Input_InsertHeaders'] = parsetemplate($TPL_Headers, $_Lang); - } - else - { - $_Lang['Table_SelectShip'] = $_Lang['Table_BadShip']; - } - } - - $_Lang['Input_Selector_ShipList'] = ''; - $_Lang['Input_Selector_ShipList2'] = ''; - foreach($_Vars_ElementCategories['fleet'] as $ID) - { - $_Lang['Input_Selector_ShipList'] .= ""; - $_Lang['Input_Selector_ShipList2'] .= ""; - } - - display(parsetemplate($TPL, $_Lang), $_Lang['Page_Title'], false, true); - } - else - { - message($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); - } - -?> \ No newline at end of file + 1, 'crystal' => 2, 'deuterium' => 4); + +if(CheckAuth('programmer')) +{ + includeLang('admin/ship_calculations'); + $TPL = gettemplate('admin/ship_calculations_body'); + + $ShipID = 0; + $TargetID = 0; + + if(isset($_GET['ship']) && $_GET['ship'] > 0) + { + $ShipID = intval($_GET['ship']); + $TargetID = isset($_GET['ship2']) ? intval($_GET['ship2']) : 0; + if(!in_array($TargetID, $_Vars_ElementCategories['fleet'])) + { + $TargetID = 0; + } + + if(in_array($ShipID, $_Vars_ElementCategories['fleet'])) + { + // Do calculations in here! + $_Lang['Input_Table_Hide'] = 'hide'; + $TPL_Headers = gettemplate('admin/ship_calculations_headers'); + $TPL_Rows = gettemplate('admin/ship_calculations_rows'); + + $Ship['Price'] = (($_Vars_Prices[$ShipID]['metal'] * $MerchantRatio['metal']) + + ($_Vars_Prices[$ShipID]['crystal'] * $MerchantRatio['crystal']) + + ($_Vars_Prices[$ShipID]['deuterium'] * $MerchantRatio['deuterium'])); + $Ship['Hull'] = ($_Vars_Prices[$ShipID]['metal'] + $_Vars_Prices[$ShipID]['crystal']) / 10; + $Ship['Life'] = $Ship['Hull'] + $_Vars_CombatData[$ShipID]['shield']; + + if($TargetID > 0) + { + if($_Vars_CombatData[$ShipID]['attack'] > 0) + { + $_Lang['Input_EnableProfitabilitySort'] = 'true'; + $Ship2['Hull'] = ($_Vars_Prices[$TargetID]['metal'] + $_Vars_Prices[$TargetID]['crystal']) / 10; + $Ship2['Life'] = $Ship2['Hull'] + $_Vars_CombatData[$TargetID]['shield']; + + $Ship['Profitability'] = $_Vars_CombatData[$ShipID]['attack'] / $Ship2['Life']; + if($Ship['Profitability'] > 1) + { + $Ship['Profitability'] = 1; + } + if($_Vars_CombatData[$ShipID]['sd'][$TargetID] > 1) + { + $Ship['Profitability'] *= $_Vars_CombatData[$ShipID]['sd'][$TargetID]; + } + $Ship['Profitability'] = $Ship['Price'] / $Ship['Profitability']; + } + else + { + $TargetID = 0; + } + } + + $_Lang['Input_InsertRows'] = ''; + foreach($_Vars_ElementCategories['fleet'] as $ID) + { + $Row = array(); + if($ID == $ShipID OR $ID == $TargetID) + { + if($ID == $ShipID) + { + $Row['Input_CurrentColor'] = 'lime'; + } + else + { + $Row['Input_CurrentColor'] = 'orange'; + } + $Row['Input_IsCurrentShip'] = 'current'; + } + $Row['Input_ID'] = $ID; + $Row['Input_Name'] = $_Lang['tech'][$ID]; + if($_Vars_Prices[$ID]['metal'] > 0 AND $_Vars_Prices[$ShipID]['metal'] > 0) + { + $Row['Input_MetalRatio']= round($_Vars_Prices[$ID]['metal'] / $_Vars_Prices[$ShipID]['metal'], 4); + } + else + { + $Row['Input_MetalRatio']= '-'; + } + if($_Vars_Prices[$ID]['crystal'] > 0 AND $_Vars_Prices[$ShipID]['crystal'] > 0) + { + $Row['Input_CrystalRatio']= round($_Vars_Prices[$ID]['crystal'] / $_Vars_Prices[$ShipID]['crystal'], 4); + } + else + { + $Row['Input_CrystalRatio']= '-'; + } + if($_Vars_Prices[$ID]['deuterium'] > 0 AND $_Vars_Prices[$ShipID]['deuterium'] > 0) + { + $Row['Input_DeuteriumRatio']= round($_Vars_Prices[$ID]['deuterium'] / $_Vars_Prices[$ShipID]['deuterium'], 4); + } + else + { + $Row['Input_DeuteriumRatio']= '-'; + } + $Row['Price'] = + ($_Vars_Prices[$ID]['metal'] * $MerchantRatio['metal']) + + ($_Vars_Prices[$ID]['crystal'] * $MerchantRatio['crystal']) + + ($_Vars_Prices[$ID]['deuterium'] * $MerchantRatio['deuterium']); + + $Row['Input_TotalPriceRatio'] = round($Row['Price']/ $Ship['Price'], 4); + + if($_Vars_CombatData[$ID]['attack'] > 0 AND $_Vars_CombatData[$ShipID]['attack'] > 0) + { + $Row['Input_ForceRatio'] = round($_Vars_CombatData[$ID]['attack'] / $_Vars_CombatData[$ShipID]['attack'], 4); + } + else + { + $Row['Input_ForceRatio'] = '-'; + } + if($_Vars_CombatData[$ID]['shield'] > 0 AND $_Vars_CombatData[$ShipID]['shield'] > 0) + { + $Row['Input_ShieldRatio'] = round($_Vars_CombatData[$ID]['shield'] / $_Vars_CombatData[$ShipID]['shield'], 4); + } + else + { + $Row['Input_ShieldRatio'] = '-'; + } + $Row['Hull'] = ($_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal']) / 10; + $Row['Life'] = $Row['Hull'] + $_Vars_CombatData[$ID]['shield']; + + $Row['Input_HullRatio'] = round($Row['Hull'] / $Ship['Hull'], 4); + if($_Vars_CombatData[$ShipID]['attack'] > 0) + { + $Row['NeedToDestroyOne'] = $_Vars_CombatData[$ShipID]['attack'] / $Row['Life']; + if($Row['NeedToDestroyOne'] > 1) + { + $Row['NeedToDestroyOne'] = 1; + } + if($_Vars_CombatData[$ShipID]['sd'][$ID] > 1) + { + $Row['DestroyInOneTurn'] = $Row['NeedToDestroyOne'] * $_Vars_CombatData[$ShipID]['sd'][$ID]; + } + else + { + $Row['DestroyInOneTurn'] = $Row['NeedToDestroyOne']; + } + $Row['Input_DestroyInOneTurn'] = floor($Row['DestroyInOneTurn']); + if($Row['Input_DestroyInOneTurn'] < 1) + { + $Row['Input_DestroyInOneTurn'] = '('.ceil(1 / $Row['DestroyInOneTurn']).')'; + } + } + else + { + $Row['Input_DestroyInOneTurn']= '-'; + } + $Row['Input_RapidFireValue'] = $_Vars_CombatData[$ShipID]['sd'][$ID]; + + if($TargetID == 0) + { + $Row['Input_CompareProfitability'] = '0'; + } + else + { + if($_Vars_CombatData[$ID]['attack'] > 0) + { + $Row['Profitability'] = $_Vars_CombatData[$ID]['attack'] / $Ship2['Life']; + if($Row['Profitability'] > 1) + { + $Row['Profitability'] = 1; + } + if($_Vars_CombatData[$ID]['sd'][$TargetID] > 1) + { + $Row['Profitability'] *= $_Vars_CombatData[$ID]['sd'][$TargetID]; + } + $Row['Profitability'] = $Row['Price'] / $Row['Profitability']; + + $Row['Input_CompareProfitability'] = $Ship['Profitability'] / $Row['Profitability']; + } + else + { + $Row['Input_CompareProfitability'] = '0'; + } + } + + $_Lang['Input_InsertRows'] .= parsetemplate($TPL_Rows, $Row); + } + + $_Lang['Input_InsertHeaders'] = parsetemplate($TPL_Headers, $_Lang); + } + else + { + $_Lang['Table_SelectShip'] = $_Lang['Table_BadShip']; + } + } + + $_Lang['Input_Selector_ShipList'] = ''; + $_Lang['Input_Selector_ShipList2'] = ''; + foreach($_Vars_ElementCategories['fleet'] as $ID) + { + $_Lang['Input_Selector_ShipList'] .= ""; + $_Lang['Input_Selector_ShipList2'] .= ""; + } + + display(parsetemplate($TPL, $_Lang), $_Lang['Page_Title'], false, true); +} +else +{ + message($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); +} + +?> diff --git a/admin/unbanuser.php b/admin/unbanuser.php index ba22f2d24..0fa7a0ef7 100644 --- a/admin/unbanuser.php +++ b/admin/unbanuser.php @@ -1,158 +1,158 @@ - 0) - { - while($Data = mysql_fetch_assoc($CheckUsers)) - { - if($Data['is_banned'] == 1 AND $Data['ban_endtime'] > $Now) - { - $UnbanUsers[$Data['id']] = $Data; - if($Data['is_onvacation'] == 1) - { - $UpdatePlanets[] = $Data['id']; - } - } - } - } - if(!empty($UnbanUsers)) - { - $UnbannedCount = count($UnbanUsers); - - $UpdateFields[] = "`is_banned` = 0"; - $UpdateFields[] = "`ban_endtime` = 0"; - if($Opt_RemoveVacation) - { - $UpdateFields[] = "`is_onvacation` = 0"; - $UpdateFields[] = "`vacation_starttime` = 0"; - $UpdateFields[] = "`vacation_endtime` = 0"; - } - else - { - $EndVacation = $Now + (MAXVACATIONS_REG * TIME_DAY); - $UpdateFields[] = "`vacation_endtime` = IF(`is_onvacation` = 1, {$EndVacation}, `vacation_endtime`)"; - } - $UpdateFields[] = "`block_cookies` = 0"; - - $UserIDs = implode(', ', array_keys($UnbanUsers)); - doquery("UPDATE {{table}} SET ".implode(', ', $UpdateFields)." WHERE `id` IN ({$UserIDs});", 'users'); - doquery("UPDATE {{table}} SET `Active` = 0, `Removed` = 1, `RemoveDate` = {$Now} WHERE `Active` = 1 AND `EndTime` > {$Now} AND `UserID` IN ({$UserIDs});", 'bans'); - if($Opt_RemoveVacation AND !empty($UpdatePlanets)) - { - $PlanetUsers = implode(', ', $UpdatePlanets); - doquery("UPDATE {{table}} SET `last_update` = {$Now} WHERE `id_owner` IN ({$PlanetUsers});", 'planets'); - } - - $UserLinkTPL = gettemplate('admin/banuser_userlink'); - foreach($UnbanUsers as $UserID => $UserData) - { - $UserLinks[] = parsetemplate($UserLinkTPL, array('ID' => $UserID, 'Username' => $UserData['username'])); - } - $UserLinks = implode(', ', $UserLinks); - $_Lang['InsertInfoBoxText'] = sprintf(($UnbannedCount > 1 ? $_Lang['Msg_UnbanMOK'] : $_Lang['Msg_Unban1OK']), $UserLinks); - $_Lang['InsertInfoBoxColor'] = 'lime'; - $_Lang['Insert_SearchBox'] = ''; - } - else - { - $_Lang['InsertInfoBoxText'] = $_Lang['Error_NoOne2Unban']; - } - } - else - { - $_Lang['InsertInfoBoxText'] = $_Lang['Error_BadSearch']; - } - } - else - { - $_Lang['InsertInfoBoxText'] = $_Lang['Error_EmptySearch']; - } - } - - if(!empty($_GET['ids'])) - { - $InsertIDs = explode(',', $_GET['ids']); - foreach($InsertIDs as $ThisID) - { - $_Lang['InsertUsernames'][] = "[{$ThisID}]"; - } - $_Lang['InsertUsernames'] = implode(',', $_Lang['InsertUsernames']); - } - else if(!empty($_GET['user'])) - { - $_Lang['InsertUsernames'] = $_GET['user']; - } - - display(parsetemplate(gettemplate('admin/unbanuser'), $_Lang), $_Lang['Page_Title'], false, true); - -?> \ No newline at end of file + 0) + { + while($Data = mysql_fetch_assoc($CheckUsers)) + { + if($Data['is_banned'] == 1 AND $Data['ban_endtime'] > $Now) + { + $UnbanUsers[$Data['id']] = $Data; + if($Data['is_onvacation'] == 1) + { + $UpdatePlanets[] = $Data['id']; + } + } + } + } + if(!empty($UnbanUsers)) + { + $UnbannedCount = count($UnbanUsers); + + $UpdateFields[] = "`is_banned` = 0"; + $UpdateFields[] = "`ban_endtime` = 0"; + if($Opt_RemoveVacation) + { + $UpdateFields[] = "`is_onvacation` = 0"; + $UpdateFields[] = "`vacation_starttime` = 0"; + $UpdateFields[] = "`vacation_endtime` = 0"; + } + else + { + $EndVacation = $Now + (MAXVACATIONS_REG * TIME_DAY); + $UpdateFields[] = "`vacation_endtime` = IF(`is_onvacation` = 1, {$EndVacation}, `vacation_endtime`)"; + } + $UpdateFields[] = "`block_cookies` = 0"; + + $UserIDs = implode(', ', array_keys($UnbanUsers)); + doquery("UPDATE {{table}} SET ".implode(', ', $UpdateFields)." WHERE `id` IN ({$UserIDs});", 'users'); + doquery("UPDATE {{table}} SET `Active` = 0, `Removed` = 1, `RemoveDate` = {$Now} WHERE `Active` = 1 AND `EndTime` > {$Now} AND `UserID` IN ({$UserIDs});", 'bans'); + if($Opt_RemoveVacation AND !empty($UpdatePlanets)) + { + $PlanetUsers = implode(', ', $UpdatePlanets); + doquery("UPDATE {{table}} SET `last_update` = {$Now} WHERE `id_owner` IN ({$PlanetUsers});", 'planets'); + } + + $UserLinkTPL = gettemplate('admin/banuser_userlink'); + foreach($UnbanUsers as $UserID => $UserData) + { + $UserLinks[] = parsetemplate($UserLinkTPL, array('ID' => $UserID, 'Username' => $UserData['username'])); + } + $UserLinks = implode(', ', $UserLinks); + $_Lang['InsertInfoBoxText'] = sprintf(($UnbannedCount > 1 ? $_Lang['Msg_UnbanMOK'] : $_Lang['Msg_Unban1OK']), $UserLinks); + $_Lang['InsertInfoBoxColor'] = 'lime'; + $_Lang['Insert_SearchBox'] = ''; + } + else + { + $_Lang['InsertInfoBoxText'] = $_Lang['Error_NoOne2Unban']; + } + } + else + { + $_Lang['InsertInfoBoxText'] = $_Lang['Error_BadSearch']; + } + } + else + { + $_Lang['InsertInfoBoxText'] = $_Lang['Error_EmptySearch']; + } +} + +if(!empty($_GET['ids'])) +{ + $InsertIDs = explode(',', $_GET['ids']); + foreach($InsertIDs as $ThisID) + { + $_Lang['InsertUsernames'][] = "[{$ThisID}]"; + } + $_Lang['InsertUsernames'] = implode(',', $_Lang['InsertUsernames']); +} +else if(!empty($_GET['user'])) +{ + $_Lang['InsertUsernames'] = $_GET['user']; +} + +display(parsetemplate(gettemplate('admin/unbanuser'), $_Lang), $_Lang['Page_Title'], false, true); + +?> diff --git a/admin/updater.php b/admin/updater.php index 91feae86a..95cbbc206 100644 --- a/admin/updater.php +++ b/admin/updater.php @@ -1,57 +1,57 @@ - $lastUpdate) - { - $updatesFound[] = $version; - } - } - } - - if(!empty($updatesFound)) - { - define('IN_UPDATER', true); - - foreach($updatesFound as $version) - { - include_once('updates/update'.$version.'.php'); - } - - $lastUpdate = end($updatesFound); - doquery("UPDATE {{table}} SET `config_value` = '{$lastUpdate}' WHERE `config_name` = 'UniEngine_Updater_LastUpdateApplied';", 'config'); - $_GameConfig['UniEngine_Updater_LastUpdateApplied'] = $lastUpdate; - $_MemCache->GameConfig = $_GameConfig; - - AdminMessage(sprintf($_Lang['Updater_Done'], $lastUpdate), $_Lang['Updater_Title']); - } - else - { - AdminMessage($_Lang['Updater_NothingFound'], $_Lang['Updater_Title']); - } - -?> \ No newline at end of file + $lastUpdate) + { + $updatesFound[] = $version; + } + } +} + +if(!empty($updatesFound)) +{ + define('IN_UPDATER', true); + + foreach($updatesFound as $version) + { + include_once('updates/update'.$version.'.php'); + } + + $lastUpdate = end($updatesFound); + doquery("UPDATE {{table}} SET `config_value` = '{$lastUpdate}' WHERE `config_name` = 'UniEngine_Updater_LastUpdateApplied';", 'config'); + $_GameConfig['UniEngine_Updater_LastUpdateApplied'] = $lastUpdate; + $_MemCache->GameConfig = $_GameConfig; + + AdminMessage(sprintf($_Lang['Updater_Done'], $lastUpdate), $_Lang['Updater_Title']); +} +else +{ + AdminMessage($_Lang['Updater_NothingFound'], $_Lang['Updater_Title']); +} + +?> diff --git a/admin/updates/index.php b/admin/updates/index.php index 2c5d40047..bc99142d1 100644 --- a/admin/updates/index.php +++ b/admin/updates/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/admin/updates/update1.php b/admin/updates/update1.php index 209639f81..01b34ba95 100644 --- a/admin/updates/update1.php +++ b/admin/updates/update1.php @@ -1,15 +1,15 @@ - \ No newline at end of file + diff --git a/admin/user_info.php b/admin/user_info.php index bcb49184e..f5701e783 100644 --- a/admin/user_info.php +++ b/admin/user_info.php @@ -1,722 +1,722 @@ -= {$_User['authlevel']} AND `id` != {$_User['id']};"; - $Result = doquery($Query, 'users'); - if(mysql_num_rows($Result) > 0) - { - while($Data = mysql_fetch_assoc($Result)) - { - $ExcludedUsers[] = $Data['id']; - } - } - - if(!empty($_GET['uid'])) - { - $UID = intval($_GET['uid']); - if($UID <= 0) - { - message($_Lang['Error_BadUID'], $Error); - } - else - { - $WhereClausure = "`user`.`id` = {$UID}"; - $OnNotFoundError = 'UID'; - } - } - else - { - if(!empty($_GET['name'])) - { - $Name = trim($_GET['name']); - if(preg_match(REGEXP_USERNAME_ABSOLUTE, $Name)) - { - $WhereClausure = "`user`.`username` = '{$Name}'"; - $OnNotFoundError = 'Name'; - } - else - { - message($_Lang['Error_BadName'], $Error); - } - } - else - { - message($_Lang['Error_NoUID_NoName'], $Error); - } - } - - $Query_GetUser = ''; - $Query_GetUser .= "SELECT `user`.*, `planet`.`name` AS `mothername`, "; - $Query_GetUser .= "`ally`.`ally_name`, `ally`.`ally_name` AS `ally_request_name`, `ally`.`ally_owner` AS `ally_owner`, "; - $Query_GetUser .= "`inviter`.`username` AS `inviter_username` "; - $Query_GetUser .= "FROM {{table}} AS `user` "; - $Query_GetUser .= "LEFT JOIN `{{prefix}}planets` AS `planet` ON `planet`.`id` = `user`.`id_planet` "; - $Query_GetUser .= "LEFT JOIN `{{prefix}}alliance` AS `ally` ON "; - $Query_GetUser .= "(`user`.`ally_request` > 0 AND `ally`.`id` = `user`.`ally_request`) "; - $Query_GetUser .= "OR "; - $Query_GetUser .= "(`user`.`ally_id` > 0 AND `ally`.`id` = `user`.`ally_id`) "; - $Query_GetUser .= "LEFT JOIN `{{prefix}}users` AS `inviter` ON `user`.`referred` > 0 AND `user`.`referred` = `inviter`.`id` "; - $Query_GetUser .= "WHERE {$WhereClausure} "; - $Query_GetUser .= "LIMIT 1;"; - $Result = doquery($Query_GetUser, 'users'); - - if(mysql_num_rows($Result) == 0) - { - message($_Lang['Error_NotFound_'.$OnNotFoundError], $Error); - } - - $Now = time(); - $Data = mysql_fetch_assoc($Result); - $UID = $Data['id']; - - if(!empty($ExcludedUsers)) - { - if(in_array($UID, $ExcludedUsers)) - { - message($_Lang['Error_NoEnoughAccess'], $Error); - } - } - - $Query = "SELECT * FROM {{table}} WHERE `id_owner` = {$UID} AND `stat_type` = 1 LIMIT 1;"; - $Result = doquery($Query, 'statpoints'); - if(mysql_num_rows($Result) == 0) - { - $Data['stats'] = 'EMPTY'; - } - else - { - $Data['stats'] = mysql_fetch_assoc($Result); - } - - $Query = "SELECT * FROM {{table}} WHERE `fleet_owner` = {$UID} OR `fleet_target_owner` = {$UID};"; - $Result = doquery($Query, 'fleets'); - if(mysql_num_rows($Result) == 0) - { - $Data['fleets'] = 'EMPTY'; - } - else - { - while($Fleets = mysql_fetch_assoc($Result)) - { - $GetACSData[] = $Fleets['fleet_id']; - $Data['fleets'][$Fleets['fleet_id']] = $Fleets; - if(empty($GetUserNicks) OR !in_array($Fleets['fleet_owner'], $GetUserNicks)) - { - $GetUserNicks[] = $Fleets['fleet_owner']; - } - if(empty($GetUserNicks) OR !in_array($Fleets['fleet_target_owner'], $GetUserNicks) AND $Fleets['fleet_target_owner'] > 0) - { - $GetUserNicks[] = $Fleets['fleet_target_owner']; - } - } - if(!empty($GetUserNicks)) - { - $Query = "SELECT `id`, `username` FROM {{table}} WHERE `id` IN (".implode(', ', $GetUserNicks).");"; - $Result = doquery($Query, 'users'); - if(mysql_num_rows($Result) > 0) - { - while($UserData = mysql_fetch_assoc($Result)) - { - $UsersNicks[$UserData['id']] = $UserData['username']; - } - } - } - if(!empty($GetACSData)) - { - foreach($GetACSData as $ACSTempData) - { - $CheckJoinedFleets[] = "`fleets_id` LIKE '%|{$ACSTempData}|%'"; - } - $CheckJoinedFleets = implode(' OR ', $CheckJoinedFleets); - $Query = "SELECT `id`, `main_fleet_id`, `fleets_id` FROM {{table}} WHERE `main_fleet_id` IN (".implode(', ', $GetACSData).") OR {$CheckJoinedFleets};"; - $Result = doquery($Query, 'acs'); - if(mysql_num_rows($Result) > 0) - { - while($TempACSData = mysql_fetch_assoc($Result)) - { - $TempFleetsFromACS = false; - $Temp1 = explode(',', str_replace('|', '', $TempACSData['fleets_id'])); - foreach($Temp1 as $TempData) - { - $ACSData[$TempData] = $TempACSData['id']; - } - $ACSData[$TempACSData['main_fleet_id']] = $TempACSData['id']; - } - } - } - } - - $TPL = gettemplate('admin/user_info'); - $Parse= $_Lang; - - if(empty($_GET['mark']) OR $_GET['mark'] == '1') - { - $Parse['MarkSelect'] = '01'; - } - else - { - $Parse['MarkSelect'] = "0{$_GET['mark']}"; - } - - // --- Create General Overview Marker! --- - - $Player['Name'] = $Data['username']; - $Player['Email'] = $Data['email']; - $Player['Email2'] = $Data['email_2']; - $Player['LastIP'] = (!empty($Data['user_lastip']) ? "{$Data['user_lastip']}" : $_Lang['NoLogin']); - $Player['RegIP'] = (!empty($Data['ip_at_reg']) ? "{$Data['ip_at_reg']}" : $_Lang['No_Data']); - - // - Last Activity - $OnlineDiff = $Now - $Data['onlinetime']; - if($OnlineDiff >= 28 * TIME_DAY) - { - $OLColor = 'red'; - } - else if($OnlineDiff >= 7 * TIME_DAY) - { - $OLColor = '#FFA0A0'; - } - else if($OnlineDiff >= TIME_DAY) - { - $OLColor = 'orange'; - } - else if($OnlineDiff > TIME_ONLINE) - { - $OLColor = 'yellow'; - } - else - { - $OLColor = 'lime'; - } - $OnlineDiffText = '('.pretty_time($OnlineDiff).' '.$_Lang['_ago'].')'; - if($OLColor == 'lime') - { - $OnlineDiffText = "{$OnlineDiffText}"; - } - if(CheckAuth('supportadmin')) - { - $OnlineDiffText = "{$OnlineDiffText}
{$Data['current_page']}
{$_Lang['ShowLogs']}"; - } - $Player['LastActivity'] = prettyDate('d m Y, H:i:s', $Data['onlinetime'], 1)."
{$OnlineDiffText}"; - // - END - Last Activy - $Player['Browser'] = (!empty($Data['user_agent']) ? $Data['user_agent'] : $_Lang['No_Data']); - $Player['Screen'] = (!empty($Data['screen_settings']) ? str_replace('_', 'x', $Data['screen_settings']) : $_Lang['No_Data']); - - // - Registration Time - if($Data['register_time'] > 0) - { - $Bloc['adm_ul_data_regd'] = ''; - $RegisterDays = floor(($Now - $Data['register_time']) / (24*60*60)); - if($RegisterDays == 1) - { - $RegDays = $_Lang['_day']; - } - else - { - $RegDays = $_Lang['_days']; - } - $RegisterDays = prettyNumber($RegisterDays); - if($RegisterDays == 0) - { - if(date('d') == date('d', $Data['register_time'])) - { - $Player['RegisterInfo'] = $_Lang['_today']; - } - else - { - $Player['RegisterInfo'] = $_Lang['_yesterday']; - } - } - else - { - $Player['RegisterInfo'] = "{$RegisterDays} {$RegDays} {$_Lang['_ago']}"; - } - $Player['RegisterInfo'] .= '
'.prettyDate('d m Y, H:i:s', $Data['register_time'], 1); - } - else - { - $Player['RegisterInfo'] = $_Lang['No_Data']; - } - // - END - Registration Time - - // MoreInfo - Vacation Info - if(isOnVacation($Data)) - { - $Player['Vacations']= "{$_Lang['Active']}
({$_Lang['_Since']}: ".pretty_time($Now - $Data['vacation_starttime'])." / ".prettyDate('d m Y, H:i:s', $Data['vacation_starttime'], 1).")
(".($Data['vacation_endtime'] == 0 ? "{$_Lang['InfiniteVacation']}" : "{$_Lang['_Duration']}: ".pretty_time($Data['vacation_endtime'] - $Now)." / ".prettyDate('d m Y, H:i:s', $Data['vacation_endtime'], 1)).")"; - } - else - { - $Player['Vacations']= $_Lang['Inactive']; - } - - $Player['Ban'] = ''; - if($Data['is_banned'] == 1) - { - if($Data['ban_endtime'] < $Now) - { - $BanColor = 'orange'; - $BanTime= $_Lang['Ban_Expired']; - } - else - { - $BanColor = 'red'; - $BanTime= $_Lang['Ban_TimeLeft'].' '.pretty_time($Data['ban_endtime'] - $Now); - } - $Player['Ban'] = "{$_Lang['Active']}
({$_Lang['_Untill']}: ".prettyDate("d m Y, H:i:s", $Data['ban_endtime'], 1).")
({$BanTime})"; - } - else - { - $Player['Ban'] = $_Lang['Inactive']; - } - if($Data['block_cookies'] == 1) - { - $Player['Ban'] .= "
({$_Lang['CookieBanActive']})"; - } - - $Player['Delete'] = ($Data['is_ondeletion'] == 1 ? "{$_Lang['Active']}
".($Data['deletion_endtime'] < $Now ? $_Lang['Delete_Time_onNextRecalc'] : "{$_Lang['Delete_Time']}: ".pretty_time($Data['deletion_endtime'] - $Now))."
".prettyDate('d m Y, H:i:s', $Data['deletion_endtime'], 1) : $_Lang['Inactive'] ); - $Player['OldNick'] = (!empty($Data['old_username']) ? "{$Data['old_username']}
".($Data['old_username_expire'] > $Now ? $_Lang['WillExpire'].pretty_time($Data['old_username_expire'] - $Now) : "{$_Lang['Expired']}")."
".prettyDate('d m Y, H:i:s', $Data['old_username_expire'], 1) : $_Lang['No_Data']); - $Player['InvitedBy'] = ($Data['referred'] > 0 ? (!empty($Data['inviter_username']) ? "{$Data['inviter_username']} [#{$Data['referred']}]" : "{$_Lang['InviterDeleted']} [#{$Data['referred']}]") : $_Lang['NotInvited']); - - $Player['DarkEnergy'] = ($Data['darkEnergy'] > 0 ? prettyNumber($Data['darkEnergy']) : '0'); - $Player['ProTime'] = ($Data['pro_time'] > 0 ? ($Data['pro_time'] > $Now ? "{$_Lang['WillExpire']}
".pretty_time($Data['pro_time'] - $Now)."
".prettyDate('d m Y, H:i:s', $Data['pro_time'], 1) : "{$_Lang['Expired2']}
".pretty_time(-($Data['pro_time'] - $Now))." {$_Lang['_ago']}
".prettyDate('d m Y, H:i:s', $Data['pro_time'], 1)) : $_Lang['NeverBought']); - $Player['GeoTime'] = ($Data['geologist_time'] > 0 ? ($Data['geologist_time'] > $Now ? "{$_Lang['WillExpire']}
".pretty_time($Data['geologist_time'] - $Now)."
".prettyDate('d m Y, H:i:s', $Data['geologist_time'], 1) : "{$_Lang['Expired']}
".pretty_time(-($Data['geologist_time'] - $Now))." {$_Lang['_ago']}
".prettyDate('d m Y, H:i:s', $Data['geologist_time'], 1)) : $_Lang['NeverBought']); - $Player['EngTime'] = ($Data['engineer_time'] > 0 ? ($Data['engineer_time'] > $Now ? "{$_Lang['WillExpire']}
".pretty_time($Data['engineer_time'] - $Now)."
".prettyDate('d m Y, H:i:s', $Data['engineer_time'], 1) : "{$_Lang['Expired']}
".pretty_time(-($Data['engineer_time'] - $Now))." {$_Lang['_ago']}
".prettyDate('d m Y, H:i:s', $Data['engineer_time'], 1)) : $_Lang['NeverBought']); - $Player['AdmTime'] = ($Data['admiral_time'] > 0 ? ($Data['admiral_time'] > $Now ? "{$_Lang['WillExpire']}
".pretty_time($Data['admiral_time'] - $Now)."
".prettyDate('d m Y, H:i:s', $Data['admiral_time'], 1) : "{$_Lang['Expired']}
".pretty_time(-($Data['admiral_time'] - $Now))." {$_Lang['_ago']}
".prettyDate('d m Y, H:i:s', $Data['admiral_time'], 1)) : $_Lang['NeverBought']); - $Player['TecTime'] = ($Data['technocrat_time'] > 0 ? ($Data['technocrat_time'] > $Now ? "{$_Lang['WillExpire']}
".pretty_time($Data['technocrat_time'] - $Now)."
".prettyDate('d m Y, H:i:s', $Data['technocrat_time'], 1) : "{$_Lang['Expired']}
".pretty_time(-($Data['technocrat_time'] - $Now))." {$_Lang['_ago']}
".prettyDate('d m Y, H:i:s', $Data['technocrat_time'], 1)) : $_Lang['NeverBought']); - $Player['JamTime'] = ($Data['spy_jam_time'] > 0 ? ($Data['spy_jam_time'] > $Now ? "{$_Lang['WillExpire']}
".pretty_time($Data['spy_jam_time'] - $Now)."
".prettyDate('d m Y, H:i:s', $Data['spy_jam_time'], 1) : "{$_Lang['Expired']}
".pretty_time(-($Data['spy_jam_time'] - $Now))." {$_Lang['_ago']}
".prettyDate('d m Y, H:i:s', $Data['spy_jam_time'], 1)) : $_Lang['NeverBought']); - $Player['AdditionalPlanets'] = ($Data['additional_planets'] > 0 ? prettyNumber($Data['additional_planets']) : '0'); - if($Data['ally_id'] <= 0 AND $Data['ally_request'] > 0) - { - $Data['ally_id'] = $Data['ally_request']; - $Data['ally_name'] = $Data['ally_request_name']; - } - $Player['Ally'] = ($Data['ally_id'] > 0 ? ''.$Data['ally_name'].' ('.$Data['ally_id'].')'.($Data['ally_request'] != 0 ? ' ['.$_Lang['Request'].']' : ($Data['ally_owner'] == $UID ? ' ['.$_Lang['Ally_owner'].']' : '')) : ' - '); - $Player['AccountActive'] = (!empty($Data['activation_code']) ? "{$_Lang['_no']}
{$_Lang['ActivationCode']}: {$Data['activation_code']}" : "{$_Lang['_yes']}"); - $Player['DisableIPCheck'] = (($Data['noipcheck'] == 1) ? $_Lang['_no'] : $_Lang['_yes']); - $Player['MotherPlanet'] = "{$Data['mothername']} ({$_Lang['MotherPlanet_ID']}: {$Data['id_planet']}) [{$Data['galaxy']}:{$Data['system']}:{$Data['planet']}]"; - - // --- END of Creating General Overview Marker! --- - - // --- Create Statistics Marker! --- - - if($Data['stats'] == 'EMPTY') - { - $Parse['HideStatsIfUnavailable']= 'style="display: none;"'; - $Parse['ShowInfoIfStatsUnavailable']= "
{$_Lang['NoStatsAvailable']}
 "; - } - else - { - // General Pos - $Player['GeneralPos'] = $Data['stats']['total_rank']; - $Player['GeneralChange1'] = $Data['stats']['total_rank'] - $Data['stats']['total_old_rank']; - if($Data['stats']['total_yesterday_rank'] > 0) - { - $Player['GeneralChange2'] = $Data['stats']['total_rank'] - $Data['stats']['total_yesterday_rank']; - } - else - { - $Player['GeneralChange2'] = 0; - } - if($Player['GeneralChange1'] == 0) - { - $Player['GeneralChange1'] = "0"; - } - else if($Player['GeneralChange1'] < 0) - { - $Player['GeneralChange1'] = abs($Player['GeneralChange1']); - $Player['GeneralChange1'] = "+{$Player['GeneralChange1']}"; - } - else - { - $Player['GeneralChange1'] = "-{$Player['GeneralChange1']}"; - } - if($Player['GeneralChange2'] == 0) - { - $Player['GeneralChange2'] = "0"; - } - else if($Player['GeneralChange2'] < 0) - { - $Player['GeneralChange2'] = abs($Player['GeneralChange2']); - $Player['GeneralChange2'] = "+{$Player['GeneralChange2']}"; - } - else - { - $Player['GeneralChange2'] = "-{$Player['GeneralChange2']}"; - } - $Player['GeneralPoints']= prettyNumber($Data['stats']['total_points']); - - // Fleet pos - $Player['FleetPos'] = $Data['stats']['fleet_rank']; - $Player['FleetChange1'] = $Data['stats']['fleet_rank'] - $Data['stats']['fleet_old_rank']; - if($Data['stats']['fleet_yesterday_rank'] > 0) - { - $Player['FleetChange2'] = $Data['stats']['fleet_rank'] - $Data['stats']['fleet_yesterday_rank']; - } - else - { - $Player['FleetChange2'] = 0; - } - if($Player['FleetChange1'] == 0) - { - $Player['FleetChange1'] = "0"; - } - else if($Player['FleetChange1'] < 0) - { - $Player['FleetChange1'] = abs($Player['FleetChange1']); - $Player['FleetChange1'] = "+{$Player['FleetChange1']}"; - } - else - { - $Player['FleetChange1'] = "-{$Player['FleetChange1']}"; - } - if($Player['FleetChange2'] == 0) - { - $Player['FleetChange2'] = "0"; - } - else if($Player['FleetChange2'] < 0) - { - $Player['FleetChange2'] = abs($Player['FleetChange2']); - $Player['FleetChange2'] = "+{$Player['FleetChange2']}"; - } - else - { - $Player['FleetChange2'] = "-{$Player['FleetChange2']}"; - } - $Player['FleetPoints']= prettyNumber($Data['stats']['fleet_points']); - if($Data['stats']['total_points'] != 0) - { - $Player['FleetPercent'] = (round($Data['stats']['fleet_points']/$Data['stats']['total_points'], 4) * 100).'%'; - } - else - { - $Player['FleetPercent'] = '0%'; - } - - // Buildings pos - $Player['BuildingsPos'] = $Data['stats']['build_rank']; - $Player['BuildingsChange1'] = $Data['stats']['build_rank'] - $Data['stats']['build_old_rank']; - if($Data['stats']['build_yesterday_rank'] > 0) - { - $Player['BuildingsChange2'] = $Data['stats']['build_rank'] - $Data['stats']['build_yesterday_rank']; - } - else - { - $Player['BuildingsChange2'] = 0; - } - if($Player['BuildingsChange1'] == 0) - { - $Player['BuildingsChange1'] = "0"; - } - else if($Player['BuildingsChange1'] < 0) - { - $Player['BuildingsChange1'] = abs($Player['BuildingsChange1']); - $Player['BuildingsChange1'] = "+{$Player['BuildingsChange1']}"; - } - else - { - $Player['BuildingsChange1'] = "-{$Player['BuildingsChange1']}"; - } - if($Player['BuildingsChange2'] == 0) - { - $Player['BuildingsChange2'] = "0"; - } - else if($Player['BuildingsChange2'] < 0) - { - $Player['BuildingsChange2'] = abs($Player['BuildingsChange2']); - $Player['BuildingsChange2'] = "+{$Player['BuildingsChange2']}"; - } - else - { - $Player['BuildingsChange2'] = "-{$Player['BuildingsChange2']}"; - } - $Player['BuildingsPoints']= prettyNumber($Data['stats']['build_points']); - if($Data['stats']['total_points'] != 0) - { - $Player['BuildingsPercent'] = (round($Data['stats']['build_points']/$Data['stats']['total_points'], 4) * 100).'%'; - } - else - { - $Player['BuildingsPercent'] = '0%'; - } - - // Defence pos - $Player['DefencePos'] = $Data['stats']['defs_rank']; - $Player['DefenceChange1'] = $Data['stats']['defs_rank'] - $Data['stats']['defs_old_rank']; - if($Data['stats']['defs_yesterday_rank'] > 0) - { - $Player['DefenceChange2'] = $Data['stats']['defs_rank'] - $Data['stats']['defs_yesterday_rank']; - } - else - { - $Player['DefenceChange2'] = 0; - } - if($Player['DefenceChange1'] == 0) - { - $Player['DefenceChange1'] = "0"; - } - else if($Player['DefenceChange1'] < 0) - { - $Player['DefenceChange1'] = abs($Player['DefenceChange1']); - $Player['DefenceChange1'] = "+{$Player['DefenceChange1']}"; - } - else - { - $Player['DefenceChange1'] = "-{$Player['DefenceChange1']}"; - } - if($Player['DefenceChange2'] == 0) - { - $Player['DefenceChange2'] = "0"; - } - else if($Player['DefenceChange2'] < 0) - { - $Player['DefenceChange2'] = abs($Player['DefenceChange2']); - $Player['DefenceChange2'] = "+{$Player['DefenceChange2']}"; - } - else - { - $Player['DefenceChange2'] = "-{$Player['DefenceChange2']}"; - } - $Player['DefencePoints']= prettyNumber($Data['stats']['defs_points']); - if($Data['stats']['total_points'] != 0) - { - $Player['DefencePercent'] = (round($Data['stats']['defs_points']/$Data['stats']['total_points'], 4) * 100).'%'; - } - else - { - $Player['DefencePercent'] = '0%'; - } - - // Research pos - $Player['ResearchPos'] = $Data['stats']['tech_rank']; - $Player['ResearchChange1'] = $Data['stats']['tech_rank'] - $Data['stats']['tech_old_rank']; - if($Data['stats']['tech_yesterday_rank'] > 0) - { - $Player['ResearchChange2'] = $Data['stats']['tech_rank'] - $Data['stats']['tech_yesterday_rank']; - } - else - { - $Player['ResearchChange2'] = 0; - } - if($Player['ResearchChange1'] == 0) - { - $Player['ResearchChange1'] = "0"; - } - else if($Player['ResearchChange1'] < 0) - { - $Player['ResearchChange1'] = abs($Player['ResearchChange1']); - $Player['ResearchChange1'] = "+{$Player['ResearchChange1']}"; - } - else - { - $Player['ResearchChange1'] = "-{$Player['ResearchChange1']}"; - } - if($Player['ResearchChange2'] == 0) - { - $Player['ResearchChange2'] = "0"; - } - else if($Player['ResearchChange2'] < 0) - { - $Player['ResearchChange2'] = abs($Player['ResearchChange2']); - $Player['ResearchChange2'] = "+{$Player['ResearchChange2']}"; - } - else - { - $Player['ResearchChange2'] = "-{$Player['ResearchChange2']}"; - } - $Player['ResearchPoints']= prettyNumber($Data['stats']['tech_points']); - if($Data['stats']['total_points'] != 0) - { - $Player['ResearchPercent'] = (round($Data['stats']['tech_points']/$Data['stats']['total_points'], 4) * 100).'%'; - } - else - { - $Player['ResearchPercent'] = '0%'; - } - } - - // --- END of Creating Statistics Marker! --- - - // --- Create Fleet Control Marker! --- - - if($Data['fleets'] == 'EMPTY') - { - $Parse['FleetControlContent']= "
{$_Lang['NoFleetsInFlight']}
 "; - } - else - { - $FleetTPL = gettemplate('admin/user_info_fleet_row'); - $FleetHeadTPL = gettemplate('admin/user_info_fleet_header'); - - include("{$_EnginePath}/includes/functions/InsertJavaScriptChronoApplet.php"); - - $AllFleetParse = ''; - foreach($Data['fleets'] as $FleetID => $FleetData) - { - $FleetParse = false; - $FleetArray = false; - $FleetShipsTemp = false; - $FleetCount = 0; - $FleetShipsParsed = false; - - $FleetParse['Fleet_ID'] = $FleetID; - $FleetParse['Fleet_Owner'] = "{$UsersNicks[$FleetData['fleet_owner']]}
[{$FleetData['fleet_owner']}]"; - if($FleetData['fleet_owner'] == $UID) - { - $FleetParse['Fleet_Owner_color'] = 'lime'; - } - else - { - if(in_array($FleetData['fleet_mission'], array(1, 2, 6, 9, 10, 11))) - { - $FleetParse['Fleet_Owner_color'] = 'red'; - } - else - { - $FleetParse['Fleet_Owner_color'] = 'blue'; - } - $FleetParse['Fleet_Owner'] = "{$FleetParse['Fleet_Owner']}"; - } - $FleetParse['Fleet_Mission'] = $_Lang['type_mission'][$FleetData['fleet_mission']]; - if($ACSData[$FleetID] > 0) - { - if($FleetData['fleet_mission'] == 1) - { - $FleetParse['Fleet_Mission'] = $_Lang['type_mission'][2]; - } - $FleetParse['Fleet_Mission'] = "{$FleetParse['Fleet_Mission']}
[ACS: {$ACSData[$FleetID]}]"; - if($FleetData['fleet_mission'] == 1) - { - $FleetParse['Fleet_Mission'] = "{$FleetParse['Fleet_Mission']}"; - } - } - if($FleetData['fleet_mess'] == 1 AND $FleetData['fleet_mission'] != 5) - { - $FleetParse['Fleet_Mission'] = "{$FleetParse['Fleet_Mission']}
[{$_Lang['Coming_back']}]"; - } - if(($FleetData['fleet_mess'] == 0 AND $FleetData['fleet_start_time'] <= $Now) OR ($FleetData['fleet_mess'] != 0 AND $FleetData['fleet_end_time'] <= $Now)) - { - $FleetParse['Fleet_Mission'] = "{$FleetParse['Fleet_Mission']}
[{$_Lang['Not_calculated']}]"; - } - - $FleetArray = explode(';', $FleetData['fleet_array']); - foreach($FleetArray as $FleetShipsTemp) - { - if(!empty($FleetShipsTemp)) - { - $FleetShipsTemp = explode(',', $FleetShipsTemp); - $FleetCount += $FleetShipsTemp[1]; - $FleetShipsParsed[] = "{$_Lang['tech'][$FleetShipsTemp[0]]}".prettyNumber($FleetShipsTemp[1]).""; - } - } - $FleetCount = prettyNumber($FleetCount); - $FleetParse['Fleet_Ships'] = "".implode('', $FleetShipsParsed)."
"; - $FleetParse['Fleet_Array'] = "{$FleetCount}
(?)"; - if($FleetData['fleet_resource_metal'] == 0 AND $FleetData['fleet_resource_crystal'] == 0 AND $FleetData['fleet_resource_deuterium'] == 0) - { - $FleetParse['Fleet_Cargo'] = $_Lang['No_cargo']; - } - else - { - $FleetParse['Fleet_Cargo'] = $_Lang['See_cargo']; - $FleetParse['Fleet_Resources'] = "
{$_Lang['Metal']}".prettyNumber($FleetData['fleet_resource_metal'])."
{$_Lang['Crystal']}".prettyNumber($FleetData['fleet_resource_crystal'])."
{$_Lang['Deuterium']}".prettyNumber($FleetData['fleet_resource_deuterium'])."
"; - $FleetParse['Fleet_Cargo_class'] = ' fCar'; - } - $FleetParse['Fleet_Start_Title'] = ($FleetData['fleet_start_type'] == '1' ? $_Lang['Start_from_planet'] : $_Lang['Start_from_moon']); - $FleetParse['Fleet_Start'] = "[{$FleetData['fleet_start_galaxy']}:{$FleetData['fleet_start_system']}:{$FleetData['fleet_start_planet']}] ".($FleetData['fleet_start_type'] == '1' ? $_Lang['Planet_sign'] : $_Lang['Moon_sign']).""; - $FleetParse['Fleet_Start'].= "
".date('d.m.Y', $FleetData['fleet_send_time'])."
".date('H:i:s', $FleetData['fleet_send_time'])."
(".pretty_time($Now - $FleetData['fleet_send_time'], true, 'D')." {$_Lang['_ago']})"; - $_Lang['ChronoApplets'] .= InsertJavaScriptChronoApplet('a', $FleetID, $FleetData['fleet_send_time'], true, true); - - $FleetParse['Fleet_End_Title'] = ($FleetData['fleet_end_type'] == '1' ? $_Lang['Target_is_planet'] : ($FleetData['fleet_end_type'] == '2' ? $_Lang['Target_is_debris'] : $_Lang['Target_is_moon'])); - $FleetParse['Fleet_End'] = "[{$FleetData['fleet_end_galaxy']}:{$FleetData['fleet_end_system']}:{$FleetData['fleet_end_planet']}] ".($FleetData['fleet_end_type'] == '1' ? $_Lang['Planet_sign'] : ($FleetData['fleet_end_type'] == '2' ? $_Lang['Debris_sign'] : $_Lang['Moon_sign'])).""; - if($FleetData['fleet_start_time'] <= $Now) - { - $FleetParse['Fleet_end_time_set'] = "{$_Lang['TargetAchieved']}"; - } - else - { - $FleetParse['Fleet_end_time_set'] = pretty_time($FleetData['fleet_start_time'] - $Now, true, 'D'); - $_Lang['ChronoApplets'] .= InsertJavaScriptChronoApplet('b', $FleetID, $FleetData['fleet_start_time'] - $Now); - } - $FleetParse['Fleet_End'].= "
".date('d.m.Y', $FleetData['fleet_start_time'])."
".date('H:i:s', $FleetData['fleet_start_time'])."
({$FleetParse['Fleet_end_time_set']})"; - - $FleetParse['Fleet_End_owner']= "{$UsersNicks[$FleetData['fleet_target_owner']]}
[{$FleetData['fleet_target_owner']}]"; - if($FleetData['fleet_target_owner'] == $UID) - { - $FleetParse['Fleet_End_owner_color'] = 'lime'; - } - else - { - if(in_array($FleetData['fleet_mission'], array(1, 2, 6, 9, 10, 11))) - { - $FleetParse['Fleet_End_owner_color'] = 'red'; - } - else - { - $FleetParse['Fleet_End_owner_color'] = 'blue'; - } - $FleetParse['Fleet_End_owner'] = "{$FleetParse['Fleet_End_owner']}"; - } - - if($FleetData['fleet_end_time'] <= $Now) - { - $FleetParse['Fleet_back_time_set'] = "{$_Lang['FleetCameBack']}"; - } - else - { - $FleetParse['Fleet_back_time_set'] = pretty_time($FleetData['fleet_end_time'] - $Now, true, 'D'); - $_Lang['ChronoApplets'] .= InsertJavaScriptChronoApplet('c', $FleetID, $FleetData['fleet_end_time'] - $Now); - } - $FleetParse['Fleet_Back_time'].= date('d.m.Y - H:i:s', $FleetData['fleet_end_time'])."
({$FleetParse['Fleet_back_time_set']})"; - - $AllFleetParse .= parsetemplate($FleetTPL, $FleetParse); - } - - $_Lang['FleetParsed'] = $AllFleetParse; - - $Parse['FleetControlContent'] = parsetemplate($FleetHeadTPL, $_Lang); - } - - // --- END of Creating Fleet Control Marker! --- - - foreach($Player as $Key => $Val) - { - if(empty($Val)) - { - if($Val === 0 OR $Val === '0') - { - $Val = '0'; - } - else - { - $Val = ' '; - } - } - $Parse['Player'.$Key] = $Val; - } - - $Page = parsetemplate($TPL, $Parse); - display($Page, $_Lang['PageTitle'], false, true); - } - else - { - message($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); - } - -?> \ No newline at end of file += {$_User['authlevel']} AND `id` != {$_User['id']};"; + $Result = doquery($Query, 'users'); + if(mysql_num_rows($Result) > 0) + { + while($Data = mysql_fetch_assoc($Result)) + { + $ExcludedUsers[] = $Data['id']; + } + } + + if(!empty($_GET['uid'])) + { + $UID = intval($_GET['uid']); + if($UID <= 0) + { + message($_Lang['Error_BadUID'], $Error); + } + else + { + $WhereClausure = "`user`.`id` = {$UID}"; + $OnNotFoundError = 'UID'; + } + } + else + { + if(!empty($_GET['name'])) + { + $Name = trim($_GET['name']); + if(preg_match(REGEXP_USERNAME_ABSOLUTE, $Name)) + { + $WhereClausure = "`user`.`username` = '{$Name}'"; + $OnNotFoundError = 'Name'; + } + else + { + message($_Lang['Error_BadName'], $Error); + } + } + else + { + message($_Lang['Error_NoUID_NoName'], $Error); + } + } + + $Query_GetUser = ''; + $Query_GetUser .= "SELECT `user`.*, `planet`.`name` AS `mothername`, "; + $Query_GetUser .= "`ally`.`ally_name`, `ally`.`ally_name` AS `ally_request_name`, `ally`.`ally_owner` AS `ally_owner`, "; + $Query_GetUser .= "`inviter`.`username` AS `inviter_username` "; + $Query_GetUser .= "FROM {{table}} AS `user` "; + $Query_GetUser .= "LEFT JOIN `{{prefix}}planets` AS `planet` ON `planet`.`id` = `user`.`id_planet` "; + $Query_GetUser .= "LEFT JOIN `{{prefix}}alliance` AS `ally` ON "; + $Query_GetUser .= "(`user`.`ally_request` > 0 AND `ally`.`id` = `user`.`ally_request`) "; + $Query_GetUser .= "OR "; + $Query_GetUser .= "(`user`.`ally_id` > 0 AND `ally`.`id` = `user`.`ally_id`) "; + $Query_GetUser .= "LEFT JOIN `{{prefix}}users` AS `inviter` ON `user`.`referred` > 0 AND `user`.`referred` = `inviter`.`id` "; + $Query_GetUser .= "WHERE {$WhereClausure} "; + $Query_GetUser .= "LIMIT 1;"; + $Result = doquery($Query_GetUser, 'users'); + + if(mysql_num_rows($Result) == 0) + { + message($_Lang['Error_NotFound_'.$OnNotFoundError], $Error); + } + + $Now = time(); + $Data = mysql_fetch_assoc($Result); + $UID = $Data['id']; + + if(!empty($ExcludedUsers)) + { + if(in_array($UID, $ExcludedUsers)) + { + message($_Lang['Error_NoEnoughAccess'], $Error); + } + } + + $Query = "SELECT * FROM {{table}} WHERE `id_owner` = {$UID} AND `stat_type` = 1 LIMIT 1;"; + $Result = doquery($Query, 'statpoints'); + if(mysql_num_rows($Result) == 0) + { + $Data['stats'] = 'EMPTY'; + } + else + { + $Data['stats'] = mysql_fetch_assoc($Result); + } + + $Query = "SELECT * FROM {{table}} WHERE `fleet_owner` = {$UID} OR `fleet_target_owner` = {$UID};"; + $Result = doquery($Query, 'fleets'); + if(mysql_num_rows($Result) == 0) + { + $Data['fleets'] = 'EMPTY'; + } + else + { + while($Fleets = mysql_fetch_assoc($Result)) + { + $GetACSData[] = $Fleets['fleet_id']; + $Data['fleets'][$Fleets['fleet_id']] = $Fleets; + if(empty($GetUserNicks) OR !in_array($Fleets['fleet_owner'], $GetUserNicks)) + { + $GetUserNicks[] = $Fleets['fleet_owner']; + } + if(empty($GetUserNicks) OR !in_array($Fleets['fleet_target_owner'], $GetUserNicks) AND $Fleets['fleet_target_owner'] > 0) + { + $GetUserNicks[] = $Fleets['fleet_target_owner']; + } + } + if(!empty($GetUserNicks)) + { + $Query = "SELECT `id`, `username` FROM {{table}} WHERE `id` IN (".implode(', ', $GetUserNicks).");"; + $Result = doquery($Query, 'users'); + if(mysql_num_rows($Result) > 0) + { + while($UserData = mysql_fetch_assoc($Result)) + { + $UsersNicks[$UserData['id']] = $UserData['username']; + } + } + } + if(!empty($GetACSData)) + { + foreach($GetACSData as $ACSTempData) + { + $CheckJoinedFleets[] = "`fleets_id` LIKE '%|{$ACSTempData}|%'"; + } + $CheckJoinedFleets = implode(' OR ', $CheckJoinedFleets); + $Query = "SELECT `id`, `main_fleet_id`, `fleets_id` FROM {{table}} WHERE `main_fleet_id` IN (".implode(', ', $GetACSData).") OR {$CheckJoinedFleets};"; + $Result = doquery($Query, 'acs'); + if(mysql_num_rows($Result) > 0) + { + while($TempACSData = mysql_fetch_assoc($Result)) + { + $TempFleetsFromACS = false; + $Temp1 = explode(',', str_replace('|', '', $TempACSData['fleets_id'])); + foreach($Temp1 as $TempData) + { + $ACSData[$TempData] = $TempACSData['id']; + } + $ACSData[$TempACSData['main_fleet_id']] = $TempACSData['id']; + } + } + } + } + + $TPL = gettemplate('admin/user_info'); + $Parse= $_Lang; + + if(empty($_GET['mark']) OR $_GET['mark'] == '1') + { + $Parse['MarkSelect'] = '01'; + } + else + { + $Parse['MarkSelect'] = "0{$_GET['mark']}"; + } + + // --- Create General Overview Marker! --- + + $Player['Name'] = $Data['username']; + $Player['Email'] = $Data['email']; + $Player['Email2'] = $Data['email_2']; + $Player['LastIP'] = (!empty($Data['user_lastip']) ? "{$Data['user_lastip']}" : $_Lang['NoLogin']); + $Player['RegIP'] = (!empty($Data['ip_at_reg']) ? "{$Data['ip_at_reg']}" : $_Lang['No_Data']); + + // - Last Activity + $OnlineDiff = $Now - $Data['onlinetime']; + if($OnlineDiff >= 28 * TIME_DAY) + { + $OLColor = 'red'; + } + else if($OnlineDiff >= 7 * TIME_DAY) + { + $OLColor = '#FFA0A0'; + } + else if($OnlineDiff >= TIME_DAY) + { + $OLColor = 'orange'; + } + else if($OnlineDiff > TIME_ONLINE) + { + $OLColor = 'yellow'; + } + else + { + $OLColor = 'lime'; + } + $OnlineDiffText = '('.pretty_time($OnlineDiff).' '.$_Lang['_ago'].')'; + if($OLColor == 'lime') + { + $OnlineDiffText = "{$OnlineDiffText}"; + } + if(CheckAuth('supportadmin')) + { + $OnlineDiffText = "{$OnlineDiffText}
{$Data['current_page']}
{$_Lang['ShowLogs']}"; + } + $Player['LastActivity'] = prettyDate('d m Y, H:i:s', $Data['onlinetime'], 1)."
{$OnlineDiffText}"; + // - END - Last Activy + $Player['Browser'] = (!empty($Data['user_agent']) ? $Data['user_agent'] : $_Lang['No_Data']); + $Player['Screen'] = (!empty($Data['screen_settings']) ? str_replace('_', 'x', $Data['screen_settings']) : $_Lang['No_Data']); + + // - Registration Time + if($Data['register_time'] > 0) + { + $Bloc['adm_ul_data_regd'] = ''; + $RegisterDays = floor(($Now - $Data['register_time']) / (24*60*60)); + if($RegisterDays == 1) + { + $RegDays = $_Lang['_day']; + } + else + { + $RegDays = $_Lang['_days']; + } + $RegisterDays = prettyNumber($RegisterDays); + if($RegisterDays == 0) + { + if(date('d') == date('d', $Data['register_time'])) + { + $Player['RegisterInfo'] = $_Lang['_today']; + } + else + { + $Player['RegisterInfo'] = $_Lang['_yesterday']; + } + } + else + { + $Player['RegisterInfo'] = "{$RegisterDays} {$RegDays} {$_Lang['_ago']}"; + } + $Player['RegisterInfo'] .= '
'.prettyDate('d m Y, H:i:s', $Data['register_time'], 1); + } + else + { + $Player['RegisterInfo'] = $_Lang['No_Data']; + } + // - END - Registration Time + + // MoreInfo - Vacation Info + if(isOnVacation($Data)) + { + $Player['Vacations']= "{$_Lang['Active']}
({$_Lang['_Since']}: ".pretty_time($Now - $Data['vacation_starttime'])." / ".prettyDate('d m Y, H:i:s', $Data['vacation_starttime'], 1).")
(".($Data['vacation_endtime'] == 0 ? "{$_Lang['InfiniteVacation']}" : "{$_Lang['_Duration']}: ".pretty_time($Data['vacation_endtime'] - $Now)." / ".prettyDate('d m Y, H:i:s', $Data['vacation_endtime'], 1)).")"; + } + else + { + $Player['Vacations']= $_Lang['Inactive']; + } + + $Player['Ban'] = ''; + if($Data['is_banned'] == 1) + { + if($Data['ban_endtime'] < $Now) + { + $BanColor = 'orange'; + $BanTime= $_Lang['Ban_Expired']; + } + else + { + $BanColor = 'red'; + $BanTime= $_Lang['Ban_TimeLeft'].' '.pretty_time($Data['ban_endtime'] - $Now); + } + $Player['Ban'] = "{$_Lang['Active']}
({$_Lang['_Untill']}: ".prettyDate("d m Y, H:i:s", $Data['ban_endtime'], 1).")
({$BanTime})"; + } + else + { + $Player['Ban'] = $_Lang['Inactive']; + } + if($Data['block_cookies'] == 1) + { + $Player['Ban'] .= "
({$_Lang['CookieBanActive']})"; + } + + $Player['Delete'] = ($Data['is_ondeletion'] == 1 ? "{$_Lang['Active']}
".($Data['deletion_endtime'] < $Now ? $_Lang['Delete_Time_onNextRecalc'] : "{$_Lang['Delete_Time']}: ".pretty_time($Data['deletion_endtime'] - $Now))."
".prettyDate('d m Y, H:i:s', $Data['deletion_endtime'], 1) : $_Lang['Inactive'] ); + $Player['OldNick'] = (!empty($Data['old_username']) ? "{$Data['old_username']}
".($Data['old_username_expire'] > $Now ? $_Lang['WillExpire'].pretty_time($Data['old_username_expire'] - $Now) : "{$_Lang['Expired']}")."
".prettyDate('d m Y, H:i:s', $Data['old_username_expire'], 1) : $_Lang['No_Data']); + $Player['InvitedBy'] = ($Data['referred'] > 0 ? (!empty($Data['inviter_username']) ? "{$Data['inviter_username']} [#{$Data['referred']}]" : "{$_Lang['InviterDeleted']} [#{$Data['referred']}]") : $_Lang['NotInvited']); + + $Player['DarkEnergy'] = ($Data['darkEnergy'] > 0 ? prettyNumber($Data['darkEnergy']) : '0'); + $Player['ProTime'] = ($Data['pro_time'] > 0 ? ($Data['pro_time'] > $Now ? "{$_Lang['WillExpire']}
".pretty_time($Data['pro_time'] - $Now)."
".prettyDate('d m Y, H:i:s', $Data['pro_time'], 1) : "{$_Lang['Expired2']}
".pretty_time(-($Data['pro_time'] - $Now))." {$_Lang['_ago']}
".prettyDate('d m Y, H:i:s', $Data['pro_time'], 1)) : $_Lang['NeverBought']); + $Player['GeoTime'] = ($Data['geologist_time'] > 0 ? ($Data['geologist_time'] > $Now ? "{$_Lang['WillExpire']}
".pretty_time($Data['geologist_time'] - $Now)."
".prettyDate('d m Y, H:i:s', $Data['geologist_time'], 1) : "{$_Lang['Expired']}
".pretty_time(-($Data['geologist_time'] - $Now))." {$_Lang['_ago']}
".prettyDate('d m Y, H:i:s', $Data['geologist_time'], 1)) : $_Lang['NeverBought']); + $Player['EngTime'] = ($Data['engineer_time'] > 0 ? ($Data['engineer_time'] > $Now ? "{$_Lang['WillExpire']}
".pretty_time($Data['engineer_time'] - $Now)."
".prettyDate('d m Y, H:i:s', $Data['engineer_time'], 1) : "{$_Lang['Expired']}
".pretty_time(-($Data['engineer_time'] - $Now))." {$_Lang['_ago']}
".prettyDate('d m Y, H:i:s', $Data['engineer_time'], 1)) : $_Lang['NeverBought']); + $Player['AdmTime'] = ($Data['admiral_time'] > 0 ? ($Data['admiral_time'] > $Now ? "{$_Lang['WillExpire']}
".pretty_time($Data['admiral_time'] - $Now)."
".prettyDate('d m Y, H:i:s', $Data['admiral_time'], 1) : "{$_Lang['Expired']}
".pretty_time(-($Data['admiral_time'] - $Now))." {$_Lang['_ago']}
".prettyDate('d m Y, H:i:s', $Data['admiral_time'], 1)) : $_Lang['NeverBought']); + $Player['TecTime'] = ($Data['technocrat_time'] > 0 ? ($Data['technocrat_time'] > $Now ? "{$_Lang['WillExpire']}
".pretty_time($Data['technocrat_time'] - $Now)."
".prettyDate('d m Y, H:i:s', $Data['technocrat_time'], 1) : "{$_Lang['Expired']}
".pretty_time(-($Data['technocrat_time'] - $Now))." {$_Lang['_ago']}
".prettyDate('d m Y, H:i:s', $Data['technocrat_time'], 1)) : $_Lang['NeverBought']); + $Player['JamTime'] = ($Data['spy_jam_time'] > 0 ? ($Data['spy_jam_time'] > $Now ? "{$_Lang['WillExpire']}
".pretty_time($Data['spy_jam_time'] - $Now)."
".prettyDate('d m Y, H:i:s', $Data['spy_jam_time'], 1) : "{$_Lang['Expired']}
".pretty_time(-($Data['spy_jam_time'] - $Now))." {$_Lang['_ago']}
".prettyDate('d m Y, H:i:s', $Data['spy_jam_time'], 1)) : $_Lang['NeverBought']); + $Player['AdditionalPlanets'] = ($Data['additional_planets'] > 0 ? prettyNumber($Data['additional_planets']) : '0'); + if($Data['ally_id'] <= 0 AND $Data['ally_request'] > 0) + { + $Data['ally_id'] = $Data['ally_request']; + $Data['ally_name'] = $Data['ally_request_name']; + } + $Player['Ally'] = ($Data['ally_id'] > 0 ? ''.$Data['ally_name'].' ('.$Data['ally_id'].')'.($Data['ally_request'] != 0 ? ' ['.$_Lang['Request'].']' : ($Data['ally_owner'] == $UID ? ' ['.$_Lang['Ally_owner'].']' : '')) : ' - '); + $Player['AccountActive'] = (!empty($Data['activation_code']) ? "{$_Lang['_no']}
{$_Lang['ActivationCode']}: {$Data['activation_code']}" : "{$_Lang['_yes']}"); + $Player['DisableIPCheck'] = (($Data['noipcheck'] == 1) ? $_Lang['_no'] : $_Lang['_yes']); + $Player['MotherPlanet'] = "{$Data['mothername']} ({$_Lang['MotherPlanet_ID']}: {$Data['id_planet']}) [{$Data['galaxy']}:{$Data['system']}:{$Data['planet']}]"; + + // --- END of Creating General Overview Marker! --- + + // --- Create Statistics Marker! --- + + if($Data['stats'] == 'EMPTY') + { + $Parse['HideStatsIfUnavailable']= 'style="display: none;"'; + $Parse['ShowInfoIfStatsUnavailable']= "
{$_Lang['NoStatsAvailable']}
 "; + } + else + { + // General Pos + $Player['GeneralPos'] = $Data['stats']['total_rank']; + $Player['GeneralChange1'] = $Data['stats']['total_rank'] - $Data['stats']['total_old_rank']; + if($Data['stats']['total_yesterday_rank'] > 0) + { + $Player['GeneralChange2'] = $Data['stats']['total_rank'] - $Data['stats']['total_yesterday_rank']; + } + else + { + $Player['GeneralChange2'] = 0; + } + if($Player['GeneralChange1'] == 0) + { + $Player['GeneralChange1'] = "0"; + } + else if($Player['GeneralChange1'] < 0) + { + $Player['GeneralChange1'] = abs($Player['GeneralChange1']); + $Player['GeneralChange1'] = "+{$Player['GeneralChange1']}"; + } + else + { + $Player['GeneralChange1'] = "-{$Player['GeneralChange1']}"; + } + if($Player['GeneralChange2'] == 0) + { + $Player['GeneralChange2'] = "0"; + } + else if($Player['GeneralChange2'] < 0) + { + $Player['GeneralChange2'] = abs($Player['GeneralChange2']); + $Player['GeneralChange2'] = "+{$Player['GeneralChange2']}"; + } + else + { + $Player['GeneralChange2'] = "-{$Player['GeneralChange2']}"; + } + $Player['GeneralPoints']= prettyNumber($Data['stats']['total_points']); + + // Fleet pos + $Player['FleetPos'] = $Data['stats']['fleet_rank']; + $Player['FleetChange1'] = $Data['stats']['fleet_rank'] - $Data['stats']['fleet_old_rank']; + if($Data['stats']['fleet_yesterday_rank'] > 0) + { + $Player['FleetChange2'] = $Data['stats']['fleet_rank'] - $Data['stats']['fleet_yesterday_rank']; + } + else + { + $Player['FleetChange2'] = 0; + } + if($Player['FleetChange1'] == 0) + { + $Player['FleetChange1'] = "0"; + } + else if($Player['FleetChange1'] < 0) + { + $Player['FleetChange1'] = abs($Player['FleetChange1']); + $Player['FleetChange1'] = "+{$Player['FleetChange1']}"; + } + else + { + $Player['FleetChange1'] = "-{$Player['FleetChange1']}"; + } + if($Player['FleetChange2'] == 0) + { + $Player['FleetChange2'] = "0"; + } + else if($Player['FleetChange2'] < 0) + { + $Player['FleetChange2'] = abs($Player['FleetChange2']); + $Player['FleetChange2'] = "+{$Player['FleetChange2']}"; + } + else + { + $Player['FleetChange2'] = "-{$Player['FleetChange2']}"; + } + $Player['FleetPoints']= prettyNumber($Data['stats']['fleet_points']); + if($Data['stats']['total_points'] != 0) + { + $Player['FleetPercent'] = (round($Data['stats']['fleet_points']/$Data['stats']['total_points'], 4) * 100).'%'; + } + else + { + $Player['FleetPercent'] = '0%'; + } + + // Buildings pos + $Player['BuildingsPos'] = $Data['stats']['build_rank']; + $Player['BuildingsChange1'] = $Data['stats']['build_rank'] - $Data['stats']['build_old_rank']; + if($Data['stats']['build_yesterday_rank'] > 0) + { + $Player['BuildingsChange2'] = $Data['stats']['build_rank'] - $Data['stats']['build_yesterday_rank']; + } + else + { + $Player['BuildingsChange2'] = 0; + } + if($Player['BuildingsChange1'] == 0) + { + $Player['BuildingsChange1'] = "0"; + } + else if($Player['BuildingsChange1'] < 0) + { + $Player['BuildingsChange1'] = abs($Player['BuildingsChange1']); + $Player['BuildingsChange1'] = "+{$Player['BuildingsChange1']}"; + } + else + { + $Player['BuildingsChange1'] = "-{$Player['BuildingsChange1']}"; + } + if($Player['BuildingsChange2'] == 0) + { + $Player['BuildingsChange2'] = "0"; + } + else if($Player['BuildingsChange2'] < 0) + { + $Player['BuildingsChange2'] = abs($Player['BuildingsChange2']); + $Player['BuildingsChange2'] = "+{$Player['BuildingsChange2']}"; + } + else + { + $Player['BuildingsChange2'] = "-{$Player['BuildingsChange2']}"; + } + $Player['BuildingsPoints']= prettyNumber($Data['stats']['build_points']); + if($Data['stats']['total_points'] != 0) + { + $Player['BuildingsPercent'] = (round($Data['stats']['build_points']/$Data['stats']['total_points'], 4) * 100).'%'; + } + else + { + $Player['BuildingsPercent'] = '0%'; + } + + // Defence pos + $Player['DefencePos'] = $Data['stats']['defs_rank']; + $Player['DefenceChange1'] = $Data['stats']['defs_rank'] - $Data['stats']['defs_old_rank']; + if($Data['stats']['defs_yesterday_rank'] > 0) + { + $Player['DefenceChange2'] = $Data['stats']['defs_rank'] - $Data['stats']['defs_yesterday_rank']; + } + else + { + $Player['DefenceChange2'] = 0; + } + if($Player['DefenceChange1'] == 0) + { + $Player['DefenceChange1'] = "0"; + } + else if($Player['DefenceChange1'] < 0) + { + $Player['DefenceChange1'] = abs($Player['DefenceChange1']); + $Player['DefenceChange1'] = "+{$Player['DefenceChange1']}"; + } + else + { + $Player['DefenceChange1'] = "-{$Player['DefenceChange1']}"; + } + if($Player['DefenceChange2'] == 0) + { + $Player['DefenceChange2'] = "0"; + } + else if($Player['DefenceChange2'] < 0) + { + $Player['DefenceChange2'] = abs($Player['DefenceChange2']); + $Player['DefenceChange2'] = "+{$Player['DefenceChange2']}"; + } + else + { + $Player['DefenceChange2'] = "-{$Player['DefenceChange2']}"; + } + $Player['DefencePoints']= prettyNumber($Data['stats']['defs_points']); + if($Data['stats']['total_points'] != 0) + { + $Player['DefencePercent'] = (round($Data['stats']['defs_points']/$Data['stats']['total_points'], 4) * 100).'%'; + } + else + { + $Player['DefencePercent'] = '0%'; + } + + // Research pos + $Player['ResearchPos'] = $Data['stats']['tech_rank']; + $Player['ResearchChange1'] = $Data['stats']['tech_rank'] - $Data['stats']['tech_old_rank']; + if($Data['stats']['tech_yesterday_rank'] > 0) + { + $Player['ResearchChange2'] = $Data['stats']['tech_rank'] - $Data['stats']['tech_yesterday_rank']; + } + else + { + $Player['ResearchChange2'] = 0; + } + if($Player['ResearchChange1'] == 0) + { + $Player['ResearchChange1'] = "0"; + } + else if($Player['ResearchChange1'] < 0) + { + $Player['ResearchChange1'] = abs($Player['ResearchChange1']); + $Player['ResearchChange1'] = "+{$Player['ResearchChange1']}"; + } + else + { + $Player['ResearchChange1'] = "-{$Player['ResearchChange1']}"; + } + if($Player['ResearchChange2'] == 0) + { + $Player['ResearchChange2'] = "0"; + } + else if($Player['ResearchChange2'] < 0) + { + $Player['ResearchChange2'] = abs($Player['ResearchChange2']); + $Player['ResearchChange2'] = "+{$Player['ResearchChange2']}"; + } + else + { + $Player['ResearchChange2'] = "-{$Player['ResearchChange2']}"; + } + $Player['ResearchPoints']= prettyNumber($Data['stats']['tech_points']); + if($Data['stats']['total_points'] != 0) + { + $Player['ResearchPercent'] = (round($Data['stats']['tech_points']/$Data['stats']['total_points'], 4) * 100).'%'; + } + else + { + $Player['ResearchPercent'] = '0%'; + } + } + + // --- END of Creating Statistics Marker! --- + + // --- Create Fleet Control Marker! --- + + if($Data['fleets'] == 'EMPTY') + { + $Parse['FleetControlContent']= "
{$_Lang['NoFleetsInFlight']}
 "; + } + else + { + $FleetTPL = gettemplate('admin/user_info_fleet_row'); + $FleetHeadTPL = gettemplate('admin/user_info_fleet_header'); + + include("{$_EnginePath}/includes/functions/InsertJavaScriptChronoApplet.php"); + + $AllFleetParse = ''; + foreach($Data['fleets'] as $FleetID => $FleetData) + { + $FleetParse = false; + $FleetArray = false; + $FleetShipsTemp = false; + $FleetCount = 0; + $FleetShipsParsed = false; + + $FleetParse['Fleet_ID'] = $FleetID; + $FleetParse['Fleet_Owner'] = "{$UsersNicks[$FleetData['fleet_owner']]}
[{$FleetData['fleet_owner']}]"; + if($FleetData['fleet_owner'] == $UID) + { + $FleetParse['Fleet_Owner_color'] = 'lime'; + } + else + { + if(in_array($FleetData['fleet_mission'], array(1, 2, 6, 9, 10, 11))) + { + $FleetParse['Fleet_Owner_color'] = 'red'; + } + else + { + $FleetParse['Fleet_Owner_color'] = 'blue'; + } + $FleetParse['Fleet_Owner'] = "{$FleetParse['Fleet_Owner']}"; + } + $FleetParse['Fleet_Mission'] = $_Lang['type_mission'][$FleetData['fleet_mission']]; + if($ACSData[$FleetID] > 0) + { + if($FleetData['fleet_mission'] == 1) + { + $FleetParse['Fleet_Mission'] = $_Lang['type_mission'][2]; + } + $FleetParse['Fleet_Mission'] = "{$FleetParse['Fleet_Mission']}
[ACS: {$ACSData[$FleetID]}]"; + if($FleetData['fleet_mission'] == 1) + { + $FleetParse['Fleet_Mission'] = "{$FleetParse['Fleet_Mission']}"; + } + } + if($FleetData['fleet_mess'] == 1 AND $FleetData['fleet_mission'] != 5) + { + $FleetParse['Fleet_Mission'] = "{$FleetParse['Fleet_Mission']}
[{$_Lang['Coming_back']}]"; + } + if(($FleetData['fleet_mess'] == 0 AND $FleetData['fleet_start_time'] <= $Now) OR ($FleetData['fleet_mess'] != 0 AND $FleetData['fleet_end_time'] <= $Now)) + { + $FleetParse['Fleet_Mission'] = "{$FleetParse['Fleet_Mission']}
[{$_Lang['Not_calculated']}]"; + } + + $FleetArray = explode(';', $FleetData['fleet_array']); + foreach($FleetArray as $FleetShipsTemp) + { + if(!empty($FleetShipsTemp)) + { + $FleetShipsTemp = explode(',', $FleetShipsTemp); + $FleetCount += $FleetShipsTemp[1]; + $FleetShipsParsed[] = "{$_Lang['tech'][$FleetShipsTemp[0]]}".prettyNumber($FleetShipsTemp[1]).""; + } + } + $FleetCount = prettyNumber($FleetCount); + $FleetParse['Fleet_Ships'] = "".implode('', $FleetShipsParsed)."
"; + $FleetParse['Fleet_Array'] = "{$FleetCount}
(?)"; + if($FleetData['fleet_resource_metal'] == 0 AND $FleetData['fleet_resource_crystal'] == 0 AND $FleetData['fleet_resource_deuterium'] == 0) + { + $FleetParse['Fleet_Cargo'] = $_Lang['No_cargo']; + } + else + { + $FleetParse['Fleet_Cargo'] = $_Lang['See_cargo']; + $FleetParse['Fleet_Resources'] = "
{$_Lang['Metal']}".prettyNumber($FleetData['fleet_resource_metal'])."
{$_Lang['Crystal']}".prettyNumber($FleetData['fleet_resource_crystal'])."
{$_Lang['Deuterium']}".prettyNumber($FleetData['fleet_resource_deuterium'])."
"; + $FleetParse['Fleet_Cargo_class'] = ' fCar'; + } + $FleetParse['Fleet_Start_Title'] = ($FleetData['fleet_start_type'] == '1' ? $_Lang['Start_from_planet'] : $_Lang['Start_from_moon']); + $FleetParse['Fleet_Start'] = "[{$FleetData['fleet_start_galaxy']}:{$FleetData['fleet_start_system']}:{$FleetData['fleet_start_planet']}] ".($FleetData['fleet_start_type'] == '1' ? $_Lang['Planet_sign'] : $_Lang['Moon_sign']).""; + $FleetParse['Fleet_Start'].= "
".date('d.m.Y', $FleetData['fleet_send_time'])."
".date('H:i:s', $FleetData['fleet_send_time'])."
(".pretty_time($Now - $FleetData['fleet_send_time'], true, 'D')." {$_Lang['_ago']})"; + $_Lang['ChronoApplets'] .= InsertJavaScriptChronoApplet('a', $FleetID, $FleetData['fleet_send_time'], true, true); + + $FleetParse['Fleet_End_Title'] = ($FleetData['fleet_end_type'] == '1' ? $_Lang['Target_is_planet'] : ($FleetData['fleet_end_type'] == '2' ? $_Lang['Target_is_debris'] : $_Lang['Target_is_moon'])); + $FleetParse['Fleet_End'] = "[{$FleetData['fleet_end_galaxy']}:{$FleetData['fleet_end_system']}:{$FleetData['fleet_end_planet']}] ".($FleetData['fleet_end_type'] == '1' ? $_Lang['Planet_sign'] : ($FleetData['fleet_end_type'] == '2' ? $_Lang['Debris_sign'] : $_Lang['Moon_sign'])).""; + if($FleetData['fleet_start_time'] <= $Now) + { + $FleetParse['Fleet_end_time_set'] = "{$_Lang['TargetAchieved']}"; + } + else + { + $FleetParse['Fleet_end_time_set'] = pretty_time($FleetData['fleet_start_time'] - $Now, true, 'D'); + $_Lang['ChronoApplets'] .= InsertJavaScriptChronoApplet('b', $FleetID, $FleetData['fleet_start_time'] - $Now); + } + $FleetParse['Fleet_End'].= "
".date('d.m.Y', $FleetData['fleet_start_time'])."
".date('H:i:s', $FleetData['fleet_start_time'])."
({$FleetParse['Fleet_end_time_set']})"; + + $FleetParse['Fleet_End_owner']= "{$UsersNicks[$FleetData['fleet_target_owner']]}
[{$FleetData['fleet_target_owner']}]"; + if($FleetData['fleet_target_owner'] == $UID) + { + $FleetParse['Fleet_End_owner_color'] = 'lime'; + } + else + { + if(in_array($FleetData['fleet_mission'], array(1, 2, 6, 9, 10, 11))) + { + $FleetParse['Fleet_End_owner_color'] = 'red'; + } + else + { + $FleetParse['Fleet_End_owner_color'] = 'blue'; + } + $FleetParse['Fleet_End_owner'] = "{$FleetParse['Fleet_End_owner']}"; + } + + if($FleetData['fleet_end_time'] <= $Now) + { + $FleetParse['Fleet_back_time_set'] = "{$_Lang['FleetCameBack']}"; + } + else + { + $FleetParse['Fleet_back_time_set'] = pretty_time($FleetData['fleet_end_time'] - $Now, true, 'D'); + $_Lang['ChronoApplets'] .= InsertJavaScriptChronoApplet('c', $FleetID, $FleetData['fleet_end_time'] - $Now); + } + $FleetParse['Fleet_Back_time'].= date('d.m.Y - H:i:s', $FleetData['fleet_end_time'])."
({$FleetParse['Fleet_back_time_set']})"; + + $AllFleetParse .= parsetemplate($FleetTPL, $FleetParse); + } + + $_Lang['FleetParsed'] = $AllFleetParse; + + $Parse['FleetControlContent'] = parsetemplate($FleetHeadTPL, $_Lang); + } + + // --- END of Creating Fleet Control Marker! --- + + foreach($Player as $Key => $Val) + { + if(empty($Val)) + { + if($Val === 0 OR $Val === '0') + { + $Val = '0'; + } + else + { + $Val = ' '; + } + } + $Parse['Player'.$Key] = $Val; + } + + $Page = parsetemplate($TPL, $Parse); + display($Page, $_Lang['PageTitle'], false, true); +} +else +{ + message($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); +} + +?> diff --git a/admin/userlist.php b/admin/userlist.php index 011ced5e3..d6b051d0a 100644 --- a/admin/userlist.php +++ b/admin/userlist.php @@ -1,925 +1,925 @@ - 0) - { - if(CheckAuth('supportadmin')) - { - if($DeleteID != $_User['id']) - { - doquery("UPDATE {{table}} SET `is_ondeletion` = 1, `deletion_endtime` = UNIX_TIMESTAMP() WHERE `id` = {$DeleteID};", 'users'); - } - } - else - { - message($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); - } - } - } - - if(isset($_POST['cmd']) && $_POST['cmd'] == 'sort' AND !empty($_POST['type']) AND (!isset($_POST['nosort']) || $_POST['nosort'] != 'on')) - { - if(in_array($_POST['type'], $AllowedSortTypes)) - { - $TypeSort = $_POST['type']; - $parse['FormSortType'] = $TypeSort; - } - else - { - $TypeSort = 'id'; - } - } - else - { - $TypeSort = 'id'; - $parse['DontShowNoSort'] = 'inv'; - } - - if(empty($_POST['mode']) || (isset($_POST['nosort']) && $_POST['nosort'] == 'on')) - { - $parse['sort_mode'] = 'asc'; - $SortMode = 'ASC'; - } - else - { - if($_POST['mode'] == 'asc') - { - $SortMode = 'ASC'; - $parse['FormSortMode'] = 'asc'; - $parse['sort_mode'] = 'desc'; - } - else - { - $SortMode = 'DESC'; - $parse['FormSortMode'] = 'desc'; - $parse['sort_mode'] = 'asc'; - } - } - - if(!empty($_POST['pp'])) - { - $PerPage = intval($_POST['pp']); - if($PerPage <= 0) - { - $PerPage = 20; - } - $parse['per_page'] = '&pp='.$PerPage; - $parse['InitPerPage'] = $PerPage; - setcookie('ACP_UserList_PerPage', $PerPage, 0, 'admin/'); - } - else - { - if(!empty($_COOKIE['ACP_UserList_PerPage'])) - { - $PerPage = intval($_COOKIE['ACP_UserList_PerPage']); - if($PerPage <= 0) - { - $PerPage = 20; - } - } - else - { - $PerPage = 20; - } - } - $parse['DefaultPerPage'] = 20; - $parse['perPageSelect_'.$PerPage] = 'selected'; - - // ---------------------------- - // Get Overrides -------------- - if(!empty($_GET['uid'])) - { - $_GET['uid'] = intval($_GET['uid']); - if($_GET['uid'] > 0) - { - $_POST['search_user'] = $_GET['uid']; - $_POST['search_by'] = 'uid'; - } - } - if(!empty($_GET['ipid'])) - { - if(preg_match(REGEXP_IP, $_GET['ipid'])) - { - $_POST['search_user'] = $_GET['ipid']; - $_POST['search_by'] = 'ip'; - $_POST['anyip'] = 'on'; - } - } - if(!empty($_GET['search_user']) AND !empty($_GET['search_by'])) - { - $_POST['search_user'] = $_GET['search_user']; - $_POST['search_by'] = $_GET['search_by']; - } - - // ---------------------------- - - $PerPageArray = array(5, 10, 15, 20, 25, 50); - if(!in_array($PerPage, $PerPageArray)) - { - $parse['perPageSelect_0'] = 'selected'; - } - - $CurrentPage = (isset($_POST['page']) ? intval($_POST['page']) : 0); - if($CurrentPage < 1) - { - $CurrentPage = 1; - } - $parse['FormPage'] = $CurrentPage; - $GetStart = (string) ((($CurrentPage - 1) * $PerPage) + 0); - - $PageTPL = gettemplate('admin/userlist_body'); - $RowsTPL = gettemplate('admin/userlist_rows'); - - $parse['AllySearchTypeDisplay'] = $_Hide; - $parse['AllyInRequestDisplay'] = $_Hide; - $parse['AnyIPDisplay'] = $_Hide; - $parse['AnyIPChecked'] = $_Checked; - $parse['AllySearch_name_Checked'] = $_Checked; - $parse['AllySearch_tag_Checked'] = $_Checked; - - include($_EnginePath.'includes/functions/Filters.php'); - - if(isset($_POST['preserve']) && strstr($_POST['preserve'], 'over=yes') !== false) - { - $_GET['over'] = 'yes'; - } - - if(isset($_GET['over']) && $_GET['over'] == 'yes') - { - $_POST['online_yes'] = 'on'; - $parse['FormPreserve'][] = 'over=yes'; - } - - if(!empty($parse['FormPreserve'])) - { - $parse['FormPreserve'] = implode('|', $parse['FormPreserve']); - } - - $Search['Flags']['strict'] = (isset($_POST['strict']) && $_POST['strict'] == 'on' ? true : false); - $Search['Flags']['utableOnly'] = (isset($_POST['anyip']) && $_POST['anyip'] == 'on' ? false : true); - $Search['Flags']['isOnline'] = (isset($_POST['online_yes']) && $_POST['online_yes'] == 'on' ? true : (isset($_POST['online_no']) && $_POST['online_no'] == 'on' ? false : null)); - $Search['Flags']['onVacation'] = (isset($_POST['onvacation_yes']) && $_POST['onvacation_yes'] == 'on' ? true : (isset($_POST['onvacation_no']) && $_POST['onvacation_no'] == 'on' ? false : null)); - $Search['Flags']['isBanned'] = (isset($_POST['isbanned_yes']) && $_POST['isbanned_yes'] == 'on' ? true : (isset($_POST['isbanned_no']) && $_POST['isbanned_no'] == 'on' ? false : null)); - $Search['Flags']['isAI'] = (isset($_POST['isai_yes']) && $_POST['isai_yes'] == 'on' ? true : (isset($_POST['isai_no']) && $_POST['isai_no'] == 'on' ? false : null)); - $Search['Flags']['inDeletion'] = (isset($_POST['isdeleting_yes']) && $_POST['isdeleting_yes'] == 'on' ? true : (isset($_POST['isdeleting_no']) && $_POST['isdeleting_no'] == 'on' ? false : null)); - $Search['Flags']['inAlly'] = (isset($_POST['isinally_yes']) && $_POST['isinally_yes'] == 'on' ? true : (isset($_POST['isinally_no']) && $_POST['isinally_no'] == 'on' ? false : null)); - $Search['Flags']['isActive'] = (isset($_POST['isactive_yes']) && $_POST['isactive_yes'] == 'on' ? true : (isset($_POST['isactive_no']) && $_POST['isactive_no'] == 'on' ? false : null)); - $Search['Flags']['allyRequest'] = (isset($_POST['allyinrequest_yes']) && $_POST['allyinrequest_yes'] == 'on' ? true : (isset($_POST['allyinrequest_no']) && $_POST['allyinrequest_no'] == 'on' ? false : null)); - if(isset($_POST['search_by']) && $_POST['search_by'] == 'ally') - { - $parse['searchBySelect_ally'] = $_Selected; - if(isset($_POST['allysearch_name']) && isset($_POST['allysearch_tag']) && $_POST['allysearch_name'] == 'on' && $_POST['allysearch_tag'] == 'on') - { - $_POST['search_by'] = 'astring'; - } - else if(isset($_POST['allysearch_name']) && $_POST['allysearch_name'] == 'on') - { - $_POST['search_by'] = 'aname'; - $parse['AllySearch_tag_Checked'] = ''; - } - else if(isset($_POST['allysearch_tag']) && $_POST['allysearch_tag'] == 'on') - { - $_POST['search_by'] = 'atag'; - $parse['AllySearch_name_Checked'] = ''; - } - else - { - $_POST['search_by'] = 'astring'; - $parse['AllySearch_name_Checked'] = ''; - $parse['AllySearch_tag_Checked'] = ''; - } - $parse['AllySearchTypeDisplay'] = ''; - $parse['AllyInRequestDisplay'] = ''; - } - if(isset($_POST['search_by']) && $_POST['search_by'] == 'aid') - { - $parse['AllyInRequestDisplay'] = ''; - } - - // Check settings in Form - if(isset($_POST['strict']) && $_POST['strict'] == 'on') - { - $parse['StrictChecked'] = $_Checked; - } - if(isset($_POST['online_yes']) && $_POST['online_yes'] == 'on') - { - if(isset($_GET['over']) && $_GET['over'] == 'yes') - { - $parse['UsingOverviewShortcut'] = 'orange'; - } - else - { - $parse['Online_Yes_Checked'] = $_Checked; - } - } - if(isset($_POST['online_no']) && $_POST['online_no'] == 'on') - { - $parse['Online_No_Checked'] = $_Checked; - } - if(isset($_POST['onvacation_yes']) && $_POST['onvacation_yes'] == 'on') - { - $parse['OnVacation_Yes_Checked'] = $_Checked; - } - if(isset($_POST['onvacation_no']) && $_POST['onvacation_no'] == 'on') - { - $parse['OnVacation_No_Checked'] = $_Checked; - } - if(isset($_POST['isbanned_yes']) && $_POST['isbanned_yes'] == 'on') - { - $parse['IsBanned_Yes_Checked'] = $_Checked; - } - if(isset($_POST['isbanned_no']) && $_POST['isbanned_no'] == 'on') - { - $parse['IsBanned_No_Checked'] = $_Checked; - } - if(isset($_POST['isai_yes']) && $_POST['isai_yes'] == 'on') - { - $parse['IsAi_Yes_Checked'] = $_Checked; - } - if(isset($_POST['isai_no']) && $_POST['isai_no'] == 'on') - { - $parse['IsAi_No_Checked'] = $_Checked; - } - if(isset($_POST['isdeleting_yes']) && $_POST['isdeleting_yes'] == 'on') - { - $parse['IsDeleting_Yes_Checked'] = $_Checked; - } - if(isset($_POST['isdeleting_no']) && $_POST['isdeleting_no'] == 'on') - { - $parse['IsDeleting_No_Checked'] = $_Checked; - } - if(isset($_POST['isinally_yes']) && $_POST['isinally_yes'] == 'on') - { - $parse['IsInAlly_Yes_Checked'] = $_Checked; - } - if(isset($_POST['isinally_no']) && $_POST['isinally_no'] == 'on') - { - $parse['IsInAlly_No_Checked'] = $_Checked; - } - if(isset($_POST['isactive_yes']) && $_POST['isactive_yes'] == 'on') - { - $parse['IsActive_Yes_Checked'] = $_Checked; - } - if(isset($_POST['isactive_no']) && $_POST['isactive_no'] == 'on') - { - $parse['IsActive_No_Checked'] = $_Checked; - } - if(isset($_POST['anyip']) && $_POST['anyip'] == 'on') - { - $parse['AnyIPChecked'] = $_Checked; - } - if(isset($_POST['allysearch_name']) && $_POST['allysearch_name'] == 'on') - { - $parse['AllySearch_name_Checked'] = $_Checked; - } - if(isset($_POST['allysearch_tag']) && $_POST['allysearch_tag'] == 'on') - { - $parse['AllySearch_tag_Checked'] = $_Checked; - } - if(isset($_POST['allyinrequest_yes']) && $_POST['allyinrequest_yes'] == 'on') - { - $parse['AllyInRequest_Yes_Checked'] = $_Checked; - } - if(isset($_POST['allyinrequest_no']) && $_POST['allyinrequest_no'] == 'on') - { - $parse['AllyInRequest_No_Checked'] = $_Checked; - } - - $parse['search_user_val'] = (isset($_POST['search_user']) ? $_POST['search_user'] : null); - - $UserFields = array - ( - 'id', 'username', 'ally_id', 'ally_request', 'authlevel', 'email', 'email_2', 'user_agent', 'screen_settings', 'ip_at_reg', - 'user_lastip', 'register_time', 'onlinetime', 'current_page', 'is_banned', 'ban_endtime', 'is_onvacation', - 'vacation_starttime', 'vacation_endtime', 'pro_time', 'multi_validated', 'activation_code', 'is_ondeletion', 'deletion_endtime', - ); - array_walk($UserFields, function(&$Value){ $Value = "`{$Value}`"; }); - $UserFields = implode(', ', $UserFields); - - if(empty($_POST['search_user'])) - { - $Search['mode'] = 1; - $Search['string'] = ''; - $Search['type'] = ''; - } - else - { - $Search['mode'] = 2; - $Search['string'] = $_POST['search_user']; - if($_POST['search_by'] == 'uid') - { - $Search['type'] = 'uid'; - } - else if($_POST['search_by'] == 'astring' || $_POST['search_by'] == 'aname' || $_POST['search_by'] == 'atag') - { - $Search['type'] = $_POST['search_by']; - } - else if($_POST['search_by'] == 'aid') - { - $Search['type'] = 'aid'; - } - else if($_POST['search_by'] == 'ip') - { - $Search['type'] = 'ipstring'; - $parse['AnyIPDisplay'] = ''; - } - else - { - $Search['type'] = 'uname'; - $_POST['search_by'] = 'name'; - } - $parse['searchBySelect_'.$_POST['search_by']] = 'selected'; - } - - $Search['StartTime'] = microtime(true); - $FilterResult = Filter_Users($Search['string'], $Search['type'], $Search['Flags']); - $Search['EndTime'] = microtime(true); - - if(!empty($_POST['massAction'])) - { - if($_POST['massAction'] == 'ban' || $_POST['massAction'] == 'unban') - { - if(isset($_POST['useAllFiltered']) && $_POST['useAllFiltered'] == '1') - { - if($FilterResult !== true AND $FilterResult !== false) - { - $PassIDs = implode(',', $FilterResult); - } - } - else - { - $GetIDs = explode(',', trim($_POST['massActionIDs'])); - foreach($GetIDs as $ThisID) - { - $ThisID = round($ThisID); - if($ThisID > 0) - { - $PassIDs[] = $ThisID; - } - } - if(!empty($PassIDs)) - { - $PassIDs = implode(',', $PassIDs); - } - } - - if(!empty($PassIDs)) - { - if($_POST['massAction'] == 'ban') - { - header('Location: banuser.php?ids='.$PassIDs); - } - else if($_POST['massAction'] == 'unban') - { - header('Location: unbanuser.php?ids='.$PassIDs); - } - safeDie(); - } - } - } - - $Loading['StartTime'] = microtime(true); - if($FilterResult !== true) - { - if(!empty($FilterResult)) - { - $WhereClausure = implode(', ', $FilterResult); - $SelectCount = count($FilterResult); - if($GetStart >= $SelectCount) - { - $CurrentPage = ceil($SelectCount / $PerPage); - $GetStart = (string) ((($CurrentPage - 1) * $PerPage) + 0); - } - $query = doquery("SELECT {$UserFields} FROM {{table}} WHERE `id` IN ({$WhereClausure}) ORDER BY `{$TypeSort}` {$SortMode} LIMIT {$GetStart}, {$PerPage};", 'users'); - } - else - { - $SelectCount = 0; - if($FilterResult === false) - { - $parse['AdditionalInfoBox'] = $_Lang['UserFilter_NoGoodStrings']; - $parse['AdditionalInfoBox_Color'] = 'red'; - } - } - } - else - { - $SelectCount = doquery("SELECT COUNT(`id`) AS `Count` FROM {{table}};", 'users', true); - $SelectCount = $SelectCount['Count']; - if($GetStart >= $SelectCount) - { - $CurrentPage = ceil($SelectCount / $PerPage); - $GetStart = (string) ((($CurrentPage - 1) * $PerPage) + 0); - } - $query = doquery("SELECT {$UserFields} FROM {{table}} ORDER BY `{$TypeSort}` {$SortMode} LIMIT {$GetStart}, {$PerPage};", 'users'); - } - $Loading['EndTime'] = microtime(true); - - if($SelectCount > $PerPage) - { - include_once($_EnginePath.'includes/functions/Pagination.php'); - $Pagin = CreatePaginationArray($SelectCount, $PerPage, $CurrentPage, 7); - $PaginationTPL = "{\$ShowValue}"; - $PaginationViewOpt = array('CurrentPage_Classes' => 'orange', 'Breaker_View' => '...'); - $CreatePagination = implode(' ', ParsePaginationArray($Pagin, $CurrentPage, $PaginationTPL, $PaginationViewOpt)); - $parse['pagination'] = ''.$CreatePagination.''; - } - - if($SelectCount > 0) - { - while($UserData = mysql_fetch_assoc($query)) - { - $Users[$UserData['id']] = - array - ( - 'username' => $UserData['username'], - 'ally_id' => $UserData['ally_id'], - 'ally_request' => $UserData['ally_request'], - 'authlevel' => $UserData['authlevel'], - 'email' => $UserData['email'], - 'email_2' => $UserData['email_2'], - 'uagent' => $UserData['user_agent'], - 'resolution' => $UserData['screen_settings'], - 'ip_at_reg' => $UserData['ip_at_reg'], - 'user_lastip' => $UserData['user_lastip'], - 'register_time' => $UserData['register_time'], - 'onlinetime' => $UserData['onlinetime'], - 'current_page' => $UserData['current_page'], - 'is_banned' => $UserData['is_banned'], - 'ban_endtime' => $UserData['ban_endtime'], - 'vacation' => $UserData['is_onvacation'], - 'vacation_since' => $UserData['vacation_starttime'], - 'vacation_endtime' => $UserData['vacation_endtime'], - 'is_ondeletion' => $UserData['is_ondeletion'], - 'deletion_endtime' => $UserData['deletion_endtime'], - 'pro_till' => $UserData['pro_time'], - 'multi_validated' => $UserData['multi_validated'], - 'activation_code' => $UserData['activation_code'], - ); - - if(!empty($UserData['ip_at_reg'])) - { - $GetIPs['ip_at_reg'][] = "'{$UserData['ip_at_reg']}'"; - } - if(!empty($UserData['user_lastip'])) - { - $GetIPs['user_lastip'][] = "'{$UserData['user_lastip']}'"; - } - - if($UserData['ally_id'] > 0) - { - if(!empty($GetAllys)) - { - if(!in_array($UserData['ally_id'], $GetAllys)) - { - $GetAllys[] = $UserData['ally_id']; - } - } - else - { - $GetAllys[] = $UserData['ally_id']; - } - } - else - { - if(!empty($UserData['ally_request'])) - { - if(!empty($GetAllys)) - { - if(!in_array($UserData['ally_request'], $GetAllys)) - { - $GetAllys[] = $UserData['ally_request']; - } - } - else - { - $GetAllys[] = $UserData['ally_request']; - } - } - } - } - - $Profiling['repeatedIPs'] = microtime(true); - foreach($GetIPs as $Field => $Values) - { - $GetIPsWhere[$Field] = implode(', ', $Values); - } - if(!empty($GetIPsWhere['user_lastip'])) - { - $GetIPsQuery[] = "SELECT `user_lastip` AS `ip`, COUNT(`user_lastip`) AS `count`, '1' AS `type` FROM {{table}} WHERE `user_lastip` IN ({$GetIPsWhere['user_lastip']}) GROUP BY `user_lastip`"; - } - if(!empty($GetIPsWhere['ip_at_reg'])) - { - $GetIPsQuery[] = "SELECT `ip_at_reg` AS `ip`, COUNT(`ip_at_reg`) AS `count`, '2' AS `type` FROM {{table}} WHERE `ip_at_reg` IN ({$GetIPsWhere['ip_at_reg']}) GROUP BY `ip_at_reg`"; - } - - if(!empty($GetIPsQuery)) - { - $GetIPsResult = doquery(implode(' UNION ', $GetIPsQuery), 'users'); - if(mysql_num_rows($GetIPsResult) > 0) - { - while($IPsData = mysql_fetch_assoc($GetIPsResult)) - { - if($IPsData['type'] == 1) - { - $Key = 'user_lastip'; - } - else - { - $Key = 'ip_at_reg'; - } - $IPsList[$Key][$IPsData['ip']] = $IPsData['count']; - } - } - $Profiling['repeatedIPs'] = microtime(true) - $Profiling['repeatedIPs']; - } - - if(!empty($GetAllys)) - { - $Query = "SELECT `id`, `ally_name`, `ally_owner` FROM {{table}} WHERE `id` IN (".implode(', ', $GetAllys).");"; - $Result = doquery($Query, 'alliance'); - if(mysql_num_rows($Result) > 0) - { - while($Data = mysql_fetch_assoc($Result)) - { - $Allys[$Data['id']] = - array - ( - 'name'=> $Data['ally_name'], - 'owner' => $Data['ally_owner'] - ); - } - } - } - } - - $parse['adm_ul_table'] = ''; - if(!empty($Users)) - { - $ThisDate['d'] = date('d'); - $ThisDate['dmy'] = date('d.m.Y'); - $ThisDate['dmyp'] = date('d.m.Y', $Now - TIME_DAY); - $Times['28d'] = TIME_DAY * 28; - $Times['7d'] = TIME_DAY * 7; - - foreach($Users as $ID => $Data) - { - $HasHigherAuthlevel = ($Data['authlevel'] > $_User['authlevel'] ? true : false); - - if(isset($IPsList['user_lastip'][$Data['user_lastip']]) && $IPsList['user_lastip'][$Data['user_lastip']] > 1) - { - if($Data['multi_validated'] == 1) - { - $ColorIP = 'orange'; - } - else - { - $ColorIP = 'red'; - } - } - else - { - $ColorIP = 'lime'; - } - if(isset($IPsList['ip_at_reg'][$Data['ip_at_reg']]) && $IPsList['ip_at_reg'][$Data['ip_at_reg']] > 1) - { - if($Data['multi_validated'] == 1) - { - $ColorReg = 'orange'; - } - else - { - $ColorReg = 'red'; - } - } - else - { - $ColorReg = 'lime'; - } - - // ------------------------------ - // Here start creating user Bloc! - // RowElement - ID - $Bloc['adm_ul_data_id'] = $ID; - - // RowElement - Username - if($Data['is_ondeletion'] == 1) - { - $AddClass4Name = ' orange'; - } - else if($Data['ban_endtime'] > $Now) - { - $AddClass4Name = ' banned'; - } - else if($Data['vacation'] == 1) - { - $AddClass4Name = ' vacations'; - } - else - { - $AddClass4Name = ''; - } - $Bloc['adm_ul_data_name'] = "{$Data['username']}"; - if($Data['is_ondeletion'] == 1) - { - $Bloc['adm_ul_data_name'] = "{$Bloc['adm_ul_data_name']}"; - } - - // RowElement - User Alliance - if($Data['ally_id'] > 0 OR $Data['ally_request'] > 0) - { - if($Data['ally_id'] <= 0) - { - $Data['ally_id'] = $Data['ally_request']; - } - $Bloc['UserAlliance'] = "".wordwrap($Allys[$Data['ally_id']]['name'], 15, '
', true)."
"; - if($ID == $Allys[$Data['ally_id']]['owner']) - { - $Bloc['UserAlliance'] = "{$Bloc['UserAlliance']}"; - } - if($Data['ally_id'] == $Data['ally_request']) - { - $Bloc['UserAlliance'] = "{$Bloc['UserAlliance']}"; - } - } - else - { - $Bloc['UserAlliance'] = ' '; - } - - // RowElement - Email (mail) - if($HasHigherAuthlevel) - { - $Bloc['adm_ul_data_mail'] = $_Lang['ThisData_NoAccess']; - } - else - { - $Bloc['adm_ul_data_mail'] = $Data['email']; - } - - // RowElement - User IPs - if($HasHigherAuthlevel) - { - $Bloc['ip_adress_at_register'] = $_Lang['ThisData_NoAccess']; - } - else - { - if(!empty($Data['ip_at_reg'])) - { - $Bloc['ip_adress_at_register'] = "{$Data['ip_at_reg']}"; - } - else - { - $Bloc['ip_adress_at_register'] = "{$_Lang['_NoIP']}"; - } - } - if($HasHigherAuthlevel) - { - $Bloc['adm_ul_data_adip'] = $_Lang['ThisData_NoAccess']; - } - else - { - if(!empty($Data['user_lastip'])) - { - $Bloc['adm_ul_data_adip'] = "{$Data['user_lastip']}"; - } - else - { - $Bloc['adm_ul_data_adip'] = "{$_Lang['_NoIP']}"; - } - } - - // RowElement - Registration Time - if($Data['register_time'] > 0) - { - $Bloc['adm_ul_data_regd'] = ''; - $RegisterDays = floor(($Now - $Data['register_time']) / TIME_DAY); - if($RegisterDays == 1) - { - $RegDays = $_Lang['_day']; - } - else - { - $RegDays = $_Lang['_days']; - } - $RegisterDays = prettyNumber($RegisterDays); - if($RegisterDays == 0) - { - if($ThisDate['d'] == date('d', $Data['register_time'])) - { - $Bloc['adm_ul_data_regd'] = $_Lang['_today']; - } - else - { - $Bloc['adm_ul_data_regd'] = $_Lang['_yesterday']; - } - } - else - { - $Bloc['adm_ul_data_regd'] = "{$RegisterDays} {$RegDays} {$_Lang['_ago']}"; - } - $Bloc['RegDate_TH_Title'] = '
'.prettyDate('d m Y, H:i:s', $Data['register_time'], 1).'
'; - } - else - { - $Bloc['adm_ul_data_regd'] = ' '; - $Bloc['RegDate_TH_Title'] = $_Lang['No_Data']; - } - - // RowElement - Last Onlinetime - if($ThisDate['dmy'] == date('d.m.Y', $Data['onlinetime'])) - { - if($Data['onlinetime'] >= ($Now - TIME_ONLINE)) - { - $OnlineDate = pretty_time($Now - $Data['onlinetime'], false, 'ms'); - } - else - { - $OnlineDate = $_Lang['_today']; - } - } - else if($ThisDate['dmyp'] == date('d.m.Y', $Data['onlinetime'])) - { - $OnlineDate = $_Lang['_yesterday']; - } - else - { - $OnlineDate = date('d.m.Y', $Data['onlinetime']); - } - $Bloc['adm_ul_data_lconn'] = $OnlineDate; - $OnlineDiff = $Now - $Data['onlinetime']; - - if($OnlineDiff >= $Times['28d']) - { - $OLColor = 'red'; - } - elseif($OnlineDiff >= $Times['7d']) - { - $OLColor = '#FFA0A0'; - } - elseif($OnlineDiff >= TIME_DAY) - { - $OLColor = 'orange'; - } - elseif($OnlineDiff > TIME_ONLINE) - { - $OLColor = 'yellow'; - } - else - { - $OLColor = 'lime'; - } - $OnlineDiffText = '('.pretty_time($OnlineDiff).' '.$_Lang['_ago'].')'; - if(CheckAuth('supportadmin')) - { - $Bloc['OnlineDate_TH_Title'] = "
{$Data['current_page']}"; - } - $Bloc['OnlineDate_TH_Title'] = "
".prettyDate('d m Y, H:i:s', $Data['onlinetime'], 1)."
{$OnlineDiffText}{$Bloc['OnlineDate_TH_Title']}
"; - $Bloc['adm_ul_data_lconn'] = ''.$Bloc['adm_ul_data_lconn'].''; - - // RowElement - Expanded Info (MoreInfo) - // ------------------------------------- - - // MoreInfo - Browser and Screen - if($HasHigherAuthlevel) - { - $Bloc['UserMoreInfo'] = $_Lang['ThisData_NoAccess']; - } - else - { - $Bloc['UserMoreInfo'] = "{$_Lang['Userlist_Browser']}: ".(!empty($Data['uagent']) ? $Data['uagent'] : $_Lang['No_Data'])."
{$_Lang['Userlist_Screen']}: ".(!empty($Data['resolution']) ? str_replace('_', 'x', $Data['resolution']) : $_Lang['No_Data']); - } - // MoreInfo - EMails - if($HasHigherAuthlevel) - { - $Bloc['UserMoreInfo'] .= '
'.$_Lang['ThisData_NoAccess']; - } - else - { - $Bloc['UserMoreInfo'] .= "
{$_Lang['EMails']}: {$Data['email']} ({$Data['email_2']})[".(($Data['email'] == $Data['email_2']) ? $_Lang['_same'] : $_Lang['_notsame'])."]"; - } - // MoreInfo - IPs - if($HasHigherAuthlevel) - { - $Bloc['UserMoreInfo'] .= '
'.$_Lang['ThisData_NoAccess']; - } - else - { - $Bloc['UserMoreInfo'] .= "
{$_Lang['IPs']}: {$Bloc['adm_ul_data_adip']} / {$Bloc['ip_adress_at_register']}[{$_Lang['Lookup']}: {$_Lang['LastIPLook']} | {$_Lang['RegIPLook']}]"; - } - // MoreInfo - Vacation Info - if($Data['vacation'] == 1) - { - $Bloc['UserMoreInfo'] .= "
{$_Lang['UserOnVacation']}"; - $Bloc['UserMoreInfo'] .= "({$_Lang['_Since']}: ".pretty_time($Now - $Data['vacation_since'])." / ".date('d.m.Y, H:i:s', $Data['vacation_since'])." | ".($Data['vacation_endtime'] == 0 ? "{$_Lang['InfiniteVacation']}" : "{$_Lang['_Duration']}: ".pretty_time($Data['vacation_endtime'] - $Now)." / ".date('d.m.Y, H:i:s', $Data['vacation_endtime'])).")"; - } - // MoreInfo - Ban Info - if($Data['is_banned'] == 1) - { - if($Data['ban_endtime'] < $Now) - { - $BanColor = 'orange'; - $BanTime = $_Lang['Ban_Expired']; - } - else - { - $BanColor = 'red'; - $BanTime = $_Lang['Ban_TimeLeft'].' '.pretty_time($Data['ban_endtime'] - $Now); - } - $Bloc['UserMoreInfo'] .= "
{$_Lang['UserIsBanned']}: ".date('d.m.Y, H:i:s', $Data['ban_endtime'])."({$BanTime})"; - } - // MoreInfo - Activation Link - if(!empty($Data['activation_code'])) - { - $Bloc['UserMoreInfo'] .= "
{$_Lang['UserNotActivated']}[{$_Lang['UserActivationLink']}: ".(GAMEURL)."activate.php?code={$Data['activation_code']}]"; - } - // MoreInfo - is On Deletion - if($Data['is_ondeletion'] == 1) - { - $Bloc['UserMoreInfo'] .= "
{$_Lang['UserIsOnDeletion']}[{$_Lang['UserDeleteIn']}: ".($Data['deletion_endtime'] > $Now ? (pretty_time($Data['deletion_endtime'] - $Now)." / ".date('d.m.Y, H:i:s', $Data['deletion_endtime'])) : $_Lang['DeleteInNextCalc'])."]"; - } - - // MoreInfo - Action Links - $UserActions = false; - // > Action Links for GameOperator (GO) and higher ranks - if(CheckAuth('go')) - { - $UserActions[] = "{$_Lang['UserInfo']}"; - $UserActions[] = "{$_Lang['UserPM']}"; - $UserActions[] = "{$_Lang['ShowUserMessages']}"; - } - // > Action Links for SuperGameOperator (SGO) and higher ranks - if(CheckAuth('sgo')){ - if($Data['is_banned'] == 1) - { - $UserActions[] = "{$_Lang['UserUnban']}"; - } - else - { - $UserActions[] = "{$_Lang['UserBan']}"; - } - } - // > Action Links for Administrator (Admin) and higher ranks - if(CheckAuth('supportadmin')) - { - $UserActions[] = "{$_Lang['ShowActionLogs']}"; - $UserActions[] = "{$_Lang['UserDelete']}"; - } - $Bloc['UserActions'] = implode(' | ', $UserActions); - // > End of Action Links HERE - // End of MoreInfo HERE - // End of RowElement HERE - - // - Create Bloc! - $parse['adm_ul_table'] .= parsetemplate($RowsTPL, $Bloc); - $Bloc = false; - } - } - else - { - $parse['adm_ul_table'] .= ''.$_Lang['Userlist_NoUsersFound'].''; - } - - $parse['FoundUsers_Count'] = sprintf($_Lang['FoundUsers_Count'], prettyNumber($SelectCount)); - $parse['Filtering_Time'] = sprintf($_Lang['Filtering_Time'], sprintf('%0.5f', ($Search['EndTime'] - $Search['StartTime']))); - $parse['Loading_Time'] = sprintf($_Lang['Loading_Time'], sprintf('%0.5f', ($Loading['EndTime'] - $Loading['StartTime']))); - - if(!empty($parse['AdditionalInfoBox'])) - { - $parse['AdditionalInfoBox'] = ''.$parse['AdditionalInfoBox'].''; - } - - $page = parsetemplate($PageTPL, $parse); - display($page, $_Lang['Userlist_Title'], false, true); - -?> \ No newline at end of file + 0) + { + if(CheckAuth('supportadmin')) + { + if($DeleteID != $_User['id']) + { + doquery("UPDATE {{table}} SET `is_ondeletion` = 1, `deletion_endtime` = UNIX_TIMESTAMP() WHERE `id` = {$DeleteID};", 'users'); + } + } + else + { + message($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); + } + } +} + +if(isset($_POST['cmd']) && $_POST['cmd'] == 'sort' AND !empty($_POST['type']) AND (!isset($_POST['nosort']) || $_POST['nosort'] != 'on')) +{ + if(in_array($_POST['type'], $AllowedSortTypes)) + { + $TypeSort = $_POST['type']; + $parse['FormSortType'] = $TypeSort; + } + else + { + $TypeSort = 'id'; + } +} +else +{ + $TypeSort = 'id'; + $parse['DontShowNoSort'] = 'inv'; +} + +if(empty($_POST['mode']) || (isset($_POST['nosort']) && $_POST['nosort'] == 'on')) +{ + $parse['sort_mode'] = 'asc'; + $SortMode = 'ASC'; +} +else +{ + if($_POST['mode'] == 'asc') + { + $SortMode = 'ASC'; + $parse['FormSortMode'] = 'asc'; + $parse['sort_mode'] = 'desc'; + } + else + { + $SortMode = 'DESC'; + $parse['FormSortMode'] = 'desc'; + $parse['sort_mode'] = 'asc'; + } +} + +if(!empty($_POST['pp'])) +{ + $PerPage = intval($_POST['pp']); + if($PerPage <= 0) + { + $PerPage = 20; + } + $parse['per_page'] = '&pp='.$PerPage; + $parse['InitPerPage'] = $PerPage; + setcookie('ACP_UserList_PerPage', $PerPage, 0, 'admin/'); +} +else +{ + if(!empty($_COOKIE['ACP_UserList_PerPage'])) + { + $PerPage = intval($_COOKIE['ACP_UserList_PerPage']); + if($PerPage <= 0) + { + $PerPage = 20; + } + } + else + { + $PerPage = 20; + } +} +$parse['DefaultPerPage'] = 20; +$parse['perPageSelect_'.$PerPage] = 'selected'; + +// ---------------------------- +// Get Overrides -------------- +if(!empty($_GET['uid'])) +{ + $_GET['uid'] = intval($_GET['uid']); + if($_GET['uid'] > 0) + { + $_POST['search_user'] = $_GET['uid']; + $_POST['search_by'] = 'uid'; + } +} +if(!empty($_GET['ipid'])) +{ + if(preg_match(REGEXP_IP, $_GET['ipid'])) + { + $_POST['search_user'] = $_GET['ipid']; + $_POST['search_by'] = 'ip'; + $_POST['anyip'] = 'on'; + } +} +if(!empty($_GET['search_user']) AND !empty($_GET['search_by'])) +{ + $_POST['search_user'] = $_GET['search_user']; + $_POST['search_by'] = $_GET['search_by']; +} + +// ---------------------------- + +$PerPageArray = array(5, 10, 15, 20, 25, 50); +if(!in_array($PerPage, $PerPageArray)) +{ + $parse['perPageSelect_0'] = 'selected'; +} + +$CurrentPage = (isset($_POST['page']) ? intval($_POST['page']) : 0); +if($CurrentPage < 1) +{ + $CurrentPage = 1; +} +$parse['FormPage'] = $CurrentPage; +$GetStart = (string) ((($CurrentPage - 1) * $PerPage) + 0); + +$PageTPL = gettemplate('admin/userlist_body'); +$RowsTPL = gettemplate('admin/userlist_rows'); + +$parse['AllySearchTypeDisplay'] = $_Hide; +$parse['AllyInRequestDisplay'] = $_Hide; +$parse['AnyIPDisplay'] = $_Hide; +$parse['AnyIPChecked'] = $_Checked; +$parse['AllySearch_name_Checked'] = $_Checked; +$parse['AllySearch_tag_Checked'] = $_Checked; + +include($_EnginePath.'includes/functions/Filters.php'); + +if(isset($_POST['preserve']) && strstr($_POST['preserve'], 'over=yes') !== false) +{ + $_GET['over'] = 'yes'; +} + +if(isset($_GET['over']) && $_GET['over'] == 'yes') +{ + $_POST['online_yes'] = 'on'; + $parse['FormPreserve'][] = 'over=yes'; +} + +if(!empty($parse['FormPreserve'])) +{ + $parse['FormPreserve'] = implode('|', $parse['FormPreserve']); +} + +$Search['Flags']['strict'] = (isset($_POST['strict']) && $_POST['strict'] == 'on' ? true : false); +$Search['Flags']['utableOnly'] = (isset($_POST['anyip']) && $_POST['anyip'] == 'on' ? false : true); +$Search['Flags']['isOnline'] = (isset($_POST['online_yes']) && $_POST['online_yes'] == 'on' ? true : (isset($_POST['online_no']) && $_POST['online_no'] == 'on' ? false : null)); +$Search['Flags']['onVacation'] = (isset($_POST['onvacation_yes']) && $_POST['onvacation_yes'] == 'on' ? true : (isset($_POST['onvacation_no']) && $_POST['onvacation_no'] == 'on' ? false : null)); +$Search['Flags']['isBanned'] = (isset($_POST['isbanned_yes']) && $_POST['isbanned_yes'] == 'on' ? true : (isset($_POST['isbanned_no']) && $_POST['isbanned_no'] == 'on' ? false : null)); +$Search['Flags']['isAI'] = (isset($_POST['isai_yes']) && $_POST['isai_yes'] == 'on' ? true : (isset($_POST['isai_no']) && $_POST['isai_no'] == 'on' ? false : null)); +$Search['Flags']['inDeletion'] = (isset($_POST['isdeleting_yes']) && $_POST['isdeleting_yes'] == 'on' ? true : (isset($_POST['isdeleting_no']) && $_POST['isdeleting_no'] == 'on' ? false : null)); +$Search['Flags']['inAlly'] = (isset($_POST['isinally_yes']) && $_POST['isinally_yes'] == 'on' ? true : (isset($_POST['isinally_no']) && $_POST['isinally_no'] == 'on' ? false : null)); +$Search['Flags']['isActive'] = (isset($_POST['isactive_yes']) && $_POST['isactive_yes'] == 'on' ? true : (isset($_POST['isactive_no']) && $_POST['isactive_no'] == 'on' ? false : null)); +$Search['Flags']['allyRequest'] = (isset($_POST['allyinrequest_yes']) && $_POST['allyinrequest_yes'] == 'on' ? true : (isset($_POST['allyinrequest_no']) && $_POST['allyinrequest_no'] == 'on' ? false : null)); +if(isset($_POST['search_by']) && $_POST['search_by'] == 'ally') +{ + $parse['searchBySelect_ally'] = $_Selected; + if(isset($_POST['allysearch_name']) && isset($_POST['allysearch_tag']) && $_POST['allysearch_name'] == 'on' && $_POST['allysearch_tag'] == 'on') + { + $_POST['search_by'] = 'astring'; + } + else if(isset($_POST['allysearch_name']) && $_POST['allysearch_name'] == 'on') + { + $_POST['search_by'] = 'aname'; + $parse['AllySearch_tag_Checked'] = ''; + } + else if(isset($_POST['allysearch_tag']) && $_POST['allysearch_tag'] == 'on') + { + $_POST['search_by'] = 'atag'; + $parse['AllySearch_name_Checked'] = ''; + } + else + { + $_POST['search_by'] = 'astring'; + $parse['AllySearch_name_Checked'] = ''; + $parse['AllySearch_tag_Checked'] = ''; + } + $parse['AllySearchTypeDisplay'] = ''; + $parse['AllyInRequestDisplay'] = ''; +} +if(isset($_POST['search_by']) && $_POST['search_by'] == 'aid') +{ + $parse['AllyInRequestDisplay'] = ''; +} + +// Check settings in Form +if(isset($_POST['strict']) && $_POST['strict'] == 'on') +{ + $parse['StrictChecked'] = $_Checked; +} +if(isset($_POST['online_yes']) && $_POST['online_yes'] == 'on') +{ + if(isset($_GET['over']) && $_GET['over'] == 'yes') + { + $parse['UsingOverviewShortcut'] = 'orange'; + } + else + { + $parse['Online_Yes_Checked'] = $_Checked; + } +} +if(isset($_POST['online_no']) && $_POST['online_no'] == 'on') +{ + $parse['Online_No_Checked'] = $_Checked; +} +if(isset($_POST['onvacation_yes']) && $_POST['onvacation_yes'] == 'on') +{ + $parse['OnVacation_Yes_Checked'] = $_Checked; +} +if(isset($_POST['onvacation_no']) && $_POST['onvacation_no'] == 'on') +{ + $parse['OnVacation_No_Checked'] = $_Checked; +} +if(isset($_POST['isbanned_yes']) && $_POST['isbanned_yes'] == 'on') +{ + $parse['IsBanned_Yes_Checked'] = $_Checked; +} +if(isset($_POST['isbanned_no']) && $_POST['isbanned_no'] == 'on') +{ + $parse['IsBanned_No_Checked'] = $_Checked; +} +if(isset($_POST['isai_yes']) && $_POST['isai_yes'] == 'on') +{ + $parse['IsAi_Yes_Checked'] = $_Checked; +} +if(isset($_POST['isai_no']) && $_POST['isai_no'] == 'on') +{ + $parse['IsAi_No_Checked'] = $_Checked; +} +if(isset($_POST['isdeleting_yes']) && $_POST['isdeleting_yes'] == 'on') +{ + $parse['IsDeleting_Yes_Checked'] = $_Checked; +} +if(isset($_POST['isdeleting_no']) && $_POST['isdeleting_no'] == 'on') +{ + $parse['IsDeleting_No_Checked'] = $_Checked; +} +if(isset($_POST['isinally_yes']) && $_POST['isinally_yes'] == 'on') +{ + $parse['IsInAlly_Yes_Checked'] = $_Checked; +} +if(isset($_POST['isinally_no']) && $_POST['isinally_no'] == 'on') +{ + $parse['IsInAlly_No_Checked'] = $_Checked; +} +if(isset($_POST['isactive_yes']) && $_POST['isactive_yes'] == 'on') +{ + $parse['IsActive_Yes_Checked'] = $_Checked; +} +if(isset($_POST['isactive_no']) && $_POST['isactive_no'] == 'on') +{ + $parse['IsActive_No_Checked'] = $_Checked; +} +if(isset($_POST['anyip']) && $_POST['anyip'] == 'on') +{ + $parse['AnyIPChecked'] = $_Checked; +} +if(isset($_POST['allysearch_name']) && $_POST['allysearch_name'] == 'on') +{ + $parse['AllySearch_name_Checked'] = $_Checked; +} +if(isset($_POST['allysearch_tag']) && $_POST['allysearch_tag'] == 'on') +{ + $parse['AllySearch_tag_Checked'] = $_Checked; +} +if(isset($_POST['allyinrequest_yes']) && $_POST['allyinrequest_yes'] == 'on') +{ + $parse['AllyInRequest_Yes_Checked'] = $_Checked; +} +if(isset($_POST['allyinrequest_no']) && $_POST['allyinrequest_no'] == 'on') +{ + $parse['AllyInRequest_No_Checked'] = $_Checked; +} + +$parse['search_user_val'] = (isset($_POST['search_user']) ? $_POST['search_user'] : null); + +$UserFields = array +( + 'id', 'username', 'ally_id', 'ally_request', 'authlevel', 'email', 'email_2', 'user_agent', 'screen_settings', 'ip_at_reg', + 'user_lastip', 'register_time', 'onlinetime', 'current_page', 'is_banned', 'ban_endtime', 'is_onvacation', + 'vacation_starttime', 'vacation_endtime', 'pro_time', 'multi_validated', 'activation_code', 'is_ondeletion', 'deletion_endtime', +); +array_walk($UserFields, function(&$Value){ $Value = "`{$Value}`"; }); +$UserFields = implode(', ', $UserFields); + +if(empty($_POST['search_user'])) +{ + $Search['mode'] = 1; + $Search['string'] = ''; + $Search['type'] = ''; +} +else +{ + $Search['mode'] = 2; + $Search['string'] = $_POST['search_user']; + if($_POST['search_by'] == 'uid') + { + $Search['type'] = 'uid'; + } + else if($_POST['search_by'] == 'astring' || $_POST['search_by'] == 'aname' || $_POST['search_by'] == 'atag') + { + $Search['type'] = $_POST['search_by']; + } + else if($_POST['search_by'] == 'aid') + { + $Search['type'] = 'aid'; + } + else if($_POST['search_by'] == 'ip') + { + $Search['type'] = 'ipstring'; + $parse['AnyIPDisplay'] = ''; + } + else + { + $Search['type'] = 'uname'; + $_POST['search_by'] = 'name'; + } + $parse['searchBySelect_'.$_POST['search_by']] = 'selected'; +} + +$Search['StartTime'] = microtime(true); +$FilterResult = Filter_Users($Search['string'], $Search['type'], $Search['Flags']); +$Search['EndTime'] = microtime(true); + +if(!empty($_POST['massAction'])) +{ + if($_POST['massAction'] == 'ban' || $_POST['massAction'] == 'unban') + { + if(isset($_POST['useAllFiltered']) && $_POST['useAllFiltered'] == '1') + { + if($FilterResult !== true AND $FilterResult !== false) + { + $PassIDs = implode(',', $FilterResult); + } + } + else + { + $GetIDs = explode(',', trim($_POST['massActionIDs'])); + foreach($GetIDs as $ThisID) + { + $ThisID = round($ThisID); + if($ThisID > 0) + { + $PassIDs[] = $ThisID; + } + } + if(!empty($PassIDs)) + { + $PassIDs = implode(',', $PassIDs); + } + } + + if(!empty($PassIDs)) + { + if($_POST['massAction'] == 'ban') + { + header('Location: banuser.php?ids='.$PassIDs); + } + else if($_POST['massAction'] == 'unban') + { + header('Location: unbanuser.php?ids='.$PassIDs); + } + safeDie(); + } + } +} + +$Loading['StartTime'] = microtime(true); +if($FilterResult !== true) +{ + if(!empty($FilterResult)) + { + $WhereClausure = implode(', ', $FilterResult); + $SelectCount = count($FilterResult); + if($GetStart >= $SelectCount) + { + $CurrentPage = ceil($SelectCount / $PerPage); + $GetStart = (string) ((($CurrentPage - 1) * $PerPage) + 0); + } + $query = doquery("SELECT {$UserFields} FROM {{table}} WHERE `id` IN ({$WhereClausure}) ORDER BY `{$TypeSort}` {$SortMode} LIMIT {$GetStart}, {$PerPage};", 'users'); + } + else + { + $SelectCount = 0; + if($FilterResult === false) + { + $parse['AdditionalInfoBox'] = $_Lang['UserFilter_NoGoodStrings']; + $parse['AdditionalInfoBox_Color'] = 'red'; + } + } +} +else +{ + $SelectCount = doquery("SELECT COUNT(`id`) AS `Count` FROM {{table}};", 'users', true); + $SelectCount = $SelectCount['Count']; + if($GetStart >= $SelectCount) + { + $CurrentPage = ceil($SelectCount / $PerPage); + $GetStart = (string) ((($CurrentPage - 1) * $PerPage) + 0); + } + $query = doquery("SELECT {$UserFields} FROM {{table}} ORDER BY `{$TypeSort}` {$SortMode} LIMIT {$GetStart}, {$PerPage};", 'users'); +} +$Loading['EndTime'] = microtime(true); + +if($SelectCount > $PerPage) +{ + include_once($_EnginePath.'includes/functions/Pagination.php'); + $Pagin = CreatePaginationArray($SelectCount, $PerPage, $CurrentPage, 7); + $PaginationTPL = "{\$ShowValue}"; + $PaginationViewOpt = array('CurrentPage_Classes' => 'orange', 'Breaker_View' => '...'); + $CreatePagination = implode(' ', ParsePaginationArray($Pagin, $CurrentPage, $PaginationTPL, $PaginationViewOpt)); + $parse['pagination'] = ''.$CreatePagination.''; +} + +if($SelectCount > 0) +{ + while($UserData = mysql_fetch_assoc($query)) + { + $Users[$UserData['id']] = + array + ( + 'username' => $UserData['username'], + 'ally_id' => $UserData['ally_id'], + 'ally_request' => $UserData['ally_request'], + 'authlevel' => $UserData['authlevel'], + 'email' => $UserData['email'], + 'email_2' => $UserData['email_2'], + 'uagent' => $UserData['user_agent'], + 'resolution' => $UserData['screen_settings'], + 'ip_at_reg' => $UserData['ip_at_reg'], + 'user_lastip' => $UserData['user_lastip'], + 'register_time' => $UserData['register_time'], + 'onlinetime' => $UserData['onlinetime'], + 'current_page' => $UserData['current_page'], + 'is_banned' => $UserData['is_banned'], + 'ban_endtime' => $UserData['ban_endtime'], + 'vacation' => $UserData['is_onvacation'], + 'vacation_since' => $UserData['vacation_starttime'], + 'vacation_endtime' => $UserData['vacation_endtime'], + 'is_ondeletion' => $UserData['is_ondeletion'], + 'deletion_endtime' => $UserData['deletion_endtime'], + 'pro_till' => $UserData['pro_time'], + 'multi_validated' => $UserData['multi_validated'], + 'activation_code' => $UserData['activation_code'], + ); + + if(!empty($UserData['ip_at_reg'])) + { + $GetIPs['ip_at_reg'][] = "'{$UserData['ip_at_reg']}'"; + } + if(!empty($UserData['user_lastip'])) + { + $GetIPs['user_lastip'][] = "'{$UserData['user_lastip']}'"; + } + + if($UserData['ally_id'] > 0) + { + if(!empty($GetAllys)) + { + if(!in_array($UserData['ally_id'], $GetAllys)) + { + $GetAllys[] = $UserData['ally_id']; + } + } + else + { + $GetAllys[] = $UserData['ally_id']; + } + } + else + { + if(!empty($UserData['ally_request'])) + { + if(!empty($GetAllys)) + { + if(!in_array($UserData['ally_request'], $GetAllys)) + { + $GetAllys[] = $UserData['ally_request']; + } + } + else + { + $GetAllys[] = $UserData['ally_request']; + } + } + } + } + + $Profiling['repeatedIPs'] = microtime(true); + foreach($GetIPs as $Field => $Values) + { + $GetIPsWhere[$Field] = implode(', ', $Values); + } + if(!empty($GetIPsWhere['user_lastip'])) + { + $GetIPsQuery[] = "SELECT `user_lastip` AS `ip`, COUNT(`user_lastip`) AS `count`, '1' AS `type` FROM {{table}} WHERE `user_lastip` IN ({$GetIPsWhere['user_lastip']}) GROUP BY `user_lastip`"; + } + if(!empty($GetIPsWhere['ip_at_reg'])) + { + $GetIPsQuery[] = "SELECT `ip_at_reg` AS `ip`, COUNT(`ip_at_reg`) AS `count`, '2' AS `type` FROM {{table}} WHERE `ip_at_reg` IN ({$GetIPsWhere['ip_at_reg']}) GROUP BY `ip_at_reg`"; + } + + if(!empty($GetIPsQuery)) + { + $GetIPsResult = doquery(implode(' UNION ', $GetIPsQuery), 'users'); + if(mysql_num_rows($GetIPsResult) > 0) + { + while($IPsData = mysql_fetch_assoc($GetIPsResult)) + { + if($IPsData['type'] == 1) + { + $Key = 'user_lastip'; + } + else + { + $Key = 'ip_at_reg'; + } + $IPsList[$Key][$IPsData['ip']] = $IPsData['count']; + } + } + $Profiling['repeatedIPs'] = microtime(true) - $Profiling['repeatedIPs']; + } + + if(!empty($GetAllys)) + { + $Query = "SELECT `id`, `ally_name`, `ally_owner` FROM {{table}} WHERE `id` IN (".implode(', ', $GetAllys).");"; + $Result = doquery($Query, 'alliance'); + if(mysql_num_rows($Result) > 0) + { + while($Data = mysql_fetch_assoc($Result)) + { + $Allys[$Data['id']] = + array + ( + 'name'=> $Data['ally_name'], + 'owner' => $Data['ally_owner'] + ); + } + } + } +} + +$parse['adm_ul_table'] = ''; +if(!empty($Users)) +{ + $ThisDate['d'] = date('d'); + $ThisDate['dmy'] = date('d.m.Y'); + $ThisDate['dmyp'] = date('d.m.Y', $Now - TIME_DAY); + $Times['28d'] = TIME_DAY * 28; + $Times['7d'] = TIME_DAY * 7; + + foreach($Users as $ID => $Data) + { + $HasHigherAuthlevel = ($Data['authlevel'] > $_User['authlevel'] ? true : false); + + if(isset($IPsList['user_lastip'][$Data['user_lastip']]) && $IPsList['user_lastip'][$Data['user_lastip']] > 1) + { + if($Data['multi_validated'] == 1) + { + $ColorIP = 'orange'; + } + else + { + $ColorIP = 'red'; + } + } + else + { + $ColorIP = 'lime'; + } + if(isset($IPsList['ip_at_reg'][$Data['ip_at_reg']]) && $IPsList['ip_at_reg'][$Data['ip_at_reg']] > 1) + { + if($Data['multi_validated'] == 1) + { + $ColorReg = 'orange'; + } + else + { + $ColorReg = 'red'; + } + } + else + { + $ColorReg = 'lime'; + } + + // ------------------------------ + // Here start creating user Bloc! + // RowElement - ID + $Bloc['adm_ul_data_id'] = $ID; + + // RowElement - Username + if($Data['is_ondeletion'] == 1) + { + $AddClass4Name = ' orange'; + } + else if($Data['ban_endtime'] > $Now) + { + $AddClass4Name = ' banned'; + } + else if($Data['vacation'] == 1) + { + $AddClass4Name = ' vacations'; + } + else + { + $AddClass4Name = ''; + } + $Bloc['adm_ul_data_name'] = "{$Data['username']}"; + if($Data['is_ondeletion'] == 1) + { + $Bloc['adm_ul_data_name'] = "{$Bloc['adm_ul_data_name']}"; + } + + // RowElement - User Alliance + if($Data['ally_id'] > 0 OR $Data['ally_request'] > 0) + { + if($Data['ally_id'] <= 0) + { + $Data['ally_id'] = $Data['ally_request']; + } + $Bloc['UserAlliance'] = "".wordwrap($Allys[$Data['ally_id']]['name'], 15, '
', true)."
"; + if($ID == $Allys[$Data['ally_id']]['owner']) + { + $Bloc['UserAlliance'] = "{$Bloc['UserAlliance']}"; + } + if($Data['ally_id'] == $Data['ally_request']) + { + $Bloc['UserAlliance'] = "{$Bloc['UserAlliance']}"; + } + } + else + { + $Bloc['UserAlliance'] = ' '; + } + + // RowElement - Email (mail) + if($HasHigherAuthlevel) + { + $Bloc['adm_ul_data_mail'] = $_Lang['ThisData_NoAccess']; + } + else + { + $Bloc['adm_ul_data_mail'] = $Data['email']; + } + + // RowElement - User IPs + if($HasHigherAuthlevel) + { + $Bloc['ip_adress_at_register'] = $_Lang['ThisData_NoAccess']; + } + else + { + if(!empty($Data['ip_at_reg'])) + { + $Bloc['ip_adress_at_register'] = "{$Data['ip_at_reg']}"; + } + else + { + $Bloc['ip_adress_at_register'] = "{$_Lang['_NoIP']}"; + } + } + if($HasHigherAuthlevel) + { + $Bloc['adm_ul_data_adip'] = $_Lang['ThisData_NoAccess']; + } + else + { + if(!empty($Data['user_lastip'])) + { + $Bloc['adm_ul_data_adip'] = "{$Data['user_lastip']}"; + } + else + { + $Bloc['adm_ul_data_adip'] = "{$_Lang['_NoIP']}"; + } + } + + // RowElement - Registration Time + if($Data['register_time'] > 0) + { + $Bloc['adm_ul_data_regd'] = ''; + $RegisterDays = floor(($Now - $Data['register_time']) / TIME_DAY); + if($RegisterDays == 1) + { + $RegDays = $_Lang['_day']; + } + else + { + $RegDays = $_Lang['_days']; + } + $RegisterDays = prettyNumber($RegisterDays); + if($RegisterDays == 0) + { + if($ThisDate['d'] == date('d', $Data['register_time'])) + { + $Bloc['adm_ul_data_regd'] = $_Lang['_today']; + } + else + { + $Bloc['adm_ul_data_regd'] = $_Lang['_yesterday']; + } + } + else + { + $Bloc['adm_ul_data_regd'] = "{$RegisterDays} {$RegDays} {$_Lang['_ago']}"; + } + $Bloc['RegDate_TH_Title'] = '
'.prettyDate('d m Y, H:i:s', $Data['register_time'], 1).'
'; + } + else + { + $Bloc['adm_ul_data_regd'] = ' '; + $Bloc['RegDate_TH_Title'] = $_Lang['No_Data']; + } + + // RowElement - Last Onlinetime + if($ThisDate['dmy'] == date('d.m.Y', $Data['onlinetime'])) + { + if($Data['onlinetime'] >= ($Now - TIME_ONLINE)) + { + $OnlineDate = pretty_time($Now - $Data['onlinetime'], false, 'ms'); + } + else + { + $OnlineDate = $_Lang['_today']; + } + } + else if($ThisDate['dmyp'] == date('d.m.Y', $Data['onlinetime'])) + { + $OnlineDate = $_Lang['_yesterday']; + } + else + { + $OnlineDate = date('d.m.Y', $Data['onlinetime']); + } + $Bloc['adm_ul_data_lconn'] = $OnlineDate; + $OnlineDiff = $Now - $Data['onlinetime']; + + if($OnlineDiff >= $Times['28d']) + { + $OLColor = 'red'; + } + elseif($OnlineDiff >= $Times['7d']) + { + $OLColor = '#FFA0A0'; + } + elseif($OnlineDiff >= TIME_DAY) + { + $OLColor = 'orange'; + } + elseif($OnlineDiff > TIME_ONLINE) + { + $OLColor = 'yellow'; + } + else + { + $OLColor = 'lime'; + } + $OnlineDiffText = '('.pretty_time($OnlineDiff).' '.$_Lang['_ago'].')'; + if(CheckAuth('supportadmin')) + { + $Bloc['OnlineDate_TH_Title'] = "
{$Data['current_page']}"; + } + $Bloc['OnlineDate_TH_Title'] = "
".prettyDate('d m Y, H:i:s', $Data['onlinetime'], 1)."
{$OnlineDiffText}{$Bloc['OnlineDate_TH_Title']}
"; + $Bloc['adm_ul_data_lconn'] = ''.$Bloc['adm_ul_data_lconn'].''; + + // RowElement - Expanded Info (MoreInfo) + // ------------------------------------- + + // MoreInfo - Browser and Screen + if($HasHigherAuthlevel) + { + $Bloc['UserMoreInfo'] = $_Lang['ThisData_NoAccess']; + } + else + { + $Bloc['UserMoreInfo'] = "{$_Lang['Userlist_Browser']}: ".(!empty($Data['uagent']) ? $Data['uagent'] : $_Lang['No_Data'])."
{$_Lang['Userlist_Screen']}: ".(!empty($Data['resolution']) ? str_replace('_', 'x', $Data['resolution']) : $_Lang['No_Data']); + } + // MoreInfo - EMails + if($HasHigherAuthlevel) + { + $Bloc['UserMoreInfo'] .= '
'.$_Lang['ThisData_NoAccess']; + } + else + { + $Bloc['UserMoreInfo'] .= "
{$_Lang['EMails']}: {$Data['email']} ({$Data['email_2']})[".(($Data['email'] == $Data['email_2']) ? $_Lang['_same'] : $_Lang['_notsame'])."]"; + } + // MoreInfo - IPs + if($HasHigherAuthlevel) + { + $Bloc['UserMoreInfo'] .= '
'.$_Lang['ThisData_NoAccess']; + } + else + { + $Bloc['UserMoreInfo'] .= "
{$_Lang['IPs']}: {$Bloc['adm_ul_data_adip']} / {$Bloc['ip_adress_at_register']}[{$_Lang['Lookup']}: {$_Lang['LastIPLook']} | {$_Lang['RegIPLook']}]"; + } + // MoreInfo - Vacation Info + if($Data['vacation'] == 1) + { + $Bloc['UserMoreInfo'] .= "
{$_Lang['UserOnVacation']}"; + $Bloc['UserMoreInfo'] .= "({$_Lang['_Since']}: ".pretty_time($Now - $Data['vacation_since'])." / ".date('d.m.Y, H:i:s', $Data['vacation_since'])." | ".($Data['vacation_endtime'] == 0 ? "{$_Lang['InfiniteVacation']}" : "{$_Lang['_Duration']}: ".pretty_time($Data['vacation_endtime'] - $Now)." / ".date('d.m.Y, H:i:s', $Data['vacation_endtime'])).")"; + } + // MoreInfo - Ban Info + if($Data['is_banned'] == 1) + { + if($Data['ban_endtime'] < $Now) + { + $BanColor = 'orange'; + $BanTime = $_Lang['Ban_Expired']; + } + else + { + $BanColor = 'red'; + $BanTime = $_Lang['Ban_TimeLeft'].' '.pretty_time($Data['ban_endtime'] - $Now); + } + $Bloc['UserMoreInfo'] .= "
{$_Lang['UserIsBanned']}: ".date('d.m.Y, H:i:s', $Data['ban_endtime'])."({$BanTime})"; + } + // MoreInfo - Activation Link + if(!empty($Data['activation_code'])) + { + $Bloc['UserMoreInfo'] .= "
{$_Lang['UserNotActivated']}[{$_Lang['UserActivationLink']}: ".(GAMEURL)."activate.php?code={$Data['activation_code']}]"; + } + // MoreInfo - is On Deletion + if($Data['is_ondeletion'] == 1) + { + $Bloc['UserMoreInfo'] .= "
{$_Lang['UserIsOnDeletion']}[{$_Lang['UserDeleteIn']}: ".($Data['deletion_endtime'] > $Now ? (pretty_time($Data['deletion_endtime'] - $Now)." / ".date('d.m.Y, H:i:s', $Data['deletion_endtime'])) : $_Lang['DeleteInNextCalc'])."]"; + } + + // MoreInfo - Action Links + $UserActions = false; + // > Action Links for GameOperator (GO) and higher ranks + if(CheckAuth('go')) + { + $UserActions[] = "{$_Lang['UserInfo']}"; + $UserActions[] = "{$_Lang['UserPM']}"; + $UserActions[] = "{$_Lang['ShowUserMessages']}"; + } + // > Action Links for SuperGameOperator (SGO) and higher ranks + if(CheckAuth('sgo')){ + if($Data['is_banned'] == 1) + { + $UserActions[] = "{$_Lang['UserUnban']}"; + } + else + { + $UserActions[] = "{$_Lang['UserBan']}"; + } + } + // > Action Links for Administrator (Admin) and higher ranks + if(CheckAuth('supportadmin')) + { + $UserActions[] = "{$_Lang['ShowActionLogs']}"; + $UserActions[] = "{$_Lang['UserDelete']}"; + } + $Bloc['UserActions'] = implode(' | ', $UserActions); + // > End of Action Links HERE + // End of MoreInfo HERE + // End of RowElement HERE + + // - Create Bloc! + $parse['adm_ul_table'] .= parsetemplate($RowsTPL, $Bloc); + $Bloc = false; + } +} +else +{ + $parse['adm_ul_table'] .= ''.$_Lang['Userlist_NoUsersFound'].''; +} + +$parse['FoundUsers_Count'] = sprintf($_Lang['FoundUsers_Count'], prettyNumber($SelectCount)); +$parse['Filtering_Time'] = sprintf($_Lang['Filtering_Time'], sprintf('%0.5f', ($Search['EndTime'] - $Search['StartTime']))); +$parse['Loading_Time'] = sprintf($_Lang['Loading_Time'], sprintf('%0.5f', ($Loading['EndTime'] - $Loading['StartTime']))); + +if(!empty($parse['AdditionalInfoBox'])) +{ + $parse['AdditionalInfoBox'] = ''.$parse['AdditionalInfoBox'].''; +} + +$page = parsetemplate($PageTPL, $parse); +display($page, $_Lang['Userlist_Title'], false, true); + +?> diff --git a/admin/users_techmanager.php b/admin/users_techmanager.php index 5de567407..4c67089e3 100644 --- a/admin/users_techmanager.php +++ b/admin/users_techmanager.php @@ -1,192 +1,192 @@ - &$Items_Technologies, - ); - - if(isset($_POST['sent']) && $_POST['sent'] == 1) - { - $UserID = round($_POST['userID']); - $TabID = intval($_POST['tab']); - $ThisCMD = (isset($_POST['cmd']) ? $_POST['cmd'] : null); - - $_Lang['Insert_PreviousUserID'] = $UserID; - $_Lang['Insert_SelectCMD_'.$ThisCMD] = 'checked'; - $_Lang['Insert_DefaultTab'] = $TabID - 1; - - if($UserID > 0) - { - if(in_array($ThisCMD, $Allowed_CMD)) - { - if(in_array($TabID, array_keys($Allowed_Tabs))) - { - if(!empty($_POST['res'][$TabID])) - { - $Query_GetUser = ''; - $Query_GetUser .= "SELECT `id`, `username` "; - $Query_GetUser .= "FROM {{table}} WHERE `id` = {$UserID} LIMIT 1; -- admin/user_techmanager.php - Query #1"; - $Result_GetUser = doquery($Query_GetUser, 'users', true); - if($Result_GetUser['id'] == $UserID) - { - foreach($_POST['res'][$TabID] as $ThisID => $ThisValue) - { - if(in_array($ThisID, $Allowed_Tabs[$TabID])) - { - if($ThisCMD == 'set' AND empty($ThisValue)) - { - continue; - } - $ThisValue = round(str_replace('.', '', $ThisValue)); - if(($ThisCMD == 'set' AND $ThisValue >= 0) OR ($ThisCMD != 'set' AND $ThisValue > 0)) - { - if($ThisValue > $_ResLimit) - { - $ThisValue = $_ResLimit; - } - $Query_Update_Data[$ThisID] = $ThisValue; - } - } - } - - if(!empty($Query_Update_Data)) - { - if($ThisCMD == 'add') - { - $Query_Update = ''; - $Query_Update .= "UPDATE {{table}} SET "; - foreach($Query_Update_Data as $ThisID => $ThisValue) - { - $Query_Update_Array[] = "`{$_Vars_GameElements[$ThisID]}` = `{$_Vars_GameElements[$ThisID]}` + {$ThisValue}"; - } - $Query_Update .= implode(',', $Query_Update_Array); - $Query_Update .= " WHERE `id` = {$UserID} LIMIT 1;"; - } - else if($ThisCMD == 'set') - { - $Query_Update = ''; - $Query_Update .= "UPDATE {{table}} SET "; - foreach($Query_Update_Data as $ThisID => $ThisValue) - { - $Query_Update_Array[] = "`{$_Vars_GameElements[$ThisID]}` = {$ThisValue}"; - } - $Query_Update .= implode(',', $Query_Update_Array); - $Query_Update .= " WHERE `id` = {$UserID} LIMIT 1;"; - } - else if($ThisCMD == 'sub') - { - foreach($Query_Update_Data as $ThisID => $ThisValue) - { - $Query_Update_Fields[] = "`{$_Vars_GameElements[$ThisID]}`"; - $Query_Update_Values[] = $ThisValue; - $Query_Update_Set[] = "`{$_Vars_GameElements[$ThisID]}` = IF(VALUES(`{$_Vars_GameElements[$ThisID]}`) > `{$_Vars_GameElements[$ThisID]}`, 0, `{$_Vars_GameElements[$ThisID]}` - VALUES(`{$_Vars_GameElements[$ThisID]}`))"; - } - $Query_Update = ''; - $Query_Update .= "INSERT INTO {{table}} (`id`, ".implode(', ', $Query_Update_Fields).") "; - $Query_Update .= "VALUES ({$UserID}, ".implode(', ', $Query_Update_Values).") "; - $Query_Update .= "ON DUPLICATE KEY UPDATE "; - $Query_Update .= implode(',', $Query_Update_Set); - } - doquery($Query_Update, 'users'); - if(mysql_affected_rows() > 0) - { - $_MsgBox = array - ( - 'color' => 'lime', - 'text' => sprintf - ( - $_Lang['MsgBox_UpdateOK'], - $Result_GetUser['id'], $Result_GetUser['username'], $Result_GetUser['id'], - prettyNumber(count($Query_Update_Data)) - ) - ); - } - else - { - $_MsgBox = array - ( - 'color' => 'orange', - 'text' => sprintf - ( - $_Lang['MsgBox_UpdateNotAffected'], - $Result_GetUser['id'], $Result_GetUser['username'], $Result_GetUser['id'] - ) - ); - } - } - else - { - $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_BadInput']); - } - } - else - { - $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_PlanetDoesntExist']); - } - } - else - { - $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_EmptyInput']); - } - } - else - { - $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_BadTabID']); - } - } - else - { - $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_BadCMD']); - } - } - else - { - $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_BadUserID']); - } - } - - $_Lang['Insert_Rows_Technologies'] = ''; - foreach($Items_Technologies as $ItemID) - { - $_Lang['Insert_Rows_Technologies'] .= parsetemplate($TPL_Row, array - ( - 'Name' => "{$_Lang['tech'][$ItemID]} [#{$ItemID}]", - 'TabNo' => 1, - 'ResID' => $ItemID - )); - } - - if(!empty($_MsgBox)) - { - $_Lang['MsgBox_Text'] = $_MsgBox['text']; - $_Lang['MsgBox_Color'] = $_MsgBox['color']; - } - else - { - $_Lang['MsgBox_Text'] = ' '; - } - - display(parsetemplate($TPL_Body, $_Lang), $_Lang['PageTitle'], false, true); - -?> \ No newline at end of file + &$Items_Technologies, +); + +if(isset($_POST['sent']) && $_POST['sent'] == 1) +{ + $UserID = round($_POST['userID']); + $TabID = intval($_POST['tab']); + $ThisCMD = (isset($_POST['cmd']) ? $_POST['cmd'] : null); + + $_Lang['Insert_PreviousUserID'] = $UserID; + $_Lang['Insert_SelectCMD_'.$ThisCMD] = 'checked'; + $_Lang['Insert_DefaultTab'] = $TabID - 1; + + if($UserID > 0) + { + if(in_array($ThisCMD, $Allowed_CMD)) + { + if(in_array($TabID, array_keys($Allowed_Tabs))) + { + if(!empty($_POST['res'][$TabID])) + { + $Query_GetUser = ''; + $Query_GetUser .= "SELECT `id`, `username` "; + $Query_GetUser .= "FROM {{table}} WHERE `id` = {$UserID} LIMIT 1; -- admin/user_techmanager.php - Query #1"; + $Result_GetUser = doquery($Query_GetUser, 'users', true); + if($Result_GetUser['id'] == $UserID) + { + foreach($_POST['res'][$TabID] as $ThisID => $ThisValue) + { + if(in_array($ThisID, $Allowed_Tabs[$TabID])) + { + if($ThisCMD == 'set' AND empty($ThisValue)) + { + continue; + } + $ThisValue = round(str_replace('.', '', $ThisValue)); + if(($ThisCMD == 'set' AND $ThisValue >= 0) OR ($ThisCMD != 'set' AND $ThisValue > 0)) + { + if($ThisValue > $_ResLimit) + { + $ThisValue = $_ResLimit; + } + $Query_Update_Data[$ThisID] = $ThisValue; + } + } + } + + if(!empty($Query_Update_Data)) + { + if($ThisCMD == 'add') + { + $Query_Update = ''; + $Query_Update .= "UPDATE {{table}} SET "; + foreach($Query_Update_Data as $ThisID => $ThisValue) + { + $Query_Update_Array[] = "`{$_Vars_GameElements[$ThisID]}` = `{$_Vars_GameElements[$ThisID]}` + {$ThisValue}"; + } + $Query_Update .= implode(',', $Query_Update_Array); + $Query_Update .= " WHERE `id` = {$UserID} LIMIT 1;"; + } + else if($ThisCMD == 'set') + { + $Query_Update = ''; + $Query_Update .= "UPDATE {{table}} SET "; + foreach($Query_Update_Data as $ThisID => $ThisValue) + { + $Query_Update_Array[] = "`{$_Vars_GameElements[$ThisID]}` = {$ThisValue}"; + } + $Query_Update .= implode(',', $Query_Update_Array); + $Query_Update .= " WHERE `id` = {$UserID} LIMIT 1;"; + } + else if($ThisCMD == 'sub') + { + foreach($Query_Update_Data as $ThisID => $ThisValue) + { + $Query_Update_Fields[] = "`{$_Vars_GameElements[$ThisID]}`"; + $Query_Update_Values[] = $ThisValue; + $Query_Update_Set[] = "`{$_Vars_GameElements[$ThisID]}` = IF(VALUES(`{$_Vars_GameElements[$ThisID]}`) > `{$_Vars_GameElements[$ThisID]}`, 0, `{$_Vars_GameElements[$ThisID]}` - VALUES(`{$_Vars_GameElements[$ThisID]}`))"; + } + $Query_Update = ''; + $Query_Update .= "INSERT INTO {{table}} (`id`, ".implode(', ', $Query_Update_Fields).") "; + $Query_Update .= "VALUES ({$UserID}, ".implode(', ', $Query_Update_Values).") "; + $Query_Update .= "ON DUPLICATE KEY UPDATE "; + $Query_Update .= implode(',', $Query_Update_Set); + } + doquery($Query_Update, 'users'); + if(mysql_affected_rows() > 0) + { + $_MsgBox = array + ( + 'color' => 'lime', + 'text' => sprintf + ( + $_Lang['MsgBox_UpdateOK'], + $Result_GetUser['id'], $Result_GetUser['username'], $Result_GetUser['id'], + prettyNumber(count($Query_Update_Data)) + ) + ); + } + else + { + $_MsgBox = array + ( + 'color' => 'orange', + 'text' => sprintf + ( + $_Lang['MsgBox_UpdateNotAffected'], + $Result_GetUser['id'], $Result_GetUser['username'], $Result_GetUser['id'] + ) + ); + } + } + else + { + $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_BadInput']); + } + } + else + { + $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_PlanetDoesntExist']); + } + } + else + { + $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_EmptyInput']); + } + } + else + { + $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_BadTabID']); + } + } + else + { + $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_BadCMD']); + } + } + else + { + $_MsgBox = array('color' => 'red', 'text' => $_Lang['MsgBox_BadUserID']); + } +} + +$_Lang['Insert_Rows_Technologies'] = ''; +foreach($Items_Technologies as $ItemID) +{ + $_Lang['Insert_Rows_Technologies'] .= parsetemplate($TPL_Row, array + ( + 'Name' => "{$_Lang['tech'][$ItemID]} [#{$ItemID}]", + 'TabNo' => 1, + 'ResID' => $ItemID + )); +} + +if(!empty($_MsgBox)) +{ + $_Lang['MsgBox_Text'] = $_MsgBox['text']; + $_Lang['MsgBox_Color'] = $_MsgBox['color']; +} +else +{ + $_Lang['MsgBox_Text'] = ' '; +} + +display(parsetemplate($TPL_Body, $_Lang), $_Lang['PageTitle'], false, true); + +?> diff --git a/ainfo.php b/ainfo.php index 843fd5328..a9d94a680 100644 --- a/ainfo.php +++ b/ainfo.php @@ -1,10 +1,10 @@ - \ No newline at end of file + diff --git a/ajax/chat.add.php b/ajax/chat.add.php index 04832b6bb..13a0494c7 100644 --- a/ajax/chat.add.php +++ b/ajax/chat.add.php @@ -1,70 +1,71 @@ - 0) - { - safeDie('1'); // Inserted - } - else - { - safeDie('2'); // Not inserted - } -?> \ No newline at end of file + 0) +{ + safeDie('1'); // Inserted +} +else +{ + safeDie('2'); // Not inserted +} + +?> diff --git a/ajax/chat.del.php b/ajax/chat.del.php index 1743affba..671cbc84d 100644 --- a/ajax/chat.del.php +++ b/ajax/chat.del.php @@ -1,58 +1,58 @@ - 0) - { - $Result = doquery("DELETE FROM {{table}} WHERE `ID` = {$GivenID} LIMIT 1;", 'chat_messages'); - if($Result !== false) - { - if(mysql_affected_rows() == 1) - { - echo '1'; - } - else - { - echo '2'; - } - } - else - { - echo '3'; - } - } - else - { - echo '2'; - } - } - else - { - echo '4'; - } - } - else - { - echo '5'; - } - safeDie(); - -?> \ No newline at end of file + 0) + { + $Result = doquery("DELETE FROM {{table}} WHERE `ID` = {$GivenID} LIMIT 1;", 'chat_messages'); + if($Result !== false) + { + if(mysql_affected_rows() == 1) + { + echo '1'; + } + else + { + echo '2'; + } + } + else + { + echo '3'; + } + } + else + { + echo '2'; + } + } + else + { + echo '4'; + } +} +else +{ + echo '5'; +} +safeDie(); + +?> diff --git a/ajax/chat.msg.php b/ajax/chat.msg.php index 568e02c8e..d94ab5db3 100644 --- a/ajax/chat.msg.php +++ b/ajax/chat.msg.php @@ -1,273 +1,273 @@ - '003'))); }; - -$_SetAccessLogPreFilename = 'ajax/'; -$_SetAccessLogPath = '../'; -$_EnginePath = '../'; - -include($_EnginePath.'common.php'); - -$PerPage = 100; -$OnlineCheck = 30; - - loggedCheck(true); - includeLang('chat'); - $Now = time(); - $OnlineCheck = $Now - $OnlineCheck; - - $RoomID = (isset($_GET['rid']) ? intval($_GET['rid']) : 0); - $FirstID = (isset($_GET['fID']) ? round($_GET['fID']) : 0); - $LastID = (isset($_GET['lID']) ? round($_GET['lID']) : 0); - $LastGet = (isset($_GET['lGet']) ? intval($_GET['lGet']) + SERVER_MAINOPEN_TSTAMP : SERVER_MAINOPEN_TSTAMP); - $LastCount = (isset($_GET['lCnt']) ? intval($_GET['lCnt']) : 0); - - $isInit = ($FirstID == 0 && $LastID == 0 ? true : false); - if($RoomID < 0) - { - $RoomID = 0; - } - else - { - include($_EnginePath.'includes/functions/ChatUtilities.php'); - $CheckAccess = Chat_CheckAccess($RoomID, $_User); - if($CheckAccess !== true) - { - if($CheckAccess === null) - { - $ErrorCode = '001'; - } - else - { - $ErrorCode = '002'; - } - safeDie(json_encode(array('Err' => $ErrorCode))); - } - } - if($FirstID < 0) - { - $FirstID = 0; - } - if($LastID < 0) - { - $LastID = 0; - } - if($LastGet < 0) - { - $LastGet = 0; - } - if($LastCount < 0) - { - $LastCount = 0; - } - - $Query_GetMessages = ''; - $Query_GetMessages .= "SELECT `chat`.*, `user`.`username`, `user`.`authlevel` "; - $Query_GetMessages .= "FROM {{table}} AS `chat` "; - $Query_GetMessages .= "LEFT JOIN `{{prefix}}users` AS `user` ON `user`.`id` = `chat`.`UID` "; - $Query_GetMessages .= "WHERE `RID` = {$RoomID} "; - $Query_GetMessages .= "ORDER BY `ID` DESC LIMIT {$PerPage};"; - $Query = doquery($Query_GetMessages, 'chat_messages'); - $MessagesCount = mysql_num_rows($Query); - if($MessagesCount > 0) - { - include($_EnginePath.'includes/functions/BBcodeFunction.php'); - - $ThrowNew = array(); - $Edited = array(); - $Deleted = array(); - $DeletedBetween = array(); - - $msg_i = 0; - $FirstGet = false; - - while($Message = mysql_fetch_assoc($Query)) - { - $isNew = false; - $msg_i += 1; - - if($FirstGet === false) - { - if($isInit !== true && $Message['ID'] < $LastID) - { - $Range = range($LastID, $Message['ID'] + 1, 1); - $Deleted = array_merge($Deleted, $Range); - } - $FirstGet = true; - $msg_lastID = $LastGetID = $Message['ID']; - } - else - { - if($isInit !== true && $msg_lastID - $Message['ID'] > 1) - { - $Range = range($msg_lastID - 1, $Message['ID'] + 1, 1); - $DeletedBetween = array_merge($DeletedBetween, $Range); - } - if($msg_i == $MessagesCount) - { - if($isInit !== true && $Message['ID'] > $FirstID) - { - $Range = range($FirstID, $Message['ID'] - 1, 1); - $Deleted = array_merge($Deleted, $Range); - } - $FirstGetID = $Message['ID']; - } - } - - if($isInit === true || $Message['ID'] < $FirstID) - { - $isNew = true; - $ThrowNew[] = $Message['ID']; - } - else if($isInit === true || $Message['ID'] > $LastID) - { - $isNew = true; - $ThrowNew[] = $Message['ID']; - } - else - { - if($isInit !== true && $Message['TimeStamp_Edit'] > $LastGet && !in_array($Message['ID'], $ThrowNew)) - { - $Edited[] = $Message['ID']; - } - } - - if(!isset($UsersArray[$Message['UID']])) - { - $UsersArray[$Message['UID']] = array('username' => $Message['username'], 'authlevel' => GetAuthLabel($Message), 'isNew' => $isNew); - } - else - { - if($isNew === false) - { - $UsersArray[$Message['UID']]['isNew'] = false; - } - } - - $Message['Text'] = bbcodeChat($Message['Text']); - - $Messages[$Message['ID']] = array('id' => floatval($Message['ID']), 'u' => intval($Message['UID']), 'd' => $Message['TimeStamp_Add'] - SERVER_MAINOPEN_TSTAMP, 't' => $Message['Text']); - - $msg_lastID = $Message['ID']; - } - - if(!empty($ThrowNew)) - { - foreach($ThrowNew as $MID) - { - $Return['newm'][] = $Messages[$MID]; - } - } - if(!empty($Edited)) - { - foreach($Edited as $MID) - { - $Return['edit'][$MID] = array('t' => $Messages[$MID]['t']); - } - } - $ToDelete = array(); - if(!empty($Deleted)) - { - $ToDelete = $Deleted; - } - if(!empty($DeletedBetween)) - { - if(($FirstID != $FirstGetID OR $LastID != $LastGetID) OR $LastCount != $MessagesCount) - { - $ToDelete = array_merge($ToDelete, $DeletedBetween); - } - } - if(!empty($ToDelete)) - { - $Return['del'] = $ToDelete; - } - - foreach($UsersArray as $UserID => $UserData) - { - if($UserData['isNew'] === true) - { - $Return['usr'][$UserID] = array('n' => $UserData['username'], 'c' => GetAuthLabel($UserData)); - } - } - } - else - { - if($isInit === false) - { - $Return['cmd'] = 'delall'; - } - } - - $Query_GetOnline = ''; - $Query_GetOnline .= "SELECT `chat`.`UID`, `user`.`username`, `user`.`authlevel`, `user`.`chat_GhostMode`, `user`.`chat_GhostMode_DontCount` "; - $Query_GetOnline .= "FROM {{table}} AS `chat` "; - $Query_GetOnline .= "LEFT JOIN `{{prefix}}users` AS `user` ON `user`.`id` = `chat`.`UID` "; - $Query_GetOnline .= "WHERE `chat`.`UID` != {$_User['id']} AND `chat`.`RID` = {$RoomID} AND `lastOnline` >= {$OnlineCheck} ORDER BY `authlevel` DESC, `id` ASC;"; - $SelectOnline = doquery($Query_GetOnline, 'chat_online'); - $OnlineNo = mysql_num_rows($SelectOnline); - if($OnlineNo > 0) - { - while($UserOn = mysql_fetch_assoc($SelectOnline)) - { - if(empty($UserOn['username'])) - { - continue; - } - if($UserOn['chat_GhostMode_DontCount'] == 0 OR $UserOn['chat_GhostMode'] == 0 OR CheckAuth('user', AUTHCHECK_HIGHER)) - { - if(!isset($Return['onlCnt'])) - { - $Return['onlCnt'] = 0; - } - $Return['onlCnt'] += 1; - } - if($UserOn['chat_GhostMode'] == 1 AND !CheckAuth('user', AUTHCHECK_HIGHER)) - { - continue; - } - $UserOn['return'][0] = $UserOn['UID']; - $UserOn['return'][1] = $UserOn['username']; - $UserOn['return'][2] = GetAuthLabel($UserOn); - if($UserOn['chat_GhostMode'] == 1) - { - $UserOn['return'][3] = 1; - } - $Temp = array_keys($UserOn['return']); - $UserOn['returnMax'] = array_pop($Temp); - for($i = 0; $i <= $UserOn['returnMax']; $i += 1) - { - if(empty($UserOn['return'][$i])) - { - $UserOn['return'][$i] = '0'; - } - } - $Return['onl'][] = implode('|', $UserOn['return']); - } - } - - $Query_UpdateOnline = ''; - $Query_UpdateOnline .= "INSERT INTO {{table}} VALUES ({$RoomID}, {$_User['id']}, {$Now}) "; - $Query_UpdateOnline .= "ON DUPLICATE KEY UPDATE "; - $Query_UpdateOnline .= "`LastOnline` = VALUES(`LastOnline`);"; - doquery($Query_UpdateOnline, 'chat_online'); - - $SelectMsgs = doquery("SELECT COUNT(`id`) as `Count` FROM {{table}} WHERE `id_owner` = {$_User['id']} AND `deleted` = false AND `read` = false;", 'messages', true); - $Msg_Count = floatval($SelectMsgs['Count']); - if($Msg_Count > 0) - { - $Return['lmMC'] = $Msg_Count; - } - - if(!empty($Return)) - { - echo json_encode($Return); - } - safeDie(); - -?> \ No newline at end of file + '003'))); }; + +$_SetAccessLogPreFilename = 'ajax/'; +$_SetAccessLogPath = '../'; +$_EnginePath = '../'; + +include($_EnginePath.'common.php'); + +$PerPage = 100; +$OnlineCheck = 30; + +loggedCheck(true); +includeLang('chat'); +$Now = time(); +$OnlineCheck = $Now - $OnlineCheck; + +$RoomID = (isset($_GET['rid']) ? intval($_GET['rid']) : 0); +$FirstID = (isset($_GET['fID']) ? round($_GET['fID']) : 0); +$LastID = (isset($_GET['lID']) ? round($_GET['lID']) : 0); +$LastGet = (isset($_GET['lGet']) ? intval($_GET['lGet']) + SERVER_MAINOPEN_TSTAMP : SERVER_MAINOPEN_TSTAMP); +$LastCount = (isset($_GET['lCnt']) ? intval($_GET['lCnt']) : 0); + +$isInit = ($FirstID == 0 && $LastID == 0 ? true : false); +if($RoomID < 0) +{ + $RoomID = 0; +} +else +{ + include($_EnginePath.'includes/functions/ChatUtilities.php'); + $CheckAccess = Chat_CheckAccess($RoomID, $_User); + if($CheckAccess !== true) + { + if($CheckAccess === null) + { + $ErrorCode = '001'; + } + else + { + $ErrorCode = '002'; + } + safeDie(json_encode(array('Err' => $ErrorCode))); + } +} +if($FirstID < 0) +{ + $FirstID = 0; +} +if($LastID < 0) +{ + $LastID = 0; +} +if($LastGet < 0) +{ + $LastGet = 0; +} +if($LastCount < 0) +{ + $LastCount = 0; +} + +$Query_GetMessages = ''; +$Query_GetMessages .= "SELECT `chat`.*, `user`.`username`, `user`.`authlevel` "; +$Query_GetMessages .= "FROM {{table}} AS `chat` "; +$Query_GetMessages .= "LEFT JOIN `{{prefix}}users` AS `user` ON `user`.`id` = `chat`.`UID` "; +$Query_GetMessages .= "WHERE `RID` = {$RoomID} "; +$Query_GetMessages .= "ORDER BY `ID` DESC LIMIT {$PerPage};"; +$Query = doquery($Query_GetMessages, 'chat_messages'); +$MessagesCount = mysql_num_rows($Query); +if($MessagesCount > 0) +{ + include($_EnginePath.'includes/functions/BBcodeFunction.php'); + + $ThrowNew = array(); + $Edited = array(); + $Deleted = array(); + $DeletedBetween = array(); + + $msg_i = 0; + $FirstGet = false; + + while($Message = mysql_fetch_assoc($Query)) + { + $isNew = false; + $msg_i += 1; + + if($FirstGet === false) + { + if($isInit !== true && $Message['ID'] < $LastID) + { + $Range = range($LastID, $Message['ID'] + 1, 1); + $Deleted = array_merge($Deleted, $Range); + } + $FirstGet = true; + $msg_lastID = $LastGetID = $Message['ID']; + } + else + { + if($isInit !== true && $msg_lastID - $Message['ID'] > 1) + { + $Range = range($msg_lastID - 1, $Message['ID'] + 1, 1); + $DeletedBetween = array_merge($DeletedBetween, $Range); + } + if($msg_i == $MessagesCount) + { + if($isInit !== true && $Message['ID'] > $FirstID) + { + $Range = range($FirstID, $Message['ID'] - 1, 1); + $Deleted = array_merge($Deleted, $Range); + } + $FirstGetID = $Message['ID']; + } + } + + if($isInit === true || $Message['ID'] < $FirstID) + { + $isNew = true; + $ThrowNew[] = $Message['ID']; + } + else if($isInit === true || $Message['ID'] > $LastID) + { + $isNew = true; + $ThrowNew[] = $Message['ID']; + } + else + { + if($isInit !== true && $Message['TimeStamp_Edit'] > $LastGet && !in_array($Message['ID'], $ThrowNew)) + { + $Edited[] = $Message['ID']; + } + } + + if(!isset($UsersArray[$Message['UID']])) + { + $UsersArray[$Message['UID']] = array('username' => $Message['username'], 'authlevel' => GetAuthLabel($Message), 'isNew' => $isNew); + } + else + { + if($isNew === false) + { + $UsersArray[$Message['UID']]['isNew'] = false; + } + } + + $Message['Text'] = bbcodeChat($Message['Text']); + + $Messages[$Message['ID']] = array('id' => floatval($Message['ID']), 'u' => intval($Message['UID']), 'd' => $Message['TimeStamp_Add'] - SERVER_MAINOPEN_TSTAMP, 't' => $Message['Text']); + + $msg_lastID = $Message['ID']; + } + + if(!empty($ThrowNew)) + { + foreach($ThrowNew as $MID) + { + $Return['newm'][] = $Messages[$MID]; + } + } + if(!empty($Edited)) + { + foreach($Edited as $MID) + { + $Return['edit'][$MID] = array('t' => $Messages[$MID]['t']); + } + } + $ToDelete = array(); + if(!empty($Deleted)) + { + $ToDelete = $Deleted; + } + if(!empty($DeletedBetween)) + { + if(($FirstID != $FirstGetID OR $LastID != $LastGetID) OR $LastCount != $MessagesCount) + { + $ToDelete = array_merge($ToDelete, $DeletedBetween); + } + } + if(!empty($ToDelete)) + { + $Return['del'] = $ToDelete; + } + + foreach($UsersArray as $UserID => $UserData) + { + if($UserData['isNew'] === true) + { + $Return['usr'][$UserID] = array('n' => $UserData['username'], 'c' => GetAuthLabel($UserData)); + } + } +} +else +{ + if($isInit === false) + { + $Return['cmd'] = 'delall'; + } +} + +$Query_GetOnline = ''; +$Query_GetOnline .= "SELECT `chat`.`UID`, `user`.`username`, `user`.`authlevel`, `user`.`chat_GhostMode`, `user`.`chat_GhostMode_DontCount` "; +$Query_GetOnline .= "FROM {{table}} AS `chat` "; +$Query_GetOnline .= "LEFT JOIN `{{prefix}}users` AS `user` ON `user`.`id` = `chat`.`UID` "; +$Query_GetOnline .= "WHERE `chat`.`UID` != {$_User['id']} AND `chat`.`RID` = {$RoomID} AND `lastOnline` >= {$OnlineCheck} ORDER BY `authlevel` DESC, `id` ASC;"; +$SelectOnline = doquery($Query_GetOnline, 'chat_online'); +$OnlineNo = mysql_num_rows($SelectOnline); +if($OnlineNo > 0) +{ + while($UserOn = mysql_fetch_assoc($SelectOnline)) + { + if(empty($UserOn['username'])) + { + continue; + } + if($UserOn['chat_GhostMode_DontCount'] == 0 OR $UserOn['chat_GhostMode'] == 0 OR CheckAuth('user', AUTHCHECK_HIGHER)) + { + if(!isset($Return['onlCnt'])) + { + $Return['onlCnt'] = 0; + } + $Return['onlCnt'] += 1; + } + if($UserOn['chat_GhostMode'] == 1 AND !CheckAuth('user', AUTHCHECK_HIGHER)) + { + continue; + } + $UserOn['return'][0] = $UserOn['UID']; + $UserOn['return'][1] = $UserOn['username']; + $UserOn['return'][2] = GetAuthLabel($UserOn); + if($UserOn['chat_GhostMode'] == 1) + { + $UserOn['return'][3] = 1; + } + $Temp = array_keys($UserOn['return']); + $UserOn['returnMax'] = array_pop($Temp); + for($i = 0; $i <= $UserOn['returnMax']; $i += 1) + { + if(empty($UserOn['return'][$i])) + { + $UserOn['return'][$i] = '0'; + } + } + $Return['onl'][] = implode('|', $UserOn['return']); + } +} + +$Query_UpdateOnline = ''; +$Query_UpdateOnline .= "INSERT INTO {{table}} VALUES ({$RoomID}, {$_User['id']}, {$Now}) "; +$Query_UpdateOnline .= "ON DUPLICATE KEY UPDATE "; +$Query_UpdateOnline .= "`LastOnline` = VALUES(`LastOnline`);"; +doquery($Query_UpdateOnline, 'chat_online'); + +$SelectMsgs = doquery("SELECT COUNT(`id`) as `Count` FROM {{table}} WHERE `id_owner` = {$_User['id']} AND `deleted` = false AND `read` = false;", 'messages', true); +$Msg_Count = floatval($SelectMsgs['Count']); +if($Msg_Count > 0) +{ + $Return['lmMC'] = $Msg_Count; +} + +if(!empty($Return)) +{ + echo json_encode($Return); +} +safeDie(); + +?> diff --git a/ajax/chat.settings.php b/ajax/chat.settings.php index f997123c0..e0a26ea14 100644 --- a/ajax/chat.settings.php +++ b/ajax/chat.settings.php @@ -1,68 +1,68 @@ - 'GhostMode', '2' => 'GhostMode_DontCount'); - $ValSettings = array('1' => 'checkbox', '2' => 'checkbox'); - foreach($_POST as $Key => $Val) - { - if(strstr($Key, 'setChg_')) - { - $Key = str_replace('setChg_', '', $Key); - if(in_array($Key, $Allowed)) - { - $ToChange[$Key] = $Val; - } - } - } - if(!empty($ToChange)) - { - $UpdateQuery = ''; - $UpdateQuery .= "UPDATE {{table}} SET "; - foreach($ToChange as $Key => $Val) - { - if($ValSettings[$Key] == 'checkbox') - { - if($Val == 'true') - { - $Val = '1'; - } - else - { - $Val = '0'; - } - } - $UpdateQueryArray[] = "`chat_{$KeyEquivalents[$Key]}` = '{$Val}'"; - } - $UpdateQuery .= implode(', ', $UpdateQueryArray); - $UpdateQuery .= " WHERE `id` = {$_User['id']} LIMIT 1;"; - doquery($UpdateQuery, 'users'); - safeDie('1'); - } - safeDie('2'); - } - safeDie('4'); - -?> \ No newline at end of file + 'GhostMode', '2' => 'GhostMode_DontCount'); + $ValSettings = array('1' => 'checkbox', '2' => 'checkbox'); + foreach($_POST as $Key => $Val) + { + if(strstr($Key, 'setChg_')) + { + $Key = str_replace('setChg_', '', $Key); + if(in_array($Key, $Allowed)) + { + $ToChange[$Key] = $Val; + } + } + } + if(!empty($ToChange)) + { + $UpdateQuery = ''; + $UpdateQuery .= "UPDATE {{table}} SET "; + foreach($ToChange as $Key => $Val) + { + if($ValSettings[$Key] == 'checkbox') + { + if($Val == 'true') + { + $Val = '1'; + } + else + { + $Val = '0'; + } + } + $UpdateQueryArray[] = "`chat_{$KeyEquivalents[$Key]}` = '{$Val}'"; + } + $UpdateQuery .= implode(', ', $UpdateQueryArray); + $UpdateQuery .= " WHERE `id` = {$_User['id']} LIMIT 1;"; + doquery($UpdateQuery, 'users'); + safeDie('1'); + } + safeDie('2'); +} +safeDie('4'); + +?> diff --git a/ajax/checkSkin.php b/ajax/checkSkin.php index 8bda52c4e..ded30a094 100644 --- a/ajax/checkSkin.php +++ b/ajax/checkSkin.php @@ -1,68 +1,68 @@ - \ No newline at end of file + diff --git a/ajax/galaxy.php b/ajax/galaxy.php index 6efffe7d8..7b492cfbe 100644 --- a/ajax/galaxy.php +++ b/ajax/galaxy.php @@ -1,84 +1,84 @@ - '601')); - } - - include($_EnginePath.'includes/functions/ShowGalaxyRows.php'); - include($_EnginePath.'includes/functions/GalaxyRowPos.php'); - include($_EnginePath.'includes/functions/GalaxyRowPlanet.php'); - include($_EnginePath.'includes/functions/GalaxyRowPlanetName.php'); - include($_EnginePath.'includes/functions/GalaxyRowMoon.php'); - include($_EnginePath.'includes/functions/GalaxyRowDebris.php'); - include($_EnginePath.'includes/functions/GalaxyRowUser.php'); - include($_EnginePath.'includes/functions/GalaxyRowAlly.php'); - include($_EnginePath.'includes/functions/GalaxyRowActions.php'); - include($_EnginePath.'includes/functions/GetMissileRange.php'); - include($_EnginePath.'includes/functions/GetPhalanxRange.php'); - - includeLang('galaxy'); - $Time = time(); - $planetcount = 0; - - $_Planet = doquery("SELECT * FROM {{table}} WHERE `id` = {$_User['current_planet']};", 'planets', true); - if($_Planet['id'] <= 0) - { - SetSelectedPlanet($_User, $_User['id_planet']); - $_Planet = doquery("SELECT * FROM {{table}} WHERE `id` = {$_User['id_planet']};", 'planets', true); - if($_Planet['id'] <= 0) - { - ajaxReturn(array('Err' => '697')); - } - } - - $SelectMsgs = doquery("SELECT COUNT(`id`) as `Count` FROM {{table}} WHERE `id_owner` = {$_User['id']} AND `deleted` = false AND `read` = false;", 'messages', true); - - $GetFlyingFleetsCount = doquery("SELECT COUNT(*) AS `Count` FROM {{table}} WHERE `fleet_owner` = {$_User['id']};", 'fleets', true); - - $CurrentMIP = $_Planet['interplanetary_missile']; - $CurrentRC = $_Planet['recycler']; - $CurrentSP = $_Planet['espionage_probe']; - $CurrentCS = $_Planet['colony_ship']; - $SensonPhalanxLevel = $_Planet['sensor_phalanx']; - $CurrentSystem = $_Planet['system']; - $CurrentGalaxy = $_Planet['galaxy']; - $CanDestroy = ($_Planet[$_Vars_GameElements[214]] > 0 ? true : false); - - $Galaxy = intval($_GET['galaxy']); - $System = intval($_GET['system']); - if(!($Galaxy > 0 AND $Galaxy <= MAX_GALAXY_IN_WORLD)) - { - $Galaxy = 1; - } - if(!($System > 0 AND $System <= MAX_SYSTEM_IN_GALAXY)) - { - $System = 1; - } - - $Response = ShowGalaxyRows($Galaxy, $System); - - $planetcount = intval($planetcount); - $Msg_Count = floatval($SelectMsgs['Count']); - $FlyingFleets_Count = intval($GetFlyingFleetsCount['Count']); - - ajaxReturn(array('PC' => $planetcount, 'G' => $Galaxy, 'S' => $System, 'msg' => $Msg_Count, 'fly' => $FlyingFleets_Count, 'Data' => $Response)); - -?> \ No newline at end of file + '601')); +} + +include($_EnginePath.'includes/functions/ShowGalaxyRows.php'); +include($_EnginePath.'includes/functions/GalaxyRowPos.php'); +include($_EnginePath.'includes/functions/GalaxyRowPlanet.php'); +include($_EnginePath.'includes/functions/GalaxyRowPlanetName.php'); +include($_EnginePath.'includes/functions/GalaxyRowMoon.php'); +include($_EnginePath.'includes/functions/GalaxyRowDebris.php'); +include($_EnginePath.'includes/functions/GalaxyRowUser.php'); +include($_EnginePath.'includes/functions/GalaxyRowAlly.php'); +include($_EnginePath.'includes/functions/GalaxyRowActions.php'); +include($_EnginePath.'includes/functions/GetMissileRange.php'); +include($_EnginePath.'includes/functions/GetPhalanxRange.php'); + +includeLang('galaxy'); +$Time = time(); +$planetcount = 0; + +$_Planet = doquery("SELECT * FROM {{table}} WHERE `id` = {$_User['current_planet']};", 'planets', true); +if($_Planet['id'] <= 0) +{ + SetSelectedPlanet($_User, $_User['id_planet']); + $_Planet = doquery("SELECT * FROM {{table}} WHERE `id` = {$_User['id_planet']};", 'planets', true); + if($_Planet['id'] <= 0) + { + ajaxReturn(array('Err' => '697')); + } +} + +$SelectMsgs = doquery("SELECT COUNT(`id`) as `Count` FROM {{table}} WHERE `id_owner` = {$_User['id']} AND `deleted` = false AND `read` = false;", 'messages', true); + +$GetFlyingFleetsCount = doquery("SELECT COUNT(*) AS `Count` FROM {{table}} WHERE `fleet_owner` = {$_User['id']};", 'fleets', true); + +$CurrentMIP = $_Planet['interplanetary_missile']; +$CurrentRC = $_Planet['recycler']; +$CurrentSP = $_Planet['espionage_probe']; +$CurrentCS = $_Planet['colony_ship']; +$SensonPhalanxLevel = $_Planet['sensor_phalanx']; +$CurrentSystem = $_Planet['system']; +$CurrentGalaxy = $_Planet['galaxy']; +$CanDestroy = ($_Planet[$_Vars_GameElements[214]] > 0 ? true : false); + +$Galaxy = intval($_GET['galaxy']); +$System = intval($_GET['system']); +if(!($Galaxy > 0 AND $Galaxy <= MAX_GALAXY_IN_WORLD)) +{ + $Galaxy = 1; +} +if(!($System > 0 AND $System <= MAX_SYSTEM_IN_GALAXY)) +{ + $System = 1; +} + +$Response = ShowGalaxyRows($Galaxy, $System); + +$planetcount = intval($planetcount); +$Msg_Count = floatval($SelectMsgs['Count']); +$FlyingFleets_Count = intval($GetFlyingFleetsCount['Count']); + +ajaxReturn(array('PC' => $planetcount, 'G' => $Galaxy, 'S' => $System, 'msg' => $Msg_Count, 'fly' => $FlyingFleets_Count, 'Data' => $Response)); + +?> diff --git a/ajax/galaxyfleet.php b/ajax/galaxyfleet.php index 96ecda823..720fc1fc6 100644 --- a/ajax/galaxyfleet.php +++ b/ajax/galaxyfleet.php @@ -1,640 +1,640 @@ - 0 AND $System > 0 AND $Planet > 0 AND $Galaxy <= MAX_GALAXY_IN_WORLD AND $System <= MAX_SYSTEM_IN_GALAXY AND $Planet <= MAX_PLANET_IN_SYSTEM)) - { - CreateReturn('603'); - } - if(!($Type == 1 OR $Type == 2 OR $Type == 3)) - { - CreateReturn('604'); - } - - $CurrentPlanet = &$_Planet; - $FlyingFleets = doquery("SELECT COUNT(`fleet_id`) as `Number` FROM {{table}} WHERE `fleet_owner` = '{$_User['id']}';", 'fleets', true); - - $Recyclers = $CurrentPlanet['recycler']; - $Spy_Probes = $CurrentPlanet['espionage_probe']; - $Colonizers = $CurrentPlanet['colony_ship']; - $ActualFleets = $FlyingFleets['Number']; - - if(MORALE_ENABLED) - { - Morale_ReCalculate($_User, $Time); - } - - if(($_User[$_Vars_GameElements[108]] + 1 + (($_User['admiral_time'] > 0) ? 2 : 0)) <= $ActualFleets) - { - $Update = '1'; - CreateReturn('609'); - } - - switch($Mission) - { - case 6: - { - //Spy - if(!($Type == 1 OR $Type == 3)) - { - CreateReturn('613'); - } - - $ShipID = 210; - $ShipCount = $_User['settings_spyprobescount']; - - if($Type == 1) - { - $Query_GetTarget_Galaxy = 'id_planet'; - } - else - { - $Query_GetTarget_Galaxy = 'id_moon'; - } - $Query_GetTarget = ''; - $Query_GetTarget .= "SELECT `pl`.`id`, `pl`.`id_owner`, `galaxy`.`galaxy_id` FROM {{table}} AS `pl` "; - $Query_GetTarget .= "LEFT JOIN `{{prefix}}galaxy` AS `galaxy` ON `pl`.`id` = `galaxy`.`{$Query_GetTarget_Galaxy}` "; - $Query_GetTarget .= "WHERE `pl`.`galaxy` = {$Galaxy} AND `pl`.`system` = {$System} AND `pl`.`planet` = {$Planet} AND `pl`.`planet_type` = {$Type} "; - $Query_GetTarget .= "LIMIT 1; -- GalaxyFleet|GetTarget"; - $TargetPlanet = doquery($Query_GetTarget, 'planets', true); - - $GalaxyRow['galaxy_id'] = $TargetPlanet['galaxy_id']; - $TargetUser = $TargetPlanet['id_owner']; - $TargetID = $TargetPlanet['id']; - $TargetPlanetType = $Type; - - if($TargetID <= 0) - { - CreateReturn('614'); - } - if($TargetUser == $_User['id']) - { - CreateReturn('615'); - } - - $protection = $_GameConfig['noobprotection']; - $protectiontime = $_GameConfig['noobprotectiontime']; - $protectionmulti = $_GameConfig['noobprotectionmulti']; - $adminprotection = $_GameConfig['adminprotection']; - $allyprotection = $_GameConfig['allyprotection']; - $noNoobProtect = $_GameConfig['no_noob_protect']; - $noIdleProtect = $_GameConfig['no_idle_protect']; - $Protections['idleTime'] = $_GameConfig['no_idle_protect'] * TIME_DAY; - - if($TargetUser > 0) - { - $Query_GetUser = ''; - $Query_GetUser .= "SELECT `usr`.`ally_id`, `usr`.`is_onvacation`, `usr`.`is_banned`, `usr`.`onlinetime`, `usr`.`authlevel`, `usr`.`first_login`, `usr`.`NoobProtection_EndTime`, "; - $Query_GetUser .= "`stat`.`total_points`, `stat`.`total_rank` "; - $Query_GetUser .= "FROM {{table}} as `usr` "; - $Query_GetUser .= "LEFT JOIN `{{prefix}}statpoints` AS `stat` ON `stat`.`stat_type` = 1 AND `stat`.`id_owner` = `usr`.`id` "; - $Query_GetUser .= "WHERE `id` = {$TargetUser} LIMIT 1;"; - $HeDBRec = doquery($Query_GetUser, 'users', true); - - $SaveMyTotalRank = false; - if(!CheckAuth('programmer')) - { - $MyGameLevel = $_User['total_points']; - } - else - { - $MyGameLevel = $HeDBRec['total_points']; - if($_User['total_rank'] <= 0) - { - $SaveMyTotalRank = $_User['total_rank']; - $_User['total_rank'] = $HeDBRec['total_rank']; - } - } - $HeGameLevel = $HeDBRec['total_points']; - - if($allyprotection == 1 AND $_User['ally_id'] > 0 AND $_User['ally_id'] == $HeDBRec['ally_id']) - { - CreateReturn('616'); - } - if((CheckAuth('supportadmin') OR CheckAuth('supportadmin', AUTHCHECK_NORMAL, $HeDBRec)) AND $adminprotection == 1) - { - if(CheckAuth('supportadmin')) - { - CreateReturn('623'); - } - else - { - CreateReturn('625'); - } - } - if(isOnVacation($HeDBRec)) - { - if($HeDBRec['is_banned'] == 1) - { - CreateReturn('617'); - } - else - { - CreateReturn('618'); - } - } - - if($protection == 1) - { - if($_User['total_rank'] < 1) - { - CreateReturn('631'); - } - if($HeDBRec['total_rank'] < 1) - { - CreateReturn('630'); - } - - if($_User['NoobProtection_EndTime'] > $Time) - { - CreateReturn('632'); // You are under Newcommer protection - } - else if($HeDBRec['first_login'] == 0) - { - CreateReturn('634'); // Newcommer protection (never logged in) - } - else if($HeDBRec['NoobProtection_EndTime'] > $Time) - { - CreateReturn('633'); // Newcommer protection - } - - if($HeDBRec['onlinetime'] >= ($Time - (TIME_DAY * $noIdleProtect))) - { - if($HeGameLevel < ($protectiontime * 1000)) - { - CreateReturn('619'); //Player under n00b protection time - } - else if($MyGameLevel < ($protectiontime * 1000)) - { - CreateReturn('620'); //You are under n00b protection time - } - else - { - if($MyGameLevel < ($noNoobProtect * 1000) OR $HeGameLevel < ($noNoobProtect * 1000)) - { - if(($MyGameLevel > ($HeGameLevel * $protectionmulti))) - { - CreateReturn('621'); //Player is too weak - } - else if(($MyGameLevel * $protectionmulti) < $HeGameLevel) - { - CreateReturn('622'); //Player is too strony - } - } - } - } - } - if($SaveMyTotalRank !== false) - { - $_User['total_rank'] = $SaveMyTotalRank; - } - } - break; - } - case 8: - { - //Recycling - $ShipID = 209; - if($Type != 2) - { - CreateReturn('612'); - } - - $GalaxyRow = doquery("SELECT `galaxy_id`, `metal`,`crystal` FROM {{table}} WHERE `galaxy` = {$Galaxy} AND `system` = {$System} AND `planet` = {$Planet} LIMIT 1;", 'galaxy', true); - if(!($GalaxyRow['metal'] > 0 OR $GalaxyRow['crystal'] > 0)) - { - CreateReturn('611'); - } - $ShipCount = ceil(($GalaxyRow['metal'] + $GalaxyRow['crystal']) / $_Vars_Prices[$ShipID]['capacity']); - break; - } - case 7: - { - //Colonization - $ShipID = 208; - if($Type != 1) - { - CreateReturn('612'); - } - - $PlanetCheck = doquery("SELECT `id` FROM {{table}} WHERE `galaxy` = {$Galaxy} AND `system` = {$System} AND `planet` = {$Planet} AND `planet_type` = 1 LIMIT 1;", 'planets', true); - if($PlanetCheck['id'] > 0) - { - CreateReturn('624'); - } - $ShipCount = 1; - break; - } - } - - // Fleet Blockade System - $BlockFleet = false; - $SFBSelectWhere[] = "(`Type` = 1 AND (`EndTime` > UNIX_TIMESTAMP() OR `PostEndTime` > UNIX_TIMESTAMP()))"; - if($Mission == 6) - { - if($TargetUser > 0) - { - $SFBSelectWhere[] = "(`Type` = 2 AND `ElementID` = {$TargetUser} AND `EndTime` > UNIX_TIMESTAMP())"; - } - $SFBSelectWhere[] = "(`Type` = 3 AND `ElementID` = {$TargetID} AND `EndTime` > UNIX_TIMESTAMP())"; - } - $SFBSelectWhere[] = "(`Type` = 2 AND `ElementID` = {$_User['id']} AND `EndTime` > UNIX_TIMESTAMP())"; - $SFBSelectWhere[] = "(`Type` = 3 AND `ElementID` = {$CurrentPlanet['id']} AND `EndTime` > UNIX_TIMESTAMP())"; - - $SFBSelect = ''; - $SFBSelect .= "SELECT `Type`, `BlockMissions`, `Reason`, `StartTime`, `EndTime`, `PostEndTime`, `ElementID`, `DontBlockIfIdle` FROM {{table}} WHERE `StartTime` <= UNIX_TIMESTAMP() AND "; - $SFBSelect .= implode(' OR ', $SFBSelectWhere); - $SFBSelect .= " ORDER BY `Type` ASC, `EndTime` DESC;"; - $LoadSFBData = doquery($SFBSelect, 'smart_fleet_blockade'); - - if(mysql_num_rows($LoadSFBData) > 0) - { - while($GetSFBData = mysql_fetch_assoc($LoadSFBData)) - { - $BlockedMissions = false; - if($GetSFBData['BlockMissions'] == '0') - { - $BlockedMissions = true; - $AllMissionsBlocked = true; - } - else - { - $BlockedMissions = explode(',', $GetSFBData['BlockMissions']); - } - - if($BlockedMissions === true OR in_array($Mission, $BlockedMissions)) - { - if($GetSFBData['Type'] == 1) - { - // Global Blockade - if($GetSFBData['EndTime'] > $Time) - { - // Normal Blockade - if(!($GetSFBData['DontBlockIfIdle'] == 1 AND in_array($Mission, $_Vars_FleetMissions['military']) AND $TargetUser > 0 AND $HeDBRec['onlinetime'] <= ($Time - $Protections['idleTime']))) - { - CreateReturn('628'); - } - } - else if($GetSFBData['PostEndTime'] > $Time) - { - // Post Blockade - if(in_array($Mission, $_Vars_FleetMissions['military']) AND $TargetUser > 0 AND - ( - ($AllMissionsBlocked !== true AND $HeDBRec['onlinetime'] > ($Time - $Protections['idleTime']) AND $HeDBRec['onlinetime'] < $GetSFBData['StartTime']) - OR - ($AllMissionsBlocked === true AND $HeDBRec['onlinetime'] > ($Time - $Protections['idleTime']) AND $HeDBRec['onlinetime'] < $GetSFBData['EndTime']) - )) - { - CreateReturn('635'); - } - } - } - else if($GetSFBData['Type'] == 2) - { - // Per User Blockade - if($GetSFBData['ElementID'] == $_User['id']) - { - CreateReturn('636'); - } - else - { - CreateReturn('637'); - } - } - else if($GetSFBData['Type'] == 3) - { - // Per Planet Blockade - if($GetSFBData['ElementID'] == $CurrentPlanet['id']) - { - // SFB per Planet (your) is Active - if($CurrentPlanet['planet_type'] == 1) - { - CreateReturn('638'); - } - else - { - CreateReturn('639'); - } - } - else - { - // SFB per Planet (target) is Active - if($TargetPlanetType == 1) - { - CreateReturn('640'); - } - else - { - CreateReturn('641'); - } - } - } - } - } - } - - if($ShipCount < 0) - { - CreateReturn('605'); - } - if($ShipCount == 0) - { - $Update = 1; - CreateReturn('610'); - } - if($CurrentPlanet[$_Vars_GameElements[$ShipID]] <= 0) - { - //No ships - switch($Mission) - { - case 6: - { - //Spy - $Return = '606_1'; - break; - } - case 8: - { - //Recycling - $Return = '606_2'; - break; - } - case 7: - { - //Colonization - $Return = '606_3'; - break; - } - } - $Update = '1'; - CreateReturn($Return); - } - - if($CurrentPlanet[$_Vars_GameElements[$ShipID]] < $ShipCount) - { - $ShipCount = $CurrentPlanet[$_Vars_GameElements[$ShipID]]; - } - - // Create SpeedsArray - $SpeedsAvailable = array(10, 9, 8, 7, 6, 5, 4, 3, 2, 1); - - if($_User['admiral_time'] > $Time) - { - $SpeedsAvailable[] = 12; - $SpeedsAvailable[] = 11; - $SpeedsAvailable[] = 0.5; - $SpeedsAvailable[] = 0.25; - } - if(MORALE_ENABLED) - { - $MaxAvailableSpeed = max($SpeedsAvailable); - if($_User['morale_level'] >= MORALE_BONUS_FLEETSPEEDUP1) - { - $SpeedsAvailable[] = $MaxAvailableSpeed + (MORALE_BONUS_FLEETSPEEDUP1_VALUE / 10); - } - if($_User['morale_level'] >= MORALE_BONUS_FLEETSPEEDUP2) - { - $SpeedsAvailable[] = $MaxAvailableSpeed + (MORALE_BONUS_FLEETSPEEDUP2_VALUE / 10); - } - } - arsort($SpeedsAvailable); - reset($SpeedsAvailable); - - $AllFleetSpeed = GetFleetMaxSpeed('', $ShipID, $_User); - $GenFleetSpeed = current($SpeedsAvailable); - $SpeedFactor = GetGameSpeedFactor(); - $MaxFleetSpeed = $AllFleetSpeed; - if(MORALE_ENABLED) - { - if($_User['morale_level'] <= MORALE_PENALTY_FLEETSLOWDOWN) - { - $MaxFleetSpeed *= MORALE_PENALTY_FLEETSLOWDOWN_VALUE; - } - } - $distance = GetTargetDistance($CurrentPlanet['galaxy'], $Galaxy, $CurrentPlanet['system'], $System, $CurrentPlanet['planet'], $Planet); - $duration = GetMissionDuration($GenFleetSpeed, $MaxFleetSpeed, $distance, $SpeedFactor); - $consumption = GetFleetConsumption(array($ShipID => $ShipCount), $SpeedFactor, $duration, $distance, $_User); - $fleet['start_time'] = $duration + $Time; - $fleet['end_time'] = (2 * $duration) + $Time; - - if($CurrentPlanet['deuterium'] >= $consumption) - { - $FleetStorage = $_Vars_Prices[$ShipID]['capacity'] * $ShipCount; - if($Mission == 6) - { - // Try to SlowDown fleet only if it's Espionage Mission - while($FleetStorage < $consumption) - { - $GenFleetSpeed = next($SpeedsAvailable); - if($GenFleetSpeed !== false) - { - $duration = GetMissionDuration($GenFleetSpeed, $MaxFleetSpeed, $distance, $SpeedFactor); - $consumption = GetFleetConsumption(array($ShipID => $ShipCount), $SpeedFactor, $duration, $distance, $_User); - $fleet['start_time'] = $duration + $Time; - $fleet['end_time'] = (2 * $duration) + $Time; - } - else - { - break; - } - } - } - - if($FleetStorage >= $consumption) - { - switch($Mission) - { - case 6: //Spy - $TargetOwner = $TargetUser; - break; - case 8: //Recycling - $TargetOwner = 0; - break; - case 7: //Colonization - $TargetOwner = 0; - break; - } - } - else - { - CreateReturn('608'); - } - } - else - { - CreateReturn('607'); - } - - if(!isset($TargetID) || $TargetID <= 0) - { - $TargetID = '0'; - } - if(empty($GalaxyRow['galaxy_id'])) - { - $GalaxyRow['galaxy_id'] = '0'; - } - - $FleetArray[$ShipID] = $ShipCount; - $FleetArrayQuery = Array2String($FleetArray); - - $QryInsertFleet = ''; - $QryInsertFleet .= "INSERT INTO {{table}} SET "; - $QryInsertFleet .= "`fleet_owner` = '{$_User['id']}', "; - $QryInsertFleet .= "`fleet_mission` = '{$Mission}', "; - $QryInsertFleet .= "`fleet_amount` = '{$ShipCount}', "; - $QryInsertFleet .= "`fleet_array` = '{$FleetArrayQuery}', "; - $QryInsertFleet .= "`fleet_start_time` = '{$fleet['start_time']}', "; - $QryInsertFleet .= "`fleet_start_id` = {$CurrentPlanet['id']}, "; - $QryInsertFleet .= "`fleet_start_galaxy` = '{$CurrentPlanet['galaxy']}', "; - $QryInsertFleet .= "`fleet_start_system` = '{$CurrentPlanet['system']}', "; - $QryInsertFleet .= "`fleet_start_planet` = '{$CurrentPlanet['planet']}', "; - $QryInsertFleet .= "`fleet_start_type` = '{$CurrentPlanet['planet_type']}', "; - $QryInsertFleet .= "`fleet_end_time` = '{$fleet['end_time']}', "; - $QryInsertFleet .= "`fleet_end_id` = {$TargetID}, "; - $QryInsertFleet .= "`fleet_end_id_galaxy` = {$GalaxyRow['galaxy_id']}, "; - $QryInsertFleet .= "`fleet_end_stay` = '0', "; - $QryInsertFleet .= "`fleet_end_galaxy` = '{$Galaxy}', "; - $QryInsertFleet .= "`fleet_end_system` = '{$System}', "; - $QryInsertFleet .= "`fleet_end_planet` = '{$Planet}', "; - $QryInsertFleet .= "`fleet_end_type` = '{$Type}', "; - $QryInsertFleet .= "`fleet_resource_metal` = '0', "; - $QryInsertFleet .= "`fleet_resource_crystal` = '0', "; - $QryInsertFleet .= "`fleet_resource_deuterium` = '0', "; - $QryInsertFleet .= "`fleet_target_owner` = '{$TargetOwner}', "; - $QryInsertFleet .= "`fleet_send_time` = UNIX_TIMESTAMP();"; - doquery($QryInsertFleet, 'fleets'); - - $LastFleetID = doquery("SELECT LAST_INSERT_ID() as `id`;", '', true); - $LastFleetID = $LastFleetID['id']; - - $QryArchive = ''; - $QryArchive .= "INSERT INTO {{table}} SET "; - $QryArchive .= "`Fleet_ID` = {$LastFleetID}, "; - $QryArchive .= "`Fleet_Owner` = {$_User['id']}, "; - $QryArchive .= "`Fleet_Mission` = {$Mission}, "; - $QryArchive .= "`Fleet_Array` = '{$FleetArrayQuery}', "; - $QryArchive .= "`Fleet_Time_Send` = UNIX_TIMESTAMP(), "; - $QryArchive .= "`Fleet_Time_Start` = {$fleet['start_time']}, "; - $QryArchive .= "`Fleet_Time_End` = {$fleet['end_time']}, "; - $QryArchive .= "`Fleet_Start_ID` = {$CurrentPlanet['id']}, "; - $QryArchive .= "`Fleet_Start_Galaxy` = {$CurrentPlanet['galaxy']}, "; - $QryArchive .= "`Fleet_Start_System` = {$CurrentPlanet['system']}, "; - $QryArchive .= "`Fleet_Start_Planet` = {$CurrentPlanet['planet']}, "; - $QryArchive .= "`Fleet_Start_Type` = {$CurrentPlanet['planet_type']}, "; - $QryArchive .= "`Fleet_End_ID` = '{$TargetID}', "; - $QryArchive .= "`Fleet_End_ID_Galaxy` = '{$GalaxyRow['galaxy_id']}', "; - $QryArchive .= "`Fleet_End_Galaxy` = {$Galaxy}, "; - $QryArchive .= "`Fleet_End_System` = {$System}, "; - $QryArchive .= "`Fleet_End_Planet` = {$Planet}, "; - $QryArchive .= "`Fleet_End_Type` = {$Type}, "; - $QryArchive .= "`Fleet_End_Owner` = '{$TargetOwner}' "; - doquery($QryArchive, 'fleet_archive'); - - $CurrentPlanet['deuterium'] = $CurrentPlanet['deuterium'] - $consumption; - - $QryUpdatePlanet = ''; - $QryUpdatePlanet .= "UPDATE {{table}} SET "; - $QryUpdatePlanet .= "`{$_Vars_GameElements[$ShipID]}` = `{$_Vars_GameElements[$ShipID]}` - {$ShipCount}, "; - $QryUpdatePlanet .= "`deuterium` = '{$CurrentPlanet["deuterium"]}' "; - $QryUpdatePlanet .= "WHERE "; - $QryUpdatePlanet .= "`id` = '{$CurrentPlanet['id']}'"; - - doquery("LOCK TABLE {{table}} WRITE", 'planets'); - doquery($QryUpdatePlanet, "planets"); - doquery("UNLOCK TABLES", ''); - - // User Development Log - if($consumption > 0) - { - $FleetArray['F'] = $consumption; - } - $FleetArrayDevLog = Array2String($FleetArray); - $UserDev_Log[] = array('PlanetID' => $CurrentPlanet['id'], 'Date' => $Time, 'Place' => 9, 'Code' => $Mission, 'ElementID' => $LastFleetID, 'AdditionalData' => $FleetArrayDevLog); - - $ActualFleets += 1; - switch($Mission) - { - case 6: - { - //Spy - $Spy_Probes -= $ShipCount; - $Return = '600_1'; //OK - break; - } - case 8: - { - //Recycling - $Recyclers -= $ShipCount; - $Return = '600_2'; //OK - break; - } - case 7: - { - //Colonization - $Colonizers -= $ShipCount; - $Return = '600_3'; //OK - break; - } - } - $Update = '1'; - if(empty($Return)) - { - $Return = '694'; - } - CreateReturn($Return); - -?> \ No newline at end of file + 0 AND $System > 0 AND $Planet > 0 AND $Galaxy <= MAX_GALAXY_IN_WORLD AND $System <= MAX_SYSTEM_IN_GALAXY AND $Planet <= MAX_PLANET_IN_SYSTEM)) +{ + CreateReturn('603'); +} +if(!($Type == 1 OR $Type == 2 OR $Type == 3)) +{ + CreateReturn('604'); +} + +$CurrentPlanet = &$_Planet; +$FlyingFleets = doquery("SELECT COUNT(`fleet_id`) as `Number` FROM {{table}} WHERE `fleet_owner` = '{$_User['id']}';", 'fleets', true); + +$Recyclers = $CurrentPlanet['recycler']; +$Spy_Probes = $CurrentPlanet['espionage_probe']; +$Colonizers = $CurrentPlanet['colony_ship']; +$ActualFleets = $FlyingFleets['Number']; + +if(MORALE_ENABLED) +{ + Morale_ReCalculate($_User, $Time); +} + +if(($_User[$_Vars_GameElements[108]] + 1 + (($_User['admiral_time'] > 0) ? 2 : 0)) <= $ActualFleets) +{ + $Update = '1'; + CreateReturn('609'); +} + +switch($Mission) +{ + case 6: + { + //Spy + if(!($Type == 1 OR $Type == 3)) + { + CreateReturn('613'); + } + + $ShipID = 210; + $ShipCount = $_User['settings_spyprobescount']; + + if($Type == 1) + { + $Query_GetTarget_Galaxy = 'id_planet'; + } + else + { + $Query_GetTarget_Galaxy = 'id_moon'; + } + $Query_GetTarget = ''; + $Query_GetTarget .= "SELECT `pl`.`id`, `pl`.`id_owner`, `galaxy`.`galaxy_id` FROM {{table}} AS `pl` "; + $Query_GetTarget .= "LEFT JOIN `{{prefix}}galaxy` AS `galaxy` ON `pl`.`id` = `galaxy`.`{$Query_GetTarget_Galaxy}` "; + $Query_GetTarget .= "WHERE `pl`.`galaxy` = {$Galaxy} AND `pl`.`system` = {$System} AND `pl`.`planet` = {$Planet} AND `pl`.`planet_type` = {$Type} "; + $Query_GetTarget .= "LIMIT 1; -- GalaxyFleet|GetTarget"; + $TargetPlanet = doquery($Query_GetTarget, 'planets', true); + + $GalaxyRow['galaxy_id'] = $TargetPlanet['galaxy_id']; + $TargetUser = $TargetPlanet['id_owner']; + $TargetID = $TargetPlanet['id']; + $TargetPlanetType = $Type; + + if($TargetID <= 0) + { + CreateReturn('614'); + } + if($TargetUser == $_User['id']) + { + CreateReturn('615'); + } + + $protection = $_GameConfig['noobprotection']; + $protectiontime = $_GameConfig['noobprotectiontime']; + $protectionmulti = $_GameConfig['noobprotectionmulti']; + $adminprotection = $_GameConfig['adminprotection']; + $allyprotection = $_GameConfig['allyprotection']; + $noNoobProtect = $_GameConfig['no_noob_protect']; + $noIdleProtect = $_GameConfig['no_idle_protect']; + $Protections['idleTime'] = $_GameConfig['no_idle_protect'] * TIME_DAY; + + if($TargetUser > 0) + { + $Query_GetUser = ''; + $Query_GetUser .= "SELECT `usr`.`ally_id`, `usr`.`is_onvacation`, `usr`.`is_banned`, `usr`.`onlinetime`, `usr`.`authlevel`, `usr`.`first_login`, `usr`.`NoobProtection_EndTime`, "; + $Query_GetUser .= "`stat`.`total_points`, `stat`.`total_rank` "; + $Query_GetUser .= "FROM {{table}} as `usr` "; + $Query_GetUser .= "LEFT JOIN `{{prefix}}statpoints` AS `stat` ON `stat`.`stat_type` = 1 AND `stat`.`id_owner` = `usr`.`id` "; + $Query_GetUser .= "WHERE `id` = {$TargetUser} LIMIT 1;"; + $HeDBRec = doquery($Query_GetUser, 'users', true); + + $SaveMyTotalRank = false; + if(!CheckAuth('programmer')) + { + $MyGameLevel = $_User['total_points']; + } + else + { + $MyGameLevel = $HeDBRec['total_points']; + if($_User['total_rank'] <= 0) + { + $SaveMyTotalRank = $_User['total_rank']; + $_User['total_rank'] = $HeDBRec['total_rank']; + } + } + $HeGameLevel = $HeDBRec['total_points']; + + if($allyprotection == 1 AND $_User['ally_id'] > 0 AND $_User['ally_id'] == $HeDBRec['ally_id']) + { + CreateReturn('616'); + } + if((CheckAuth('supportadmin') OR CheckAuth('supportadmin', AUTHCHECK_NORMAL, $HeDBRec)) AND $adminprotection == 1) + { + if(CheckAuth('supportadmin')) + { + CreateReturn('623'); + } + else + { + CreateReturn('625'); + } + } + if(isOnVacation($HeDBRec)) + { + if($HeDBRec['is_banned'] == 1) + { + CreateReturn('617'); + } + else + { + CreateReturn('618'); + } + } + + if($protection == 1) + { + if($_User['total_rank'] < 1) + { + CreateReturn('631'); + } + if($HeDBRec['total_rank'] < 1) + { + CreateReturn('630'); + } + + if($_User['NoobProtection_EndTime'] > $Time) + { + CreateReturn('632'); // You are under Newcommer protection + } + else if($HeDBRec['first_login'] == 0) + { + CreateReturn('634'); // Newcommer protection (never logged in) + } + else if($HeDBRec['NoobProtection_EndTime'] > $Time) + { + CreateReturn('633'); // Newcommer protection + } + + if($HeDBRec['onlinetime'] >= ($Time - (TIME_DAY * $noIdleProtect))) + { + if($HeGameLevel < ($protectiontime * 1000)) + { + CreateReturn('619'); //Player under n00b protection time + } + else if($MyGameLevel < ($protectiontime * 1000)) + { + CreateReturn('620'); //You are under n00b protection time + } + else + { + if($MyGameLevel < ($noNoobProtect * 1000) OR $HeGameLevel < ($noNoobProtect * 1000)) + { + if(($MyGameLevel > ($HeGameLevel * $protectionmulti))) + { + CreateReturn('621'); //Player is too weak + } + else if(($MyGameLevel * $protectionmulti) < $HeGameLevel) + { + CreateReturn('622'); //Player is too strony + } + } + } + } + } + if($SaveMyTotalRank !== false) + { + $_User['total_rank'] = $SaveMyTotalRank; + } + } + break; + } + case 8: + { + //Recycling + $ShipID = 209; + if($Type != 2) + { + CreateReturn('612'); + } + + $GalaxyRow = doquery("SELECT `galaxy_id`, `metal`,`crystal` FROM {{table}} WHERE `galaxy` = {$Galaxy} AND `system` = {$System} AND `planet` = {$Planet} LIMIT 1;", 'galaxy', true); + if(!($GalaxyRow['metal'] > 0 OR $GalaxyRow['crystal'] > 0)) + { + CreateReturn('611'); + } + $ShipCount = ceil(($GalaxyRow['metal'] + $GalaxyRow['crystal']) / $_Vars_Prices[$ShipID]['capacity']); + break; + } + case 7: + { + //Colonization + $ShipID = 208; + if($Type != 1) + { + CreateReturn('612'); + } + + $PlanetCheck = doquery("SELECT `id` FROM {{table}} WHERE `galaxy` = {$Galaxy} AND `system` = {$System} AND `planet` = {$Planet} AND `planet_type` = 1 LIMIT 1;", 'planets', true); + if($PlanetCheck['id'] > 0) + { + CreateReturn('624'); + } + $ShipCount = 1; + break; + } +} + +// Fleet Blockade System +$BlockFleet = false; +$SFBSelectWhere[] = "(`Type` = 1 AND (`EndTime` > UNIX_TIMESTAMP() OR `PostEndTime` > UNIX_TIMESTAMP()))"; +if($Mission == 6) +{ + if($TargetUser > 0) + { + $SFBSelectWhere[] = "(`Type` = 2 AND `ElementID` = {$TargetUser} AND `EndTime` > UNIX_TIMESTAMP())"; + } + $SFBSelectWhere[] = "(`Type` = 3 AND `ElementID` = {$TargetID} AND `EndTime` > UNIX_TIMESTAMP())"; +} +$SFBSelectWhere[] = "(`Type` = 2 AND `ElementID` = {$_User['id']} AND `EndTime` > UNIX_TIMESTAMP())"; +$SFBSelectWhere[] = "(`Type` = 3 AND `ElementID` = {$CurrentPlanet['id']} AND `EndTime` > UNIX_TIMESTAMP())"; + +$SFBSelect = ''; +$SFBSelect .= "SELECT `Type`, `BlockMissions`, `Reason`, `StartTime`, `EndTime`, `PostEndTime`, `ElementID`, `DontBlockIfIdle` FROM {{table}} WHERE `StartTime` <= UNIX_TIMESTAMP() AND "; +$SFBSelect .= implode(' OR ', $SFBSelectWhere); +$SFBSelect .= " ORDER BY `Type` ASC, `EndTime` DESC;"; +$LoadSFBData = doquery($SFBSelect, 'smart_fleet_blockade'); + +if(mysql_num_rows($LoadSFBData) > 0) +{ + while($GetSFBData = mysql_fetch_assoc($LoadSFBData)) + { + $BlockedMissions = false; + if($GetSFBData['BlockMissions'] == '0') + { + $BlockedMissions = true; + $AllMissionsBlocked = true; + } + else + { + $BlockedMissions = explode(',', $GetSFBData['BlockMissions']); + } + + if($BlockedMissions === true OR in_array($Mission, $BlockedMissions)) + { + if($GetSFBData['Type'] == 1) + { + // Global Blockade + if($GetSFBData['EndTime'] > $Time) + { + // Normal Blockade + if(!($GetSFBData['DontBlockIfIdle'] == 1 AND in_array($Mission, $_Vars_FleetMissions['military']) AND $TargetUser > 0 AND $HeDBRec['onlinetime'] <= ($Time - $Protections['idleTime']))) + { + CreateReturn('628'); + } + } + else if($GetSFBData['PostEndTime'] > $Time) + { + // Post Blockade + if(in_array($Mission, $_Vars_FleetMissions['military']) AND $TargetUser > 0 AND + ( + ($AllMissionsBlocked !== true AND $HeDBRec['onlinetime'] > ($Time - $Protections['idleTime']) AND $HeDBRec['onlinetime'] < $GetSFBData['StartTime']) + OR + ($AllMissionsBlocked === true AND $HeDBRec['onlinetime'] > ($Time - $Protections['idleTime']) AND $HeDBRec['onlinetime'] < $GetSFBData['EndTime']) + )) + { + CreateReturn('635'); + } + } + } + else if($GetSFBData['Type'] == 2) + { + // Per User Blockade + if($GetSFBData['ElementID'] == $_User['id']) + { + CreateReturn('636'); + } + else + { + CreateReturn('637'); + } + } + else if($GetSFBData['Type'] == 3) + { + // Per Planet Blockade + if($GetSFBData['ElementID'] == $CurrentPlanet['id']) + { + // SFB per Planet (your) is Active + if($CurrentPlanet['planet_type'] == 1) + { + CreateReturn('638'); + } + else + { + CreateReturn('639'); + } + } + else + { + // SFB per Planet (target) is Active + if($TargetPlanetType == 1) + { + CreateReturn('640'); + } + else + { + CreateReturn('641'); + } + } + } + } + } +} + +if($ShipCount < 0) +{ + CreateReturn('605'); +} +if($ShipCount == 0) +{ + $Update = 1; + CreateReturn('610'); +} +if($CurrentPlanet[$_Vars_GameElements[$ShipID]] <= 0) +{ + //No ships + switch($Mission) + { + case 6: + { + //Spy + $Return = '606_1'; + break; + } + case 8: + { + //Recycling + $Return = '606_2'; + break; + } + case 7: + { + //Colonization + $Return = '606_3'; + break; + } + } + $Update = '1'; + CreateReturn($Return); +} + +if($CurrentPlanet[$_Vars_GameElements[$ShipID]] < $ShipCount) +{ + $ShipCount = $CurrentPlanet[$_Vars_GameElements[$ShipID]]; +} + +// Create SpeedsArray +$SpeedsAvailable = array(10, 9, 8, 7, 6, 5, 4, 3, 2, 1); + +if($_User['admiral_time'] > $Time) +{ + $SpeedsAvailable[] = 12; + $SpeedsAvailable[] = 11; + $SpeedsAvailable[] = 0.5; + $SpeedsAvailable[] = 0.25; +} +if(MORALE_ENABLED) +{ + $MaxAvailableSpeed = max($SpeedsAvailable); + if($_User['morale_level'] >= MORALE_BONUS_FLEETSPEEDUP1) + { + $SpeedsAvailable[] = $MaxAvailableSpeed + (MORALE_BONUS_FLEETSPEEDUP1_VALUE / 10); + } + if($_User['morale_level'] >= MORALE_BONUS_FLEETSPEEDUP2) + { + $SpeedsAvailable[] = $MaxAvailableSpeed + (MORALE_BONUS_FLEETSPEEDUP2_VALUE / 10); + } +} +arsort($SpeedsAvailable); +reset($SpeedsAvailable); + +$AllFleetSpeed = GetFleetMaxSpeed('', $ShipID, $_User); +$GenFleetSpeed = current($SpeedsAvailable); +$SpeedFactor = GetGameSpeedFactor(); +$MaxFleetSpeed = $AllFleetSpeed; +if(MORALE_ENABLED) +{ + if($_User['morale_level'] <= MORALE_PENALTY_FLEETSLOWDOWN) + { + $MaxFleetSpeed *= MORALE_PENALTY_FLEETSLOWDOWN_VALUE; + } +} +$distance = GetTargetDistance($CurrentPlanet['galaxy'], $Galaxy, $CurrentPlanet['system'], $System, $CurrentPlanet['planet'], $Planet); +$duration = GetMissionDuration($GenFleetSpeed, $MaxFleetSpeed, $distance, $SpeedFactor); +$consumption = GetFleetConsumption(array($ShipID => $ShipCount), $SpeedFactor, $duration, $distance, $_User); +$fleet['start_time'] = $duration + $Time; +$fleet['end_time'] = (2 * $duration) + $Time; + +if($CurrentPlanet['deuterium'] >= $consumption) +{ + $FleetStorage = $_Vars_Prices[$ShipID]['capacity'] * $ShipCount; + if($Mission == 6) + { + // Try to SlowDown fleet only if it's Espionage Mission + while($FleetStorage < $consumption) + { + $GenFleetSpeed = next($SpeedsAvailable); + if($GenFleetSpeed !== false) + { + $duration = GetMissionDuration($GenFleetSpeed, $MaxFleetSpeed, $distance, $SpeedFactor); + $consumption = GetFleetConsumption(array($ShipID => $ShipCount), $SpeedFactor, $duration, $distance, $_User); + $fleet['start_time'] = $duration + $Time; + $fleet['end_time'] = (2 * $duration) + $Time; + } + else + { + break; + } + } + } + + if($FleetStorage >= $consumption) + { + switch($Mission) + { + case 6: //Spy + $TargetOwner = $TargetUser; + break; + case 8: //Recycling + $TargetOwner = 0; + break; + case 7: //Colonization + $TargetOwner = 0; + break; + } + } + else + { + CreateReturn('608'); + } +} +else +{ + CreateReturn('607'); +} + +if(!isset($TargetID) || $TargetID <= 0) +{ + $TargetID = '0'; +} +if(empty($GalaxyRow['galaxy_id'])) +{ + $GalaxyRow['galaxy_id'] = '0'; +} + +$FleetArray[$ShipID] = $ShipCount; +$FleetArrayQuery = Array2String($FleetArray); + +$QryInsertFleet = ''; +$QryInsertFleet .= "INSERT INTO {{table}} SET "; +$QryInsertFleet .= "`fleet_owner` = '{$_User['id']}', "; +$QryInsertFleet .= "`fleet_mission` = '{$Mission}', "; +$QryInsertFleet .= "`fleet_amount` = '{$ShipCount}', "; +$QryInsertFleet .= "`fleet_array` = '{$FleetArrayQuery}', "; +$QryInsertFleet .= "`fleet_start_time` = '{$fleet['start_time']}', "; +$QryInsertFleet .= "`fleet_start_id` = {$CurrentPlanet['id']}, "; +$QryInsertFleet .= "`fleet_start_galaxy` = '{$CurrentPlanet['galaxy']}', "; +$QryInsertFleet .= "`fleet_start_system` = '{$CurrentPlanet['system']}', "; +$QryInsertFleet .= "`fleet_start_planet` = '{$CurrentPlanet['planet']}', "; +$QryInsertFleet .= "`fleet_start_type` = '{$CurrentPlanet['planet_type']}', "; +$QryInsertFleet .= "`fleet_end_time` = '{$fleet['end_time']}', "; +$QryInsertFleet .= "`fleet_end_id` = {$TargetID}, "; +$QryInsertFleet .= "`fleet_end_id_galaxy` = {$GalaxyRow['galaxy_id']}, "; +$QryInsertFleet .= "`fleet_end_stay` = '0', "; +$QryInsertFleet .= "`fleet_end_galaxy` = '{$Galaxy}', "; +$QryInsertFleet .= "`fleet_end_system` = '{$System}', "; +$QryInsertFleet .= "`fleet_end_planet` = '{$Planet}', "; +$QryInsertFleet .= "`fleet_end_type` = '{$Type}', "; +$QryInsertFleet .= "`fleet_resource_metal` = '0', "; +$QryInsertFleet .= "`fleet_resource_crystal` = '0', "; +$QryInsertFleet .= "`fleet_resource_deuterium` = '0', "; +$QryInsertFleet .= "`fleet_target_owner` = '{$TargetOwner}', "; +$QryInsertFleet .= "`fleet_send_time` = UNIX_TIMESTAMP();"; +doquery($QryInsertFleet, 'fleets'); + +$LastFleetID = doquery("SELECT LAST_INSERT_ID() as `id`;", '', true); +$LastFleetID = $LastFleetID['id']; + +$QryArchive = ''; +$QryArchive .= "INSERT INTO {{table}} SET "; +$QryArchive .= "`Fleet_ID` = {$LastFleetID}, "; +$QryArchive .= "`Fleet_Owner` = {$_User['id']}, "; +$QryArchive .= "`Fleet_Mission` = {$Mission}, "; +$QryArchive .= "`Fleet_Array` = '{$FleetArrayQuery}', "; +$QryArchive .= "`Fleet_Time_Send` = UNIX_TIMESTAMP(), "; +$QryArchive .= "`Fleet_Time_Start` = {$fleet['start_time']}, "; +$QryArchive .= "`Fleet_Time_End` = {$fleet['end_time']}, "; +$QryArchive .= "`Fleet_Start_ID` = {$CurrentPlanet['id']}, "; +$QryArchive .= "`Fleet_Start_Galaxy` = {$CurrentPlanet['galaxy']}, "; +$QryArchive .= "`Fleet_Start_System` = {$CurrentPlanet['system']}, "; +$QryArchive .= "`Fleet_Start_Planet` = {$CurrentPlanet['planet']}, "; +$QryArchive .= "`Fleet_Start_Type` = {$CurrentPlanet['planet_type']}, "; +$QryArchive .= "`Fleet_End_ID` = '{$TargetID}', "; +$QryArchive .= "`Fleet_End_ID_Galaxy` = '{$GalaxyRow['galaxy_id']}', "; +$QryArchive .= "`Fleet_End_Galaxy` = {$Galaxy}, "; +$QryArchive .= "`Fleet_End_System` = {$System}, "; +$QryArchive .= "`Fleet_End_Planet` = {$Planet}, "; +$QryArchive .= "`Fleet_End_Type` = {$Type}, "; +$QryArchive .= "`Fleet_End_Owner` = '{$TargetOwner}' "; +doquery($QryArchive, 'fleet_archive'); + +$CurrentPlanet['deuterium'] = $CurrentPlanet['deuterium'] - $consumption; + +$QryUpdatePlanet = ''; +$QryUpdatePlanet .= "UPDATE {{table}} SET "; +$QryUpdatePlanet .= "`{$_Vars_GameElements[$ShipID]}` = `{$_Vars_GameElements[$ShipID]}` - {$ShipCount}, "; +$QryUpdatePlanet .= "`deuterium` = '{$CurrentPlanet["deuterium"]}' "; +$QryUpdatePlanet .= "WHERE "; +$QryUpdatePlanet .= "`id` = '{$CurrentPlanet['id']}'"; + +doquery("LOCK TABLE {{table}} WRITE", 'planets'); +doquery($QryUpdatePlanet, "planets"); +doquery("UNLOCK TABLES", ''); + +// User Development Log +if($consumption > 0) +{ + $FleetArray['F'] = $consumption; +} +$FleetArrayDevLog = Array2String($FleetArray); +$UserDev_Log[] = array('PlanetID' => $CurrentPlanet['id'], 'Date' => $Time, 'Place' => 9, 'Code' => $Mission, 'ElementID' => $LastFleetID, 'AdditionalData' => $FleetArrayDevLog); + +$ActualFleets += 1; +switch($Mission) +{ + case 6: + { + //Spy + $Spy_Probes -= $ShipCount; + $Return = '600_1'; //OK + break; + } + case 8: + { + //Recycling + $Recyclers -= $ShipCount; + $Return = '600_2'; //OK + break; + } + case 7: + { + //Colonization + $Colonizers -= $ShipCount; + $Return = '600_3'; //OK + break; + } +} +$Update = '1'; +if(empty($Return)) +{ + $Return = '694'; +} +CreateReturn($Return); + +?> diff --git a/ajax/index.php b/ajax/index.php index ee150fd01..bc99142d1 100644 --- a/ajax/index.php +++ b/ajax/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/ajax/messages.conversation.php b/ajax/messages.conversation.php index 674f43638..de5c6bd2b 100644 --- a/ajax/messages.conversation.php +++ b/ajax/messages.conversation.php @@ -1,206 +1,206 @@ - '001')); - } - $ThreadID = (isset($_GET['tid']) ? round($_GET['tid']) : 0); - if($ThreadID <= 0) - { - ajaxReturn(array('Err' => '002')); - } - if(isset($_GET['exc']) && !empty($_GET['exc'])) - { - $Temp = explode(',', $_GET['exc']); - foreach($Temp as $Value) - { - $Value = round($Value); - if($Value > 0) - { - $ExcludeIDs[] = $Value; - } - } - } - $MaxMessageID = 0; - if(isset($_GET['mid']) && !empty($_GET['mid'])) - { - $MaxMessageID = round($_GET['mid']); - } - $_ThisCategory = 0; - if(isset($_GET['nc']) && $_GET['nc'] == '1') - { - $_ThisCategory = 100; - } - - $Query_GetMessages = "SELECT `m`.*, `u`.`username`, `u`.`authlevel` FROM {{table}} AS `m` "; - $Query_GetMessages .= "LEFT JOIN `{{prefix}}users` AS `u` ON `u`.`id` = `m`.`id_sender` "; - $Query_GetMessages .= "WHERE (`m`.`deleted` = false OR `m`.`id_sender` = {$_User['id']}) AND (`m`.`id_owner` = {$_User['id']} OR `m`.`id_sender` = {$_User['id']}) AND `m`.`Thread_ID` = {$ThreadID} "; - $Query_GetMessages .= " AND (`m`.`Thread_IsLast` = 0 OR `m`.`id_owner` != {$_User['id']}) "; - $Query_GetMessages .= (!empty($ExcludeIDs) ? " AND `m`.`id` NOT IN (".implode(', ', $ExcludeIDs).") " : ''); - $Query_GetMessages .= ($MaxMessageID > 0 ? " AND `m`.`id` < {$MaxMessageID} " : ''); - $Query_GetMessages .= "ORDER BY `m`.`time` DESC, `m`.`id` DESC;"; - $GetMessages = doquery($Query_GetMessages, 'messages'); - if(mysql_num_rows($GetMessages) <= 0) - { - ajaxReturn(array('Err' => '003')); - } - else - { - includeLang('messages'); - includeLang('messageSystem'); - includeLang('spyReport'); - includeLang('FleetMission_MissileAttack'); - - $MsgColors = array(0 => 'c0', 1 => 'c1', 2 => 'c2', 3 => 'c3', 4 => 'c4', 5 => 'c5', 15 => 'c15', 80 => 'c80', 50 => 'c50', 70 => 'c70', 100 => 'c100'); - - if($_GameConfig['enable_bbcode'] == 1) - { - include($_EnginePath.'includes/functions/BBcodeFunction.php'); - } - - $Messages = array(); - while($CurMess = mysql_fetch_assoc($GetMessages)) - { - $MsgCache[] = $CurMess; - } - - foreach($MsgCache as $MsgIndex => $CurMess) - { - $parseMSG = array(); - // Message sent by User - $AddFrom = ''; - if(!empty($CurMess['from'])) - { - $AddFrom = ' '.$CurMess['from']; - } - $CurMess['from'] = "{$_Lang['msg_const']['senders']['rangs'][GetAuthLabel($CurMess)]} {$CurMess['username']}{$AddFrom}"; - - if(in_array($CurMess['type'], array(2, 80)) AND preg_match('/^\{COPY\_MSG\_\#([0-9]{1,}){1}\}$/D', $CurMess['text'], $ThisMatch)) - { - $GetMassMsgs[] = $ThisMatch[1]; - $CopyMsgMap[$ThisMatch[1]][] = $CurMess['id']; - $CurMess['text'] = sprintf($_Lang['msg_const']['msgs']['err4'], $CopyData['id']); - } - else - { - if($_GameConfig['enable_bbcode'] == 1) - { - $CurMess['text'] = bbcode(image($CurMess['text'])); - } - $CurMess['text'] = nl2br($CurMess['text']); - } - - $parseMSG['CurrMSG_ID'] = $CurMess['id']; - if($CurMess['read'] == false) - { - $parseMSG['CurrMSG_IsUnread'] = ' class="isNew"'; - } - $parseMSG['CurrMSG_date'] = date('d.m.Y', $CurMess['time']); - $parseMSG['CurrMSG_time'] = date('H:i:s', $CurMess['time']); - $parseMSG['CurrMSG_from'] = $CurMess['from']; - $parseMSG['CurrMSG_subject'] = $CurMess['subject']; - $parseMSG['CurrMSG_text'] = stripslashes(nl2br($CurMess['text'])); - if($_ThisCategory == 100) - { - $parseMSG['CurrMSG_color'] = $MsgColors[$CurMess['type']]; - } - else - { - $parseMSG['CurrMSG_color'] = ''; - } - if($CurMess['type'] == 80 OR $CurMess['id_sender'] == $_User['id']) - { - $parseMSG['CurrMSG_HideCheckbox'] = 'class="inv"'; - } - $parseMSG['CurrMSG_send'] = sprintf(($CurMess['id_owner'] == $_User['id'] ? $_Lang['mess_send_date'] : $_Lang['mess_sendbyyou_date']), $parseMSG['CurrMSG_date'], $parseMSG['CurrMSG_time']); - if($CurMess['id_owner'] == $_User['id']) - { - if($CurMess['id_sender'] != $_User['id']) - { - $parseMSG['CurrMSG_buttons'][] = " 0 ? $CurMess['Thread_ID'] : $CurMess['id'])."\">{$_Lang['mess_reply']}"; - } - if($CurMess['type'] == 2 AND $_User['ally_id'] > 0) - { - $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_reply_toally']}"; - } - - if($CurMess['type'] != 80 AND $CurMess['type'] != 2 AND !CheckAuth('supportadmin', AUTHCHECK_HIGHER, $CurMess)) - { - $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_ignore']}"; - } - $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_report']}"; - $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_delete_single']}"; - } - if(!empty($parseMSG['CurrMSG_buttons'])) - { - $parseMSG['CurrMSG_buttons'] = implode('', $parseMSG['CurrMSG_buttons']); - } - - $Messages[$CurMess['id']] = $parseMSG; - } - $MsgCache = null; - - if(!empty($GetMassMsgs)) - { - if($_ThisCategory == 100) - { - $QryGetMassMsg = doquery("SELECT `id`, `type`, `subject`, `text` FROM {{table}} WHERE `id` IN (".implode(', ', $GetMassMsgs).");", 'messages'); - } - else - { - $QryGetMassMsg = doquery("SELECT `id`, `type`, `subject`, `text`, `from` FROM {{table}} WHERE `id` IN (".implode(', ', $GetMassMsgs).");", 'messages'); - } - while($CopyData = mysql_fetch_assoc($QryGetMassMsg)) - { - if($CopyData['type'] == 80 OR $CopyData['type'] == 2) - { - foreach($CopyMsgMap[$CopyData['id']] as $MsgKey) - { - $Messages[$MsgKey]['CurrMSG_subject'] = $CopyData['subject']; - $Messages[$MsgKey]['CurrMSG_text'] = $CopyData['text']; - if($CopyData['type'] == 2) - { - $Messages[$MsgKey]['CurrMSG_from'] .= ' '.$CopyData['from']; - } - } - } - else - { - foreach($CopyMsgMap[$CopyData['id']] as $MsgKey) - { - $Messages[$MsgKey]['CurrMSG_subject'] = $_Lang['msg_const']['subjects']['019']; - $Messages[$MsgKey]['CurrMSG_text'] = sprintf($_Lang['msg_const']['msgs']['err3'], $CopyData['id']); - } - } - } - } - - $MsgTPL = gettemplate('message_mailbox_body'); - foreach($Messages as $MessageData) - { - $AllMessages[] = parsetemplate($MsgTPL, $MessageData); - } - - ajaxReturn(array('Code' => implode('', $AllMessages))); - } - -?> \ No newline at end of file + '001')); +} +$ThreadID = (isset($_GET['tid']) ? round($_GET['tid']) : 0); +if($ThreadID <= 0) +{ + ajaxReturn(array('Err' => '002')); +} +if(isset($_GET['exc']) && !empty($_GET['exc'])) +{ + $Temp = explode(',', $_GET['exc']); + foreach($Temp as $Value) + { + $Value = round($Value); + if($Value > 0) + { + $ExcludeIDs[] = $Value; + } + } +} +$MaxMessageID = 0; +if(isset($_GET['mid']) && !empty($_GET['mid'])) +{ + $MaxMessageID = round($_GET['mid']); +} +$_ThisCategory = 0; +if(isset($_GET['nc']) && $_GET['nc'] == '1') +{ + $_ThisCategory = 100; +} + +$Query_GetMessages = "SELECT `m`.*, `u`.`username`, `u`.`authlevel` FROM {{table}} AS `m` "; +$Query_GetMessages .= "LEFT JOIN `{{prefix}}users` AS `u` ON `u`.`id` = `m`.`id_sender` "; +$Query_GetMessages .= "WHERE (`m`.`deleted` = false OR `m`.`id_sender` = {$_User['id']}) AND (`m`.`id_owner` = {$_User['id']} OR `m`.`id_sender` = {$_User['id']}) AND `m`.`Thread_ID` = {$ThreadID} "; +$Query_GetMessages .= " AND (`m`.`Thread_IsLast` = 0 OR `m`.`id_owner` != {$_User['id']}) "; +$Query_GetMessages .= (!empty($ExcludeIDs) ? " AND `m`.`id` NOT IN (".implode(', ', $ExcludeIDs).") " : ''); +$Query_GetMessages .= ($MaxMessageID > 0 ? " AND `m`.`id` < {$MaxMessageID} " : ''); +$Query_GetMessages .= "ORDER BY `m`.`time` DESC, `m`.`id` DESC;"; +$GetMessages = doquery($Query_GetMessages, 'messages'); +if(mysql_num_rows($GetMessages) <= 0) +{ + ajaxReturn(array('Err' => '003')); +} +else +{ + includeLang('messages'); + includeLang('messageSystem'); + includeLang('spyReport'); + includeLang('FleetMission_MissileAttack'); + + $MsgColors = array(0 => 'c0', 1 => 'c1', 2 => 'c2', 3 => 'c3', 4 => 'c4', 5 => 'c5', 15 => 'c15', 80 => 'c80', 50 => 'c50', 70 => 'c70', 100 => 'c100'); + + if($_GameConfig['enable_bbcode'] == 1) + { + include($_EnginePath.'includes/functions/BBcodeFunction.php'); + } + + $Messages = array(); + while($CurMess = mysql_fetch_assoc($GetMessages)) + { + $MsgCache[] = $CurMess; + } + + foreach($MsgCache as $MsgIndex => $CurMess) + { + $parseMSG = array(); + // Message sent by User + $AddFrom = ''; + if(!empty($CurMess['from'])) + { + $AddFrom = ' '.$CurMess['from']; + } + $CurMess['from'] = "{$_Lang['msg_const']['senders']['rangs'][GetAuthLabel($CurMess)]} {$CurMess['username']}{$AddFrom}"; + + if(in_array($CurMess['type'], array(2, 80)) AND preg_match('/^\{COPY\_MSG\_\#([0-9]{1,}){1}\}$/D', $CurMess['text'], $ThisMatch)) + { + $GetMassMsgs[] = $ThisMatch[1]; + $CopyMsgMap[$ThisMatch[1]][] = $CurMess['id']; + $CurMess['text'] = sprintf($_Lang['msg_const']['msgs']['err4'], $CopyData['id']); + } + else + { + if($_GameConfig['enable_bbcode'] == 1) + { + $CurMess['text'] = bbcode(image($CurMess['text'])); + } + $CurMess['text'] = nl2br($CurMess['text']); + } + + $parseMSG['CurrMSG_ID'] = $CurMess['id']; + if($CurMess['read'] == false) + { + $parseMSG['CurrMSG_IsUnread'] = ' class="isNew"'; + } + $parseMSG['CurrMSG_date'] = date('d.m.Y', $CurMess['time']); + $parseMSG['CurrMSG_time'] = date('H:i:s', $CurMess['time']); + $parseMSG['CurrMSG_from'] = $CurMess['from']; + $parseMSG['CurrMSG_subject'] = $CurMess['subject']; + $parseMSG['CurrMSG_text'] = stripslashes(nl2br($CurMess['text'])); + if($_ThisCategory == 100) + { + $parseMSG['CurrMSG_color'] = $MsgColors[$CurMess['type']]; + } + else + { + $parseMSG['CurrMSG_color'] = ''; + } + if($CurMess['type'] == 80 OR $CurMess['id_sender'] == $_User['id']) + { + $parseMSG['CurrMSG_HideCheckbox'] = 'class="inv"'; + } + $parseMSG['CurrMSG_send'] = sprintf(($CurMess['id_owner'] == $_User['id'] ? $_Lang['mess_send_date'] : $_Lang['mess_sendbyyou_date']), $parseMSG['CurrMSG_date'], $parseMSG['CurrMSG_time']); + if($CurMess['id_owner'] == $_User['id']) + { + if($CurMess['id_sender'] != $_User['id']) + { + $parseMSG['CurrMSG_buttons'][] = " 0 ? $CurMess['Thread_ID'] : $CurMess['id'])."\">{$_Lang['mess_reply']}"; + } + if($CurMess['type'] == 2 AND $_User['ally_id'] > 0) + { + $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_reply_toally']}"; + } + + if($CurMess['type'] != 80 AND $CurMess['type'] != 2 AND !CheckAuth('supportadmin', AUTHCHECK_HIGHER, $CurMess)) + { + $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_ignore']}"; + } + $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_report']}"; + $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_delete_single']}"; + } + if(!empty($parseMSG['CurrMSG_buttons'])) + { + $parseMSG['CurrMSG_buttons'] = implode('', $parseMSG['CurrMSG_buttons']); + } + + $Messages[$CurMess['id']] = $parseMSG; + } + $MsgCache = null; + + if(!empty($GetMassMsgs)) + { + if($_ThisCategory == 100) + { + $QryGetMassMsg = doquery("SELECT `id`, `type`, `subject`, `text` FROM {{table}} WHERE `id` IN (".implode(', ', $GetMassMsgs).");", 'messages'); + } + else + { + $QryGetMassMsg = doquery("SELECT `id`, `type`, `subject`, `text`, `from` FROM {{table}} WHERE `id` IN (".implode(', ', $GetMassMsgs).");", 'messages'); + } + while($CopyData = mysql_fetch_assoc($QryGetMassMsg)) + { + if($CopyData['type'] == 80 OR $CopyData['type'] == 2) + { + foreach($CopyMsgMap[$CopyData['id']] as $MsgKey) + { + $Messages[$MsgKey]['CurrMSG_subject'] = $CopyData['subject']; + $Messages[$MsgKey]['CurrMSG_text'] = $CopyData['text']; + if($CopyData['type'] == 2) + { + $Messages[$MsgKey]['CurrMSG_from'] .= ' '.$CopyData['from']; + } + } + } + else + { + foreach($CopyMsgMap[$CopyData['id']] as $MsgKey) + { + $Messages[$MsgKey]['CurrMSG_subject'] = $_Lang['msg_const']['subjects']['019']; + $Messages[$MsgKey]['CurrMSG_text'] = sprintf($_Lang['msg_const']['msgs']['err3'], $CopyData['id']); + } + } + } + } + + $MsgTPL = gettemplate('message_mailbox_body'); + foreach($Messages as $MessageData) + { + $AllMessages[] = parsetemplate($MsgTPL, $MessageData); + } + + ajaxReturn(array('Code' => implode('', $AllMessages))); +} + +?> diff --git a/ajax/sendmissiles.php b/ajax/sendmissiles.php index 7ce4abaaf..f0e8da9e3 100644 --- a/ajax/sendmissiles.php +++ b/ajax/sendmissiles.php @@ -1,364 +1,364 @@ - $Now) ? 2 : 0); - if($FlyingFleets >= $MaxFleets) - { - CreateReturn('609'); - } - - $protection = $_GameConfig['noobprotection']; - $protectiontime = $_GameConfig['noobprotectiontime']; - $protectionmulti = $_GameConfig['noobprotectionmulti']; - $adminprotection = $_GameConfig['adminprotection']; - $allyprotection = $_GameConfig['allyprotection']; - $noNoobProtect = $_GameConfig['no_noob_protect']; - $noIdleProtect = $_GameConfig['no_idle_protect']; - $Protections['idleTime'] = $_GameConfig['no_idle_protect'] * TIME_DAY; - - $Galaxy = (isset($_POST['galaxy']) ? intval($_POST['galaxy']) : 0); - $System = (isset($_POST['system']) ? intval($_POST['system']) : 0); - $Planet = (isset($_POST['planet']) ? intval($_POST['planet']) : 0); - $Type = 1; - - $Mission = 10; - $Missiles = (isset($_POST['count']) ? round(str_replace('.', '', $_POST['count'])) : 0); - $PrimTarget = (isset($_POST['target']) ? intval($_POST['target']) : 0); - if($PrimTarget == 0) - { - $PrimTarget = '0'; - } - - $Dist = abs($System - $_Planet['system']); - include($_EnginePath.'includes/functions/GetMissileRange.php'); - $MissilesRange = GetMissileRange(); - $FlightTime = round(((30 + (60 * $Dist)) * 2500) / $_GameConfig['game_speed']); - - if($Missiles <= 0) - { - CreateReturn('651'); - } - if($Galaxy <= 0 OR $Planet <= 0 OR $System <= 0 OR $PrimTarget < 0 OR $PrimTarget > 99) - { - CreateReturn('652'); - } - if($_Planet['missile_silo'] < 4) - { - CreateReturn('649'); - } - if($MissilesRange <= 0) - { - CreateReturn('648'); - } - if($Dist > $MissilesRange OR $Galaxy != $_Planet['galaxy']) - { - CreateReturn('647'); - } - if($Missiles > $_Planet['interplanetary_missile']) - { - CreateReturn('646', '1'); - } - - $Query_GetPlanet = ''; - $Query_GetPlanet .= "SELECT `pl`.`id`, `pl`.`id_owner`, `galaxy`.`galaxy_id` FROM {{table}} AS `pl` "; - $Query_GetPlanet .= "LEFT JOIN `{{prefix}}galaxy` AS `galaxy` ON `galaxy`.`id_planet` = `pl`.`id` "; - $Query_GetPlanet .= "WHERE `pl`.`galaxy` = {$Galaxy} AND `pl`.`system` = {$System} AND `pl`.`planet` = {$Planet} AND `pl`.`planet_type` = {$Type} "; - $Query_GetPlanet .= "LIMIT 1; -- SendMissiles|GetPlanet"; - $PlanetData = doquery($Query_GetPlanet, 'planets', true); - - if($PlanetData['id'] <= 0) - { - CreateReturn('650'); - } - if($PlanetData['id_owner'] == $_User['id']) - { - CreateReturn('645'); - } - - if($PlanetData['id_owner'] > 0) - { - $Query_GetUser = ''; - $Query_GetUser .= "SELECT `usr`.`is_onvacation`, `usr`.`is_banned`, `usr`.`ally_id`, `usr`.`first_login`, `usr`.`NoobProtection_EndTime`, `usr`.`onlinetime`, `usr`.`authlevel`, "; - $Query_GetUser .= "`stat`.`total_points`, `stat`.`total_rank` "; - $Query_GetUser .= "FROM {{table}} AS `usr` "; - $Query_GetUser .= "LEFT JOIN `{{prefix}}statpoints` AS `stat` ON `stat`.`stat_type` = 1 AND `stat`.`id_owner` = `usr`.`id` "; - $Query_GetUser .= "WHERE `usr`.`id` = {$PlanetData['id_owner']} LIMIT 1; -- SendMissiles|GetUser"; - $HeDBRec = doquery($Query_GetUser, 'users', true); - - if(isOnVacation($HeDBRec)) - { - if($HeDBRec['is_banned'] == 1) - { - CreateReturn('642'); - } - else - { - CreateReturn('643'); - } - } - if($allyprotection == 1) - { - if($_User['ally_id'] > 0 AND $_User['ally_id'] == $HeDBRec['ally_id']) - { - CreateReturn('644'); - } - } - - if(!CheckAuth('programmer')) - { - $MyGameLevel = $_User['total_points']; - } - else - { - $MyGameLevel = $HeDBRec['total_points']; - if($_User['total_rank'] <= 0) - { - $_User['total_rank'] = $HeDBRec['total_rank']; - } - } - $HeGameLevel = $HeDBRec['total_points']; - - if($protection == 1) - { - if($_User['total_rank'] < 1) - { - CreateReturn('663'); - } - if($HeDBRec['total_rank'] < 1) - { - CreateReturn('662'); - } - - if($_User['NoobProtection_EndTime'] > $Now) - { - CreateReturn('653'); - } - else if($HeDBRec['first_login'] == 0) - { - CreateReturn('655'); - } - else if($HeDBRec['NoobProtection_EndTime'] > $Now) - { - CreateReturn('654'); - } - - if($HeDBRec['onlinetime'] >= ($Now - (TIME_DAY * $noIdleProtect))) - { - if($HeGameLevel < ($protectiontime * 1000)) - { - CreateReturn('656'); - } - else if($MyGameLevel < ($protectiontime * 1000)) - { - CreateReturn('657'); - } - else - { - if($MyGameLevel < ($noNoobProtect * 1000) OR $HeGameLevel < ($noNoobProtect * 1000)) - { - if(($MyGameLevel > ($HeGameLevel * $protectionmulti))) - { - CreateReturn('656'); - } - else if(($MyGameLevel * $protectionmulti) < $HeGameLevel) - { - CreateReturn('658'); - } - } - } - } - } - if((CheckAuth('supportadmin') OR CheckAuth('supportadmin', AUTHCHECK_NORMAL, $HeDBRec)) AND $adminprotection == 1) - { - if(CheckAuth('supportadmin')) - { - CreateReturn('659'); - } - else - { - CreateReturn('660'); - } - } - } - - // Fleet Blockade System - $SFBSelectWhere[] = "(`Type` = 1 AND (`EndTime` > UNIX_TIMESTAMP() OR `PostEndTime` > UNIX_TIMESTAMP()))"; - if($PlanetData['id_owner'] > 0) - { - $SFBSelectWhere[] = "(`Type` = 2 AND `ElementID` = {$PlanetData['id_owner']} AND `EndTime` > UNIX_TIMESTAMP())"; - } - $SFBSelectWhere[] = "(`Type` = 3 AND `ElementID` = {$PlanetData['id']} AND `EndTime` > UNIX_TIMESTAMP())"; - $SFBSelectWhere[] = "(`Type` = 2 AND `ElementID` = {$_User['id']} AND `EndTime` > UNIX_TIMESTAMP())"; - $SFBSelectWhere[] = "(`Type` = 3 AND `ElementID` = {$_Planet['id']} AND `EndTime` > UNIX_TIMESTAMP())"; - - $SFBSelect = ''; - $SFBSelect .= "SELECT `Type`, `BlockMissions`, `Reason`, `StartTime`, `EndTime`, `PostEndTime`, `ElementID`, `DontBlockIfIdle` FROM {{table}} WHERE `StartTime` <= UNIX_TIMESTAMP() AND "; - $SFBSelect .= implode(' OR ', $SFBSelectWhere); - $SFBSelect .= " ORDER BY `Type` ASC, `EndTime` DESC;"; - - $LoadSFBData = doquery($SFBSelect, 'smart_fleet_blockade'); - if(mysql_num_rows($LoadSFBData) > 0) - { - while($GetSFBData = mysql_fetch_assoc($LoadSFBData)) - { - $BlockedMissions = false; - if($GetSFBData['BlockMissions'] == '0') - { - $BlockedMissions = true; - $AllMissionsBlocked = true; - } - else - { - $BlockedMissions = explode(',', $GetSFBData['BlockMissions']); - } - - if($BlockedMissions === true OR in_array($Mission, $BlockedMissions)) - { - if($GetSFBData['Type'] == 1) - { - // Global Blockade - if($GetSFBData['EndTime'] > $Now) - { - // Normal Blockade - if(!($GetSFBData['DontBlockIfIdle'] == 1 AND in_array($Mission, $_Vars_FleetMissions['military']) AND $PlanetData['id_owner'] > 0 AND $HeDBRec['onlinetime'] <= ($Now - $Protections['idleTime']))) - { - $BlockFleet = true; - $BlockReason = $_Lang['SFB_Stop_GlobalBlockade']; - } - } - else if($GetSFBData['PostEndTime'] > $Now) - { - // Post Blockade - if(in_array($Mission, $_Vars_FleetMissions['military']) AND $PlanetData['id_owner'] > 0 AND - ( - ($AllMissionsBlocked !== true AND $HeDBRec['onlinetime'] > ($Now - $Protections['idleTime']) AND $HeDBRec['onlinetime'] < $GetSFBData['StartTime']) - OR - ($AllMissionsBlocked === true AND $HeDBRec['onlinetime'] > ($Now - $Protections['idleTime']) AND $HeDBRec['onlinetime'] < $GetSFBData['EndTime']) - )) - { - $BlockFleet = true; - $BlockReason = sprintf($_Lang['SFB_Stop_GlobalPostBlockade'], prettyDate('d m Y, H:i:s', $GetSFBData['PostEndTime'], 1)); - } - } - } - else if($GetSFBData['Type'] == 2) - { - // Per User Blockade - $BlockFleet = true; - $BlockGivenReason = (empty($GetSFBData['Reason']) ? $_Lang['SFB_Stop_ReasonNotGiven'] : "\"{$GetSFBData['Reason']}\""); - $BlockReason = sprintf(($GetSFBData['ElementID'] == $_User['id'] ? $_Lang['SFB_Stop_UserBlockadeOwn'] : $_Lang['SFB_Stop_UserBlockade']), prettyDate('d m Y', $GetSFBData['EndTime'], 1), date('H:i:s', $GetSFBData['EndTime']), $BlockGivenReason); - } - else if($GetSFBData['Type'] == 3) - { - // Per Planet Blockade - $BlockFleet = true; - $BlockGivenReason = (empty($GetSFBData['Reason']) ? $_Lang['SFB_Stop_ReasonNotGiven'] : "\"{$GetSFBData['Reason']}\""); - if($GetSFBData['ElementID'] == $_Planet['id']) - { - $UseLangVar = ($_Planet['planet_type'] == 1 ? $_Lang['SFB_Stop_PlanetBlockadeOwn_Planet'] : $_Lang['SFB_Stop_PlanetBlockadeOwn_Moon']); - } - else - { - $UseLangVar = ($Type == 1 ? $_Lang['SFB_Stop_PlanetBlockade_Planet'] : $_Lang['SFB_Stop_PlanetBlockade_Moon']); - } - $BlockReason = sprintf($UseLangVar, prettyDate('d m Y', $GetSFBData['EndTime'], 1), date('H:i:s', $GetSFBData['EndTime']), $BlockGivenReason); - } - } - - if($BlockFleet === true) - { - message(''.$BlockReason.$_Lang['SFB_Stop_LearnMore'].'', $_Lang['SFB_BoxTitle'], 'galaxy.php', '-1'); - } - } - } - - $CreateMIPAttack = ''; - $CreateMIPAttack .= "INSERT INTO {{table}} SET "; - $CreateMIPAttack .= "`fleet_owner` = {$_User['id']}, "; - $CreateMIPAttack .= "`fleet_mission` = {$Mission}, "; - $CreateMIPAttack .= "`fleet_amount` = {$Missiles}, "; - $CreateMIPAttack .= "`fleet_array` = '503,{$Missiles};primary_target,{$PrimTarget}', "; - $CreateMIPAttack .= "`fleet_start_time` = (UNIX_TIMESTAMP() + {$FlightTime}), "; - $CreateMIPAttack .= "`fleet_start_id` = {$_Planet['id']}, "; - $CreateMIPAttack .= "`fleet_start_galaxy` = {$_Planet['galaxy']}, "; - $CreateMIPAttack .= "`fleet_start_system` = {$_Planet['system']}, "; - $CreateMIPAttack .= "`fleet_start_planet` = {$_Planet['planet']}, "; - $CreateMIPAttack .= "`fleet_start_type` = 1, "; - $CreateMIPAttack .= "`fleet_end_time` = (UNIX_TIMESTAMP() + {$FlightTime}), "; - $CreateMIPAttack .= "`fleet_end_id` = {$PlanetData['id']}, "; - $CreateMIPAttack .= "`fleet_end_id_galaxy` = {$PlanetData['galaxy_id']}, "; - $CreateMIPAttack .= "`fleet_end_galaxy` = {$Galaxy}, "; - $CreateMIPAttack .= "`fleet_end_system` = {$System}, "; - $CreateMIPAttack .= "`fleet_end_planet` = {$Planet}, "; - $CreateMIPAttack .= "`fleet_end_type` = 1, "; - $CreateMIPAttack .= "`fleet_target_owner` = '{$PlanetData['id_owner']}', "; - $CreateMIPAttack .= "`fleet_send_time` = UNIX_TIMESTAMP();"; - doquery($CreateMIPAttack, 'fleets'); - - $LastFleetID = doquery("SELECT LAST_INSERT_ID() as `id`;", '', true); - $LastFleetID = $LastFleetID['id']; - - doquery("UPDATE {{table}} SET `interplanetary_missile` = `interplanetary_missile` - {$Missiles} WHERE `id` = {$_Planet['id']};", 'planets'); - - $QryArchive = ''; - $QryArchive .= "INSERT INTO {{table}} SET "; - $QryArchive .= "`Fleet_ID` = {$LastFleetID}, "; - $QryArchive .= "`Fleet_Owner` = {$_User['id']}, "; - $QryArchive .= "`Fleet_Mission` = 10, "; - $QryArchive .= "`Fleet_Array` = '503,{$Missiles};primary_target,{$PrimTarget}', "; - $QryArchive .= "`Fleet_Time_Send` = UNIX_TIMESTAMP(), "; - $QryArchive .= "`Fleet_Time_Start` = (UNIX_TIMESTAMP() + {$FlightTime}), "; - $QryArchive .= "`Fleet_Start_ID` = {$_Planet['id']}, "; - $QryArchive .= "`Fleet_Start_Galaxy` = {$_Planet['galaxy']}, "; - $QryArchive .= "`Fleet_Start_System` = {$_Planet['system']}, "; - $QryArchive .= "`Fleet_Start_Planet` = {$_Planet['planet']}, "; - $QryArchive .= "`Fleet_Start_Type` = {$_Planet['planet_type']}, "; - $QryArchive .= "`Fleet_End_ID` = '{$PlanetData['id']}', "; - $QryArchive .= "`Fleet_End_ID_Galaxy` = '{$PlanetData['galaxy_id']}', "; - $QryArchive .= "`Fleet_End_Galaxy` = {$Galaxy}, "; - $QryArchive .= "`Fleet_End_System` = {$System}, "; - $QryArchive .= "`Fleet_End_Planet` = {$Planet}, "; - $QryArchive .= "`Fleet_End_Type` = 1, "; - $QryArchive .= "`Fleet_End_Owner` = '{$PlanetData['id_owner']}' "; - doquery($QryArchive, 'fleet_archive'); - - // User Development Log - $UserDev_Log[] = array('PlanetID' => $_Planet['id'], 'Date' => $Now, 'Place' => 11, 'Code' => '0', 'ElementID' => $LastFleetID, 'AdditionalData' => 'R,'.$Missiles); - // --- - - $FlyingFleets += 1; - $_Planet['interplanetary_missile'] -= $Missiles; - CreateReturn('600_4', 1); - -?> \ No newline at end of file + $Now) ? 2 : 0); +if($FlyingFleets >= $MaxFleets) +{ + CreateReturn('609'); +} + +$protection = $_GameConfig['noobprotection']; +$protectiontime = $_GameConfig['noobprotectiontime']; +$protectionmulti = $_GameConfig['noobprotectionmulti']; +$adminprotection = $_GameConfig['adminprotection']; +$allyprotection = $_GameConfig['allyprotection']; +$noNoobProtect = $_GameConfig['no_noob_protect']; +$noIdleProtect = $_GameConfig['no_idle_protect']; +$Protections['idleTime'] = $_GameConfig['no_idle_protect'] * TIME_DAY; + +$Galaxy = (isset($_POST['galaxy']) ? intval($_POST['galaxy']) : 0); +$System = (isset($_POST['system']) ? intval($_POST['system']) : 0); +$Planet = (isset($_POST['planet']) ? intval($_POST['planet']) : 0); +$Type = 1; + +$Mission = 10; +$Missiles = (isset($_POST['count']) ? round(str_replace('.', '', $_POST['count'])) : 0); +$PrimTarget = (isset($_POST['target']) ? intval($_POST['target']) : 0); +if($PrimTarget == 0) +{ + $PrimTarget = '0'; +} + +$Dist = abs($System - $_Planet['system']); +include($_EnginePath.'includes/functions/GetMissileRange.php'); +$MissilesRange = GetMissileRange(); +$FlightTime = round(((30 + (60 * $Dist)) * 2500) / $_GameConfig['game_speed']); + +if($Missiles <= 0) +{ + CreateReturn('651'); +} +if($Galaxy <= 0 OR $Planet <= 0 OR $System <= 0 OR $PrimTarget < 0 OR $PrimTarget > 99) +{ + CreateReturn('652'); +} +if($_Planet['missile_silo'] < 4) +{ + CreateReturn('649'); +} +if($MissilesRange <= 0) +{ + CreateReturn('648'); +} +if($Dist > $MissilesRange OR $Galaxy != $_Planet['galaxy']) +{ + CreateReturn('647'); +} +if($Missiles > $_Planet['interplanetary_missile']) +{ + CreateReturn('646', '1'); +} + +$Query_GetPlanet = ''; +$Query_GetPlanet .= "SELECT `pl`.`id`, `pl`.`id_owner`, `galaxy`.`galaxy_id` FROM {{table}} AS `pl` "; +$Query_GetPlanet .= "LEFT JOIN `{{prefix}}galaxy` AS `galaxy` ON `galaxy`.`id_planet` = `pl`.`id` "; +$Query_GetPlanet .= "WHERE `pl`.`galaxy` = {$Galaxy} AND `pl`.`system` = {$System} AND `pl`.`planet` = {$Planet} AND `pl`.`planet_type` = {$Type} "; +$Query_GetPlanet .= "LIMIT 1; -- SendMissiles|GetPlanet"; +$PlanetData = doquery($Query_GetPlanet, 'planets', true); + +if($PlanetData['id'] <= 0) +{ + CreateReturn('650'); +} +if($PlanetData['id_owner'] == $_User['id']) +{ + CreateReturn('645'); +} + +if($PlanetData['id_owner'] > 0) +{ + $Query_GetUser = ''; + $Query_GetUser .= "SELECT `usr`.`is_onvacation`, `usr`.`is_banned`, `usr`.`ally_id`, `usr`.`first_login`, `usr`.`NoobProtection_EndTime`, `usr`.`onlinetime`, `usr`.`authlevel`, "; + $Query_GetUser .= "`stat`.`total_points`, `stat`.`total_rank` "; + $Query_GetUser .= "FROM {{table}} AS `usr` "; + $Query_GetUser .= "LEFT JOIN `{{prefix}}statpoints` AS `stat` ON `stat`.`stat_type` = 1 AND `stat`.`id_owner` = `usr`.`id` "; + $Query_GetUser .= "WHERE `usr`.`id` = {$PlanetData['id_owner']} LIMIT 1; -- SendMissiles|GetUser"; + $HeDBRec = doquery($Query_GetUser, 'users', true); + + if(isOnVacation($HeDBRec)) + { + if($HeDBRec['is_banned'] == 1) + { + CreateReturn('642'); + } + else + { + CreateReturn('643'); + } + } + if($allyprotection == 1) + { + if($_User['ally_id'] > 0 AND $_User['ally_id'] == $HeDBRec['ally_id']) + { + CreateReturn('644'); + } + } + + if(!CheckAuth('programmer')) + { + $MyGameLevel = $_User['total_points']; + } + else + { + $MyGameLevel = $HeDBRec['total_points']; + if($_User['total_rank'] <= 0) + { + $_User['total_rank'] = $HeDBRec['total_rank']; + } + } + $HeGameLevel = $HeDBRec['total_points']; + + if($protection == 1) + { + if($_User['total_rank'] < 1) + { + CreateReturn('663'); + } + if($HeDBRec['total_rank'] < 1) + { + CreateReturn('662'); + } + + if($_User['NoobProtection_EndTime'] > $Now) + { + CreateReturn('653'); + } + else if($HeDBRec['first_login'] == 0) + { + CreateReturn('655'); + } + else if($HeDBRec['NoobProtection_EndTime'] > $Now) + { + CreateReturn('654'); + } + + if($HeDBRec['onlinetime'] >= ($Now - (TIME_DAY * $noIdleProtect))) + { + if($HeGameLevel < ($protectiontime * 1000)) + { + CreateReturn('656'); + } + else if($MyGameLevel < ($protectiontime * 1000)) + { + CreateReturn('657'); + } + else + { + if($MyGameLevel < ($noNoobProtect * 1000) OR $HeGameLevel < ($noNoobProtect * 1000)) + { + if(($MyGameLevel > ($HeGameLevel * $protectionmulti))) + { + CreateReturn('656'); + } + else if(($MyGameLevel * $protectionmulti) < $HeGameLevel) + { + CreateReturn('658'); + } + } + } + } + } + if((CheckAuth('supportadmin') OR CheckAuth('supportadmin', AUTHCHECK_NORMAL, $HeDBRec)) AND $adminprotection == 1) + { + if(CheckAuth('supportadmin')) + { + CreateReturn('659'); + } + else + { + CreateReturn('660'); + } + } +} + +// Fleet Blockade System +$SFBSelectWhere[] = "(`Type` = 1 AND (`EndTime` > UNIX_TIMESTAMP() OR `PostEndTime` > UNIX_TIMESTAMP()))"; +if($PlanetData['id_owner'] > 0) +{ + $SFBSelectWhere[] = "(`Type` = 2 AND `ElementID` = {$PlanetData['id_owner']} AND `EndTime` > UNIX_TIMESTAMP())"; +} +$SFBSelectWhere[] = "(`Type` = 3 AND `ElementID` = {$PlanetData['id']} AND `EndTime` > UNIX_TIMESTAMP())"; +$SFBSelectWhere[] = "(`Type` = 2 AND `ElementID` = {$_User['id']} AND `EndTime` > UNIX_TIMESTAMP())"; +$SFBSelectWhere[] = "(`Type` = 3 AND `ElementID` = {$_Planet['id']} AND `EndTime` > UNIX_TIMESTAMP())"; + +$SFBSelect = ''; +$SFBSelect .= "SELECT `Type`, `BlockMissions`, `Reason`, `StartTime`, `EndTime`, `PostEndTime`, `ElementID`, `DontBlockIfIdle` FROM {{table}} WHERE `StartTime` <= UNIX_TIMESTAMP() AND "; +$SFBSelect .= implode(' OR ', $SFBSelectWhere); +$SFBSelect .= " ORDER BY `Type` ASC, `EndTime` DESC;"; + +$LoadSFBData = doquery($SFBSelect, 'smart_fleet_blockade'); +if(mysql_num_rows($LoadSFBData) > 0) +{ + while($GetSFBData = mysql_fetch_assoc($LoadSFBData)) + { + $BlockedMissions = false; + if($GetSFBData['BlockMissions'] == '0') + { + $BlockedMissions = true; + $AllMissionsBlocked = true; + } + else + { + $BlockedMissions = explode(',', $GetSFBData['BlockMissions']); + } + + if($BlockedMissions === true OR in_array($Mission, $BlockedMissions)) + { + if($GetSFBData['Type'] == 1) + { + // Global Blockade + if($GetSFBData['EndTime'] > $Now) + { + // Normal Blockade + if(!($GetSFBData['DontBlockIfIdle'] == 1 AND in_array($Mission, $_Vars_FleetMissions['military']) AND $PlanetData['id_owner'] > 0 AND $HeDBRec['onlinetime'] <= ($Now - $Protections['idleTime']))) + { + $BlockFleet = true; + $BlockReason = $_Lang['SFB_Stop_GlobalBlockade']; + } + } + else if($GetSFBData['PostEndTime'] > $Now) + { + // Post Blockade + if(in_array($Mission, $_Vars_FleetMissions['military']) AND $PlanetData['id_owner'] > 0 AND + ( + ($AllMissionsBlocked !== true AND $HeDBRec['onlinetime'] > ($Now - $Protections['idleTime']) AND $HeDBRec['onlinetime'] < $GetSFBData['StartTime']) + OR + ($AllMissionsBlocked === true AND $HeDBRec['onlinetime'] > ($Now - $Protections['idleTime']) AND $HeDBRec['onlinetime'] < $GetSFBData['EndTime']) + )) + { + $BlockFleet = true; + $BlockReason = sprintf($_Lang['SFB_Stop_GlobalPostBlockade'], prettyDate('d m Y, H:i:s', $GetSFBData['PostEndTime'], 1)); + } + } + } + else if($GetSFBData['Type'] == 2) + { + // Per User Blockade + $BlockFleet = true; + $BlockGivenReason = (empty($GetSFBData['Reason']) ? $_Lang['SFB_Stop_ReasonNotGiven'] : "\"{$GetSFBData['Reason']}\""); + $BlockReason = sprintf(($GetSFBData['ElementID'] == $_User['id'] ? $_Lang['SFB_Stop_UserBlockadeOwn'] : $_Lang['SFB_Stop_UserBlockade']), prettyDate('d m Y', $GetSFBData['EndTime'], 1), date('H:i:s', $GetSFBData['EndTime']), $BlockGivenReason); + } + else if($GetSFBData['Type'] == 3) + { + // Per Planet Blockade + $BlockFleet = true; + $BlockGivenReason = (empty($GetSFBData['Reason']) ? $_Lang['SFB_Stop_ReasonNotGiven'] : "\"{$GetSFBData['Reason']}\""); + if($GetSFBData['ElementID'] == $_Planet['id']) + { + $UseLangVar = ($_Planet['planet_type'] == 1 ? $_Lang['SFB_Stop_PlanetBlockadeOwn_Planet'] : $_Lang['SFB_Stop_PlanetBlockadeOwn_Moon']); + } + else + { + $UseLangVar = ($Type == 1 ? $_Lang['SFB_Stop_PlanetBlockade_Planet'] : $_Lang['SFB_Stop_PlanetBlockade_Moon']); + } + $BlockReason = sprintf($UseLangVar, prettyDate('d m Y', $GetSFBData['EndTime'], 1), date('H:i:s', $GetSFBData['EndTime']), $BlockGivenReason); + } + } + + if($BlockFleet === true) + { + message(''.$BlockReason.$_Lang['SFB_Stop_LearnMore'].'', $_Lang['SFB_BoxTitle'], 'galaxy.php', '-1'); + } + } +} + +$CreateMIPAttack = ''; +$CreateMIPAttack .= "INSERT INTO {{table}} SET "; +$CreateMIPAttack .= "`fleet_owner` = {$_User['id']}, "; +$CreateMIPAttack .= "`fleet_mission` = {$Mission}, "; +$CreateMIPAttack .= "`fleet_amount` = {$Missiles}, "; +$CreateMIPAttack .= "`fleet_array` = '503,{$Missiles};primary_target,{$PrimTarget}', "; +$CreateMIPAttack .= "`fleet_start_time` = (UNIX_TIMESTAMP() + {$FlightTime}), "; +$CreateMIPAttack .= "`fleet_start_id` = {$_Planet['id']}, "; +$CreateMIPAttack .= "`fleet_start_galaxy` = {$_Planet['galaxy']}, "; +$CreateMIPAttack .= "`fleet_start_system` = {$_Planet['system']}, "; +$CreateMIPAttack .= "`fleet_start_planet` = {$_Planet['planet']}, "; +$CreateMIPAttack .= "`fleet_start_type` = 1, "; +$CreateMIPAttack .= "`fleet_end_time` = (UNIX_TIMESTAMP() + {$FlightTime}), "; +$CreateMIPAttack .= "`fleet_end_id` = {$PlanetData['id']}, "; +$CreateMIPAttack .= "`fleet_end_id_galaxy` = {$PlanetData['galaxy_id']}, "; +$CreateMIPAttack .= "`fleet_end_galaxy` = {$Galaxy}, "; +$CreateMIPAttack .= "`fleet_end_system` = {$System}, "; +$CreateMIPAttack .= "`fleet_end_planet` = {$Planet}, "; +$CreateMIPAttack .= "`fleet_end_type` = 1, "; +$CreateMIPAttack .= "`fleet_target_owner` = '{$PlanetData['id_owner']}', "; +$CreateMIPAttack .= "`fleet_send_time` = UNIX_TIMESTAMP();"; +doquery($CreateMIPAttack, 'fleets'); + +$LastFleetID = doquery("SELECT LAST_INSERT_ID() as `id`;", '', true); +$LastFleetID = $LastFleetID['id']; + +doquery("UPDATE {{table}} SET `interplanetary_missile` = `interplanetary_missile` - {$Missiles} WHERE `id` = {$_Planet['id']};", 'planets'); + +$QryArchive = ''; +$QryArchive .= "INSERT INTO {{table}} SET "; +$QryArchive .= "`Fleet_ID` = {$LastFleetID}, "; +$QryArchive .= "`Fleet_Owner` = {$_User['id']}, "; +$QryArchive .= "`Fleet_Mission` = 10, "; +$QryArchive .= "`Fleet_Array` = '503,{$Missiles};primary_target,{$PrimTarget}', "; +$QryArchive .= "`Fleet_Time_Send` = UNIX_TIMESTAMP(), "; +$QryArchive .= "`Fleet_Time_Start` = (UNIX_TIMESTAMP() + {$FlightTime}), "; +$QryArchive .= "`Fleet_Start_ID` = {$_Planet['id']}, "; +$QryArchive .= "`Fleet_Start_Galaxy` = {$_Planet['galaxy']}, "; +$QryArchive .= "`Fleet_Start_System` = {$_Planet['system']}, "; +$QryArchive .= "`Fleet_Start_Planet` = {$_Planet['planet']}, "; +$QryArchive .= "`Fleet_Start_Type` = {$_Planet['planet_type']}, "; +$QryArchive .= "`Fleet_End_ID` = '{$PlanetData['id']}', "; +$QryArchive .= "`Fleet_End_ID_Galaxy` = '{$PlanetData['galaxy_id']}', "; +$QryArchive .= "`Fleet_End_Galaxy` = {$Galaxy}, "; +$QryArchive .= "`Fleet_End_System` = {$System}, "; +$QryArchive .= "`Fleet_End_Planet` = {$Planet}, "; +$QryArchive .= "`Fleet_End_Type` = 1, "; +$QryArchive .= "`Fleet_End_Owner` = '{$PlanetData['id_owner']}' "; +doquery($QryArchive, 'fleet_archive'); + +// User Development Log +$UserDev_Log[] = array('PlanetID' => $_Planet['id'], 'Date' => $Now, 'Place' => 11, 'Code' => '0', 'ElementID' => $LastFleetID, 'AdditionalData' => 'R,'.$Missiles); +// --- + +$FlyingFleets += 1; +$_Planet['interplanetary_missile'] -= $Missiles; +CreateReturn('600_4', 1); + +?> diff --git a/alliance.php b/alliance.php index f66a93a74..af4847061 100644 --- a/alliance.php +++ b/alliance.php @@ -1,2640 +1,2641 @@ -'; - } - if(!empty($AllyRow['ally_description'])) - { - $_Lang['ally_description'] = nl2br(bbcode(stripslashes($AllyRow['ally_description']))); - } - else - { - $_Lang['ally_description'] = $_Lang['AInfo_NoAllyDesc']; - } - if(!empty($AllyRow['ally_web']) && ($AllyRow['ally_web_reveal'] == 1 || $_User['ally_id'] == $AllyRow['id'])) - { - $AllyRow['ally_web'] = stripslashes($AllyRow['ally_web']); - $_Lang['ally_web'] = "{$_Lang['AInfo_WebPage']}{$AllyRow['ally_web']}"; - } - $_Lang['ally_members'] = $AllyRow['ally_members']; - $_Lang['ally_name']= $AllyRow['ally_name']; - $_Lang['ally_tag'] = $AllyRow['ally_tag']; - - if($_User['ally_id'] == 0) - { - if($AllyRow['ally_request_notallow'] == 0) - { - $_Lang['Insert_Actions'] = "
"; - } - else - { - $_Lang['Insert_Actions'] = "{$_Lang['AInfo_RequestNotAllow']}"; - } - } - else if($_User['ally_id'] > 0 && $_User['ally_id'] == $AllyRow['id']) - { - $_Lang['Insert_Actions'] = "{$_Lang['AInfo_BelongToAlly']}"; - } - - $Page = parsetemplate(gettemplate('alliance_ainfo'), $_Lang); - display($Page, $_Lang['Alliance_information']); - } - // End of Ally Informations - - // --- Alliance Control - if($_User['ally_id'] == 0) - { - // User has no Ally - if(isOnVacation()) - { - message($_Lang['Vacation_WarnMsg'], $_Lang['Vacation']); - } - if($_User['ally_request'] == 0) - { - // User has no any Request - if($mode == 'make') - { - // User wants to Make alliance - if(isset($_GET['yes'])) - { - // User sent data - $MsgTitle = &$_Lang['AMake_Title']; - - $CreateTag = trim($_POST['atag']); - $CreateName = trim($_POST['aname']); - $TagLength = strlen($CreateTag); - $NameLength = strlen($CreateName); - // Data checking - if($TagLength < $_MinLength_ATag) - { - message($_Lang['AMake_TagShort'], $MsgTitle, 'alliance.php?mode=make', 3); - } - if($TagLength > $_MaxLength_ATag) - { - message($_Lang['AMake_TagLong'], $MsgTitle, 'alliance.php?mode=make', 3); - } - if(!preg_match(REGEXP_ALLYTAG_ABSOLUTE, $CreateTag)) - { - message($_Lang['AMake_BadTag'], $MsgTitle, 'alliance.php?mode=make', 3); - } - if($NameLength < 1) - { - message($_Lang['AMake_NoName'], $MsgTitle, 'alliance.php?mode=make', 3); - } - if($NameLength > $_MaxLength_AName) - { - message($_Lang['AMake_NameLong'], $MsgTitle, 'alliance.php?mode=make', 3); - } - if(!preg_match(REGEXP_ALLYNAME_ABSOLUTE, $CreateName)) - { - message($_Lang['AMake_BadName'], $MsgTitle, 'alliance.php?mode=make', 3); - } - - $Query_ACreate_Check = ''; - $Query_ACreate_Check .= "SELECT `ally_tag`, `ally_name` FROM {{table}} "; - $Query_ACreate_Check .= "WHERE `ally_tag` = '{$CreateTag}' OR `ally_name` = '{$CreateName}' LIMIT 2;"; - - $Result_ACreate_Check = doquery($Query_ACreate_Check, 'alliance'); - $WarningBox = array(); - if(mysql_num_rows($Result_ACreate_Check)) - { - while($checkData = mysql_fetch_assoc($Result_ACreate_Check)) - { - if(strtolower($checkData['ally_tag']) == strtolower($CreateTag)) - { - $WarningBox[] = sprintf($_Lang['AMake_TagExists'], $CreateTag); - } - if(strtolower($checkData['ally_name']) == strtolower($CreateName)) - { - $WarningBox[] = sprintf($_Lang['AMake_NameExists'], $CreateName); - } - } - } - if(!empty($WarningBox)) - { - message(implode('
', $WarningBox), $MsgTitle, 'alliance.php?mode=make', 3); - } - - $RankDataLabelsCount = count($RankDataLabels) - 1; - $AllyCreate_Ranks = array(array('name' => $_Lang['AMake_AllyLeader'], 'vals' => true), array('name' => $_Lang['AMake_AllyNewComer'], 'vals' => false)); - foreach($AllyCreate_Ranks as $ThisRowData) - { - $ThisArray = array_fill(1, $RankDataLabelsCount, $ThisRowData['vals']); - $ThisArray = array_merge(array($ThisRowData['name']), $ThisArray); - $AllyCreate_RanksArray[] = $ThisArray; - } - $AllyCreate_RanksArray = mysql_real_escape_string(json_encode($AllyCreate_RanksArray)); - - $Query_ACreate_Create = ''; - $Query_ACreate_Create .= "INSERT INTO {{table}} SET "; - $Query_ACreate_Create .= "`ally_name` = '{$CreateName}', "; - $Query_ACreate_Create .= "`ally_tag`= '{$CreateTag}', "; - $Query_ACreate_Create .= "`ally_owner` = {$_User['id']}, "; - $Query_ACreate_Create .= "`ally_ranks` = '{$AllyCreate_RanksArray}', "; - $Query_ACreate_Create .= "`ally_members` = 1, "; - $Query_ACreate_Create .= "`ally_register_time` = UNIX_TIMESTAMP();"; - doquery($Query_ACreate_Create, 'alliance'); - - $Result_GetLastID = doquery("SELECT LAST_INSERT_ID() AS `ID`;", 'alliance', true); - $Result_GetLastID = $Result_GetLastID['ID']; - - $Query_ACreate_MakeChatRoom = ''; - $Query_ACreate_MakeChatRoom .= "INSERT INTO {{table}} SET "; - $Query_ACreate_MakeChatRoom .= "`AccessType` = 1, "; - $Query_ACreate_MakeChatRoom .= "`AccessCheck` = {$Result_GetLastID};"; - doquery($Query_ACreate_MakeChatRoom, 'chat_rooms'); - - $Query_ACreate_UpdateAlly = ''; - $Query_ACreate_UpdateAlly .= "UPDATE {{table}} SET `ally_ChatRoom_ID` = LAST_INSERT_ID() "; - $Query_ACreate_UpdateAlly .= "WHERE `id` = {$Result_GetLastID} LIMIT 1;"; - doquery($Query_ACreate_UpdateAlly, 'alliance'); - - $Query_ACreate_UpdateUser = ''; - $Query_ACreate_UpdateUser .= "UPDATE {{table}} SET "; - $Query_ACreate_UpdateUser .= "`ally_id` = {$Result_GetLastID}, "; - $Query_ACreate_UpdateUser .= "`ally_register_time` = UNIX_TIMESTAMP() "; - $Query_ACreate_UpdateUser .= "WHERE `id` = {$_User['id']};"; - doquery($Query_ACreate_UpdateUser, 'users'); - - CheckJobsDone('BUDDY_OR_ALLY_TASK', $_User['id']); - - message(sprintf($_Lang['AMake_Done'], $CreateName, $CreateTag), $MsgTitle, 'alliance.php', 3); - } - else - { - // Show Form - $Page = parsetemplate(gettemplate('alliance_make'), $_Lang); - display($Page, $_Lang['AMake_Title']); - } - } - else if($mode == 'search') - { - // Ally search engine - $searchText = null; - if(!empty($_POST['searchtext'])) - { - $searchText = trim($_POST['searchtext']); - } - else if(!empty($_GET['searchtext'])) - { - $searchText = trim($_GET['searchtext']); - } - $_Lang['searchtext'] = $searchText; - $ProtectedSearchText = preg_replace($Sanitize4SQLSearch, $Sanitize4SQLReplace, $searchText); - - // Show Form - $Page = parsetemplate(gettemplate('alliance_searchform'), $_Lang); - - if(!empty($searchText)) - { - if(!preg_match(REGEXP_ALLYNAMEANDTAG, $searchText)) - { - message($_Lang['AFind_BadSigns'], $_Lang['AFind_Title'], 'alliance.php?mode=search', 3); - } - - $sPage = (isset($_GET['spage']) ? intval($_GET['spage']) : 0); - if($sPage < 1) - { - $sPage = 1; - } - $perPage = 20; - $startFrom = ($sPage - 1) * $perPage; - - $Query_ASearch_Count = ''; - $Query_ASearch_Count .= "SELECT COUNT(*) AS `Count` FROM {{table}} "; - $Query_ASearch_Count .= "WHERE `ally_name` LIKE '%{$ProtectedSearchText}%' OR `ally_tag` LIKE '%{$ProtectedSearchText}%';"; - - $Result_ASearch_Count = doquery($Query_ASearch_Count, 'alliance', true); - $TotalCount = $Result_ASearch_Count['Count']; - - if($TotalCount > 0) - { - if($TotalCount < $startFrom) - { - $sPage = ceil($TotalCount / $perPage); - $startFrom = ($sPage - 1) * $perPage; - } - - $Query_ASearch_Search = ''; - $Query_ASearch_Search .= "SELECT `id`, `ally_tag`, `ally_name`, `ally_members` FROM {{table}} "; - $Query_ASearch_Search .= "WHERE ally_name LIKE '%{$ProtectedSearchText}%' or ally_tag LIKE '%{$ProtectedSearchText}%' LIMIT {$startFrom}, {$perPage};"; - - $Result_ASearch_Search = doquery($Query_ASearch_Search, 'alliance'); - - $SearchRowTPL = gettemplate('alliance_searchresult_row'); - $_Lang['result'] = ''; - while($Result = mysql_fetch_assoc($Result_ASearch_Search)) - { - $SanitizeSearch = preg_replace($TagOrNameSanitize, '\\\$1', $searchText); - $Result['ally_tag'] = preg_replace('#('.$SanitizeSearch.'){1,}#si', '$1', $Result['ally_tag']); - $Result['ally_name'] = preg_replace('#('.$SanitizeSearch.'){1,}#si', '$1', $Result['ally_name']); - $_Lang['result'] .= parsetemplate($SearchRowTPL, $Result); - } - - if($TotalCount > $perPage) - { - include_once($_EnginePath.'includes/functions/Pagination.php'); - $Pagin = CreatePaginationArray($TotalCount, $perPage, $sPage, 7); - $PaginationTPL = "{\$ShowValue}"; - $PaginationViewOpt = array('CurrentPage_Classes' => 'orange', 'Breaker_View' => '...'); - $CreatePagination = implode(' ', ParsePaginationArray($Pagin, $sPage, $PaginationTPL, $PaginationViewOpt)); - - $pagination = ''.$CreatePagination.''; - $_Lang['pagination'] = $pagination; - } - } - else - { - $_Lang['result'] = "{$_Lang['AFind_NothingFound']}"; - } - $Page .= parsetemplate(gettemplate('alliance_searchresult_table'), $_Lang); - } - display($Page, $_Lang['AFind_Title']); - } - else if($mode == 'apply') - { - // Send Request - $MsgTitle = &$_Lang['AApp_Title']; - - $AllyID = (isset($_GET['allyid']) ? intval($_GET['allyid']) : 0); - if($AllyID <= 0) - { - message($_Lang['AApp_BadID'], $MsgTitle); - } - - $Query_AApply_Check = ''; - $Query_AApply_Check .= "SELECT `id`, `ally_name`, `ally_tag`, `ally_request`, `ally_request_notallow` FROM {{table}} "; - $Query_AApply_Check .= "WHERE `id` = {$AllyID} LIMIT 1;"; - - $Result_AApply_Check = doquery($Query_AApply_Check, 'alliance', true); - if($Result_AApply_Check['id'] != $AllyID) - { - message($_Lang['AApp_AllyNoExists'], $MsgTitle); - } - if($Result_AApply_Check['ally_request_notallow'] == 1) - { - message($_Lang['AApp_AllyBlockRequest'], $MsgTitle); - } - - if(isset($_POST['send']) && $_POST['send'] == 'yes' && (!isset($_POST['action']) || $_POST['action'] != $_Lang['AApp_UseExample'])) - { - $RequestText = strip_tags(stripslashes(trim($_POST['text']))); - if(!empty($RequestText)) - { - $RequestText = mysql_real_escape_string(substr($RequestText, 0, $_MaxLength_Request)); - doquery("UPDATE {{table}} SET `ally_request` = {$AllyID}, `ally_request_text` = '{$RequestText}', `ally_register_time` = UNIX_TIMESTAMP() WHERE `id` = {$_User['id']};", 'users'); - message($_Lang['AApp_Done'], $MsgTitle, 'alliance.php', 3); - } - else - { - message($_Lang['AApp_NoText'], $MsgTitle, 'alliance.php?mode=apply&allyid='.$AllyID, 3); - } - } - - $text_apply = ($Result_AApply_Check['ally_request'] ? stripslashes($Result_AApply_Check['ally_request']) : $_Lang['AApp_NoSample']); - - $_Lang['allyid'] = $AllyID; - $_Lang['text_apply'] = $text_apply; - $_Lang['Write_to_alliance'] = sprintf($_Lang['AApp_WriteRequest'], $Result_AApply_Check['ally_name'], $Result_AApply_Check['ally_tag']); - $_Lang['Insert_MaxLength'] = $_MaxLength_Request; - - $Page = parsetemplate(gettemplate('alliance_applyform'), $_Lang); - display($Page, $MsgTitle); - } - else - { - // Show Default Menu & Invites List - - if(isset($_GET['cmd']) && ($_GET['cmd'] == 'inv_accept' || $_GET['cmd'] == 'inv_reject')) - { - $Inv_AllyID = (isset($_GET['aid']) ? intval($_GET['aid']) : 0); - if($Inv_AllyID > 0) - { - $Query_InvUse_Check = ''; - $Query_InvUse_Check .= "SELECT `ai`.`SenderID`, `ally`.`ally_new_rank_id`, `ally`.`ally_ChatRoom_ID`FROM `{{table}}` AS `ai` "; - $Query_InvUse_Check .= "LEFT JOIN `{{prefix}}alliance` AS `ally` ON `ally`.`id` = `ai`.`AllyID` "; - $Query_InvUse_Check .= "WHERE `ai`.`OwnerID` = {$_User['id']} AND `ai`.`AllyID` = {$Inv_AllyID} AND `ai`.`State` = 1;"; - $Result_InvUse_Check = doquery($Query_InvUse_Check, 'ally_invites', true); - if($Result_InvUse_Check['SenderID'] > 0) - { - if($_GET['cmd'] == 'inv_accept') - { - doquery("UPDATE {{table}} SET `ally_request` = 0, `ally_request_text` = '', `ally_id` = {$Inv_AllyID}, `ally_rank_id` = {$Result_InvUse_Check['ally_new_rank_id']}, `ally_register_time` = UNIX_TIMESTAMP() WHERE `id` = {$_User['id']};", 'users'); - doquery("UPDATE {{table}} SET `ally_members` = `ally_members` + 1 WHERE `id` = {$Inv_AllyID};", 'alliance'); - doquery("UPDATE {{table}} SET `State` = IF(`AllyID` = {$Inv_AllyID}, 0, -1) WHERE `OwnerID` = {$_User['id']} AND `State` = 1 LIMIT 1;", 'ally_invites'); - if($Result_InvUse_Check['ally_ChatRoom_ID'] > 0) - { - $Query_UpdateChatRoomOnline = ''; - $Query_UpdateChatRoomOnline .= "INSERT INTO {{table}} VALUES ({$Result_InvUse_Check['ally_ChatRoom_ID']}, {$_User['id']}, UNIX_TIMESTAMP()) "; - $Query_UpdateChatRoomOnline .= "ON DUPLICATE KEY UPDATE "; - $Query_UpdateChatRoomOnline .= "`LastOnline` = VALUES(`LastOnline`);"; - doquery($Query_UpdateChatRoomOnline, 'chat_online'); - } - CheckJobsDone('BUDDY_OR_ALLY_TASK', $_User['id']); - - message($_Lang['AMenu_Inv_MsgAcceptSuccess'], $_Lang['Ally'], 'alliance.php', 3); - } - else - { - doquery("UPDATE {{table}} SET `State` = -1 WHERE `AllyID` = {$Inv_AllyID} AND `OwnerID` = {$_User['id']} AND `State` = 1 LIMIT 1;", 'ally_invites'); - - $MsgBox = array('text' => $_Lang['AMenu_Inv_MsgRejectSuccess'], 'col' => 'lime'); - } - } - else - { - $MsgBox = array('text' => $_Lang['AMenu_Inv_MsgNotFound'], 'col' => 'red'); - } - } - else - { - $MsgBox = array('text' => $_Lang['AMenu_Inv_MsgBadID'], 'col' => 'red'); - } - } - - $Query_InvList_Get = ''; - $Query_InvList_Get .= "SELECT `ai`.*, `u`.`username` AS `Sender_Name`, `a`.`ally_name` AS `Ally_Name` FROM {{table}} AS `ai` "; - $Query_InvList_Get .= "LEFT JOIN `{{prefix}}users` AS `u` ON `u`.`id` = `ai`.`SenderID` "; - $Query_InvList_Get .= "LEFT JOIN `{{prefix}}alliance` AS `a` ON `a`.`id` = `ai`.`AllyID` "; - $Query_InvList_Get .= "WHERE `ai`.`OwnerID` = {$_User['id']} AND `State` != 0 "; - $Query_InvList_Get .= " ORDER BY `ai`.`State` DESC, `ai`.`Date` DESC;"; - $Result_InvList_Get = doquery($Query_InvList_Get, 'ally_invites'); - if(mysql_num_rows($Result_InvList_Get) > 0) - { - $TPL_Row = gettemplate('alliance_defaultmenu_invites_row'); - while($FetchData = mysql_fetch_assoc($Result_InvList_Get)) - { - $FetchData['Date'] = prettyDate('d m Y, H:i:s', $FetchData['Date'], 1); - if($FetchData['State'] == 1) - { - $FetchData['Actions'][] = ""; - $FetchData['Actions'][] = ""; - } - $FetchData['State'] = $_Lang['AMenu_Inv_States'][((string)($FetchData['State'] + 0))]; - - if(!empty($FetchData['Actions'])) - { - $FetchData['Actions'] = implode('', $FetchData['Actions']); - } - else - { - $FetchData['Actions'] = ' '; - } - $_Lang['Insert_InviteRows'][] = parsetemplate($TPL_Row, $FetchData); - } - $_Lang['Insert_InviteRows'] = implode('', $_Lang['Insert_InviteRows']); - } - else - { - $_Lang['Insert_InviteRows'] = parsetemplate(gettemplate('_singleRow'), array('Colspan' => 4, 'Classes' => 'orange pad5', 'Text' => $_Lang['AMenu_Inv_NoRows'])); - } - if(!empty($MsgBox)) - { - $_Lang['MsgBox'] = ''.$MsgBox['text'].''; - } - - $Page = parsetemplate(gettemplate('alliance_defaultmenu'), $_Lang); - display($Page, $_Lang['Ally']); - } - } - else - { - // User has a Request - $MsgTitle = $_Lang['AReq_Title']; - - $Query_ARequest_Get = "SELECT `ally_name`, `ally_tag` FROM {{table}} WHERE `id` = {$_User['ally_request']} LIMIT 1;"; - $Result_ARequest_Get = doquery($Query_ARequest_Get, 'alliance', true); - if(!empty($_POST['cancel'])) - { - // Cancel the Request - doquery("UPDATE {{table}} SET `ally_request` = 0, `ally_request_text` = '', `ally_register_time` = 0 WHERE `id` = {$_User['id']};", 'users'); - message(sprintf($_Lang['AReq_Canceled'], $Result_ARequest_Get['ally_name'], $Result_ARequest_Get['ally_tag']), $MsgTitle, 'alliance.php', 3); - } - $_Lang['RequestText'] = sprintf($_Lang['AReq_Waiting'], $_User['ally_request'], $Result_ARequest_Get['ally_name'], $Result_ARequest_Get['ally_tag']); - $Page = parsetemplate(gettemplate('alliance_apply_waitform'), $_Lang); - display($Page, $MsgTitle); - } - } - elseif($_User['ally_id'] > 0 AND $_User['ally_request'] == 0) - { - // User is in Alliance - $MsgTitle = &$_Lang['Ally_Title']; - - // First, parse AllyData - $Ally = doquery("SELECT * FROM {{table}} WHERE `id` = {$_User['ally_id']} LIMIT 1;", 'alliance', true); - if($Ally['id'] <= 0) - { - doquery("UPDATE {{table}} SET `ally_id` = 0 WHERE `id` = {$_User['id']};", 'users'); - message($_Lang['Ally_GetAllyError'], $MsgTitle); - } - - $Ally['ally_ranks'] = json_decode($Ally['ally_ranks'], true); - $Ally['ally_ranks_org'] = $Ally['ally_ranks']; - foreach($Ally['ally_ranks'] as $RankID => $RankData) - { - foreach($RankData as $DataID => $DataVal) - { - $NewRankArray[$RankID][$RankDataLabels[$DataID]] = $DataVal; - } - } - $Ally['ally_ranks'] = $NewRankArray; - $Ally['ally_ranks_count'] = count($RankDataLabels); - $NewRankArray = null; - - // Check ThisUser Rights - if($Ally['ally_owner'] == $_User['id']) - { - // This User is Main AllyAdmin (Rank #0 is only for him) - $_ThisUserRank = $Ally['ally_ranks'][0]; - $_ThisUserRank['is_admin'] = true; - } - else - { - // This User is not Main AllyAdmin - $_ThisUserRank = $Ally['ally_ranks'][$_User['ally_rank_id']]; - $_ThisUserRank['is_admin'] = false; - } - - if($mode == 'exit') - { - // User is trying to leave the Ally - if(isOnVacation()) - { - message($_Lang['Vacation_WarnMsg'], $_Lang['Vacation']); - } - - if($Ally['ally_owner'] == $_User['id']) - { - message($_Lang['Ally_Leave_MAdminInfo'], $MsgTitle, 'alliance.php', 3); - } - doquery("UPDATE {{table}} SET `ally_id` = 0 WHERE `id` = {$_User['id']};", 'users'); - doquery("UPDATE {{table}} SET `ally_members` = `ally_members` - 1 WHERE `id` = {$Ally['id']};", 'alliance'); - doquery("UPDATE {{table}} SET `State` = -2 WHERE `State` = 1 AND `SenderID` = {$_User['id']};", 'ally_invites'); - message(sprintf($_Lang['Ally_Leave_Done'], $Ally['ally_name']), $MsgTitle); - } - else if($mode == 'mlist' OR $mode == 'memberslist') - { - // User is trying to view Members List - if($_ThisUserRank['mlist'] !== true) - { - message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php', 3); - } - - createMembersList(); - $Page = parsetemplate(gettemplate('alliance_memberslist_table'), $_Lang); - display($Page, $_Lang['Ally_ML_WinTitle']); - } - else if($mode == 'pactslist') - { - // User is trying to See Ally Pacts - include($_EnginePath.'modules/ally.pactslist.php'); - } - else if($mode == 'newpact') - { - // User is trying to create new Pact - include($_EnginePath.'modules/ally.newpact.php'); - } - else if($mode == 'changepact') - { - // User is trying to modify existing Pact - include($_EnginePath.'modules/ally.changepact.php'); - } - else if($mode == 'circular' OR $mode == 'sendmsg') - { - // User is trying to Send Mass Message (to Ally Members) - if($_ThisUserRank['sendmsg'] !== true) - { - message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php', 3); - } - - $_Lang['SelectedAll'] = 'selected'; - $SendMass_Ranks = null; - $SendMass_Text = null; - if(isset($_GET['send'])) - { - $_POST['text'] = stripslashes(trim($_POST['text'])); - if(get_magic_quotes_gpc()) - { - $_POST['text'] = stripslashes($_POST['text']); - } - $SendMass_Text = substr(strip_tags($_POST['text']), 0, $_MaxLength_Text); - if($_POST['rank_select'] != 'all') - { - $SendMass_Ranks = intval($_POST['rank_select']); - if(empty($Ally['ally_ranks'][$SendMass_Ranks]['name'])) - { - $SendMass_Ranks = null; - } - } - else - { - $_Lang['SelectedAll'] = 'selected'; - $SendMass_Ranks = true; - } - if(!empty($SendMass_Text)) - { - if($SendMass_Ranks !== null) - { - $Query_AMassMsg_Members = ''; - $Query_AMassMsg_Members .= "SELECT `id`, `username` FROM {{table}} "; - $Query_AMassMsg_Members .= "WHERE `ally_id` = {$_User['ally_id']} "; - if($SendMass_Ranks !== true) - { - $Query_AMassMsg_Members .= " AND `ally_rank_id` = {$SendMass_Ranks}"; - } - $Result_AMassMsg_Members = doquery($Query_AMassMsg_Members, 'users'); - - if(mysql_num_rows($Result_AMassMsg_Members) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_AMassMsg_Members)) - { - $UsersID[] = $FetchData['id']; - $UsersNicks[] = $FetchData['username']; - } - - $FirstMSGID = SendSimpleMessage($UsersID[0], $_User['id'], $Time, 2, "[{$Ally['ally_tag']}]", $_Lang['Ally_WR_Subject'].$_User['username'], $SendMass_Text, true); - unset($UsersID[0]); - if(!empty($UsersID)) - { - Cache_Message($UsersID, $_User['id'], $Time, 2, '', '', '{COPY_MSG_#'.$FirstMSGID.'}'); - } - $MsgBox = array('text' => $_Lang['Ally_WR_Done'].implode(', ', $UsersNicks), 'col' => 'lime'); - } - else - { - $MsgBox = array('text' => $_Lang['Ally_WR_RankHasNoUsers'], 'col' => 'red'); - } - } - else - { - $MsgBox = array('text' => $_Lang['Ally_WR_NoRankSelect'], 'col' => 'red'); - } - } - else - { - $MsgBox = array('text' => $_Lang['Ally_WR_MsgEmpty'], 'col' => 'red'); - } - } - - if(!empty($MsgBox)) - { - $_Lang['MsgBox'] = ''.$MsgBox['text'].''; - } - - $_Lang['PutMessage'] = $SendMass_Text; - $_Lang['OtherRanks'] = ''; - foreach($Ally['ally_ranks'] as $Index => $Data) - { - if($SendMass_Ranks === $Index) - { - $ThisSelected = 'selected'; - } - else - { - $ThisSelected = ''; - } - $_Lang['OtherRanks'] .= ""; - } - - $_Lang['Insert_MaxLength'] = $_MaxLength_MassMsg; - $Page = parsetemplate(gettemplate('alliance_circular'), $_Lang); - display($Page, $_Lang['Ally_WR_WinTitle']); - } - else if($mode == 'invite') - { - // User is trying to Invite someone - if($_ThisUserRank['caninvite'] !== true) - { - message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php', 3); - } - - $Invite_Text = (isset($_POST['text']) ? stripslashes(strip_tags(trim($_POST['text']))) : null); - $_Lang['Insert_Text'] = $Invite_Text; - if(!empty($_GET['uid']) || (!empty($_POST['uid']) && $_POST['unamechanged'] != '1')) - { - if(!empty($_POST['uid'])) - { - $Invite_UID = intval($_POST['uid']); - } - else - { - $Invite_UID = intval($_GET['uid']); - $Invite_FromGet = true; - } - if($Invite_UID > 0) - { - $Query_AInvite_CheckUserWhere = "`id` = {$Invite_UID}"; - } - } - else if(!empty($_POST['username'])) - { - $Invite_UName = trim($_POST['username']); - if(preg_match(REGEXP_USERNAME_ABSOLUTE, $Invite_UName)) - { - $Query_AInvite_CheckUserWhere = "`username` = '{$Invite_UName}'"; - } - } - - if(!empty($Query_AInvite_CheckUserWhere)) - { - $Query_AInvite_CheckUser = "SELECT `id`, `username`, `ally_id` FROM {{table}} WHERE {$Query_AInvite_CheckUserWhere} LIMIT 1;"; - $Result_AInvite_CheckUser = doquery($Query_AInvite_CheckUser, 'users', true); - if($Result_AInvite_CheckUser['id'] > 0) - { - if($Result_AInvite_CheckUser['ally_id'] == 0) - { - $_Lang['Insert_UID'] = $Invite_UID = $Result_AInvite_CheckUser['id']; - $_Lang['Insert_Username'] = $Result_AInvite_CheckUser['username']; - if(isset($Invite_FromGet)) - { - $_Lang['Insert_LockUsername'] = 'disabled'; - } - - if($_GET['send'] == '1') - { - if(!empty($Invite_Text)) - { - $Invite_Text = substr($Invite_Text, 0, $_MaxLength_Invitation); - - $Query_AInvite_CheckInvite = ''; - $Query_AInvite_CheckInvite .= "SELECT COUNT(*) AS `Count` FROM {{table}} WHERE "; - $Query_AInvite_CheckInvite .= "`AllyID` = {$Ally['id']} AND `OwnerID` = {$Invite_UID} AND `State` = 1;"; - $Result_AInvite_CheckInvite = doquery($Query_AInvite_CheckInvite, 'ally_invites', true); - if($Result_AInvite_CheckInvite['Count'] <= 0) - { - $Query_AInvite_Insert = ''; - $Query_AInvite_Insert .= "INSERT INTO {{table}} (`AllyID`, `OwnerID`, `SenderID`, `Date`) VALUES "; - $Query_AInvite_Insert .= "({$Ally['id']}, {$Invite_UID}, {$_User['id']}, UNIX_TIMESTAMP()) "; - $Query_AInvite_Insert .= "ON DUPLICATE KEY UPDATE `AllyID` = `AllyID`;"; - doquery($Query_AInvite_Insert, 'ally_invites'); - - $Message = array(); - $Message['msg_id'] = '095'; - $Message['args'] = array - ( - $Ally['id'], $Ally['ally_name'], $Ally['ally_tag'], $_User['id'], $_User['username'], $Invite_Text - ); - $Message = json_encode($Message); - Cache_Message($Invite_UID, 0, NULL, 2, '005', '023', $Message); - - $MsgBox = array('text' => sprintf($_Lang['Ally_INV_Msg_Success'], $Invite_UID, $Result_AInvite_CheckUser['username']), 'col' => 'lime'); - } - else - { - $MsgBox = array('text' => $_Lang['Ally_INV_Msg_AlreadyInvited'], 'col' => 'red'); - } - $_Lang['Insert_UID'] = $_Lang['Insert_Username'] = $_Lang['Insert_LockUsername'] = ''; - } - else - { - $MsgBox = array('text' => $_Lang['Ally_INV_Msg_EmptyText'], 'col' => 'red'); - } - } - } - else - { - $MsgBox = array('text' => $_Lang['Ally_INV_Msg_UserInAlly'], 'col' => 'red'); - } - } - else - { - $MsgBox = array('text' => $_Lang['Ally_INV_Msg_UserNoExists'], 'col' => 'red'); - } - } - else - { - if(isset($_GET['send'])) - { - $MsgBox = array('text' => $_Lang['Ally_INV_Msg_BadInput'], 'col' => 'red'); - } - } - - if(!empty($MsgBox)) - { - $_Lang['MsgBox'] = ''.$MsgBox['text'].''; - } - - $_Lang['Insert_MaxLength'] = $_MaxLength_Invitation; - $Page = parsetemplate(gettemplate('alliance_invite'), $_Lang); - display($Page, $_Lang['Ally_INV_Title']); - } - else if($mode == 'invlist') - { - // User is trying to show Invites List - if(!empty($_GET['del'])) - { - $InvList_DelID = intval($_GET['del']); - if($InvList_DelID > 0) - { - $Query_InvList_Delete = ''; - $Query_InvList_Delete .= "SELECT `SenderID` FROM {{table}} "; - $Query_InvList_Delete .= "WHERE `AllyID` = {$Ally['id']} AND `OwnerID` = {$InvList_DelID} AND `State` = 1 LIMIT 1;"; - $Result_InvList_Delete = doquery($Query_InvList_Delete, 'ally_invites', true); - if($Result_InvList_Delete['SenderID'] > 0) - { - if($_ThisUserRank['managereq'] === true OR $_User['id'] == $Result_InvList_Delete['SenderID']) - { - if($_User['id'] == $Result_InvList_Delete['SenderID']) - { - $SetState = '-2'; - } - else - { - $SetState = '-3'; - } - doquery("UPDATE {{table}} SET `State` = {$SetState} WHERE `AllyID` = {$Ally['id']} AND `OwnerID` = {$InvList_DelID} AND `State` = 1 LIMIT 1;", 'ally_invites'); - $MsgBox = array('text' => $_Lang['Ally_INVList_MsgSuccess'], 'col' => 'lime'); - } - else - { - $MsgBox = array('text' => $_Lang['Ally_INVList_MsgCantDel'], 'col' => 'red'); - } - } - else - { - $MsgBox = array('text' => $_Lang['Ally_INVList_MsgNotFound'], 'col' => 'red'); - } - } - else - { - $MsgBox = array('text' => $_Lang['Ally_INVList_MsgBadID'], 'col' => 'red'); - } - } - - $Query_InvList_Get = ''; - $Query_InvList_Get .= "SELECT `ai`.*, `u1`.`username` AS `Owner_Name`, `u2`.`username` AS `Sender_Name` FROM {{table}} AS `ai` "; - $Query_InvList_Get .= "LEFT JOIN `{{prefix}}users` AS `u1` ON `u1`.`id` = `ai`.`OwnerID` "; - $Query_InvList_Get .= "LEFT JOIN `{{prefix}}users` AS `u2` ON `u2`.`id` = `ai`.`SenderID` "; - $Query_InvList_Get .= "WHERE `ai`.`AllyID` = {$Ally['id']} "; - if($_ThisUserRank['lookreq'] !== true) - { - $Query_InvList_Get .= " AND `ai`.`SenderID` = {$_User['id']}"; - } - $Query_InvList_Get .= " ORDER BY `ai`.`State` DESC, `ai`.`Date` DESC;"; - $Result_InvList_Get = doquery($Query_InvList_Get, 'ally_invites'); - if(mysql_num_rows($Result_InvList_Get) > 0) - { - $TPL_Row = gettemplate('alliance_invlist_row'); - while($FetchData = mysql_fetch_assoc($Result_InvList_Get)) - { - $FetchData['Date'] = prettyDate('d m Y, H:i:s', $FetchData['Date'], 1); - if($FetchData['State'] == 1 AND ($_ThisUserRank['managereq'] === true OR $_User['id'] == $FetchData['SenderID'])) - { - $FetchData['Actions'][] = ""; - } - $FetchData['State'] = $_Lang['Ally_INVList_States'][((string)($FetchData['State'] + 0))]; - - if(!empty($FetchData['Actions'])) - { - $FetchData['Actions'] = implode('', $FetchData['Actions']); - } - else - { - $FetchData['Actions'] = ' '; - } - $_Lang['Insert_Rows'][] = parsetemplate($TPL_Row, $FetchData); - } - $_Lang['Insert_Rows'] = implode('', $_Lang['Insert_Rows']); - } - else - { - $_Lang['Insert_Rows'] = parsetemplate(gettemplate('_singleRow'), array('Colspan' => 5, 'Classes' => 'orange pad5', 'Text' => $_Lang['Ally_INVList_NoRows'])); - } - - if(!empty($MsgBox)) - { - $_Lang['MsgBox'] = ''.$MsgBox['text'].''; - } - $Page = parsetemplate(gettemplate('alliance_invlist_body'), $_Lang); - display($Page, $_Lang['Ally_INVList_Title']); - } - else if($mode == 'admin') - { - // User has entered Admin mode - if(isOnVacation()) - { - message($_Lang['Vacation_WarnMsg'], $_Lang['Vacation']); - } - - if($_ThisUserRank['admingen'] !== true) - { - $_Lang['HideManageAllyData'] = 'hide'; - $Hiding += 1; - } - if($_ThisUserRank['mlist_mod'] !== true) - { - $_Lang['HideManageMemList'] = 'hide'; - $Hiding += 1; - } - if($_ThisUserRank['ranks_mod'] !== true) - { - $_Lang['HideManageRanks'] = 'hide'; - $Hiding += 1; - } - if($_ThisUserRank['lookreq'] !== true) - { - $_Lang['HideLookReq'] = 'hide'; - $Hiding += 1; - } - if(isset($Hiding) && $Hiding == 4) - { - message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php', 3); - } - - if(empty($edit)) - { - // User is on AllyAdmin Front Page - $_Lang['HideInfoBox'] = $_Lang['HideWarnBox'] = 'hide'; - $_Lang['GetLastMark'] = 'Mark01'; - - $NewcomerRankSet = array(); - $NewcomerRankSetGray = array(); - foreach($Ally['ally_ranks'] as $RankID => $RankData) - { - if($RankID == 0) - { - continue; - } - if(($RankData['like_admin'] === true AND $_ThisUserRank['is_admin'] !== true) OR $_ThisUserRank['like_admin'] !== true) - { - $NewcomerRankSetGray[] = $RankID; - } - $NewcomerRankSet[] = $RankID; - } - - if(isset($_POST['change']) && $_POST['change'] == 'texts') - { - if($_ThisUserRank['admingen'] === true) - { - $NotChanged = 0; - if($_POST['mode'] == 'saveAll' OR ($_POST['mode'] == 'saveOne' AND $_POST['saveonly'] == 'Mark01')) - { - $TempText = trim(strip_tags(stripslashes($_POST['ext_text']))); - if(strlen($TempText) > $_MaxLength_ExtText) - { - $TempText = substr($TempText, 0, $_MaxLength_ExtText); - $Warnings[] = $_Lang['ADM_ExtTextCutted']; - } - if($TempText != $Ally['ally_description']) - { - $InsertText = mysql_real_escape_string($TempText); - $ChangeQuery[] = "`ally_description` = '{$InsertText}'"; - $Ally['ally_description'] = $TempText; - $Info[] = $_Lang['ADM_ExtTextChanged']; - } - else - { - $NotChanged += 1; - } - } - if($_POST['mode'] == 'saveAll' OR ($_POST['mode'] == 'saveOne' AND $_POST['saveonly'] == 'Mark02')) - { - $TempText = trim(strip_tags(stripslashes($_POST['int_text']))); - if(strlen($TempText) > $_MaxLength_IntText) - { - $TempText = substr($TempText, 0, $_MaxLength_IntText); - $Warnings[] = $_Lang['ADM_IntTextCutted']; - } - if($TempText != $Ally['ally_text']) - { - $InsertText = mysql_real_escape_string($TempText); - $ChangeQuery[] = "`ally_text` = '{$InsertText}'"; - $Ally['ally_text'] = $TempText; - $Info[] = $_Lang['ADM_IntTextChanged']; - } - else - { - $NotChanged += 1; - } - } - if($_POST['mode'] == 'saveAll' OR ($_POST['mode'] == 'saveOne' AND $_POST['saveonly'] == 'Mark03')) - { - $TempText = trim(strip_tags(stripslashes($_POST['req_text']))); - if(strlen($TempText) > $_MaxLength_Request) - { - $TempText = substr($TempText, 0, $_MaxLength_Request); - $Warnings[] = $_Lang['ADM_ReqTextCutted']; - } - if($TempText != $Ally['ally_request']) - { - $InsertText = mysql_real_escape_string($TempText); - $ChangeQuery[] = "`ally_request` = '{$InsertText}'"; - $Ally['ally_request'] = $TempText; - $Info[] = $_Lang['ADM_ReqTextChanged']; - } - else - { - $NotChanged += 1; - } - } - if($NotChanged == 3 OR ($_POST['mode'] == 'saveOne' AND $NotChanged == 1)) - { - $Info[] = $_Lang['ADM_NothingChanged']; - } - if(!empty($ChangeQuery)) - { - doquery("UPDATE {{table}} SET ".implode(', ', $ChangeQuery)." WHERE `id` = {$Ally['id']};", 'alliance'); - } - - if(!empty($_POST['saveonly']) AND in_array($_POST['saveonly'], array('Mark01', 'Mark02', 'Mark03'))) - { - $_Lang['GetLastMark'] = $_POST['saveonly']; - } - } - else - { - $Warnings[] = $_Lang['ADM_TextChgNoAccess']; - } - } - else if(isset($_POST['change']) && $_POST['change'] == 'reqset') - { - if($_ThisUserRank['like_admin'] === true) - { - // Set, if Ally is open for new Requests - $NotChanged = 0; - - $SetAllyOpen = intval($_POST['allyOpen']); - if($SetAllyOpen == 0 OR $SetAllyOpen == 1) - { - $SetAllyOpen = ($SetAllyOpen == 1 ? 0 : 1); - if($SetAllyOpen != $Ally['ally_request_notallow']) - { - $ChangeQuery[] = "`ally_request_notallow` = {$SetAllyOpen}"; - $Ally['ally_request_notallow'] = $SetAllyOpen; - $Info[] = $_Lang['ADM_ReqSetOpenChanged']; - } - else - { - $NotChanged += 1; - } - } - else - { - $Warnings[] = $_Lang['ADM_ReqSetOpenBadOption']; - } - // Set Newcomer default Rank - $SetNewcomerRank = intval($_POST['newComerRank']); - if($SetNewcomerRank > 0) - { - if($SetNewcomerRank != $Ally['ally_new_rank_id']) - { - if(in_array($SetNewcomerRank, $NewcomerRankSet)) - { - if(!in_array($SetNewcomerRank, $NewcomerRankSetGray)) - { - $ChangeQuery[] = "`ally_new_rank_id` = {$SetNewcomerRank}"; - $Ally['ally_new_rank_id'] = $SetNewcomerRank; - $Info[] = $_Lang['ADM_ReqSetRankChanged']; - } - else - { - $Warnings[] = $_Lang['ADM_OnlyAdminCanSetThis']; - } - } - else - { - $Warnings[] = $_Lang['ADM_RankNoExist']; - } - } - else - { - $NotChanged += 1; - } - } - else - { - if($SetNewcomerRank == 0) - { - $NotChanged += 1; - } - else - { - $Warnings[] = $_Lang['ADM_ReqSetBadRank']; - } - } - - if($NotChanged == 2) - { - $Info[] = $_Lang['ADM_NothingChanged']; - } - if(!empty($ChangeQuery)) - { - doquery("UPDATE {{table}} SET ".implode(', ', $ChangeQuery)." WHERE `id` = {$Ally['id']};", 'alliance'); - } - } - else - { - $Warnings[] = $_Lang['ADM_ReqSetNoAccess']; - } - } - - if(!empty($Info)) - { - $_Lang['Info_Box'] = implode('
', $Info); - $_Lang['HideInfoBox'] = ''; - } - else - { - $_Lang['HideInfoBox'] = 'hide'; - } - if(!empty($Warnings)) - { - $_Lang['Warn_Box'] = implode('
', $Warnings); - $_Lang['HideWarnBox'] = ''; - } - else - { - $_Lang['HideWarnBox'] = 'hide'; - } - - $_Lang['Req_Text'] = $Ally['ally_request']; - $_Lang['Int_Text'] = $Ally['ally_text']; - $_Lang['Ext_Text'] = $Ally['ally_description']; - - if($Ally['ally_owner'] != $_User['id']) - { - $_Lang['HideHandOver'] = $_Lang['HideDeleteAlly'] = 'hide'; - } - $_Lang['CollapseReqSetButton'] = 'collapse'; - if($_ThisUserRank['like_admin'] !== true) - { - $_Lang['CollapseReqSet'] = 'collapsed'; - $_Lang['CollapseReqSetButton'] = 'expand'; - $_Lang['DisableReqSetInputs'] = 'disabled'; - } - if($_ThisUserRank['admingen'] !== true) - { - $_Lang['HideTextsSet'] = 'hide'; - } - $_Lang['NewComersRankRows'] = ''; - $DisabledCount = 0; - foreach($NewcomerRankSet as $RankID) - { - $ThisSetDisabled = ''; - $ThisSetSelected = ''; - if(in_array($RankID, $NewcomerRankSetGray)) - { - $ThisSetDisabled = ' class="disNCOpt" disabled'; - $DisabledCount += 1; - } - if($RankID == $Ally['ally_new_rank_id']) - { - $ThisSetSelected = ' selected'; - } - $_Lang['NewComersRankRows'] .= ""; - } - if(empty($_Lang['DisableReqSetInputs']) AND count($NewcomerRankSet) == $DisabledCount) - { - $_Lang['DisableReqSetRanks'] = 'disabled'; - } - if($Ally['ally_request_notallow'] == 0) - { - $_Lang['AcceptReq_Select'] = 'selected'; - } - else - { - $_Lang['BlockReq_Select'] = 'selected'; - } - $_Lang['Insert_MaxLength_IntText'] = $_MaxLength_IntText; - $_Lang['Insert_MaxLength_ExtText'] = $_MaxLength_ExtText; - $_Lang['Insert_MaxLength_ReqText'] = $_MaxLength_Request; - - $Page = parsetemplate(gettemplate('alliance_admin'), $_Lang); - display($Page, $_Lang['ADM_Title']); - } - else - { - // User is trying to use one of Admin Functions - if($edit == 'info') - { - // User is trying to change Data about Ally - if($_ThisUserRank['admingen'] !== true) - { - message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php?mode=admin', 3); - } - - if($Ally['ally_owner'] != $_User['id']) - { - $_Lang['HideChangeName'] = 'hide'; - $_Lang['HideChangeTag'] = 'hide'; - } - - if(isset($_POST['change']) && $_POST['change'] == 'name') - { - if($Ally['ally_owner'] != $_User['id']) - { - $Errors[] = $_Lang['ADM_OnlyLeaderChangeName']; - } - else - { - $NewName = trim($_POST['new_name']); - if(!empty($NewName)) - { - if(strlen($NewName) <= $_MaxLength_AName) - { - if(preg_match(REGEXP_ALLYNAME_ABSOLUTE, $NewName)) - { - if($NewName != $Ally['ally_name']) - { - $CheckExist = doquery("SELECT `id` FROM {{table}} WHERE `ally_name` = '{$NewName}' LIMIT 1;", 'alliance', true); - if($CheckExist['id'] <= 0) - { - doquery("UPDATE {{table}} SET `ally_name` = '{$NewName}' WHERE `id` = {$Ally['id']};", 'alliance'); - $Info[] = $_Lang['ADM_AllyNameChanged']; - } - else - { - $Errors[] = $_Lang['ADM_NewNameNotFree']; - } - } - else - { - $Errors[] = $_Lang['ADM_SameName']; - } - } - else - { - $Errors[] = $_Lang['ADM_BadNewName']; - } - } - else - { - $Errors[] = $_Lang['ADM_NewNameLong']; - } - } - else - { - $Errors[] = $_Lang['ADM_NewNameEmpty']; - } - } - } - else if(isset($_POST['change']) && $_POST['change'] == 'tag') - { - if($Ally['ally_owner'] != $_User['id']) - { - $Errors[] = $_Lang['ADM_OnlyLeaderChangeTag']; - } - else - { - $NewTag = trim($_POST['new_tag']); - if(!empty($NewTag)) - { - $NewTagLength = strlen($NewTag); - if($NewTagLength >= $_MinLength_ATag) - { - if($NewTagLength <= $_MaxLength_ATag) - { - if(preg_match(REGEXP_ALLYTAG_ABSOLUTE, $NewTag)) - { - if($NewTag != $Ally['ally_tag']) - { - $CheckExist = doquery("SELECT `id` FROM {{table}} WHERE `ally_tag` = '{$NewTag}' LIMIT 1;", 'alliance', true); - if($CheckExist['id'] <= 0) - { - doquery("UPDATE {{table}} SET `ally_tag` = '{$NewTag}' WHERE `id` = {$Ally['id']};", 'alliance'); - $Info[] = $_Lang['ADM_AllyTagChanged']; - } - else - { - $Errors[] = $_Lang['ADM_NewTagNotFree']; - } - } - else - { - $Errors[] = $_Lang['ADM_SameTag']; - } - } - else - { - $Errors[] = $_Lang['ADM_BadNewTag']; - } - } - else - { - $Errors[] = $_Lang['ADM_NewTagLong']; - } - } - else - { - $Errors[] = $_Lang['ADM_NewTagShort']; - } - } - else - { - $Errors[] = $_Lang['ADM_NewTagEmpty']; - } - } - } - else if(isset($_POST['change']) && $_POST['change'] == 'general') - { - if(empty($_POST['website'])) - { - $NewWebsite = ''; - } - else - { - $_POST['website'] = trim($_POST['website']); - if(preg_match('/^(http\:\/\/|www\.|https\:\/\/){1}.*?$/D', $_POST['website'], $Matches)) - { - $NewWebsite = mysql_real_escape_string(strip_tags($_POST['website'])); - if($Matches[1] == 'www.') - { - $NewWebsite = substr($NewWebsite, 4); - $NewWebsite = 'http://'.$NewWebsite; - } - } - else - { - $Errors[] = $_Lang['ADM_BadNewWebsite']; - $NewWebsite = null; - } - } - if($NewWebsite !== null AND $NewWebsite != $Ally['ally_web']) - { - $ChangeQuery[] = "`ally_web` = '{$NewWebsite}'"; - $Ally['ally_web'] = $NewWebsite; - } - $RevealWebsite = (isset($_POST['website_reveal']) && $_POST['website_reveal'] == 'on' ? 1 : 0); - if($RevealWebsite != $Ally['ally_web_reveal']) - { - $ChangeQuery[] = "`ally_web_reveal` = {$RevealWebsite}"; - $Ally['ally_web_reveal'] = $RevealWebsite; - } - - if(empty($_POST['logourl'])) - { - $NewLogo = ''; - } - else - { - $_POST['logourl'] = trim($_POST['logourl']); - if(preg_match('/^(http\:\/\/|www\.|https\:\/\/){1}.*?$/D', $_POST['logourl'], $Matches)) - { - $NewLogo = mysql_real_escape_string(strip_tags($_POST['logourl'])); - if($Matches[1] == 'www.') - { - $NewLogo = substr($NewLogo, 4); - $NewLogo = 'http://'.$NewLogo; - } - } - else - { - $Errors[] = $_Lang['ADM_BadNewLogo']; - $NewLogo = null; - } - } - if($NewLogo !== null AND $NewLogo != $Ally['ally_image']) - { - $ChangeQuery[] = "`ally_image` = '{$NewLogo}'"; - $Ally['ally_image'] = $NewLogo; - } - - if(!empty($ChangeQuery)) - { - doquery("UPDATE {{table}} SET ".implode(', ', $ChangeQuery)." WHERE `id` = {$Ally['id']};", 'alliance'); - $Info[] = $_Lang['ADM_AllyInfoChanged']; - } - else - { - $Errors[] = $_Lang['ADM_AllyInfoNotChanged']; - } - } - - $_Lang['HideInfoBox_name'] = 'hide'; - $_Lang['HideInfoBox_tag'] = 'hide'; - $_Lang['HideInfoBox_general'] = 'hide'; - if(isset($_POST['change'])) - { - switch($_POST['change']) - { - case 'name': - { - $TextBoxes = 'name'; - $_Lang['HideInfoBox_name'] = ''; - break; - } - case 'tag': - { - $TextBoxes = 'tag'; - $_Lang['HideInfoBox_tag']= ''; - break; - } - case 'general': - { - $TextBoxes = 'general'; - $_Lang['HideInfoBox_general']= ''; - break; - } - } - } - - if(!empty($Errors)) - { - if($TextBoxes != 'general') - { - $_Lang['InfoBox_color'] = 'red'; - $_Lang['InfoBox_'.$TextBoxes] = implode('
', $Errors); - } - else - { - $_Lang['InfoBox_'.$TextBoxes] = ''.implode('
', $Errors).'
'; - } - } - if(!empty($Info)) - { - if($TextBoxes != 'general') - { - $_Lang['InfoBox_color'] = 'lime'; - $_Lang['InfoBox_'.$TextBoxes] = implode('
', $Info); - } - else - { - if(!isset($_Lang['InfoBox_'.$TextBoxes])) - { - $_Lang['InfoBox_'.$TextBoxes] = ''; - } - $_Lang['InfoBox_'.$TextBoxes] .= (empty($_Lang['InfoBox_'.$TextBoxes]) ? '' : '
').''.implode('
', $Info).'
'; - } - } - $_Lang['CurrentWebsite'] = stripslashes($Ally['ally_web']); - $_Lang['CheckRevealWebsite'] = ($Ally['ally_web_reveal'] == 1 ? 'checked' : ''); - $_Lang['CurrentLogoUrl'] = stripslashes($Ally['ally_image']); - - $Page = parsetemplate(gettemplate('alliance_admin_changedata'), $_Lang); - display($Page, $_Lang['ADM_Title']); - } - else if($edit == 'handover') - { - // User is trying to HandOver the Ally - if($Ally['ally_owner'] != $_User['id']) - { - message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php?mode=admin', 3); - } - if($Ally['ally_members'] == 1) - { - message($_Lang['ADM_OnlyOwnerInAlly'], $MsgTitle, 'alliance.php?mode=admin', 3); - } - - $Query_AHandOver_Members = ''; - $Query_AHandOver_Members .= "SELECT `id`, `username`, `ally_rank_id` FROM {{table}} "; - $Query_AHandOver_Members .= "WHERE `ally_id` = {$Ally['id']} AND `id` != {$_User['id']};"; - - $Result_AHandOver_Members = doquery($Query_AHandOver_Members, 'users'); - $_Lang['UserList'] = ''; - while($FetchData = mysql_fetch_assoc($Result_AHandOver_Members)) - { - $_Lang['UserList'] .= ""; - $Members[$FetchData['id']] = $FetchData['ally_rank_id']; - } - - $_Lang['HideError'] = 'hide'; - if(isset($_POST['send']) && $_POST['send'] == 'yes') - { - $NewOwner = intval($_POST['new_owner']); - if($NewOwner > 0) - { - if(array_key_exists($NewOwner, $Members)) - { - doquery("UPDATE {{table}} SET `ally_owner` = {$NewOwner} WHERE `id` = {$Ally['id']};", 'alliance'); - doquery("INSERT INTO {{table}} (`id`, `ally_rank_id`) VALUES ({$_User['id']}, {$Members[$NewOwner]}), ({$NewOwner}, 0) ON DUPLICATE KEY UPDATE `ally_rank_id` = VALUES(`ally_rank_id`);", 'users'); - message($_Lang['ADM_HandOverDone'], $MsgTitle, 'alliance.php', 3); - } - else - { - $ErrorBox = $_Lang['ADM_BadUserIDHO']; - } - } - else - { - $ErrorBox = $_Lang['ADM_NoUserIDHO']; - } - $_Lang['HideError'] = ''; - $_Lang['ErrorText'] = $ErrorBox; - } - - $Page = parsetemplate(gettemplate('alliance_admin_handover'), $_Lang); - display($Page, $_Lang['ADM_Title']); - } - else if($edit == 'delete') - { - // User is trying to Delete Ally - if($Ally['ally_owner'] != $_User['id']) - { - message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php?mode=admin', 3); - } - - $_DisplaySettings['dontShow_AllyChat_MsgCount'] = true; - $_DisplaySettings['dontShow_AllyChat_Link'] = true; - - doquery("DELETE FROM {{table}} WHERE `id` = {$Ally['id']};", 'alliance'); - doquery("DELETE FROM {{table}} WHERE `AllyID` = {$Ally['id']};", 'ally_invites'); - doquery("DELETE FROM {{table}} WHERE `AllyID_Sender` = {$Ally['id']} OR `AllyID_Owner` = {$Ally['id']};", 'ally_pacts'); - if($Ally['ally_ChatRoom_ID'] > 0) - { - doquery("DELETE FROM {{table}} WHERE `ID` = {$Ally['ally_ChatRoom_ID']} LIMIT 1;", 'chat_rooms'); - doquery("DELETE FROM {{table}} WHERE `RID` = {$Ally['ally_ChatRoom_ID']};", 'chat_messages'); - doquery("DELETE FROM {{table}} WHERE `RID` = {$Ally['ally_ChatRoom_ID']};", 'chat_online'); - } - doquery("UPDATE {{table}} SET `ally_id` = 0, `ally_register_time` = 0, `ally_rank_id` = 0, `ally_request` = 0, `ally_request_text` = '' WHERE `ally_id` = {$Ally['id']} OR `ally_request` = {$Ally['id']};", 'users'); - message($_Lang['ADM_AllyDeleted'], $MsgTitle, 'alliance.php', 3); - } - else if($edit == 'members') - { - // User is trying to Manage Members - if($_ThisUserRank['mlist'] !== true OR ($_ThisUserRank['mlist_mod'] !== true AND $_ThisUserRank['cankick'] !== true)) - { - message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php?mode=admin', 3); - } - - foreach($Ally['ally_ranks'] as $RankID => $RankData) - { - if($RankID == 0 OR $RankID == $_User['ally_rank_id']) - { - continue; - } - if($_ThisUserRank['like_admin'] === true) - { - if($RankData['like_admin'] !== true OR $_ThisUserRank['is_admin'] === true) - { - $AllowedRanksChange[] = $RankID; - } - } - else - { - if($RankData['like_admin'] === true) - { - continue; - } - else - { - $DisallowChange = false; - foreach($_ThisUserRank as $Key => $Value) - { - if($Key == 'name') - { - continue; - } - if($Key == 'mlist_mod' OR $Key == 'cankick' OR $Key == 'ranks_mod') - { - if($RankData[$Key] === true) - { - $DisallowChange = true; - break; - } - } - else - { - if($Value !== true AND $RankData[$Key] === true) - { - $DisallowChange = true; - break; - } - } - } - if($DisallowChange === false) - { - $AllowedRanksChange[] = $RankID; - } - } - } - } - $_Lang['HideInfoBox'] = 'hide'; - - if(!empty($_GET['kick'])) - { - $InfoBoxCol = 'red'; - if($_ThisUserRank['cankick'] === true) - { - $KickID = intval($_GET['kick']); - if($KickID > 0) - { - if($KickID != $_User['id']) - { - $GetUser = doquery("SELECT `id`, `username`, `ally_id`, `ally_rank_id` FROM {{table}} WHERE `id` = {$KickID} LIMIT 1;", 'users', true); - if($GetUser['id'] == $KickID AND $GetUser['ally_id'] == $Ally['id']) - { - if(in_array($GetUser['ally_rank_id'], $AllowedRanksChange)) - { - doquery("UPDATE {{table}} SET `ally_id` = 0, `ally_rank_id` = 0 WHERE `id` = {$KickID};", 'users'); - doquery("UPDATE {{table}} SET `ally_members` = `ally_members` - 1 WHERE `id` = {$Ally['id']};", 'alliance'); - doquery("UPDATE {{table}} SET `State` = -3 WHERE `State` = 1 AND `SenderID` = {$KickID};", 'ally_invites'); - $Ally['ally_members'] -= 1; - $InfoBoxTxt = sprintf($_Lang['ADM_MemberXKicked'], $GetUser['username']); - $InfoBoxCol = 'lime'; - } - else - { - $InfoBoxTxt = $_Lang['ADM_CantKickRank']; - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_CantKickBadUser']; - } - } - else - { - $InfoBoxTxt = $land['ADM_CantKickYourself']; - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_CantKickBadID']; - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_YouCantKick']; - } - - $_Lang['HideInfoBox']= ''; - $_Lang['InfoBoxText']= $InfoBoxTxt; - $_Lang['InfoBoxColor'] = $InfoBoxCol; - } - else if(isset($_POST['send']) && $_POST['send'] == 'yes') - { - $InfoBoxCol = 'red'; - - $ErrorsChanging = 0; - $RankIsSame = 0; - $ErrorsSaving = 0; - - if($_ThisUserRank['mlist_mod'] === true) - { - foreach($_POST['change_rank'] as $UserID => $NewRank) - { - $UserID = intval($UserID); - $NewRank = intval($NewRank); - if($UserID > 0 AND $NewRank > 0 AND in_array($NewRank, $AllowedRanksChange)) - { - $RankChanges[$UserID] = $NewRank; - } - else - { - $ErrorsChanging += 1; - } - } - if(!empty($RankChanges)) - { - $MembersList = doquery("SELECT `id`, `ally_id`, `ally_rank_id` FROM {{table}} WHERE `id` IN (".implode(', ', array_keys($RankChanges)).");", 'users'); - if(mysql_num_rows($MembersList) > 0) - { - while($FetchData = mysql_fetch_assoc($MembersList)) - { - if($FetchData['ally_id'] == $Ally['id'] AND $RankChanges[$FetchData['id']] != $FetchData['ally_rank_id'] AND in_array($FetchData['ally_rank_id'], $AllowedRanksChange)) - { - $DoChange[$FetchData['id']] = $RankChanges[$FetchData['id']]; - } - else - { - if($RankChanges[$FetchData['id']] != $FetchData['ally_rank_id']) - { - $RankIsSame += 1; - } - else - { - $ErrorsSaving += 1; - } - } - } - - if(!empty($DoChange)) - { - $UpdateQuery = "INSERT INTO {{table}} (`id`, `ally_rank_id`) VALUES "; - foreach($DoChange as $UserID => $RankID) - { - $UpdateQueryArr[] = "({$UserID}, {$RankID})"; - } - $UpdateQuery .= implode(', ', $UpdateQueryArr); - $UpdateQuery .= " ON DUPLICATE KEY UPDATE "; - $UpdateQuery .= "`ally_rank_id` = VALUES(`ally_rank_id`);"; - doquery($UpdateQuery, 'users'); - - if(count($DoChange) == (count($RankChanges) - $RankIsSame + $ErrorsChanging)) - { - $InfoBoxTxt = $_Lang['ADM_MListModAllDone']; - } - else - { - $InfoBoxTxt = $_Lang['ADM_MListModNAllDone']; - } - $InfoBoxCol = 'lime'; - } - else - { - if($ErrorsSaving > 0) - { - $InfoBoxTxt = $_Lang['ADM_MListModBadData2']; - } - else - { - $InfoBoxTxt = $_Lang['ADM_MListModBadData']; - } - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_MListModBadData']; - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_MListModBadData']; - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_YouCantMListMod']; - } - - $_Lang['HideInfoBox'] = ''; - $_Lang['InfoBoxText'] = $InfoBoxTxt; - $_Lang['InfoBoxColor'] = $InfoBoxCol; - } - - createMembersList(true); - $Page = parsetemplate(gettemplate('alliance_admin_memberslist_table'), $_Lang); - display($Page, $_Lang['ADM_Title']); - } - else if($edit == 'reqlist') - { - // User wants to Look at Requests - if(!isset($_GET['from']) || $_GET['from'] != 'front') - { - $GoBackTo = 'alliance.php?mode=admin'; - $_Lang['GoBackLink'] = '?mode=admin'; - } - else - { - $GoBackTo = 'alliance.php'; - $_Lang['GoBackLink'] = 'alliance.php'; - } - if($_ThisUserRank['lookreq'] !== true) - { - message($_Lang['Ally_AccessDenied'], $MsgTitle, $GoBackTo, 3); - } - - if(!empty($_POST['rq'])) - { - $InfoBoxCol = 'red'; - if($_ThisUserRank['managereq'] === true) - { - $RequestUser = intval($_POST['rq']); - if($RequestUser > 0) - { - if($_POST['opt'] == 1 OR $_POST['opt'] == 2) - { - $CheckRequest = doquery("SELECT `id`, `username`, `ally_request` FROM {{table}} WHERE `id` = {$RequestUser} LIMIT 1;", 'users', true); - if($CheckRequest['id'] == $RequestUser) - { - if($CheckRequest['ally_request'] == $Ally['id']) - { - if($_POST['opt'] == 1) - { - doquery("UPDATE {{table}} SET `ally_request` = 0, `ally_request_text` = '', `ally_id` = {$Ally['id']}, `ally_rank_id` = {$Ally['ally_new_rank_id']}, `ally_register_time` = UNIX_TIMESTAMP() WHERE `id` = {$RequestUser};", 'users'); - doquery("UPDATE {{table}} SET `ally_members` = `ally_members` + 1 WHERE `id` = {$Ally['id']};", 'alliance'); - if($Ally['ally_ChatRoom_ID'] > 0) - { - $Query_UpdateChatRoomOnline = ''; - $Query_UpdateChatRoomOnline .= "INSERT INTO {{table}} VALUES ({$Ally['ally_ChatRoom_ID']}, {$RequestUser}, UNIX_TIMESTAMP()) "; - $Query_UpdateChatRoomOnline .= "ON DUPLICATE KEY UPDATE "; - $Query_UpdateChatRoomOnline .= "`LastOnline` = VALUES(`LastOnline`);"; - doquery($Query_UpdateChatRoomOnline, 'chat_online'); - } - - $Message = array(); - $Message['msg_id'] = '023'; - $Message['args'] = array($Ally['ally_name']); - $Message = json_encode($Message); - Cache_Message($RequestUser, 0, NULL, 2, '005', '010', $Message); - - $InfoBoxCol = 'lime'; - $InfoBoxTxt = sprintf($_Lang['ADM_RL_ReqAccepted'], $CheckRequest['username']); - - CheckJobsDone('BUDDY_OR_ALLY_TASK', $RequestUser); - } - else - { - doquery("UPDATE {{table}} SET `ally_request` = 0, `ally_request_text` = '', `ally_register_time` = 0 WHERE `id` = {$RequestUser};", 'users'); - - $RejectReason = strip_tags(stripslashes($_POST['rjr'])); - if(strlen($RejectReason) > $_MaxLength_Reject) - { - $RejectReason = substr($RejectReason, 0, $_MaxLength_Reject); - } - else if(strlen($RejectReason) == 0) - { - $RejectReason = $_Lang['ADM_RL_NoReason']; - } - $Message = array(); - $Message['msg_id'] = '024'; - $Message['args'] = array($Ally['ally_name'], $RejectReason); - $Message = json_encode($Message); - Cache_Message($RequestUser, 0, NULL, 2, '005', '011', $Message); - - $InfoBoxCol = 'lime'; - $InfoBoxTxt = sprintf($_Lang['ADM_RL_ReqRejected'], $CheckRequest['username']); - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_RL_UserNotInAlly']; - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_RL_UserNoExist']; - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_RL_BadOption']; - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_RL_BadID']; - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_RL_NoManageAccess']; - } - } - - if(!empty($InfoBoxTxt)) - { - $_Lang['InfoBoxText']= $InfoBoxTxt; - $_Lang['InfoBoxColor'] = $InfoBoxCol; - } - else - { - $_Lang['HideInfoBox']= 'hide'; - } - - $SortType = (isset($_GET['stype']) ? intval($_GET['stype']) : null); - $SortMode = (isset($_GET['smode']) ? intval($_GET['smode']) : null); - - $ThisSorting = 'class="sortHigh"'; - switch($SortType) - { - case 1: - $SortBy = '`username`'; - $_Lang['sortByName'] = $ThisSorting; - break; - case 2: - $SortBy = '`total_rank`'; - $_Lang['sortByStats'] = $ThisSorting; - break; - case 3: - $SortBy = '`ally_register_time`'; - $_Lang['sortBySendDate'] = $ThisSorting; - break; - default: - $SortBy = '`id`'; - break; - } - switch($SortMode) - { - case 'desc': - $SortHow = 'DESC'; - $_Lang['sortRev'] = 'asc'; - break; - default: - $SortHow = 'ASC'; - $_Lang['sortRev'] = 'desc'; - break; - } - - $Query_ARequests_Get = ''; - $Query_ARequests_Get .= "SELECT `id`, `username`, `ally_register_time`, `ally_request_text`, `Stats`.`total_rank`, `Stats`.`total_points` FROM {{table}} "; - $Query_ARequests_Get .= "LEFT JOIN {{prefix}}statpoints AS `Stats` ON `Stats`.`id_owner` = {{table}}.`id` AND `Stats`.`stat_type` = 1 "; - $Query_ARequests_Get .= "WHERE `ally_request` = {$Ally['id']} ORDER BY {$SortBy} {$SortHow};"; - - $GetRequests = doquery($Query_ARequests_Get, 'users'); - $ReqCount = mysql_num_rows($GetRequests); - $_Lang['RequestCount'] = $ReqCount; - - if($_ThisUserRank['managereq'] === true) - { - $TableTPL = gettemplate('alliance_admin_reqlist_mg_table'); - $RowTPL = gettemplate('alliance_admin_reqlist_mg_row'); - } - else - { - $TableTPL = gettemplate('alliance_admin_reqlist_lk_table'); - $RowTPL = gettemplate('alliance_admin_reqlist_lk_row'); - } - - if($ReqCount > 0) - { - $_Lang['HideNoRequests'] = 'hide'; - $_Lang['RequestRows'] = ''; - while($Request = mysql_fetch_assoc($GetRequests)) - { - $Request['ally_request_text'] = stripslashes($Request['ally_request_text']); - if($Request['total_rank'] > 0) - { - $Request['StatPoints'] = "{$Request['total_rank']} (".prettyNumber($Request['total_points'])." {$_Lang['ADM_RL_points']})"; - } - else - { - $Request['StatPoints'] = '0'; - } - $Request['SendDate'] = prettyDate('d m Y - H:i:s', $Request['ally_register_time'], 1); - $Request['ADM_RL_Accept'] = $_Lang['ADM_RL_Accept']; - $Request['ADM_RL_Refuse'] = $_Lang['ADM_RL_Refuse']; - $Request['ADM_RL_RejectReason'] = $_Lang['ADM_RL_RejectReason']; - $Request['ADM_RL_Save'] = $_Lang['ADM_RL_Save']; - - $_Lang['RequestRows'] .= parsetemplate($RowTPL, $Request); - } - } - $Page = parsetemplate($TableTPL, $_Lang); - display($Page, $_Lang['ADM_Title']); - } - else if($edit == 'ranks') - { - // User is trying to View RankList (and manage Ranks) - if($_ThisUserRank['ranks_mod'] !== true) - { - message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php?mode=admin', 3); - } - - if($_ThisUserRank['is_admin'] === true) - { - $ImAllyOwner = true; - } - else - { - $ImAllyOwner = false; - } - - // Set Default Disabled for Options - $DefaultDisabledOpt = array(); - if(!$ImAllyOwner) - { - if($_ThisUserRank['like_admin'] !== true) - { - $DefaultDisabledOpt = array(1, 8, 9, 10, 11); - if($_ThisUserRank['mlist'] !== true) - { - $DefaultDisabledOpt[] = 2; - $DefaultDisabledOpt[] = 3; - } - else if($_ThisUserRank['mlist_online'] !== true) - { - $DefaultDisabledOpt[] = 3; - } - if($_ThisUserRank['sendmsg'] !== true) - { - $DefaultDisabledOpt[] = 4; - } - if($_ThisUserRank['admingen'] !== true) - { - $DefaultDisabledOpt[] = 5; - } - if($_ThisUserRank['lookreq'] !== true) - { - $DefaultDisabledOpt[] = 6; - $DefaultDisabledOpt[] = 7; - } - else if($_ThisUserRank['managereq'] !== true) - { - $DefaultDisabledOpt[] = 7; - } - } - else - { - $DefaultDisabledOpt[] = 1; - } - } - $_Lang['HideInfoBox'] = 'hide'; - - $Result_ARanks_Counter = doquery("SELECT COUNT(*) AS `Count`, `ally_rank_id` FROM {{table}} WHERE `ally_id` = {$Ally['id']} GROUP BY `ally_rank_id`;", 'users'); - while($FetchData = mysql_fetch_assoc($Result_ARanks_Counter)) - { - $RanksCountArray[$FetchData['ally_rank_id']] = $FetchData['Count']; - } - - if(!empty($_POST['action'])) - { - $InfoBoxCol = 'red'; - if($_POST['action'] == 'add') - { - $NewName = trim($_POST['newName']); - $NewNameLower = strtolower($NewName); - $NewNameLen = strlen($NewName); - if($NewNameLen >= $_MinLength_RankName) - { - if($NewNameLen <= $_MaxLength_RankName) - { - if(preg_match($RankNameRegExp, $NewName)) - { - $BreakNameOcu = false; - foreach($Ally['ally_ranks'] as $RankID => $RankData) - { - if(strtolower($RankData['name']) == $NewNameLower) - { - $BreakNameOcu = true; - break; - } - } - if($BreakNameOcu === false) - { - $BreakBadOpt = false; - for($i = 1; $i < $Ally['ally_ranks_count']; $i += 1) - { - if(isset($_POST['opt'][$i]) && $_POST['opt'][$i] == 'on') - { - if(in_array($i, $DefaultDisabledOpt)) - { - $BreakBadOpt = true; - break; - } - else - { - $NewRankOpts[$i] = true; - } - } - else - { - $NewRankOpts[$i] = false; - } - } - if($BreakBadOpt === false) - { - if($NewRankOpts[1] === true) - { - foreach($NewRankOpts as $ID => $Value) - { - if($Value !== true) - { - $NewRankOpts[1] = false; - break; - } - } - } - if($NewRankOpts[3] === true) - { - if($NewRankOpts[2] !== true) - { - $NewRankOpts[3] = false; - } - } - if($NewRankOpts[7] === true) - { - if($NewRankOpts[6] !== true) - { - $NewRankOpts[7] = false; - } - } - $NewRankAdd = array_merge(array(0 => $NewName), $NewRankOpts); - $Ally['ally_ranks_org'][] = $NewRankAdd; - foreach($NewRankAdd as $DataID => $DataVal) - { - $NewRankData[$RankDataLabels[$DataID]] = $DataVal; - } - $Ally['ally_ranks'][] = $NewRankData; - - doquery("UPDATE {{table}} SET `ally_ranks` = '".mysql_real_escape_string(json_encode($Ally['ally_ranks_org']))."' WHERE `id` = {$Ally['id']};", 'alliance'); - $InfoBoxCol = 'lime'; - $InfoBoxTxt = $_Lang['ADM_RkL_AddedRank']; - } - else - { - if($BreakBadData) - { - $InfoBoxTxt = $_Lang['ADM_RkL_BadOptGiven']; - } - else - { - $InfoBoxTxt = $_Lang['ADM_RkL_ForbiddenOptGiven']; - } - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_RkL_RankExists']; - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_RkL_ForbiddenSigns']; - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_RkL_NameLong']; - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_RkL_NameShort']; - } - } - else if($_POST['action'] == 'saveChg') - { - if(!empty($_POST['chgData'])) - { - $ChangingErrors = 0; - $NoChanges = 0; - $RankNoExists = 0; - - foreach($Ally['ally_ranks'] as $RankData) - { - $ExistingNames[] = strtolower($RankData['name']); - } - foreach($_POST['chgData'] as $RankID => $RankChgData) - { - if(!empty($Ally['ally_ranks'][$RankID]['name'])) - { - $ParsedRankData = &$Ally['ally_ranks'][$RankID]; - if($ImAllyOwner OR ($_ThisUserRank['like_admin'] === true AND $ParsedRankData['like_admin'] !== true) OR - ( - $_ThisUserRank['like_admin'] !== true AND - $ParsedRankData['like_admin'] !== true AND - $ParsedRankData['ranks_mod'] !== true AND - $ParsedRankData['mlist_mod'] !== true AND - $ParsedRankData['cankick'] !== true - )) - { - $ThisCanChangeName= true; - $ThisCanChangeRights= true; - } - else - { - $ThisCanChangeName = false; - $ThisCanChangeRights = false; - $ThisCantChangeName = 'na_nonam'; - $ThisCantChangeRights = 'na_nochg'; - } - if($RankID == 0) - { - $ThisCanChangeRights = false; - $ThisCantChangeRights = 'adm_nochg'; - } - if($ThisCanChangeName) - { - $ChangingErrors += 1; - $ThisNewName = trim($RankChgData[0]); - $ThisNewNameLower = strtolower($ThisNewName); - $ThisNewNameLen = strlen($ThisNewName); - if($ThisNewNameLen > 0) - { - if($ThisNewNameLower != strtolower($ParsedRankData['name'])) - { - if(preg_match($RankNameRegExp, $ThisNewName)) - { - if($ThisNewNameLen >= $_MinLength_RankName) - { - if($ThisNewNameLen <= $_MaxLength_RankName) - { - if(!in_array($ThisNewNameLower, $ExistingNames)) - { - $SaveChanges[$RankID][0] = $ThisNewName; - $ChangingErrors -= 1; - } - else - { - $ErrorsFound['NameExists'] += 1; - } - } - else - { - $ErrorsFound['NameLong'] += 1; - } - } - else - { - $ErrorsFound['NameShort'] += 1; - } - } - else - { - $ErrorsFound['NamePregMatch'] += 1; - } - } - else - { - $NoChanges += 1; - $ChangingErrors -= 1; - } - } - else - { - $ErrorsFound['NameEmpty'] += 1; - } - } - if($ThisCanChangeRights) - { - for($i = 1; $i < $Ally['ally_ranks_count']; $i += 1) - { - $RankChgData[$i] = (isset($RankChgData[$i]) && $RankChgData[$i] == 'on' ? true : false); - if($RankChgData[$i] !== $Ally['ally_ranks_org'][$RankID][$i]) - { - if(in_array($i, $DefaultDisabledOpt)) - { - $ChangingErrors += 1; - $ErrorsFound['Opt'.$i.'Disabled'] += 1; - } - else - { - $SaveChanges[$RankID][$i] = $RankChgData[$i]; - } - } - else - { - $NoChanges += 1; - } - } - } - } - else - { - $RankNoExists += 1; - $ErrorsFound['RankNoExists'] += 1; - } - } - if(!empty($SaveChanges)) - { - foreach($SaveChanges as $RankID => $RankData) - { - $Recalculate = false; - foreach($RankData as $DataID => $DataValue) - { - $Ally['ally_ranks_org'][$RankID][$DataID] = $DataValue; - $Ally['ally_ranks'][$RankID][$RankDataLabels[$DataID]] = $DataValue; - } - $RankShortcut = &$Ally['ally_ranks_org'][$RankID]; - if($RankShortcut[1] === true) - { - foreach($RankShortcut as $ID => $Value) - { - if($ID == 0) - { - continue; - } - if($Value !== true) - { - $RankShortcut[1] = false; - $Recalculate = true; - break; - } - } - } - if($RankShortcut[3] === true) - { - if($RankShortcut[2] !== true) - { - $RankShortcut[3] = false; - $Recalculate = true; - } - } - if($RankShortcut[7] === true) - { - if($RankShortcut[6] !== true) - { - $RankShortcut[7] = false; - $Recalculate = true; - } - } - if($Recalculate === true) - { - foreach($RankShortcut as $DataID => $DataValue) - { - $Ally['ally_ranks'][$RankID][$RankDataLabels[$DataID]] = $DataValue; - } - } - } - doquery("UPDATE {{table}} SET `ally_ranks` = '".mysql_real_escape_string(json_encode($Ally['ally_ranks_org']))."' WHERE `id` = {$Ally['id']};", 'alliance'); - $InfoBoxCol = 'lime'; - if($RankNoExists > 0 OR $ChangingErrors > 0) - { - $InfoBoxTxt = $_Lang['ADM_RkL_PosChgSaved']; - } - else - { - $InfoBoxTxt = $_Lang['ADM_RkL_AllChgSaved']; - } - } - else - { - $InfoBoxCol = 'orange'; - $InfoBoxTxt = $_Lang['ADM_RkL_NothingChanged']; - if($RankNoExists > 0 OR $ChangingErrors > 0) - { - $InfoBoxTxt .= '
'.$_Lang['ADM_RkL_ChgErrors']; - } - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_RkL_EmptyData']; - } - } - else if(substr($_POST['action'], 0, 4) == 'del_') - { - $RankID = intval(substr($_POST['action'], 4)); - if($RankID > 0) - { - if(!empty($Ally['ally_ranks'][$RankID]['name'])) - { - if($ImAllyOwner OR ($_ThisUserRank['like_admin'] === true AND $RankData['like_admin'] !== true) OR - ( - $_ThisUserRank['like_admin'] !== true AND - $RankData['like_admin'] !== true AND - $RankData['ranks_mod'] !== true AND - $RankData['mlist_mod'] !== true AND - $RankData['cankick'] !== true - )) - { - $ThisCanDelete = true; - } - else - { - $ThisCanDelete = false; - $ThisCantDelete = 'na_nodel'; - } - if($RankID == 0) - { - $ThisCanDelete = false; - $ThisCantDelete = 'adm_nodel'; - } - if($RankID == $Ally['ally_new_rank_id']) - { - $ThisCanDelete = false; - $ThisCantDelete = 'nc_nodel'; - } - - if($ThisCanDelete) - { - if(isset($RanksCountArray[$RankID]) && $RanksCountArray[$RankID] > 0) - { - $RanksCountArray[$Ally['ally_new_rank_id']] += $RanksCountArray[$RankID]; - doquery("UPDATE {{table}} SET `ally_rank_id` = {$Ally['ally_new_rank_id']} WHERE `ally_id` = {$Ally['id']} AND `ally_rank_id` = {$RankID};", 'users'); - } - unset($Ally['ally_ranks'][$RankID]); - unset($Ally['ally_ranks_org'][$RankID]); - doquery("UPDATE {{table}} SET `ally_ranks` = '".mysql_real_escape_string(json_encode($Ally['ally_ranks_org']))."' WHERE `id` = {$Ally['id']};", 'alliance'); - - $InfoBoxCol = 'lime'; - $InfoBoxTxt = $_Lang['ADM_RkL_RankDeleted']; - } - else - { - $InfoBoxTxt = $_Lang['ADM_RkL_RankDelete_'.$ThisCantDelete]; - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_RkL_RankNoExists']; - } - } - else - { - if(substr($_POST['action'], 4) == '0') - { - $InfoBoxTxt = $_Lang['ADM_RkL_RankDelete_adm_nodel']; - } - else - { - $InfoBoxTxt = $_Lang['ADM_RkL_BadRankIDGiven']; - } - } - } - else - { - $InfoBoxTxt = $_Lang['ADM_RkL_BadPostAction']; - } - - $_Lang['HideInfoBox'] = ''; - $_Lang['InfoBoxText'] = $InfoBoxTxt; - $_Lang['InfoBoxColor'] = $InfoBoxCol; - } - - $RowTPL = gettemplate('alliance_admin_ranklist_row'); - $_Lang['RanksRows'] = ''; - $RanksCount = 0; - foreach($Ally['ally_ranks'] as $RankID => $RankData) - { - $ThisRank = array(); - - if($ImAllyOwner OR ($_ThisUserRank['like_admin'] === true AND $RankData['like_admin'] !== true) OR - ( - $_ThisUserRank['like_admin'] !== true AND - $RankData['like_admin'] !== true AND - $RankData['ranks_mod'] !== true AND - $RankData['mlist_mod'] !== true AND - $RankData['cankick'] !== true - )) - { - $ThisCanChangeName = true; - $ThisCanChangeRights = true; - $ThisCanDelete = true; - } - else - { - $ThisCanChangeName = false; - $ThisCanChangeRights = false; - $ThisCanDelete = false; - $ThisCantChangeName = 'na_nonam'; - $ThisCantChangeRights = 'na_nochg'; - $ThisCantDelete = 'na_nodel'; - } - if($RankID == 0) - { - $ThisCanChangeRights = false; - $ThisCanDelete = false; - $ThisCantChangeRights = 'adm_nochg'; - $ThisCantDelete = 'adm_nodel'; - } - if($RankID == $Ally['ally_new_rank_id']) - { - $ThisCanDelete = false; - $ThisCantDelete = 'nc_nodel'; - } - - if($ThisCanChangeName) - { - $ThisRank['RankName'] = ''; - } - else - { - $ThisRank['RankName'] = ''.$RankData['name'].''; - } - if($ThisCanChangeRights !== true) - { - $ThisRank['DisableInfo'] = ' class="'.$ThisCantChangeRights.'"'; - for($i = 1; $i < $Ally['ally_ranks_count']; $i += 1) - { - $ThisRank['CBoxes'][$i][] = 'disabled'; - $ThisRank['DisableInfo'.$i] = $ThisRank['DisableInfo']; - } - } - else - { - $ThisRank['DisableInfo'] = ' class="na_nochg"'; - for($i = 1; $i < $Ally['ally_ranks_count']; $i += 1) - { - if(in_array($i, $DefaultDisabledOpt)) - { - $ThisRank['CBoxes'][$i][] = 'disabled'; - $ThisRank['DisableInfo'.$i] = $ThisRank['DisableInfo']; - } - else - { - $ThisRank['CBoxes'][$i][] = 'name="chgData['.$RankID.']['.$i.']"'; - } - } - } - - $PropCounter = 1; - foreach($RankData as $PropKey => $PropVal) - { - if($PropKey == 'name') - { - continue; - } - if($PropVal === true) - { - $ThisRank['CBoxes'][$PropCounter][] = 'checked'; - } - $PropCounter += 1; - } - if(!empty($ThisRank['CBoxes'])) - { - foreach($ThisRank['CBoxes'] as $Index => $Vals) - { - $ThisRank['CBox_'.$Index] = implode(' ', $Vals); - } - } - - if($ThisCanDelete !== true) - { - $ThisRank['DeleteButton'] = ''.$_Lang['ADM_RkL_Delete'].''; - } - else - { - $ThisRank['DeleteButton'] = ''; - } - if(isset($RanksCountArray[$RankID]) && $RanksCountArray[$RankID] > 0) - { - $ThisRank['MembersCount'] = $RanksCountArray[$RankID]; - } - else - { - $ThisRank['MembersCount'] = '0'; - } - $_Lang['RanksRows'] .= parsetemplate($RowTPL, $ThisRank); - $RanksCount += 1; - } - $_Lang['RankCount'] = $RanksCount; - - $AddRank['DisableInfo'] = ' class="na_adchg"'; - for($i = 1; $i < $Ally['ally_ranks_count']; $i += 1) - { - if(in_array($i, $DefaultDisabledOpt)) - { - $AddRank['CBoxes'][$i][] = 'disabled'; - $_Lang['DisableInfo'.$i] = $AddRank['DisableInfo']; - } - else - { - $AddRank['CBoxes'][$i][] = 'name="opt['.$i.']"'; - } - } - if(!empty($AddRank['CBoxes'])) - { - foreach($AddRank['CBoxes'] as $Index => $Vals) - { - $_Lang['CBox_'.$Index] = implode(' ', $Vals); - } - } - - $Page = parsetemplate(gettemplate('alliance_admin_ranklist_table'), $_Lang); - display($Page, $_Lang['ADM_Title']); - } - else - { - message($_Lang['ADM_BadEditSelected'], $_Lang['ADM_Title'], 'alliance.php', 3); - } - } - } - else - { - // User is on Ally Front Page - include($_EnginePath.'includes/functions/BBcodeFunction.php'); - $_Lang = array_merge($_Lang, $Ally); - - $_Lang['ally_user_rank'] = $_ThisUserRank['name']; - if(empty($_Lang['ally_web'])) - { - $_Lang['ally_web'] = ' '; - } - else - { - $_Lang['ally_web'] = "{$_Lang['ally_web']}"; - } - - if($_ThisUserRank['mlist'] !== true) - { - $_Lang['HideShowMList'] = 'hide'; - } - if($_ThisUserRank['caninvite'] !== true) - { - $_Lang['HideInviteNewUser'] = 'hide'; - } - if($_ThisUserRank['sendmsg'] !== true) - { - $_Lang['HideSendMail'] = 'hide'; - } - if($Ally['ally_ChatRoom_ID'] <= 0 OR $_ThisUserRank['canusechat'] !== true) - { - $_Lang['HideAllyChat'] = 'hide'; - } - else - { - $_Lang['Insert_ChatRoomID'] = $Ally['ally_ChatRoom_ID']; - } - if($_ThisUserRank['admingen'] !== true) - { - $_Lang['HideAllyAdmin'] = 'hide'; - } - if($_ThisUserRank['lookreq'] !== true) - { - $_Lang['HideLookReq'] = 'hide'; - } - else - { - $RequestsCount = doquery("SELECT COUNT(*) AS `count` FROM {{table}} WHERE `ally_request` = {$Ally['id']};", 'users', true); - $RequestsCount = (string) ($RequestsCount['count'] + 0); - if($RequestsCount == 0) - { - $_Lang['HideLookReq'] = 'hide'; - } - $_Lang['RequestCount'] = $RequestsCount; - if($_ThisUserRank['managereq'] === true AND $RequestsCount > 0) - { - $_Lang['RequestColor'] = ' orange'; - } - } - - if($Ally['ally_owner'] == $_User['id']) - { - $_Lang['HideLeaveAlly'] = 'class="hide"'; - } - - // Ally Description - if(!empty($Ally['ally_description'])) - { - $_Lang['ally_description'] = nl2br(bbcode($Ally['ally_description'])); - } - else - { - $_Lang['ally_description'] = $_Lang['AFP_NoAllyDesc']; - } - // Ally InnerText - if(!empty($Ally['ally_text'])) - { - $_Lang['ally_text'] = nl2br(bbcode($Ally['ally_text'])); - } - else - { - $_Lang['ally_text'] = $_Lang['AFP_NoAllyInner']; - } - - $Page = parsetemplate(gettemplate('alliance_frontpage'), $_Lang); - display($Page, $_Lang['AFP_YouAlly']); - } - } - -?> \ No newline at end of file +'; + } + if(!empty($AllyRow['ally_description'])) + { + $_Lang['ally_description'] = nl2br(bbcode(stripslashes($AllyRow['ally_description']))); + } + else + { + $_Lang['ally_description'] = $_Lang['AInfo_NoAllyDesc']; + } + if(!empty($AllyRow['ally_web']) && ($AllyRow['ally_web_reveal'] == 1 || $_User['ally_id'] == $AllyRow['id'])) + { + $AllyRow['ally_web'] = stripslashes($AllyRow['ally_web']); + $_Lang['ally_web'] = "{$_Lang['AInfo_WebPage']}{$AllyRow['ally_web']}"; + } + $_Lang['ally_members'] = $AllyRow['ally_members']; + $_Lang['ally_name']= $AllyRow['ally_name']; + $_Lang['ally_tag'] = $AllyRow['ally_tag']; + + if($_User['ally_id'] == 0) + { + if($AllyRow['ally_request_notallow'] == 0) + { + $_Lang['Insert_Actions'] = "
"; + } + else + { + $_Lang['Insert_Actions'] = "{$_Lang['AInfo_RequestNotAllow']}"; + } + } + else if($_User['ally_id'] > 0 && $_User['ally_id'] == $AllyRow['id']) + { + $_Lang['Insert_Actions'] = "{$_Lang['AInfo_BelongToAlly']}"; + } + + $Page = parsetemplate(gettemplate('alliance_ainfo'), $_Lang); + display($Page, $_Lang['Alliance_information']); +} +// End of Ally Informations + +// --- Alliance Control +if($_User['ally_id'] == 0) +{ + // User has no Ally + if(isOnVacation()) + { + message($_Lang['Vacation_WarnMsg'], $_Lang['Vacation']); + } + if($_User['ally_request'] == 0) + { + // User has no any Request + if($mode == 'make') + { + // User wants to Make alliance + if(isset($_GET['yes'])) + { + // User sent data + $MsgTitle = &$_Lang['AMake_Title']; + + $CreateTag = trim($_POST['atag']); + $CreateName = trim($_POST['aname']); + $TagLength = strlen($CreateTag); + $NameLength = strlen($CreateName); + // Data checking + if($TagLength < $_MinLength_ATag) + { + message($_Lang['AMake_TagShort'], $MsgTitle, 'alliance.php?mode=make', 3); + } + if($TagLength > $_MaxLength_ATag) + { + message($_Lang['AMake_TagLong'], $MsgTitle, 'alliance.php?mode=make', 3); + } + if(!preg_match(REGEXP_ALLYTAG_ABSOLUTE, $CreateTag)) + { + message($_Lang['AMake_BadTag'], $MsgTitle, 'alliance.php?mode=make', 3); + } + if($NameLength < 1) + { + message($_Lang['AMake_NoName'], $MsgTitle, 'alliance.php?mode=make', 3); + } + if($NameLength > $_MaxLength_AName) + { + message($_Lang['AMake_NameLong'], $MsgTitle, 'alliance.php?mode=make', 3); + } + if(!preg_match(REGEXP_ALLYNAME_ABSOLUTE, $CreateName)) + { + message($_Lang['AMake_BadName'], $MsgTitle, 'alliance.php?mode=make', 3); + } + + $Query_ACreate_Check = ''; + $Query_ACreate_Check .= "SELECT `ally_tag`, `ally_name` FROM {{table}} "; + $Query_ACreate_Check .= "WHERE `ally_tag` = '{$CreateTag}' OR `ally_name` = '{$CreateName}' LIMIT 2;"; + + $Result_ACreate_Check = doquery($Query_ACreate_Check, 'alliance'); + $WarningBox = array(); + if(mysql_num_rows($Result_ACreate_Check)) + { + while($checkData = mysql_fetch_assoc($Result_ACreate_Check)) + { + if(strtolower($checkData['ally_tag']) == strtolower($CreateTag)) + { + $WarningBox[] = sprintf($_Lang['AMake_TagExists'], $CreateTag); + } + if(strtolower($checkData['ally_name']) == strtolower($CreateName)) + { + $WarningBox[] = sprintf($_Lang['AMake_NameExists'], $CreateName); + } + } + } + if(!empty($WarningBox)) + { + message(implode('
', $WarningBox), $MsgTitle, 'alliance.php?mode=make', 3); + } + + $RankDataLabelsCount = count($RankDataLabels) - 1; + $AllyCreate_Ranks = array(array('name' => $_Lang['AMake_AllyLeader'], 'vals' => true), array('name' => $_Lang['AMake_AllyNewComer'], 'vals' => false)); + foreach($AllyCreate_Ranks as $ThisRowData) + { + $ThisArray = array_fill(1, $RankDataLabelsCount, $ThisRowData['vals']); + $ThisArray = array_merge(array($ThisRowData['name']), $ThisArray); + $AllyCreate_RanksArray[] = $ThisArray; + } + $AllyCreate_RanksArray = mysql_real_escape_string(json_encode($AllyCreate_RanksArray)); + + $Query_ACreate_Create = ''; + $Query_ACreate_Create .= "INSERT INTO {{table}} SET "; + $Query_ACreate_Create .= "`ally_name` = '{$CreateName}', "; + $Query_ACreate_Create .= "`ally_tag`= '{$CreateTag}', "; + $Query_ACreate_Create .= "`ally_owner` = {$_User['id']}, "; + $Query_ACreate_Create .= "`ally_ranks` = '{$AllyCreate_RanksArray}', "; + $Query_ACreate_Create .= "`ally_members` = 1, "; + $Query_ACreate_Create .= "`ally_register_time` = UNIX_TIMESTAMP();"; + doquery($Query_ACreate_Create, 'alliance'); + + $Result_GetLastID = doquery("SELECT LAST_INSERT_ID() AS `ID`;", 'alliance', true); + $Result_GetLastID = $Result_GetLastID['ID']; + + $Query_ACreate_MakeChatRoom = ''; + $Query_ACreate_MakeChatRoom .= "INSERT INTO {{table}} SET "; + $Query_ACreate_MakeChatRoom .= "`AccessType` = 1, "; + $Query_ACreate_MakeChatRoom .= "`AccessCheck` = {$Result_GetLastID};"; + doquery($Query_ACreate_MakeChatRoom, 'chat_rooms'); + + $Query_ACreate_UpdateAlly = ''; + $Query_ACreate_UpdateAlly .= "UPDATE {{table}} SET `ally_ChatRoom_ID` = LAST_INSERT_ID() "; + $Query_ACreate_UpdateAlly .= "WHERE `id` = {$Result_GetLastID} LIMIT 1;"; + doquery($Query_ACreate_UpdateAlly, 'alliance'); + + $Query_ACreate_UpdateUser = ''; + $Query_ACreate_UpdateUser .= "UPDATE {{table}} SET "; + $Query_ACreate_UpdateUser .= "`ally_id` = {$Result_GetLastID}, "; + $Query_ACreate_UpdateUser .= "`ally_register_time` = UNIX_TIMESTAMP() "; + $Query_ACreate_UpdateUser .= "WHERE `id` = {$_User['id']};"; + doquery($Query_ACreate_UpdateUser, 'users'); + + CheckJobsDone('BUDDY_OR_ALLY_TASK', $_User['id']); + + message(sprintf($_Lang['AMake_Done'], $CreateName, $CreateTag), $MsgTitle, 'alliance.php', 3); + } + else + { + // Show Form + $Page = parsetemplate(gettemplate('alliance_make'), $_Lang); + display($Page, $_Lang['AMake_Title']); + } + } + else if($mode == 'search') + { + // Ally search engine + $searchText = null; + if(!empty($_POST['searchtext'])) + { + $searchText = trim($_POST['searchtext']); + } + else if(!empty($_GET['searchtext'])) + { + $searchText = trim($_GET['searchtext']); + } + $_Lang['searchtext'] = $searchText; + $ProtectedSearchText = preg_replace($Sanitize4SQLSearch, $Sanitize4SQLReplace, $searchText); + + // Show Form + $Page = parsetemplate(gettemplate('alliance_searchform'), $_Lang); + + if(!empty($searchText)) + { + if(!preg_match(REGEXP_ALLYNAMEANDTAG, $searchText)) + { + message($_Lang['AFind_BadSigns'], $_Lang['AFind_Title'], 'alliance.php?mode=search', 3); + } + + $sPage = (isset($_GET['spage']) ? intval($_GET['spage']) : 0); + if($sPage < 1) + { + $sPage = 1; + } + $perPage = 20; + $startFrom = ($sPage - 1) * $perPage; + + $Query_ASearch_Count = ''; + $Query_ASearch_Count .= "SELECT COUNT(*) AS `Count` FROM {{table}} "; + $Query_ASearch_Count .= "WHERE `ally_name` LIKE '%{$ProtectedSearchText}%' OR `ally_tag` LIKE '%{$ProtectedSearchText}%';"; + + $Result_ASearch_Count = doquery($Query_ASearch_Count, 'alliance', true); + $TotalCount = $Result_ASearch_Count['Count']; + + if($TotalCount > 0) + { + if($TotalCount < $startFrom) + { + $sPage = ceil($TotalCount / $perPage); + $startFrom = ($sPage - 1) * $perPage; + } + + $Query_ASearch_Search = ''; + $Query_ASearch_Search .= "SELECT `id`, `ally_tag`, `ally_name`, `ally_members` FROM {{table}} "; + $Query_ASearch_Search .= "WHERE ally_name LIKE '%{$ProtectedSearchText}%' or ally_tag LIKE '%{$ProtectedSearchText}%' LIMIT {$startFrom}, {$perPage};"; + + $Result_ASearch_Search = doquery($Query_ASearch_Search, 'alliance'); + + $SearchRowTPL = gettemplate('alliance_searchresult_row'); + $_Lang['result'] = ''; + while($Result = mysql_fetch_assoc($Result_ASearch_Search)) + { + $SanitizeSearch = preg_replace($TagOrNameSanitize, '\\\$1', $searchText); + $Result['ally_tag'] = preg_replace('#('.$SanitizeSearch.'){1,}#si', '$1', $Result['ally_tag']); + $Result['ally_name'] = preg_replace('#('.$SanitizeSearch.'){1,}#si', '$1', $Result['ally_name']); + $_Lang['result'] .= parsetemplate($SearchRowTPL, $Result); + } + + if($TotalCount > $perPage) + { + include_once($_EnginePath.'includes/functions/Pagination.php'); + $Pagin = CreatePaginationArray($TotalCount, $perPage, $sPage, 7); + $PaginationTPL = "{\$ShowValue}"; + $PaginationViewOpt = array('CurrentPage_Classes' => 'orange', 'Breaker_View' => '...'); + $CreatePagination = implode(' ', ParsePaginationArray($Pagin, $sPage, $PaginationTPL, $PaginationViewOpt)); + + $pagination = ''.$CreatePagination.''; + $_Lang['pagination'] = $pagination; + } + } + else + { + $_Lang['result'] = "{$_Lang['AFind_NothingFound']}"; + } + $Page .= parsetemplate(gettemplate('alliance_searchresult_table'), $_Lang); + } + display($Page, $_Lang['AFind_Title']); + } + else if($mode == 'apply') + { + // Send Request + $MsgTitle = &$_Lang['AApp_Title']; + + $AllyID = (isset($_GET['allyid']) ? intval($_GET['allyid']) : 0); + if($AllyID <= 0) + { + message($_Lang['AApp_BadID'], $MsgTitle); + } + + $Query_AApply_Check = ''; + $Query_AApply_Check .= "SELECT `id`, `ally_name`, `ally_tag`, `ally_request`, `ally_request_notallow` FROM {{table}} "; + $Query_AApply_Check .= "WHERE `id` = {$AllyID} LIMIT 1;"; + + $Result_AApply_Check = doquery($Query_AApply_Check, 'alliance', true); + if($Result_AApply_Check['id'] != $AllyID) + { + message($_Lang['AApp_AllyNoExists'], $MsgTitle); + } + if($Result_AApply_Check['ally_request_notallow'] == 1) + { + message($_Lang['AApp_AllyBlockRequest'], $MsgTitle); + } + + if(isset($_POST['send']) && $_POST['send'] == 'yes' && (!isset($_POST['action']) || $_POST['action'] != $_Lang['AApp_UseExample'])) + { + $RequestText = strip_tags(stripslashes(trim($_POST['text']))); + if(!empty($RequestText)) + { + $RequestText = mysql_real_escape_string(substr($RequestText, 0, $_MaxLength_Request)); + doquery("UPDATE {{table}} SET `ally_request` = {$AllyID}, `ally_request_text` = '{$RequestText}', `ally_register_time` = UNIX_TIMESTAMP() WHERE `id` = {$_User['id']};", 'users'); + message($_Lang['AApp_Done'], $MsgTitle, 'alliance.php', 3); + } + else + { + message($_Lang['AApp_NoText'], $MsgTitle, 'alliance.php?mode=apply&allyid='.$AllyID, 3); + } + } + + $text_apply = ($Result_AApply_Check['ally_request'] ? stripslashes($Result_AApply_Check['ally_request']) : $_Lang['AApp_NoSample']); + + $_Lang['allyid'] = $AllyID; + $_Lang['text_apply'] = $text_apply; + $_Lang['Write_to_alliance'] = sprintf($_Lang['AApp_WriteRequest'], $Result_AApply_Check['ally_name'], $Result_AApply_Check['ally_tag']); + $_Lang['Insert_MaxLength'] = $_MaxLength_Request; + + $Page = parsetemplate(gettemplate('alliance_applyform'), $_Lang); + display($Page, $MsgTitle); + } + else + { + // Show Default Menu & Invites List + + if(isset($_GET['cmd']) && ($_GET['cmd'] == 'inv_accept' || $_GET['cmd'] == 'inv_reject')) + { + $Inv_AllyID = (isset($_GET['aid']) ? intval($_GET['aid']) : 0); + if($Inv_AllyID > 0) + { + $Query_InvUse_Check = ''; + $Query_InvUse_Check .= "SELECT `ai`.`SenderID`, `ally`.`ally_new_rank_id`, `ally`.`ally_ChatRoom_ID`FROM `{{table}}` AS `ai` "; + $Query_InvUse_Check .= "LEFT JOIN `{{prefix}}alliance` AS `ally` ON `ally`.`id` = `ai`.`AllyID` "; + $Query_InvUse_Check .= "WHERE `ai`.`OwnerID` = {$_User['id']} AND `ai`.`AllyID` = {$Inv_AllyID} AND `ai`.`State` = 1;"; + $Result_InvUse_Check = doquery($Query_InvUse_Check, 'ally_invites', true); + if($Result_InvUse_Check['SenderID'] > 0) + { + if($_GET['cmd'] == 'inv_accept') + { + doquery("UPDATE {{table}} SET `ally_request` = 0, `ally_request_text` = '', `ally_id` = {$Inv_AllyID}, `ally_rank_id` = {$Result_InvUse_Check['ally_new_rank_id']}, `ally_register_time` = UNIX_TIMESTAMP() WHERE `id` = {$_User['id']};", 'users'); + doquery("UPDATE {{table}} SET `ally_members` = `ally_members` + 1 WHERE `id` = {$Inv_AllyID};", 'alliance'); + doquery("UPDATE {{table}} SET `State` = IF(`AllyID` = {$Inv_AllyID}, 0, -1) WHERE `OwnerID` = {$_User['id']} AND `State` = 1 LIMIT 1;", 'ally_invites'); + if($Result_InvUse_Check['ally_ChatRoom_ID'] > 0) + { + $Query_UpdateChatRoomOnline = ''; + $Query_UpdateChatRoomOnline .= "INSERT INTO {{table}} VALUES ({$Result_InvUse_Check['ally_ChatRoom_ID']}, {$_User['id']}, UNIX_TIMESTAMP()) "; + $Query_UpdateChatRoomOnline .= "ON DUPLICATE KEY UPDATE "; + $Query_UpdateChatRoomOnline .= "`LastOnline` = VALUES(`LastOnline`);"; + doquery($Query_UpdateChatRoomOnline, 'chat_online'); + } + CheckJobsDone('BUDDY_OR_ALLY_TASK', $_User['id']); + + message($_Lang['AMenu_Inv_MsgAcceptSuccess'], $_Lang['Ally'], 'alliance.php', 3); + } + else + { + doquery("UPDATE {{table}} SET `State` = -1 WHERE `AllyID` = {$Inv_AllyID} AND `OwnerID` = {$_User['id']} AND `State` = 1 LIMIT 1;", 'ally_invites'); + + $MsgBox = array('text' => $_Lang['AMenu_Inv_MsgRejectSuccess'], 'col' => 'lime'); + } + } + else + { + $MsgBox = array('text' => $_Lang['AMenu_Inv_MsgNotFound'], 'col' => 'red'); + } + } + else + { + $MsgBox = array('text' => $_Lang['AMenu_Inv_MsgBadID'], 'col' => 'red'); + } + } + + $Query_InvList_Get = ''; + $Query_InvList_Get .= "SELECT `ai`.*, `u`.`username` AS `Sender_Name`, `a`.`ally_name` AS `Ally_Name` FROM {{table}} AS `ai` "; + $Query_InvList_Get .= "LEFT JOIN `{{prefix}}users` AS `u` ON `u`.`id` = `ai`.`SenderID` "; + $Query_InvList_Get .= "LEFT JOIN `{{prefix}}alliance` AS `a` ON `a`.`id` = `ai`.`AllyID` "; + $Query_InvList_Get .= "WHERE `ai`.`OwnerID` = {$_User['id']} AND `State` != 0 "; + $Query_InvList_Get .= " ORDER BY `ai`.`State` DESC, `ai`.`Date` DESC;"; + $Result_InvList_Get = doquery($Query_InvList_Get, 'ally_invites'); + if(mysql_num_rows($Result_InvList_Get) > 0) + { + $TPL_Row = gettemplate('alliance_defaultmenu_invites_row'); + while($FetchData = mysql_fetch_assoc($Result_InvList_Get)) + { + $FetchData['Date'] = prettyDate('d m Y, H:i:s', $FetchData['Date'], 1); + if($FetchData['State'] == 1) + { + $FetchData['Actions'][] = ""; + $FetchData['Actions'][] = ""; + } + $FetchData['State'] = $_Lang['AMenu_Inv_States'][((string)($FetchData['State'] + 0))]; + + if(!empty($FetchData['Actions'])) + { + $FetchData['Actions'] = implode('', $FetchData['Actions']); + } + else + { + $FetchData['Actions'] = ' '; + } + $_Lang['Insert_InviteRows'][] = parsetemplate($TPL_Row, $FetchData); + } + $_Lang['Insert_InviteRows'] = implode('', $_Lang['Insert_InviteRows']); + } + else + { + $_Lang['Insert_InviteRows'] = parsetemplate(gettemplate('_singleRow'), array('Colspan' => 4, 'Classes' => 'orange pad5', 'Text' => $_Lang['AMenu_Inv_NoRows'])); + } + if(!empty($MsgBox)) + { + $_Lang['MsgBox'] = ''.$MsgBox['text'].''; + } + + $Page = parsetemplate(gettemplate('alliance_defaultmenu'), $_Lang); + display($Page, $_Lang['Ally']); + } + } + else + { + // User has a Request + $MsgTitle = $_Lang['AReq_Title']; + + $Query_ARequest_Get = "SELECT `ally_name`, `ally_tag` FROM {{table}} WHERE `id` = {$_User['ally_request']} LIMIT 1;"; + $Result_ARequest_Get = doquery($Query_ARequest_Get, 'alliance', true); + if(!empty($_POST['cancel'])) + { + // Cancel the Request + doquery("UPDATE {{table}} SET `ally_request` = 0, `ally_request_text` = '', `ally_register_time` = 0 WHERE `id` = {$_User['id']};", 'users'); + message(sprintf($_Lang['AReq_Canceled'], $Result_ARequest_Get['ally_name'], $Result_ARequest_Get['ally_tag']), $MsgTitle, 'alliance.php', 3); + } + $_Lang['RequestText'] = sprintf($_Lang['AReq_Waiting'], $_User['ally_request'], $Result_ARequest_Get['ally_name'], $Result_ARequest_Get['ally_tag']); + $Page = parsetemplate(gettemplate('alliance_apply_waitform'), $_Lang); + display($Page, $MsgTitle); + } +} +elseif($_User['ally_id'] > 0 AND $_User['ally_request'] == 0) +{ + // User is in Alliance + $MsgTitle = &$_Lang['Ally_Title']; + + // First, parse AllyData + $Ally = doquery("SELECT * FROM {{table}} WHERE `id` = {$_User['ally_id']} LIMIT 1;", 'alliance', true); + if($Ally['id'] <= 0) + { + doquery("UPDATE {{table}} SET `ally_id` = 0 WHERE `id` = {$_User['id']};", 'users'); + message($_Lang['Ally_GetAllyError'], $MsgTitle); + } + + $Ally['ally_ranks'] = json_decode($Ally['ally_ranks'], true); + $Ally['ally_ranks_org'] = $Ally['ally_ranks']; + foreach($Ally['ally_ranks'] as $RankID => $RankData) + { + foreach($RankData as $DataID => $DataVal) + { + $NewRankArray[$RankID][$RankDataLabels[$DataID]] = $DataVal; + } + } + $Ally['ally_ranks'] = $NewRankArray; + $Ally['ally_ranks_count'] = count($RankDataLabels); + $NewRankArray = null; + + // Check ThisUser Rights + if($Ally['ally_owner'] == $_User['id']) + { + // This User is Main AllyAdmin (Rank #0 is only for him) + $_ThisUserRank = $Ally['ally_ranks'][0]; + $_ThisUserRank['is_admin'] = true; + } + else + { + // This User is not Main AllyAdmin + $_ThisUserRank = $Ally['ally_ranks'][$_User['ally_rank_id']]; + $_ThisUserRank['is_admin'] = false; + } + + if($mode == 'exit') + { + // User is trying to leave the Ally + if(isOnVacation()) + { + message($_Lang['Vacation_WarnMsg'], $_Lang['Vacation']); + } + + if($Ally['ally_owner'] == $_User['id']) + { + message($_Lang['Ally_Leave_MAdminInfo'], $MsgTitle, 'alliance.php', 3); + } + doquery("UPDATE {{table}} SET `ally_id` = 0 WHERE `id` = {$_User['id']};", 'users'); + doquery("UPDATE {{table}} SET `ally_members` = `ally_members` - 1 WHERE `id` = {$Ally['id']};", 'alliance'); + doquery("UPDATE {{table}} SET `State` = -2 WHERE `State` = 1 AND `SenderID` = {$_User['id']};", 'ally_invites'); + message(sprintf($_Lang['Ally_Leave_Done'], $Ally['ally_name']), $MsgTitle); + } + else if($mode == 'mlist' OR $mode == 'memberslist') + { + // User is trying to view Members List + if($_ThisUserRank['mlist'] !== true) + { + message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php', 3); + } + + createMembersList(); + $Page = parsetemplate(gettemplate('alliance_memberslist_table'), $_Lang); + display($Page, $_Lang['Ally_ML_WinTitle']); + } + else if($mode == 'pactslist') + { + // User is trying to See Ally Pacts + include($_EnginePath.'modules/ally.pactslist.php'); + } + else if($mode == 'newpact') + { + // User is trying to create new Pact + include($_EnginePath.'modules/ally.newpact.php'); + } + else if($mode == 'changepact') + { + // User is trying to modify existing Pact + include($_EnginePath.'modules/ally.changepact.php'); + } + else if($mode == 'circular' OR $mode == 'sendmsg') + { + // User is trying to Send Mass Message (to Ally Members) + if($_ThisUserRank['sendmsg'] !== true) + { + message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php', 3); + } + + $_Lang['SelectedAll'] = 'selected'; + $SendMass_Ranks = null; + $SendMass_Text = null; + if(isset($_GET['send'])) + { + $_POST['text'] = stripslashes(trim($_POST['text'])); + if(get_magic_quotes_gpc()) + { + $_POST['text'] = stripslashes($_POST['text']); + } + $SendMass_Text = substr(strip_tags($_POST['text']), 0, $_MaxLength_Text); + if($_POST['rank_select'] != 'all') + { + $SendMass_Ranks = intval($_POST['rank_select']); + if(empty($Ally['ally_ranks'][$SendMass_Ranks]['name'])) + { + $SendMass_Ranks = null; + } + } + else + { + $_Lang['SelectedAll'] = 'selected'; + $SendMass_Ranks = true; + } + if(!empty($SendMass_Text)) + { + if($SendMass_Ranks !== null) + { + $Query_AMassMsg_Members = ''; + $Query_AMassMsg_Members .= "SELECT `id`, `username` FROM {{table}} "; + $Query_AMassMsg_Members .= "WHERE `ally_id` = {$_User['ally_id']} "; + if($SendMass_Ranks !== true) + { + $Query_AMassMsg_Members .= " AND `ally_rank_id` = {$SendMass_Ranks}"; + } + $Result_AMassMsg_Members = doquery($Query_AMassMsg_Members, 'users'); + + if(mysql_num_rows($Result_AMassMsg_Members) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_AMassMsg_Members)) + { + $UsersID[] = $FetchData['id']; + $UsersNicks[] = $FetchData['username']; + } + + $FirstMSGID = SendSimpleMessage($UsersID[0], $_User['id'], $Time, 2, "[{$Ally['ally_tag']}]", $_Lang['Ally_WR_Subject'].$_User['username'], $SendMass_Text, true); + unset($UsersID[0]); + if(!empty($UsersID)) + { + Cache_Message($UsersID, $_User['id'], $Time, 2, '', '', '{COPY_MSG_#'.$FirstMSGID.'}'); + } + $MsgBox = array('text' => $_Lang['Ally_WR_Done'].implode(', ', $UsersNicks), 'col' => 'lime'); + } + else + { + $MsgBox = array('text' => $_Lang['Ally_WR_RankHasNoUsers'], 'col' => 'red'); + } + } + else + { + $MsgBox = array('text' => $_Lang['Ally_WR_NoRankSelect'], 'col' => 'red'); + } + } + else + { + $MsgBox = array('text' => $_Lang['Ally_WR_MsgEmpty'], 'col' => 'red'); + } + } + + if(!empty($MsgBox)) + { + $_Lang['MsgBox'] = ''.$MsgBox['text'].''; + } + + $_Lang['PutMessage'] = $SendMass_Text; + $_Lang['OtherRanks'] = ''; + foreach($Ally['ally_ranks'] as $Index => $Data) + { + if($SendMass_Ranks === $Index) + { + $ThisSelected = 'selected'; + } + else + { + $ThisSelected = ''; + } + $_Lang['OtherRanks'] .= ""; + } + + $_Lang['Insert_MaxLength'] = $_MaxLength_MassMsg; + $Page = parsetemplate(gettemplate('alliance_circular'), $_Lang); + display($Page, $_Lang['Ally_WR_WinTitle']); + } + else if($mode == 'invite') + { + // User is trying to Invite someone + if($_ThisUserRank['caninvite'] !== true) + { + message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php', 3); + } + + $Invite_Text = (isset($_POST['text']) ? stripslashes(strip_tags(trim($_POST['text']))) : null); + $_Lang['Insert_Text'] = $Invite_Text; + if(!empty($_GET['uid']) || (!empty($_POST['uid']) && $_POST['unamechanged'] != '1')) + { + if(!empty($_POST['uid'])) + { + $Invite_UID = intval($_POST['uid']); + } + else + { + $Invite_UID = intval($_GET['uid']); + $Invite_FromGet = true; + } + if($Invite_UID > 0) + { + $Query_AInvite_CheckUserWhere = "`id` = {$Invite_UID}"; + } + } + else if(!empty($_POST['username'])) + { + $Invite_UName = trim($_POST['username']); + if(preg_match(REGEXP_USERNAME_ABSOLUTE, $Invite_UName)) + { + $Query_AInvite_CheckUserWhere = "`username` = '{$Invite_UName}'"; + } + } + + if(!empty($Query_AInvite_CheckUserWhere)) + { + $Query_AInvite_CheckUser = "SELECT `id`, `username`, `ally_id` FROM {{table}} WHERE {$Query_AInvite_CheckUserWhere} LIMIT 1;"; + $Result_AInvite_CheckUser = doquery($Query_AInvite_CheckUser, 'users', true); + if($Result_AInvite_CheckUser['id'] > 0) + { + if($Result_AInvite_CheckUser['ally_id'] == 0) + { + $_Lang['Insert_UID'] = $Invite_UID = $Result_AInvite_CheckUser['id']; + $_Lang['Insert_Username'] = $Result_AInvite_CheckUser['username']; + if(isset($Invite_FromGet)) + { + $_Lang['Insert_LockUsername'] = 'disabled'; + } + + if($_GET['send'] == '1') + { + if(!empty($Invite_Text)) + { + $Invite_Text = substr($Invite_Text, 0, $_MaxLength_Invitation); + + $Query_AInvite_CheckInvite = ''; + $Query_AInvite_CheckInvite .= "SELECT COUNT(*) AS `Count` FROM {{table}} WHERE "; + $Query_AInvite_CheckInvite .= "`AllyID` = {$Ally['id']} AND `OwnerID` = {$Invite_UID} AND `State` = 1;"; + $Result_AInvite_CheckInvite = doquery($Query_AInvite_CheckInvite, 'ally_invites', true); + if($Result_AInvite_CheckInvite['Count'] <= 0) + { + $Query_AInvite_Insert = ''; + $Query_AInvite_Insert .= "INSERT INTO {{table}} (`AllyID`, `OwnerID`, `SenderID`, `Date`) VALUES "; + $Query_AInvite_Insert .= "({$Ally['id']}, {$Invite_UID}, {$_User['id']}, UNIX_TIMESTAMP()) "; + $Query_AInvite_Insert .= "ON DUPLICATE KEY UPDATE `AllyID` = `AllyID`;"; + doquery($Query_AInvite_Insert, 'ally_invites'); + + $Message = array(); + $Message['msg_id'] = '095'; + $Message['args'] = array + ( + $Ally['id'], $Ally['ally_name'], $Ally['ally_tag'], $_User['id'], $_User['username'], $Invite_Text + ); + $Message = json_encode($Message); + Cache_Message($Invite_UID, 0, NULL, 2, '005', '023', $Message); + + $MsgBox = array('text' => sprintf($_Lang['Ally_INV_Msg_Success'], $Invite_UID, $Result_AInvite_CheckUser['username']), 'col' => 'lime'); + } + else + { + $MsgBox = array('text' => $_Lang['Ally_INV_Msg_AlreadyInvited'], 'col' => 'red'); + } + $_Lang['Insert_UID'] = $_Lang['Insert_Username'] = $_Lang['Insert_LockUsername'] = ''; + } + else + { + $MsgBox = array('text' => $_Lang['Ally_INV_Msg_EmptyText'], 'col' => 'red'); + } + } + } + else + { + $MsgBox = array('text' => $_Lang['Ally_INV_Msg_UserInAlly'], 'col' => 'red'); + } + } + else + { + $MsgBox = array('text' => $_Lang['Ally_INV_Msg_UserNoExists'], 'col' => 'red'); + } + } + else + { + if(isset($_GET['send'])) + { + $MsgBox = array('text' => $_Lang['Ally_INV_Msg_BadInput'], 'col' => 'red'); + } + } + + if(!empty($MsgBox)) + { + $_Lang['MsgBox'] = ''.$MsgBox['text'].''; + } + + $_Lang['Insert_MaxLength'] = $_MaxLength_Invitation; + $Page = parsetemplate(gettemplate('alliance_invite'), $_Lang); + display($Page, $_Lang['Ally_INV_Title']); + } + else if($mode == 'invlist') + { + // User is trying to show Invites List + if(!empty($_GET['del'])) + { + $InvList_DelID = intval($_GET['del']); + if($InvList_DelID > 0) + { + $Query_InvList_Delete = ''; + $Query_InvList_Delete .= "SELECT `SenderID` FROM {{table}} "; + $Query_InvList_Delete .= "WHERE `AllyID` = {$Ally['id']} AND `OwnerID` = {$InvList_DelID} AND `State` = 1 LIMIT 1;"; + $Result_InvList_Delete = doquery($Query_InvList_Delete, 'ally_invites', true); + if($Result_InvList_Delete['SenderID'] > 0) + { + if($_ThisUserRank['managereq'] === true OR $_User['id'] == $Result_InvList_Delete['SenderID']) + { + if($_User['id'] == $Result_InvList_Delete['SenderID']) + { + $SetState = '-2'; + } + else + { + $SetState = '-3'; + } + doquery("UPDATE {{table}} SET `State` = {$SetState} WHERE `AllyID` = {$Ally['id']} AND `OwnerID` = {$InvList_DelID} AND `State` = 1 LIMIT 1;", 'ally_invites'); + $MsgBox = array('text' => $_Lang['Ally_INVList_MsgSuccess'], 'col' => 'lime'); + } + else + { + $MsgBox = array('text' => $_Lang['Ally_INVList_MsgCantDel'], 'col' => 'red'); + } + } + else + { + $MsgBox = array('text' => $_Lang['Ally_INVList_MsgNotFound'], 'col' => 'red'); + } + } + else + { + $MsgBox = array('text' => $_Lang['Ally_INVList_MsgBadID'], 'col' => 'red'); + } + } + + $Query_InvList_Get = ''; + $Query_InvList_Get .= "SELECT `ai`.*, `u1`.`username` AS `Owner_Name`, `u2`.`username` AS `Sender_Name` FROM {{table}} AS `ai` "; + $Query_InvList_Get .= "LEFT JOIN `{{prefix}}users` AS `u1` ON `u1`.`id` = `ai`.`OwnerID` "; + $Query_InvList_Get .= "LEFT JOIN `{{prefix}}users` AS `u2` ON `u2`.`id` = `ai`.`SenderID` "; + $Query_InvList_Get .= "WHERE `ai`.`AllyID` = {$Ally['id']} "; + if($_ThisUserRank['lookreq'] !== true) + { + $Query_InvList_Get .= " AND `ai`.`SenderID` = {$_User['id']}"; + } + $Query_InvList_Get .= " ORDER BY `ai`.`State` DESC, `ai`.`Date` DESC;"; + $Result_InvList_Get = doquery($Query_InvList_Get, 'ally_invites'); + if(mysql_num_rows($Result_InvList_Get) > 0) + { + $TPL_Row = gettemplate('alliance_invlist_row'); + while($FetchData = mysql_fetch_assoc($Result_InvList_Get)) + { + $FetchData['Date'] = prettyDate('d m Y, H:i:s', $FetchData['Date'], 1); + if($FetchData['State'] == 1 AND ($_ThisUserRank['managereq'] === true OR $_User['id'] == $FetchData['SenderID'])) + { + $FetchData['Actions'][] = ""; + } + $FetchData['State'] = $_Lang['Ally_INVList_States'][((string)($FetchData['State'] + 0))]; + + if(!empty($FetchData['Actions'])) + { + $FetchData['Actions'] = implode('', $FetchData['Actions']); + } + else + { + $FetchData['Actions'] = ' '; + } + $_Lang['Insert_Rows'][] = parsetemplate($TPL_Row, $FetchData); + } + $_Lang['Insert_Rows'] = implode('', $_Lang['Insert_Rows']); + } + else + { + $_Lang['Insert_Rows'] = parsetemplate(gettemplate('_singleRow'), array('Colspan' => 5, 'Classes' => 'orange pad5', 'Text' => $_Lang['Ally_INVList_NoRows'])); + } + + if(!empty($MsgBox)) + { + $_Lang['MsgBox'] = ''.$MsgBox['text'].''; + } + $Page = parsetemplate(gettemplate('alliance_invlist_body'), $_Lang); + display($Page, $_Lang['Ally_INVList_Title']); + } + else if($mode == 'admin') + { + // User has entered Admin mode + if(isOnVacation()) + { + message($_Lang['Vacation_WarnMsg'], $_Lang['Vacation']); + } + + if($_ThisUserRank['admingen'] !== true) + { + $_Lang['HideManageAllyData'] = 'hide'; + $Hiding += 1; + } + if($_ThisUserRank['mlist_mod'] !== true) + { + $_Lang['HideManageMemList'] = 'hide'; + $Hiding += 1; + } + if($_ThisUserRank['ranks_mod'] !== true) + { + $_Lang['HideManageRanks'] = 'hide'; + $Hiding += 1; + } + if($_ThisUserRank['lookreq'] !== true) + { + $_Lang['HideLookReq'] = 'hide'; + $Hiding += 1; + } + if(isset($Hiding) && $Hiding == 4) + { + message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php', 3); + } + + if(empty($edit)) + { + // User is on AllyAdmin Front Page + $_Lang['HideInfoBox'] = $_Lang['HideWarnBox'] = 'hide'; + $_Lang['GetLastMark'] = 'Mark01'; + + $NewcomerRankSet = array(); + $NewcomerRankSetGray = array(); + foreach($Ally['ally_ranks'] as $RankID => $RankData) + { + if($RankID == 0) + { + continue; + } + if(($RankData['like_admin'] === true AND $_ThisUserRank['is_admin'] !== true) OR $_ThisUserRank['like_admin'] !== true) + { + $NewcomerRankSetGray[] = $RankID; + } + $NewcomerRankSet[] = $RankID; + } + + if(isset($_POST['change']) && $_POST['change'] == 'texts') + { + if($_ThisUserRank['admingen'] === true) + { + $NotChanged = 0; + if($_POST['mode'] == 'saveAll' OR ($_POST['mode'] == 'saveOne' AND $_POST['saveonly'] == 'Mark01')) + { + $TempText = trim(strip_tags(stripslashes($_POST['ext_text']))); + if(strlen($TempText) > $_MaxLength_ExtText) + { + $TempText = substr($TempText, 0, $_MaxLength_ExtText); + $Warnings[] = $_Lang['ADM_ExtTextCutted']; + } + if($TempText != $Ally['ally_description']) + { + $InsertText = mysql_real_escape_string($TempText); + $ChangeQuery[] = "`ally_description` = '{$InsertText}'"; + $Ally['ally_description'] = $TempText; + $Info[] = $_Lang['ADM_ExtTextChanged']; + } + else + { + $NotChanged += 1; + } + } + if($_POST['mode'] == 'saveAll' OR ($_POST['mode'] == 'saveOne' AND $_POST['saveonly'] == 'Mark02')) + { + $TempText = trim(strip_tags(stripslashes($_POST['int_text']))); + if(strlen($TempText) > $_MaxLength_IntText) + { + $TempText = substr($TempText, 0, $_MaxLength_IntText); + $Warnings[] = $_Lang['ADM_IntTextCutted']; + } + if($TempText != $Ally['ally_text']) + { + $InsertText = mysql_real_escape_string($TempText); + $ChangeQuery[] = "`ally_text` = '{$InsertText}'"; + $Ally['ally_text'] = $TempText; + $Info[] = $_Lang['ADM_IntTextChanged']; + } + else + { + $NotChanged += 1; + } + } + if($_POST['mode'] == 'saveAll' OR ($_POST['mode'] == 'saveOne' AND $_POST['saveonly'] == 'Mark03')) + { + $TempText = trim(strip_tags(stripslashes($_POST['req_text']))); + if(strlen($TempText) > $_MaxLength_Request) + { + $TempText = substr($TempText, 0, $_MaxLength_Request); + $Warnings[] = $_Lang['ADM_ReqTextCutted']; + } + if($TempText != $Ally['ally_request']) + { + $InsertText = mysql_real_escape_string($TempText); + $ChangeQuery[] = "`ally_request` = '{$InsertText}'"; + $Ally['ally_request'] = $TempText; + $Info[] = $_Lang['ADM_ReqTextChanged']; + } + else + { + $NotChanged += 1; + } + } + if($NotChanged == 3 OR ($_POST['mode'] == 'saveOne' AND $NotChanged == 1)) + { + $Info[] = $_Lang['ADM_NothingChanged']; + } + if(!empty($ChangeQuery)) + { + doquery("UPDATE {{table}} SET ".implode(', ', $ChangeQuery)." WHERE `id` = {$Ally['id']};", 'alliance'); + } + + if(!empty($_POST['saveonly']) AND in_array($_POST['saveonly'], array('Mark01', 'Mark02', 'Mark03'))) + { + $_Lang['GetLastMark'] = $_POST['saveonly']; + } + } + else + { + $Warnings[] = $_Lang['ADM_TextChgNoAccess']; + } + } + else if(isset($_POST['change']) && $_POST['change'] == 'reqset') + { + if($_ThisUserRank['like_admin'] === true) + { + // Set, if Ally is open for new Requests + $NotChanged = 0; + + $SetAllyOpen = intval($_POST['allyOpen']); + if($SetAllyOpen == 0 OR $SetAllyOpen == 1) + { + $SetAllyOpen = ($SetAllyOpen == 1 ? 0 : 1); + if($SetAllyOpen != $Ally['ally_request_notallow']) + { + $ChangeQuery[] = "`ally_request_notallow` = {$SetAllyOpen}"; + $Ally['ally_request_notallow'] = $SetAllyOpen; + $Info[] = $_Lang['ADM_ReqSetOpenChanged']; + } + else + { + $NotChanged += 1; + } + } + else + { + $Warnings[] = $_Lang['ADM_ReqSetOpenBadOption']; + } + // Set Newcomer default Rank + $SetNewcomerRank = intval($_POST['newComerRank']); + if($SetNewcomerRank > 0) + { + if($SetNewcomerRank != $Ally['ally_new_rank_id']) + { + if(in_array($SetNewcomerRank, $NewcomerRankSet)) + { + if(!in_array($SetNewcomerRank, $NewcomerRankSetGray)) + { + $ChangeQuery[] = "`ally_new_rank_id` = {$SetNewcomerRank}"; + $Ally['ally_new_rank_id'] = $SetNewcomerRank; + $Info[] = $_Lang['ADM_ReqSetRankChanged']; + } + else + { + $Warnings[] = $_Lang['ADM_OnlyAdminCanSetThis']; + } + } + else + { + $Warnings[] = $_Lang['ADM_RankNoExist']; + } + } + else + { + $NotChanged += 1; + } + } + else + { + if($SetNewcomerRank == 0) + { + $NotChanged += 1; + } + else + { + $Warnings[] = $_Lang['ADM_ReqSetBadRank']; + } + } + + if($NotChanged == 2) + { + $Info[] = $_Lang['ADM_NothingChanged']; + } + if(!empty($ChangeQuery)) + { + doquery("UPDATE {{table}} SET ".implode(', ', $ChangeQuery)." WHERE `id` = {$Ally['id']};", 'alliance'); + } + } + else + { + $Warnings[] = $_Lang['ADM_ReqSetNoAccess']; + } + } + + if(!empty($Info)) + { + $_Lang['Info_Box'] = implode('
', $Info); + $_Lang['HideInfoBox'] = ''; + } + else + { + $_Lang['HideInfoBox'] = 'hide'; + } + if(!empty($Warnings)) + { + $_Lang['Warn_Box'] = implode('
', $Warnings); + $_Lang['HideWarnBox'] = ''; + } + else + { + $_Lang['HideWarnBox'] = 'hide'; + } + + $_Lang['Req_Text'] = $Ally['ally_request']; + $_Lang['Int_Text'] = $Ally['ally_text']; + $_Lang['Ext_Text'] = $Ally['ally_description']; + + if($Ally['ally_owner'] != $_User['id']) + { + $_Lang['HideHandOver'] = $_Lang['HideDeleteAlly'] = 'hide'; + } + $_Lang['CollapseReqSetButton'] = 'collapse'; + if($_ThisUserRank['like_admin'] !== true) + { + $_Lang['CollapseReqSet'] = 'collapsed'; + $_Lang['CollapseReqSetButton'] = 'expand'; + $_Lang['DisableReqSetInputs'] = 'disabled'; + } + if($_ThisUserRank['admingen'] !== true) + { + $_Lang['HideTextsSet'] = 'hide'; + } + $_Lang['NewComersRankRows'] = ''; + $DisabledCount = 0; + foreach($NewcomerRankSet as $RankID) + { + $ThisSetDisabled = ''; + $ThisSetSelected = ''; + if(in_array($RankID, $NewcomerRankSetGray)) + { + $ThisSetDisabled = ' class="disNCOpt" disabled'; + $DisabledCount += 1; + } + if($RankID == $Ally['ally_new_rank_id']) + { + $ThisSetSelected = ' selected'; + } + $_Lang['NewComersRankRows'] .= ""; + } + if(empty($_Lang['DisableReqSetInputs']) AND count($NewcomerRankSet) == $DisabledCount) + { + $_Lang['DisableReqSetRanks'] = 'disabled'; + } + if($Ally['ally_request_notallow'] == 0) + { + $_Lang['AcceptReq_Select'] = 'selected'; + } + else + { + $_Lang['BlockReq_Select'] = 'selected'; + } + $_Lang['Insert_MaxLength_IntText'] = $_MaxLength_IntText; + $_Lang['Insert_MaxLength_ExtText'] = $_MaxLength_ExtText; + $_Lang['Insert_MaxLength_ReqText'] = $_MaxLength_Request; + + $Page = parsetemplate(gettemplate('alliance_admin'), $_Lang); + display($Page, $_Lang['ADM_Title']); + } + else + { + // User is trying to use one of Admin Functions + if($edit == 'info') + { + // User is trying to change Data about Ally + if($_ThisUserRank['admingen'] !== true) + { + message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php?mode=admin', 3); + } + + if($Ally['ally_owner'] != $_User['id']) + { + $_Lang['HideChangeName'] = 'hide'; + $_Lang['HideChangeTag'] = 'hide'; + } + + if(isset($_POST['change']) && $_POST['change'] == 'name') + { + if($Ally['ally_owner'] != $_User['id']) + { + $Errors[] = $_Lang['ADM_OnlyLeaderChangeName']; + } + else + { + $NewName = trim($_POST['new_name']); + if(!empty($NewName)) + { + if(strlen($NewName) <= $_MaxLength_AName) + { + if(preg_match(REGEXP_ALLYNAME_ABSOLUTE, $NewName)) + { + if($NewName != $Ally['ally_name']) + { + $CheckExist = doquery("SELECT `id` FROM {{table}} WHERE `ally_name` = '{$NewName}' LIMIT 1;", 'alliance', true); + if($CheckExist['id'] <= 0) + { + doquery("UPDATE {{table}} SET `ally_name` = '{$NewName}' WHERE `id` = {$Ally['id']};", 'alliance'); + $Info[] = $_Lang['ADM_AllyNameChanged']; + } + else + { + $Errors[] = $_Lang['ADM_NewNameNotFree']; + } + } + else + { + $Errors[] = $_Lang['ADM_SameName']; + } + } + else + { + $Errors[] = $_Lang['ADM_BadNewName']; + } + } + else + { + $Errors[] = $_Lang['ADM_NewNameLong']; + } + } + else + { + $Errors[] = $_Lang['ADM_NewNameEmpty']; + } + } + } + else if(isset($_POST['change']) && $_POST['change'] == 'tag') + { + if($Ally['ally_owner'] != $_User['id']) + { + $Errors[] = $_Lang['ADM_OnlyLeaderChangeTag']; + } + else + { + $NewTag = trim($_POST['new_tag']); + if(!empty($NewTag)) + { + $NewTagLength = strlen($NewTag); + if($NewTagLength >= $_MinLength_ATag) + { + if($NewTagLength <= $_MaxLength_ATag) + { + if(preg_match(REGEXP_ALLYTAG_ABSOLUTE, $NewTag)) + { + if($NewTag != $Ally['ally_tag']) + { + $CheckExist = doquery("SELECT `id` FROM {{table}} WHERE `ally_tag` = '{$NewTag}' LIMIT 1;", 'alliance', true); + if($CheckExist['id'] <= 0) + { + doquery("UPDATE {{table}} SET `ally_tag` = '{$NewTag}' WHERE `id` = {$Ally['id']};", 'alliance'); + $Info[] = $_Lang['ADM_AllyTagChanged']; + } + else + { + $Errors[] = $_Lang['ADM_NewTagNotFree']; + } + } + else + { + $Errors[] = $_Lang['ADM_SameTag']; + } + } + else + { + $Errors[] = $_Lang['ADM_BadNewTag']; + } + } + else + { + $Errors[] = $_Lang['ADM_NewTagLong']; + } + } + else + { + $Errors[] = $_Lang['ADM_NewTagShort']; + } + } + else + { + $Errors[] = $_Lang['ADM_NewTagEmpty']; + } + } + } + else if(isset($_POST['change']) && $_POST['change'] == 'general') + { + if(empty($_POST['website'])) + { + $NewWebsite = ''; + } + else + { + $_POST['website'] = trim($_POST['website']); + if(preg_match('/^(http\:\/\/|www\.|https\:\/\/){1}.*?$/D', $_POST['website'], $Matches)) + { + $NewWebsite = mysql_real_escape_string(strip_tags($_POST['website'])); + if($Matches[1] == 'www.') + { + $NewWebsite = substr($NewWebsite, 4); + $NewWebsite = 'http://'.$NewWebsite; + } + } + else + { + $Errors[] = $_Lang['ADM_BadNewWebsite']; + $NewWebsite = null; + } + } + if($NewWebsite !== null AND $NewWebsite != $Ally['ally_web']) + { + $ChangeQuery[] = "`ally_web` = '{$NewWebsite}'"; + $Ally['ally_web'] = $NewWebsite; + } + $RevealWebsite = (isset($_POST['website_reveal']) && $_POST['website_reveal'] == 'on' ? 1 : 0); + if($RevealWebsite != $Ally['ally_web_reveal']) + { + $ChangeQuery[] = "`ally_web_reveal` = {$RevealWebsite}"; + $Ally['ally_web_reveal'] = $RevealWebsite; + } + + if(empty($_POST['logourl'])) + { + $NewLogo = ''; + } + else + { + $_POST['logourl'] = trim($_POST['logourl']); + if(preg_match('/^(http\:\/\/|www\.|https\:\/\/){1}.*?$/D', $_POST['logourl'], $Matches)) + { + $NewLogo = mysql_real_escape_string(strip_tags($_POST['logourl'])); + if($Matches[1] == 'www.') + { + $NewLogo = substr($NewLogo, 4); + $NewLogo = 'http://'.$NewLogo; + } + } + else + { + $Errors[] = $_Lang['ADM_BadNewLogo']; + $NewLogo = null; + } + } + if($NewLogo !== null AND $NewLogo != $Ally['ally_image']) + { + $ChangeQuery[] = "`ally_image` = '{$NewLogo}'"; + $Ally['ally_image'] = $NewLogo; + } + + if(!empty($ChangeQuery)) + { + doquery("UPDATE {{table}} SET ".implode(', ', $ChangeQuery)." WHERE `id` = {$Ally['id']};", 'alliance'); + $Info[] = $_Lang['ADM_AllyInfoChanged']; + } + else + { + $Errors[] = $_Lang['ADM_AllyInfoNotChanged']; + } + } + + $_Lang['HideInfoBox_name'] = 'hide'; + $_Lang['HideInfoBox_tag'] = 'hide'; + $_Lang['HideInfoBox_general'] = 'hide'; + if(isset($_POST['change'])) + { + switch($_POST['change']) + { + case 'name': + { + $TextBoxes = 'name'; + $_Lang['HideInfoBox_name'] = ''; + break; + } + case 'tag': + { + $TextBoxes = 'tag'; + $_Lang['HideInfoBox_tag']= ''; + break; + } + case 'general': + { + $TextBoxes = 'general'; + $_Lang['HideInfoBox_general']= ''; + break; + } + } + } + + if(!empty($Errors)) + { + if($TextBoxes != 'general') + { + $_Lang['InfoBox_color'] = 'red'; + $_Lang['InfoBox_'.$TextBoxes] = implode('
', $Errors); + } + else + { + $_Lang['InfoBox_'.$TextBoxes] = ''.implode('
', $Errors).'
'; + } + } + if(!empty($Info)) + { + if($TextBoxes != 'general') + { + $_Lang['InfoBox_color'] = 'lime'; + $_Lang['InfoBox_'.$TextBoxes] = implode('
', $Info); + } + else + { + if(!isset($_Lang['InfoBox_'.$TextBoxes])) + { + $_Lang['InfoBox_'.$TextBoxes] = ''; + } + $_Lang['InfoBox_'.$TextBoxes] .= (empty($_Lang['InfoBox_'.$TextBoxes]) ? '' : '
').''.implode('
', $Info).'
'; + } + } + $_Lang['CurrentWebsite'] = stripslashes($Ally['ally_web']); + $_Lang['CheckRevealWebsite'] = ($Ally['ally_web_reveal'] == 1 ? 'checked' : ''); + $_Lang['CurrentLogoUrl'] = stripslashes($Ally['ally_image']); + + $Page = parsetemplate(gettemplate('alliance_admin_changedata'), $_Lang); + display($Page, $_Lang['ADM_Title']); + } + else if($edit == 'handover') + { + // User is trying to HandOver the Ally + if($Ally['ally_owner'] != $_User['id']) + { + message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php?mode=admin', 3); + } + if($Ally['ally_members'] == 1) + { + message($_Lang['ADM_OnlyOwnerInAlly'], $MsgTitle, 'alliance.php?mode=admin', 3); + } + + $Query_AHandOver_Members = ''; + $Query_AHandOver_Members .= "SELECT `id`, `username`, `ally_rank_id` FROM {{table}} "; + $Query_AHandOver_Members .= "WHERE `ally_id` = {$Ally['id']} AND `id` != {$_User['id']};"; + + $Result_AHandOver_Members = doquery($Query_AHandOver_Members, 'users'); + $_Lang['UserList'] = ''; + while($FetchData = mysql_fetch_assoc($Result_AHandOver_Members)) + { + $_Lang['UserList'] .= ""; + $Members[$FetchData['id']] = $FetchData['ally_rank_id']; + } + + $_Lang['HideError'] = 'hide'; + if(isset($_POST['send']) && $_POST['send'] == 'yes') + { + $NewOwner = intval($_POST['new_owner']); + if($NewOwner > 0) + { + if(array_key_exists($NewOwner, $Members)) + { + doquery("UPDATE {{table}} SET `ally_owner` = {$NewOwner} WHERE `id` = {$Ally['id']};", 'alliance'); + doquery("INSERT INTO {{table}} (`id`, `ally_rank_id`) VALUES ({$_User['id']}, {$Members[$NewOwner]}), ({$NewOwner}, 0) ON DUPLICATE KEY UPDATE `ally_rank_id` = VALUES(`ally_rank_id`);", 'users'); + message($_Lang['ADM_HandOverDone'], $MsgTitle, 'alliance.php', 3); + } + else + { + $ErrorBox = $_Lang['ADM_BadUserIDHO']; + } + } + else + { + $ErrorBox = $_Lang['ADM_NoUserIDHO']; + } + $_Lang['HideError'] = ''; + $_Lang['ErrorText'] = $ErrorBox; + } + + $Page = parsetemplate(gettemplate('alliance_admin_handover'), $_Lang); + display($Page, $_Lang['ADM_Title']); + } + else if($edit == 'delete') + { + // User is trying to Delete Ally + if($Ally['ally_owner'] != $_User['id']) + { + message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php?mode=admin', 3); + } + + $_DisplaySettings['dontShow_AllyChat_MsgCount'] = true; + $_DisplaySettings['dontShow_AllyChat_Link'] = true; + + doquery("DELETE FROM {{table}} WHERE `id` = {$Ally['id']};", 'alliance'); + doquery("DELETE FROM {{table}} WHERE `AllyID` = {$Ally['id']};", 'ally_invites'); + doquery("DELETE FROM {{table}} WHERE `AllyID_Sender` = {$Ally['id']} OR `AllyID_Owner` = {$Ally['id']};", 'ally_pacts'); + if($Ally['ally_ChatRoom_ID'] > 0) + { + doquery("DELETE FROM {{table}} WHERE `ID` = {$Ally['ally_ChatRoom_ID']} LIMIT 1;", 'chat_rooms'); + doquery("DELETE FROM {{table}} WHERE `RID` = {$Ally['ally_ChatRoom_ID']};", 'chat_messages'); + doquery("DELETE FROM {{table}} WHERE `RID` = {$Ally['ally_ChatRoom_ID']};", 'chat_online'); + } + doquery("UPDATE {{table}} SET `ally_id` = 0, `ally_register_time` = 0, `ally_rank_id` = 0, `ally_request` = 0, `ally_request_text` = '' WHERE `ally_id` = {$Ally['id']} OR `ally_request` = {$Ally['id']};", 'users'); + message($_Lang['ADM_AllyDeleted'], $MsgTitle, 'alliance.php', 3); + } + else if($edit == 'members') + { + // User is trying to Manage Members + if($_ThisUserRank['mlist'] !== true OR ($_ThisUserRank['mlist_mod'] !== true AND $_ThisUserRank['cankick'] !== true)) + { + message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php?mode=admin', 3); + } + + foreach($Ally['ally_ranks'] as $RankID => $RankData) + { + if($RankID == 0 OR $RankID == $_User['ally_rank_id']) + { + continue; + } + if($_ThisUserRank['like_admin'] === true) + { + if($RankData['like_admin'] !== true OR $_ThisUserRank['is_admin'] === true) + { + $AllowedRanksChange[] = $RankID; + } + } + else + { + if($RankData['like_admin'] === true) + { + continue; + } + else + { + $DisallowChange = false; + foreach($_ThisUserRank as $Key => $Value) + { + if($Key == 'name') + { + continue; + } + if($Key == 'mlist_mod' OR $Key == 'cankick' OR $Key == 'ranks_mod') + { + if($RankData[$Key] === true) + { + $DisallowChange = true; + break; + } + } + else + { + if($Value !== true AND $RankData[$Key] === true) + { + $DisallowChange = true; + break; + } + } + } + if($DisallowChange === false) + { + $AllowedRanksChange[] = $RankID; + } + } + } + } + $_Lang['HideInfoBox'] = 'hide'; + + if(!empty($_GET['kick'])) + { + $InfoBoxCol = 'red'; + if($_ThisUserRank['cankick'] === true) + { + $KickID = intval($_GET['kick']); + if($KickID > 0) + { + if($KickID != $_User['id']) + { + $GetUser = doquery("SELECT `id`, `username`, `ally_id`, `ally_rank_id` FROM {{table}} WHERE `id` = {$KickID} LIMIT 1;", 'users', true); + if($GetUser['id'] == $KickID AND $GetUser['ally_id'] == $Ally['id']) + { + if(in_array($GetUser['ally_rank_id'], $AllowedRanksChange)) + { + doquery("UPDATE {{table}} SET `ally_id` = 0, `ally_rank_id` = 0 WHERE `id` = {$KickID};", 'users'); + doquery("UPDATE {{table}} SET `ally_members` = `ally_members` - 1 WHERE `id` = {$Ally['id']};", 'alliance'); + doquery("UPDATE {{table}} SET `State` = -3 WHERE `State` = 1 AND `SenderID` = {$KickID};", 'ally_invites'); + $Ally['ally_members'] -= 1; + $InfoBoxTxt = sprintf($_Lang['ADM_MemberXKicked'], $GetUser['username']); + $InfoBoxCol = 'lime'; + } + else + { + $InfoBoxTxt = $_Lang['ADM_CantKickRank']; + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_CantKickBadUser']; + } + } + else + { + $InfoBoxTxt = $land['ADM_CantKickYourself']; + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_CantKickBadID']; + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_YouCantKick']; + } + + $_Lang['HideInfoBox']= ''; + $_Lang['InfoBoxText']= $InfoBoxTxt; + $_Lang['InfoBoxColor'] = $InfoBoxCol; + } + else if(isset($_POST['send']) && $_POST['send'] == 'yes') + { + $InfoBoxCol = 'red'; + + $ErrorsChanging = 0; + $RankIsSame = 0; + $ErrorsSaving = 0; + + if($_ThisUserRank['mlist_mod'] === true) + { + foreach($_POST['change_rank'] as $UserID => $NewRank) + { + $UserID = intval($UserID); + $NewRank = intval($NewRank); + if($UserID > 0 AND $NewRank > 0 AND in_array($NewRank, $AllowedRanksChange)) + { + $RankChanges[$UserID] = $NewRank; + } + else + { + $ErrorsChanging += 1; + } + } + if(!empty($RankChanges)) + { + $MembersList = doquery("SELECT `id`, `ally_id`, `ally_rank_id` FROM {{table}} WHERE `id` IN (".implode(', ', array_keys($RankChanges)).");", 'users'); + if(mysql_num_rows($MembersList) > 0) + { + while($FetchData = mysql_fetch_assoc($MembersList)) + { + if($FetchData['ally_id'] == $Ally['id'] AND $RankChanges[$FetchData['id']] != $FetchData['ally_rank_id'] AND in_array($FetchData['ally_rank_id'], $AllowedRanksChange)) + { + $DoChange[$FetchData['id']] = $RankChanges[$FetchData['id']]; + } + else + { + if($RankChanges[$FetchData['id']] != $FetchData['ally_rank_id']) + { + $RankIsSame += 1; + } + else + { + $ErrorsSaving += 1; + } + } + } + + if(!empty($DoChange)) + { + $UpdateQuery = "INSERT INTO {{table}} (`id`, `ally_rank_id`) VALUES "; + foreach($DoChange as $UserID => $RankID) + { + $UpdateQueryArr[] = "({$UserID}, {$RankID})"; + } + $UpdateQuery .= implode(', ', $UpdateQueryArr); + $UpdateQuery .= " ON DUPLICATE KEY UPDATE "; + $UpdateQuery .= "`ally_rank_id` = VALUES(`ally_rank_id`);"; + doquery($UpdateQuery, 'users'); + + if(count($DoChange) == (count($RankChanges) - $RankIsSame + $ErrorsChanging)) + { + $InfoBoxTxt = $_Lang['ADM_MListModAllDone']; + } + else + { + $InfoBoxTxt = $_Lang['ADM_MListModNAllDone']; + } + $InfoBoxCol = 'lime'; + } + else + { + if($ErrorsSaving > 0) + { + $InfoBoxTxt = $_Lang['ADM_MListModBadData2']; + } + else + { + $InfoBoxTxt = $_Lang['ADM_MListModBadData']; + } + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_MListModBadData']; + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_MListModBadData']; + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_YouCantMListMod']; + } + + $_Lang['HideInfoBox'] = ''; + $_Lang['InfoBoxText'] = $InfoBoxTxt; + $_Lang['InfoBoxColor'] = $InfoBoxCol; + } + + createMembersList(true); + $Page = parsetemplate(gettemplate('alliance_admin_memberslist_table'), $_Lang); + display($Page, $_Lang['ADM_Title']); + } + else if($edit == 'reqlist') + { + // User wants to Look at Requests + if(!isset($_GET['from']) || $_GET['from'] != 'front') + { + $GoBackTo = 'alliance.php?mode=admin'; + $_Lang['GoBackLink'] = '?mode=admin'; + } + else + { + $GoBackTo = 'alliance.php'; + $_Lang['GoBackLink'] = 'alliance.php'; + } + if($_ThisUserRank['lookreq'] !== true) + { + message($_Lang['Ally_AccessDenied'], $MsgTitle, $GoBackTo, 3); + } + + if(!empty($_POST['rq'])) + { + $InfoBoxCol = 'red'; + if($_ThisUserRank['managereq'] === true) + { + $RequestUser = intval($_POST['rq']); + if($RequestUser > 0) + { + if($_POST['opt'] == 1 OR $_POST['opt'] == 2) + { + $CheckRequest = doquery("SELECT `id`, `username`, `ally_request` FROM {{table}} WHERE `id` = {$RequestUser} LIMIT 1;", 'users', true); + if($CheckRequest['id'] == $RequestUser) + { + if($CheckRequest['ally_request'] == $Ally['id']) + { + if($_POST['opt'] == 1) + { + doquery("UPDATE {{table}} SET `ally_request` = 0, `ally_request_text` = '', `ally_id` = {$Ally['id']}, `ally_rank_id` = {$Ally['ally_new_rank_id']}, `ally_register_time` = UNIX_TIMESTAMP() WHERE `id` = {$RequestUser};", 'users'); + doquery("UPDATE {{table}} SET `ally_members` = `ally_members` + 1 WHERE `id` = {$Ally['id']};", 'alliance'); + if($Ally['ally_ChatRoom_ID'] > 0) + { + $Query_UpdateChatRoomOnline = ''; + $Query_UpdateChatRoomOnline .= "INSERT INTO {{table}} VALUES ({$Ally['ally_ChatRoom_ID']}, {$RequestUser}, UNIX_TIMESTAMP()) "; + $Query_UpdateChatRoomOnline .= "ON DUPLICATE KEY UPDATE "; + $Query_UpdateChatRoomOnline .= "`LastOnline` = VALUES(`LastOnline`);"; + doquery($Query_UpdateChatRoomOnline, 'chat_online'); + } + + $Message = array(); + $Message['msg_id'] = '023'; + $Message['args'] = array($Ally['ally_name']); + $Message = json_encode($Message); + Cache_Message($RequestUser, 0, NULL, 2, '005', '010', $Message); + + $InfoBoxCol = 'lime'; + $InfoBoxTxt = sprintf($_Lang['ADM_RL_ReqAccepted'], $CheckRequest['username']); + + CheckJobsDone('BUDDY_OR_ALLY_TASK', $RequestUser); + } + else + { + doquery("UPDATE {{table}} SET `ally_request` = 0, `ally_request_text` = '', `ally_register_time` = 0 WHERE `id` = {$RequestUser};", 'users'); + + $RejectReason = strip_tags(stripslashes($_POST['rjr'])); + if(strlen($RejectReason) > $_MaxLength_Reject) + { + $RejectReason = substr($RejectReason, 0, $_MaxLength_Reject); + } + else if(strlen($RejectReason) == 0) + { + $RejectReason = $_Lang['ADM_RL_NoReason']; + } + $Message = array(); + $Message['msg_id'] = '024'; + $Message['args'] = array($Ally['ally_name'], $RejectReason); + $Message = json_encode($Message); + Cache_Message($RequestUser, 0, NULL, 2, '005', '011', $Message); + + $InfoBoxCol = 'lime'; + $InfoBoxTxt = sprintf($_Lang['ADM_RL_ReqRejected'], $CheckRequest['username']); + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_RL_UserNotInAlly']; + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_RL_UserNoExist']; + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_RL_BadOption']; + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_RL_BadID']; + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_RL_NoManageAccess']; + } + } + + if(!empty($InfoBoxTxt)) + { + $_Lang['InfoBoxText']= $InfoBoxTxt; + $_Lang['InfoBoxColor'] = $InfoBoxCol; + } + else + { + $_Lang['HideInfoBox']= 'hide'; + } + + $SortType = (isset($_GET['stype']) ? intval($_GET['stype']) : null); + $SortMode = (isset($_GET['smode']) ? intval($_GET['smode']) : null); + + $ThisSorting = 'class="sortHigh"'; + switch($SortType) + { + case 1: + $SortBy = '`username`'; + $_Lang['sortByName'] = $ThisSorting; + break; + case 2: + $SortBy = '`total_rank`'; + $_Lang['sortByStats'] = $ThisSorting; + break; + case 3: + $SortBy = '`ally_register_time`'; + $_Lang['sortBySendDate'] = $ThisSorting; + break; + default: + $SortBy = '`id`'; + break; + } + switch($SortMode) + { + case 'desc': + $SortHow = 'DESC'; + $_Lang['sortRev'] = 'asc'; + break; + default: + $SortHow = 'ASC'; + $_Lang['sortRev'] = 'desc'; + break; + } + + $Query_ARequests_Get = ''; + $Query_ARequests_Get .= "SELECT `id`, `username`, `ally_register_time`, `ally_request_text`, `Stats`.`total_rank`, `Stats`.`total_points` FROM {{table}} "; + $Query_ARequests_Get .= "LEFT JOIN {{prefix}}statpoints AS `Stats` ON `Stats`.`id_owner` = {{table}}.`id` AND `Stats`.`stat_type` = 1 "; + $Query_ARequests_Get .= "WHERE `ally_request` = {$Ally['id']} ORDER BY {$SortBy} {$SortHow};"; + + $GetRequests = doquery($Query_ARequests_Get, 'users'); + $ReqCount = mysql_num_rows($GetRequests); + $_Lang['RequestCount'] = $ReqCount; + + if($_ThisUserRank['managereq'] === true) + { + $TableTPL = gettemplate('alliance_admin_reqlist_mg_table'); + $RowTPL = gettemplate('alliance_admin_reqlist_mg_row'); + } + else + { + $TableTPL = gettemplate('alliance_admin_reqlist_lk_table'); + $RowTPL = gettemplate('alliance_admin_reqlist_lk_row'); + } + + if($ReqCount > 0) + { + $_Lang['HideNoRequests'] = 'hide'; + $_Lang['RequestRows'] = ''; + while($Request = mysql_fetch_assoc($GetRequests)) + { + $Request['ally_request_text'] = stripslashes($Request['ally_request_text']); + if($Request['total_rank'] > 0) + { + $Request['StatPoints'] = "{$Request['total_rank']} (".prettyNumber($Request['total_points'])." {$_Lang['ADM_RL_points']})"; + } + else + { + $Request['StatPoints'] = '0'; + } + $Request['SendDate'] = prettyDate('d m Y - H:i:s', $Request['ally_register_time'], 1); + $Request['ADM_RL_Accept'] = $_Lang['ADM_RL_Accept']; + $Request['ADM_RL_Refuse'] = $_Lang['ADM_RL_Refuse']; + $Request['ADM_RL_RejectReason'] = $_Lang['ADM_RL_RejectReason']; + $Request['ADM_RL_Save'] = $_Lang['ADM_RL_Save']; + + $_Lang['RequestRows'] .= parsetemplate($RowTPL, $Request); + } + } + $Page = parsetemplate($TableTPL, $_Lang); + display($Page, $_Lang['ADM_Title']); + } + else if($edit == 'ranks') + { + // User is trying to View RankList (and manage Ranks) + if($_ThisUserRank['ranks_mod'] !== true) + { + message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php?mode=admin', 3); + } + + if($_ThisUserRank['is_admin'] === true) + { + $ImAllyOwner = true; + } + else + { + $ImAllyOwner = false; + } + + // Set Default Disabled for Options + $DefaultDisabledOpt = array(); + if(!$ImAllyOwner) + { + if($_ThisUserRank['like_admin'] !== true) + { + $DefaultDisabledOpt = array(1, 8, 9, 10, 11); + if($_ThisUserRank['mlist'] !== true) + { + $DefaultDisabledOpt[] = 2; + $DefaultDisabledOpt[] = 3; + } + else if($_ThisUserRank['mlist_online'] !== true) + { + $DefaultDisabledOpt[] = 3; + } + if($_ThisUserRank['sendmsg'] !== true) + { + $DefaultDisabledOpt[] = 4; + } + if($_ThisUserRank['admingen'] !== true) + { + $DefaultDisabledOpt[] = 5; + } + if($_ThisUserRank['lookreq'] !== true) + { + $DefaultDisabledOpt[] = 6; + $DefaultDisabledOpt[] = 7; + } + else if($_ThisUserRank['managereq'] !== true) + { + $DefaultDisabledOpt[] = 7; + } + } + else + { + $DefaultDisabledOpt[] = 1; + } + } + $_Lang['HideInfoBox'] = 'hide'; + + $Result_ARanks_Counter = doquery("SELECT COUNT(*) AS `Count`, `ally_rank_id` FROM {{table}} WHERE `ally_id` = {$Ally['id']} GROUP BY `ally_rank_id`;", 'users'); + while($FetchData = mysql_fetch_assoc($Result_ARanks_Counter)) + { + $RanksCountArray[$FetchData['ally_rank_id']] = $FetchData['Count']; + } + + if(!empty($_POST['action'])) + { + $InfoBoxCol = 'red'; + if($_POST['action'] == 'add') + { + $NewName = trim($_POST['newName']); + $NewNameLower = strtolower($NewName); + $NewNameLen = strlen($NewName); + if($NewNameLen >= $_MinLength_RankName) + { + if($NewNameLen <= $_MaxLength_RankName) + { + if(preg_match($RankNameRegExp, $NewName)) + { + $BreakNameOcu = false; + foreach($Ally['ally_ranks'] as $RankID => $RankData) + { + if(strtolower($RankData['name']) == $NewNameLower) + { + $BreakNameOcu = true; + break; + } + } + if($BreakNameOcu === false) + { + $BreakBadOpt = false; + for($i = 1; $i < $Ally['ally_ranks_count']; $i += 1) + { + if(isset($_POST['opt'][$i]) && $_POST['opt'][$i] == 'on') + { + if(in_array($i, $DefaultDisabledOpt)) + { + $BreakBadOpt = true; + break; + } + else + { + $NewRankOpts[$i] = true; + } + } + else + { + $NewRankOpts[$i] = false; + } + } + if($BreakBadOpt === false) + { + if($NewRankOpts[1] === true) + { + foreach($NewRankOpts as $ID => $Value) + { + if($Value !== true) + { + $NewRankOpts[1] = false; + break; + } + } + } + if($NewRankOpts[3] === true) + { + if($NewRankOpts[2] !== true) + { + $NewRankOpts[3] = false; + } + } + if($NewRankOpts[7] === true) + { + if($NewRankOpts[6] !== true) + { + $NewRankOpts[7] = false; + } + } + $NewRankAdd = array_merge(array(0 => $NewName), $NewRankOpts); + $Ally['ally_ranks_org'][] = $NewRankAdd; + foreach($NewRankAdd as $DataID => $DataVal) + { + $NewRankData[$RankDataLabels[$DataID]] = $DataVal; + } + $Ally['ally_ranks'][] = $NewRankData; + + doquery("UPDATE {{table}} SET `ally_ranks` = '".mysql_real_escape_string(json_encode($Ally['ally_ranks_org']))."' WHERE `id` = {$Ally['id']};", 'alliance'); + $InfoBoxCol = 'lime'; + $InfoBoxTxt = $_Lang['ADM_RkL_AddedRank']; + } + else + { + if($BreakBadData) + { + $InfoBoxTxt = $_Lang['ADM_RkL_BadOptGiven']; + } + else + { + $InfoBoxTxt = $_Lang['ADM_RkL_ForbiddenOptGiven']; + } + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_RkL_RankExists']; + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_RkL_ForbiddenSigns']; + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_RkL_NameLong']; + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_RkL_NameShort']; + } + } + else if($_POST['action'] == 'saveChg') + { + if(!empty($_POST['chgData'])) + { + $ChangingErrors = 0; + $NoChanges = 0; + $RankNoExists = 0; + + foreach($Ally['ally_ranks'] as $RankData) + { + $ExistingNames[] = strtolower($RankData['name']); + } + foreach($_POST['chgData'] as $RankID => $RankChgData) + { + if(!empty($Ally['ally_ranks'][$RankID]['name'])) + { + $ParsedRankData = &$Ally['ally_ranks'][$RankID]; + if($ImAllyOwner OR ($_ThisUserRank['like_admin'] === true AND $ParsedRankData['like_admin'] !== true) OR + ( + $_ThisUserRank['like_admin'] !== true AND + $ParsedRankData['like_admin'] !== true AND + $ParsedRankData['ranks_mod'] !== true AND + $ParsedRankData['mlist_mod'] !== true AND + $ParsedRankData['cankick'] !== true + )) + { + $ThisCanChangeName= true; + $ThisCanChangeRights= true; + } + else + { + $ThisCanChangeName = false; + $ThisCanChangeRights = false; + $ThisCantChangeName = 'na_nonam'; + $ThisCantChangeRights = 'na_nochg'; + } + if($RankID == 0) + { + $ThisCanChangeRights = false; + $ThisCantChangeRights = 'adm_nochg'; + } + if($ThisCanChangeName) + { + $ChangingErrors += 1; + $ThisNewName = trim($RankChgData[0]); + $ThisNewNameLower = strtolower($ThisNewName); + $ThisNewNameLen = strlen($ThisNewName); + if($ThisNewNameLen > 0) + { + if($ThisNewNameLower != strtolower($ParsedRankData['name'])) + { + if(preg_match($RankNameRegExp, $ThisNewName)) + { + if($ThisNewNameLen >= $_MinLength_RankName) + { + if($ThisNewNameLen <= $_MaxLength_RankName) + { + if(!in_array($ThisNewNameLower, $ExistingNames)) + { + $SaveChanges[$RankID][0] = $ThisNewName; + $ChangingErrors -= 1; + } + else + { + $ErrorsFound['NameExists'] += 1; + } + } + else + { + $ErrorsFound['NameLong'] += 1; + } + } + else + { + $ErrorsFound['NameShort'] += 1; + } + } + else + { + $ErrorsFound['NamePregMatch'] += 1; + } + } + else + { + $NoChanges += 1; + $ChangingErrors -= 1; + } + } + else + { + $ErrorsFound['NameEmpty'] += 1; + } + } + if($ThisCanChangeRights) + { + for($i = 1; $i < $Ally['ally_ranks_count']; $i += 1) + { + $RankChgData[$i] = (isset($RankChgData[$i]) && $RankChgData[$i] == 'on' ? true : false); + if($RankChgData[$i] !== $Ally['ally_ranks_org'][$RankID][$i]) + { + if(in_array($i, $DefaultDisabledOpt)) + { + $ChangingErrors += 1; + $ErrorsFound['Opt'.$i.'Disabled'] += 1; + } + else + { + $SaveChanges[$RankID][$i] = $RankChgData[$i]; + } + } + else + { + $NoChanges += 1; + } + } + } + } + else + { + $RankNoExists += 1; + $ErrorsFound['RankNoExists'] += 1; + } + } + if(!empty($SaveChanges)) + { + foreach($SaveChanges as $RankID => $RankData) + { + $Recalculate = false; + foreach($RankData as $DataID => $DataValue) + { + $Ally['ally_ranks_org'][$RankID][$DataID] = $DataValue; + $Ally['ally_ranks'][$RankID][$RankDataLabels[$DataID]] = $DataValue; + } + $RankShortcut = &$Ally['ally_ranks_org'][$RankID]; + if($RankShortcut[1] === true) + { + foreach($RankShortcut as $ID => $Value) + { + if($ID == 0) + { + continue; + } + if($Value !== true) + { + $RankShortcut[1] = false; + $Recalculate = true; + break; + } + } + } + if($RankShortcut[3] === true) + { + if($RankShortcut[2] !== true) + { + $RankShortcut[3] = false; + $Recalculate = true; + } + } + if($RankShortcut[7] === true) + { + if($RankShortcut[6] !== true) + { + $RankShortcut[7] = false; + $Recalculate = true; + } + } + if($Recalculate === true) + { + foreach($RankShortcut as $DataID => $DataValue) + { + $Ally['ally_ranks'][$RankID][$RankDataLabels[$DataID]] = $DataValue; + } + } + } + doquery("UPDATE {{table}} SET `ally_ranks` = '".mysql_real_escape_string(json_encode($Ally['ally_ranks_org']))."' WHERE `id` = {$Ally['id']};", 'alliance'); + $InfoBoxCol = 'lime'; + if($RankNoExists > 0 OR $ChangingErrors > 0) + { + $InfoBoxTxt = $_Lang['ADM_RkL_PosChgSaved']; + } + else + { + $InfoBoxTxt = $_Lang['ADM_RkL_AllChgSaved']; + } + } + else + { + $InfoBoxCol = 'orange'; + $InfoBoxTxt = $_Lang['ADM_RkL_NothingChanged']; + if($RankNoExists > 0 OR $ChangingErrors > 0) + { + $InfoBoxTxt .= '
'.$_Lang['ADM_RkL_ChgErrors']; + } + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_RkL_EmptyData']; + } + } + else if(substr($_POST['action'], 0, 4) == 'del_') + { + $RankID = intval(substr($_POST['action'], 4)); + if($RankID > 0) + { + if(!empty($Ally['ally_ranks'][$RankID]['name'])) + { + if($ImAllyOwner OR ($_ThisUserRank['like_admin'] === true AND $RankData['like_admin'] !== true) OR + ( + $_ThisUserRank['like_admin'] !== true AND + $RankData['like_admin'] !== true AND + $RankData['ranks_mod'] !== true AND + $RankData['mlist_mod'] !== true AND + $RankData['cankick'] !== true + )) + { + $ThisCanDelete = true; + } + else + { + $ThisCanDelete = false; + $ThisCantDelete = 'na_nodel'; + } + if($RankID == 0) + { + $ThisCanDelete = false; + $ThisCantDelete = 'adm_nodel'; + } + if($RankID == $Ally['ally_new_rank_id']) + { + $ThisCanDelete = false; + $ThisCantDelete = 'nc_nodel'; + } + + if($ThisCanDelete) + { + if(isset($RanksCountArray[$RankID]) && $RanksCountArray[$RankID] > 0) + { + $RanksCountArray[$Ally['ally_new_rank_id']] += $RanksCountArray[$RankID]; + doquery("UPDATE {{table}} SET `ally_rank_id` = {$Ally['ally_new_rank_id']} WHERE `ally_id` = {$Ally['id']} AND `ally_rank_id` = {$RankID};", 'users'); + } + unset($Ally['ally_ranks'][$RankID]); + unset($Ally['ally_ranks_org'][$RankID]); + doquery("UPDATE {{table}} SET `ally_ranks` = '".mysql_real_escape_string(json_encode($Ally['ally_ranks_org']))."' WHERE `id` = {$Ally['id']};", 'alliance'); + + $InfoBoxCol = 'lime'; + $InfoBoxTxt = $_Lang['ADM_RkL_RankDeleted']; + } + else + { + $InfoBoxTxt = $_Lang['ADM_RkL_RankDelete_'.$ThisCantDelete]; + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_RkL_RankNoExists']; + } + } + else + { + if(substr($_POST['action'], 4) == '0') + { + $InfoBoxTxt = $_Lang['ADM_RkL_RankDelete_adm_nodel']; + } + else + { + $InfoBoxTxt = $_Lang['ADM_RkL_BadRankIDGiven']; + } + } + } + else + { + $InfoBoxTxt = $_Lang['ADM_RkL_BadPostAction']; + } + + $_Lang['HideInfoBox'] = ''; + $_Lang['InfoBoxText'] = $InfoBoxTxt; + $_Lang['InfoBoxColor'] = $InfoBoxCol; + } + + $RowTPL = gettemplate('alliance_admin_ranklist_row'); + $_Lang['RanksRows'] = ''; + $RanksCount = 0; + foreach($Ally['ally_ranks'] as $RankID => $RankData) + { + $ThisRank = array(); + + if($ImAllyOwner OR ($_ThisUserRank['like_admin'] === true AND $RankData['like_admin'] !== true) OR + ( + $_ThisUserRank['like_admin'] !== true AND + $RankData['like_admin'] !== true AND + $RankData['ranks_mod'] !== true AND + $RankData['mlist_mod'] !== true AND + $RankData['cankick'] !== true + )) + { + $ThisCanChangeName = true; + $ThisCanChangeRights = true; + $ThisCanDelete = true; + } + else + { + $ThisCanChangeName = false; + $ThisCanChangeRights = false; + $ThisCanDelete = false; + $ThisCantChangeName = 'na_nonam'; + $ThisCantChangeRights = 'na_nochg'; + $ThisCantDelete = 'na_nodel'; + } + if($RankID == 0) + { + $ThisCanChangeRights = false; + $ThisCanDelete = false; + $ThisCantChangeRights = 'adm_nochg'; + $ThisCantDelete = 'adm_nodel'; + } + if($RankID == $Ally['ally_new_rank_id']) + { + $ThisCanDelete = false; + $ThisCantDelete = 'nc_nodel'; + } + + if($ThisCanChangeName) + { + $ThisRank['RankName'] = ''; + } + else + { + $ThisRank['RankName'] = ''.$RankData['name'].''; + } + if($ThisCanChangeRights !== true) + { + $ThisRank['DisableInfo'] = ' class="'.$ThisCantChangeRights.'"'; + for($i = 1; $i < $Ally['ally_ranks_count']; $i += 1) + { + $ThisRank['CBoxes'][$i][] = 'disabled'; + $ThisRank['DisableInfo'.$i] = $ThisRank['DisableInfo']; + } + } + else + { + $ThisRank['DisableInfo'] = ' class="na_nochg"'; + for($i = 1; $i < $Ally['ally_ranks_count']; $i += 1) + { + if(in_array($i, $DefaultDisabledOpt)) + { + $ThisRank['CBoxes'][$i][] = 'disabled'; + $ThisRank['DisableInfo'.$i] = $ThisRank['DisableInfo']; + } + else + { + $ThisRank['CBoxes'][$i][] = 'name="chgData['.$RankID.']['.$i.']"'; + } + } + } + + $PropCounter = 1; + foreach($RankData as $PropKey => $PropVal) + { + if($PropKey == 'name') + { + continue; + } + if($PropVal === true) + { + $ThisRank['CBoxes'][$PropCounter][] = 'checked'; + } + $PropCounter += 1; + } + if(!empty($ThisRank['CBoxes'])) + { + foreach($ThisRank['CBoxes'] as $Index => $Vals) + { + $ThisRank['CBox_'.$Index] = implode(' ', $Vals); + } + } + + if($ThisCanDelete !== true) + { + $ThisRank['DeleteButton'] = ''.$_Lang['ADM_RkL_Delete'].''; + } + else + { + $ThisRank['DeleteButton'] = ''; + } + if(isset($RanksCountArray[$RankID]) && $RanksCountArray[$RankID] > 0) + { + $ThisRank['MembersCount'] = $RanksCountArray[$RankID]; + } + else + { + $ThisRank['MembersCount'] = '0'; + } + $_Lang['RanksRows'] .= parsetemplate($RowTPL, $ThisRank); + $RanksCount += 1; + } + $_Lang['RankCount'] = $RanksCount; + + $AddRank['DisableInfo'] = ' class="na_adchg"'; + for($i = 1; $i < $Ally['ally_ranks_count']; $i += 1) + { + if(in_array($i, $DefaultDisabledOpt)) + { + $AddRank['CBoxes'][$i][] = 'disabled'; + $_Lang['DisableInfo'.$i] = $AddRank['DisableInfo']; + } + else + { + $AddRank['CBoxes'][$i][] = 'name="opt['.$i.']"'; + } + } + if(!empty($AddRank['CBoxes'])) + { + foreach($AddRank['CBoxes'] as $Index => $Vals) + { + $_Lang['CBox_'.$Index] = implode(' ', $Vals); + } + } + + $Page = parsetemplate(gettemplate('alliance_admin_ranklist_table'), $_Lang); + display($Page, $_Lang['ADM_Title']); + } + else + { + message($_Lang['ADM_BadEditSelected'], $_Lang['ADM_Title'], 'alliance.php', 3); + } + } + } + else + { + // User is on Ally Front Page + include($_EnginePath.'includes/functions/BBcodeFunction.php'); + $_Lang = array_merge($_Lang, $Ally); + + $_Lang['ally_user_rank'] = $_ThisUserRank['name']; + if(empty($_Lang['ally_web'])) + { + $_Lang['ally_web'] = ' '; + } + else + { + $_Lang['ally_web'] = "{$_Lang['ally_web']}"; + } + + if($_ThisUserRank['mlist'] !== true) + { + $_Lang['HideShowMList'] = 'hide'; + } + if($_ThisUserRank['caninvite'] !== true) + { + $_Lang['HideInviteNewUser'] = 'hide'; + } + if($_ThisUserRank['sendmsg'] !== true) + { + $_Lang['HideSendMail'] = 'hide'; + } + if($Ally['ally_ChatRoom_ID'] <= 0 OR $_ThisUserRank['canusechat'] !== true) + { + $_Lang['HideAllyChat'] = 'hide'; + } + else + { + $_Lang['Insert_ChatRoomID'] = $Ally['ally_ChatRoom_ID']; + } + if($_ThisUserRank['admingen'] !== true) + { + $_Lang['HideAllyAdmin'] = 'hide'; + } + if($_ThisUserRank['lookreq'] !== true) + { + $_Lang['HideLookReq'] = 'hide'; + } + else + { + $RequestsCount = doquery("SELECT COUNT(*) AS `count` FROM {{table}} WHERE `ally_request` = {$Ally['id']};", 'users', true); + $RequestsCount = (string) ($RequestsCount['count'] + 0); + if($RequestsCount == 0) + { + $_Lang['HideLookReq'] = 'hide'; + } + $_Lang['RequestCount'] = $RequestsCount; + if($_ThisUserRank['managereq'] === true AND $RequestsCount > 0) + { + $_Lang['RequestColor'] = ' orange'; + } + } + + if($Ally['ally_owner'] == $_User['id']) + { + $_Lang['HideLeaveAlly'] = 'class="hide"'; + } + + // Ally Description + if(!empty($Ally['ally_description'])) + { + $_Lang['ally_description'] = nl2br(bbcode($Ally['ally_description'])); + } + else + { + $_Lang['ally_description'] = $_Lang['AFP_NoAllyDesc']; + } + // Ally InnerText + if(!empty($Ally['ally_text'])) + { + $_Lang['ally_text'] = nl2br(bbcode($Ally['ally_text'])); + } + else + { + $_Lang['ally_text'] = $_Lang['AFP_NoAllyInner']; + } + + $Page = parsetemplate(gettemplate('alliance_frontpage'), $_Lang); + display($Page, $_Lang['AFP_YouAlly']); + } +} + +?> diff --git a/attackslist.php b/attackslist.php index e73e781aa..074e01fc6 100644 --- a/attackslist.php +++ b/attackslist.php @@ -1,214 +1,214 @@ -= {$TodayTimestamp} AND `Fleet_Owner` = {$_User['id']} AND `Fleet_Mission` IN (1, 2, 9) AND `Fleet_End_Owner_IdleHours` < 168 AND `Fleet_ReportID` > 0 AND `Fleet_End_Owner` > 0 AND `Fleet_Destroyed_Reason` NOT IN (1, 4, 11);", 'fleet_archive'); - if(mysql_num_rows($SelectAttacks) > 0) - { - $GetUsernames = array(); - $GetPlanetnames = array(); - $SkipACSID = array(); - - while($Fleet = mysql_fetch_assoc($SelectAttacks)) - { - if($Fleet['Fleet_ACSID'] > 0) - { - if(in_array($Fleet['Fleet_ACSID'], $SkipACSID)) - { - continue; - } - else - { - $SkipACSID[] = $Fleet['Fleet_ACSID']; - } - } - $Pointer = &$Records[$Fleet['Fleet_End_Owner']]; - if(!isset($Pointer['TotalCount'])) - { - $Pointer['TotalCount'] = 0; - } - $Pointer['TotalCount'] += 1; - $GetEndID = $Fleet['Fleet_End_ID']; - if($Fleet['Fleet_End_ID_Changed'] > 0) - { - $GetEndID = $Fleet['Fleet_End_ID_Changed']; - } - if(!isset($Pointer['Planets'][$GetEndID]['Count'])) - { - $Pointer['Planets'][$GetEndID]['Count'] = 0; - } - $Pointer['Planets'][$GetEndID]['Count'] += 1; - - if(!in_array($Fleet['Fleet_End_Owner'], $GetUsernames)) - { - $GetUsernames[] = $Fleet['Fleet_End_Owner']; - } - if(!in_array($GetEndID, $GetPlanetnames)) - { - if($Fleet['Fleet_End_Type_Changed'] == 1) - { - $Fleet['Fleet_End_Type'] = 1; - } - $GetPlanetnames[$GetEndID] = array - ( - 'id' => $GetEndID, - 'galaxy' => $Fleet['Fleet_End_Galaxy'], - 'system' => $Fleet['Fleet_End_System'], - 'planet' => $Fleet['Fleet_End_Planet'], - 'type' => $Fleet['Fleet_End_Type'] - ); - } - } - } - - if(!empty($Records)) - { - $_Lang['PHP_HideNoAttacks'] = 'class="hide"'; - if(!empty($GetUsernames)) - { - $Usernames = doquery("SELECT `user`.`id`, `user`.`username`, `user`.`ally_id`, `ally`.`ally_tag` FROM {{table}} AS `user` LEFT JOIN {{prefix}}alliance AS `ally` ON `ally`.`id` = `user`.`ally_id` WHERE `user`.`id` IN (".implode(', ', $GetUsernames).");", 'users'); - if(mysql_num_rows($Usernames) > 0) - { - while($Username = mysql_fetch_assoc($Usernames)) - { - if($Username['ally_id'] > 0 AND !empty($Username['ally_tag'])) - { - $FoundUsernames[$Username['id']] = "{$Username['username']} [{$Username['ally_tag']}]"; - } - else - { - $FoundUsernames[$Username['id']] = $Username['username']; - } - } - } - foreach($GetUsernames as $UID) - { - if(empty($FoundUsernames[$UID])) - { - $Users[$UID] = $_Lang['User_Deleted']; - } - else - { - $Users[$UID] = $FoundUsernames[$UID]; - } - } - } - - if(!empty($GetPlanetnames)) - { - foreach($GetPlanetnames as $Data) - { - $GetPlanetIDs[] = $Data['id']; - } - $Planets = doquery("SELECT `id`, `name` FROM {{table}} WHERE `id` IN (".implode(', ', $GetPlanetIDs).");", 'planets'); - if(mysql_num_rows($Planets) > 0) - { - while($Planet = mysql_fetch_assoc($Planets)) - { - $FoundPlanets[$Planet['id']] = $Planet['name']; - } - } - - $Planets = $GetPlanetnames; - foreach($GetPlanetnames as $PlanetData) - { - if(empty($FoundPlanets[$PlanetData['id']])) - { - $Planets[$PlanetData['id']]['name'] = $_Lang['Planet_Deleted']; - } - else - { - $Planets[$PlanetData['id']]['name'] = $FoundPlanets[$PlanetData['id']]; - } - } - } - - $RowsLoop = 0; - foreach($Records as $AtkUser => $AtkData) - { - $This = array(); - if($AtkData['TotalCount'] < $AllowedPerUser) - { - $This['AttacksStatus'] = sprintf($_Lang['Bash_StatusOKLeft'], $AllowedPerUser - $AtkData['TotalCount']); - $This['CountColor'] = 'yellow'; - } - else if($AtkData['TotalCount'] == $AllowedPerUser) - { - $This['AttacksStatus'] = $_Lang['Bash_Status0Left']; - $This['CountColor'] = 'darkorange'; - } - else - { - $This['AttacksStatus'] = $_Lang['Bash_StatusExceededUser']; - $This['CountColor'] = 'maroon'; - } - $_Lang['Rows'][$RowsLoop][] = parsetemplate($RowTPL, array('Username_Planet' => $Users[$AtkUser], 'AttacksCount' => $AtkData['TotalCount'], 'AllowedAttacks' => $AllowedPerUser, 'CountColor' => $This['CountColor'], 'AttacksStatus' => $This['AttacksStatus'])); - foreach($AtkData['Planets'] as $PlanetID => $PlanetAtkCount) - { - $This = array(); - if($PlanetAtkCount['Count'] < $AllowedPerPlanet) - { - $This['AttacksStatus'] = sprintf($_Lang['Bash_StatusOKLeft'], $AllowedPerPlanet - $PlanetAtkCount['Count']); - $This['CountColor'] = 'lime'; - } - else if($PlanetAtkCount['Count'] == $AllowedPerPlanet) - { - $This['AttacksStatus'] = $_Lang['Bash_Status0Left']; - $This['CountColor'] = 'orange'; - } - else - { - $This['AttacksStatus'] = sprintf($_Lang['Bash_StatusExceededPlanet'], ($Planets[$PlanetID]['type'] == 1 ? $_Lang['Bash_Exceeded_Planet'] : $_Lang['Bash_Exceeded_Moon'])); - $This['CountColor'] = 'red'; - } - $_Lang['Rows'][$RowsLoop][] = parsetemplate($RowTPL, array('PlanetMargin' => '»', 'Username_Planet' => $Planets[$PlanetID]['name'], 'Planet_Link' => '['.$Planets[$PlanetID]['galaxy'].':'.$Planets[$PlanetID]['system'].':'.$Planets[$PlanetID]['planet'].']', 'AttacksCount' => $PlanetAtkCount['Count'], 'AllowedAttacks' => $AllowedPerPlanet, 'CountColor' => $This['CountColor'], 'AttacksStatus' => $This['AttacksStatus'])); - } - $RowsLoop += 1; - } - - if(!empty($_Lang['Rows'])) - { - foreach($_Lang['Rows'] as $RowID => $RowSubrows) - { - $TempRows[] = implode('', $RowSubrows); - } - $_Lang['Rows'] = implode(' ', $TempRows); - } - - } - else - { - $_Lang['PHP_HideRecords'] = 'class="hide"'; - } - - $Page = parsetemplate($BodyTPL, $_Lang); - - display($Page, $_Lang['Bash_Title'], true, false); - -?> \ No newline at end of file += {$TodayTimestamp} AND `Fleet_Owner` = {$_User['id']} AND `Fleet_Mission` IN (1, 2, 9) AND `Fleet_End_Owner_IdleHours` < 168 AND `Fleet_ReportID` > 0 AND `Fleet_End_Owner` > 0 AND `Fleet_Destroyed_Reason` NOT IN (1, 4, 11);", 'fleet_archive'); +if(mysql_num_rows($SelectAttacks) > 0) +{ + $GetUsernames = array(); + $GetPlanetnames = array(); + $SkipACSID = array(); + + while($Fleet = mysql_fetch_assoc($SelectAttacks)) + { + if($Fleet['Fleet_ACSID'] > 0) + { + if(in_array($Fleet['Fleet_ACSID'], $SkipACSID)) + { + continue; + } + else + { + $SkipACSID[] = $Fleet['Fleet_ACSID']; + } + } + $Pointer = &$Records[$Fleet['Fleet_End_Owner']]; + if(!isset($Pointer['TotalCount'])) + { + $Pointer['TotalCount'] = 0; + } + $Pointer['TotalCount'] += 1; + $GetEndID = $Fleet['Fleet_End_ID']; + if($Fleet['Fleet_End_ID_Changed'] > 0) + { + $GetEndID = $Fleet['Fleet_End_ID_Changed']; + } + if(!isset($Pointer['Planets'][$GetEndID]['Count'])) + { + $Pointer['Planets'][$GetEndID]['Count'] = 0; + } + $Pointer['Planets'][$GetEndID]['Count'] += 1; + + if(!in_array($Fleet['Fleet_End_Owner'], $GetUsernames)) + { + $GetUsernames[] = $Fleet['Fleet_End_Owner']; + } + if(!in_array($GetEndID, $GetPlanetnames)) + { + if($Fleet['Fleet_End_Type_Changed'] == 1) + { + $Fleet['Fleet_End_Type'] = 1; + } + $GetPlanetnames[$GetEndID] = array + ( + 'id' => $GetEndID, + 'galaxy' => $Fleet['Fleet_End_Galaxy'], + 'system' => $Fleet['Fleet_End_System'], + 'planet' => $Fleet['Fleet_End_Planet'], + 'type' => $Fleet['Fleet_End_Type'] + ); + } + } +} + +if(!empty($Records)) +{ + $_Lang['PHP_HideNoAttacks'] = 'class="hide"'; + if(!empty($GetUsernames)) + { + $Usernames = doquery("SELECT `user`.`id`, `user`.`username`, `user`.`ally_id`, `ally`.`ally_tag` FROM {{table}} AS `user` LEFT JOIN {{prefix}}alliance AS `ally` ON `ally`.`id` = `user`.`ally_id` WHERE `user`.`id` IN (".implode(', ', $GetUsernames).");", 'users'); + if(mysql_num_rows($Usernames) > 0) + { + while($Username = mysql_fetch_assoc($Usernames)) + { + if($Username['ally_id'] > 0 AND !empty($Username['ally_tag'])) + { + $FoundUsernames[$Username['id']] = "{$Username['username']} [{$Username['ally_tag']}]"; + } + else + { + $FoundUsernames[$Username['id']] = $Username['username']; + } + } + } + foreach($GetUsernames as $UID) + { + if(empty($FoundUsernames[$UID])) + { + $Users[$UID] = $_Lang['User_Deleted']; + } + else + { + $Users[$UID] = $FoundUsernames[$UID]; + } + } + } + + if(!empty($GetPlanetnames)) + { + foreach($GetPlanetnames as $Data) + { + $GetPlanetIDs[] = $Data['id']; + } + $Planets = doquery("SELECT `id`, `name` FROM {{table}} WHERE `id` IN (".implode(', ', $GetPlanetIDs).");", 'planets'); + if(mysql_num_rows($Planets) > 0) + { + while($Planet = mysql_fetch_assoc($Planets)) + { + $FoundPlanets[$Planet['id']] = $Planet['name']; + } + } + + $Planets = $GetPlanetnames; + foreach($GetPlanetnames as $PlanetData) + { + if(empty($FoundPlanets[$PlanetData['id']])) + { + $Planets[$PlanetData['id']]['name'] = $_Lang['Planet_Deleted']; + } + else + { + $Planets[$PlanetData['id']]['name'] = $FoundPlanets[$PlanetData['id']]; + } + } + } + + $RowsLoop = 0; + foreach($Records as $AtkUser => $AtkData) + { + $This = array(); + if($AtkData['TotalCount'] < $AllowedPerUser) + { + $This['AttacksStatus'] = sprintf($_Lang['Bash_StatusOKLeft'], $AllowedPerUser - $AtkData['TotalCount']); + $This['CountColor'] = 'yellow'; + } + else if($AtkData['TotalCount'] == $AllowedPerUser) + { + $This['AttacksStatus'] = $_Lang['Bash_Status0Left']; + $This['CountColor'] = 'darkorange'; + } + else + { + $This['AttacksStatus'] = $_Lang['Bash_StatusExceededUser']; + $This['CountColor'] = 'maroon'; + } + $_Lang['Rows'][$RowsLoop][] = parsetemplate($RowTPL, array('Username_Planet' => $Users[$AtkUser], 'AttacksCount' => $AtkData['TotalCount'], 'AllowedAttacks' => $AllowedPerUser, 'CountColor' => $This['CountColor'], 'AttacksStatus' => $This['AttacksStatus'])); + foreach($AtkData['Planets'] as $PlanetID => $PlanetAtkCount) + { + $This = array(); + if($PlanetAtkCount['Count'] < $AllowedPerPlanet) + { + $This['AttacksStatus'] = sprintf($_Lang['Bash_StatusOKLeft'], $AllowedPerPlanet - $PlanetAtkCount['Count']); + $This['CountColor'] = 'lime'; + } + else if($PlanetAtkCount['Count'] == $AllowedPerPlanet) + { + $This['AttacksStatus'] = $_Lang['Bash_Status0Left']; + $This['CountColor'] = 'orange'; + } + else + { + $This['AttacksStatus'] = sprintf($_Lang['Bash_StatusExceededPlanet'], ($Planets[$PlanetID]['type'] == 1 ? $_Lang['Bash_Exceeded_Planet'] : $_Lang['Bash_Exceeded_Moon'])); + $This['CountColor'] = 'red'; + } + $_Lang['Rows'][$RowsLoop][] = parsetemplate($RowTPL, array('PlanetMargin' => '»', 'Username_Planet' => $Planets[$PlanetID]['name'], 'Planet_Link' => '['.$Planets[$PlanetID]['galaxy'].':'.$Planets[$PlanetID]['system'].':'.$Planets[$PlanetID]['planet'].']', 'AttacksCount' => $PlanetAtkCount['Count'], 'AllowedAttacks' => $AllowedPerPlanet, 'CountColor' => $This['CountColor'], 'AttacksStatus' => $This['AttacksStatus'])); + } + $RowsLoop += 1; + } + + if(!empty($_Lang['Rows'])) + { + foreach($_Lang['Rows'] as $RowID => $RowSubrows) + { + $TempRows[] = implode('', $RowSubrows); + } + $_Lang['Rows'] = implode(' ', $TempRows); + } + +} +else +{ + $_Lang['PHP_HideRecords'] = 'class="hide"'; +} + +$Page = parsetemplate($BodyTPL, $_Lang); + +display($Page, $_Lang['Bash_Title'], true, false); + +?> diff --git a/banned.php b/banned.php index 0bdde98d8..5070ec1e3 100644 --- a/banned.php +++ b/banned.php @@ -1,54 +1,54 @@ - 0 WHERE `bans`.`EndTime` > UNIX_TIMESTAMP() AND `bans`.`Active` = 1 ORDER BY `bans`.`ID`;",'bans'); - $BansCount = mysql_num_rows($SelectBans); - if($BansCount > 0) - { - $i = 0; - while($Ban = mysql_fetch_assoc($SelectBans)) - { - $Row = array(); - $Row['BanNo'] = ++$i; - $Row['BanUser'] = $Ban['username']; - if(!empty($Ban['Reason'])) - { - $Row['BanReason'] = $Ban['Reason']; - } - else - { - $Row['BanReason'] = $_Lang['Reason_NotSpecified']; - } - $Row['BanStart'] = prettyDate('d m Y<\b\r/>H:i:s', $Ban['StartTime'], 1); - $Row['BanEnd'] = prettyDate('d m Y<\b\r/>H:i:s', $Ban['EndTime'], 1); - $Row['BanBy'] = ($Ban['GiverID'] > 0 ? "{$Ban['GiverUsername']}" : "{$_Lang['ban_bysys']}"); - - $parse['Rows'] .= parsetemplate($RowTPL, $Row); - } - } - - if($BansCount == 0) - { - $parse['Rows'] .= ''.$_Lang['NoBannedPPL'].''; - } - else - { - $parse['Rows'] .= ''.$_Lang['CountOfBannedPPL'].': '.$BansCount.''; - } - - $page = parsetemplate(gettemplate('banned_body'), $parse); - display($page, $_Lang['ban_title'], false); - -?> \ No newline at end of file + 0 WHERE `bans`.`EndTime` > UNIX_TIMESTAMP() AND `bans`.`Active` = 1 ORDER BY `bans`.`ID`;",'bans'); +$BansCount = mysql_num_rows($SelectBans); +if($BansCount > 0) +{ + $i = 0; + while($Ban = mysql_fetch_assoc($SelectBans)) + { + $Row = array(); + $Row['BanNo'] = ++$i; + $Row['BanUser'] = $Ban['username']; + if(!empty($Ban['Reason'])) + { + $Row['BanReason'] = $Ban['Reason']; + } + else + { + $Row['BanReason'] = $_Lang['Reason_NotSpecified']; + } + $Row['BanStart'] = prettyDate('d m Y<\b\r/>H:i:s', $Ban['StartTime'], 1); + $Row['BanEnd'] = prettyDate('d m Y<\b\r/>H:i:s', $Ban['EndTime'], 1); + $Row['BanBy'] = ($Ban['GiverID'] > 0 ? "{$Ban['GiverUsername']}" : "{$_Lang['ban_bysys']}"); + + $parse['Rows'] .= parsetemplate($RowTPL, $Row); + } +} + +if($BansCount == 0) +{ + $parse['Rows'] .= ''.$_Lang['NoBannedPPL'].''; +} +else +{ + $parse['Rows'] .= ''.$_Lang['CountOfBannedPPL'].': '.$BansCount.''; +} + +$page = parsetemplate(gettemplate('banned_body'), $parse); +display($page, $_Lang['ban_title'], false); + +?> diff --git a/battlereport.php b/battlereport.php index b4d4f15a3..2574715bd 100644 --- a/battlereport.php +++ b/battlereport.php @@ -1,91 +1,91 @@ - 0 || $ReportHash !== false) - { - if($ReportHash !== false) - { - $WHERE = "`Hash` = '{$ReportHash}'"; - } - else - { - $WHERE = "`ID` = {$ReportID}"; - } - $Report = doquery("SELECT * FROM {{table}} WHERE {$WHERE};", ($IsSimulation ? 'sim_' : '').'battle_reports', true); - - if($Report) - { - $DisallowView = false; - if($IsSimulation == 1) - { - if($Report['time'] < time()) - { - doquery("DELETE FROM {{table}} WHERE `time` < UNIX_TIMESTAMP();", 'sim_battle_reports'); - $DisallowView = true; - $Reason = 'deleted'; - } - } - else - { - if($ReportHash === false) - { - $ReportOwners1 = explode(',', $Report['id_owner1']); - $ReportOwners2 = explode(',', $Report['id_owner2']); - foreach($ReportOwners1 as $UserID) - { - $AllowedOwners[] = trim($UserID); - } - foreach($ReportOwners2 as $UserID) - { - $AllowedOwners[] = trim($UserID); - } - if(!in_array($_User['id'], $AllowedOwners) AND !CheckAuth('supportadmin')) - { - $DisallowView = true; - $Reason = 'notyour'; - } - } - } - if($DisallowView !== true) - { - include($_EnginePath.'includes/functions/ReadBattleReport.php'); - $ParsePage['Content'] = ReadBattleReport($Report); - } - else - { - $ParsePage['Content'] = parsetemplate($TPL_Error, array('Error' => $_Lang['BattleReportReader_CannotRead'].'
'.$_Lang['BattleReportReader_'.$Reason])); - } - } - else - { - $ParsePage['Content'] = parsetemplate($TPL_Error, array('Error' => $_Lang['BattleReport_DoesntExist'])); - } - } - else - { - $ParsePage['Content'] = parsetemplate($TPL_Error, array('Error' => $_Lang['BattleReport_NoIDGiven'])); - } - - display(parsetemplate($TPL_Body, $ParsePage), $_Lang['BattleReport_title'], false); - -?> \ No newline at end of file + 0 || $ReportHash !== false) +{ + if($ReportHash !== false) + { + $WHERE = "`Hash` = '{$ReportHash}'"; + } + else + { + $WHERE = "`ID` = {$ReportID}"; + } + $Report = doquery("SELECT * FROM {{table}} WHERE {$WHERE};", ($IsSimulation ? 'sim_' : '').'battle_reports', true); + + if($Report) + { + $DisallowView = false; + if($IsSimulation == 1) + { + if($Report['time'] < time()) + { + doquery("DELETE FROM {{table}} WHERE `time` < UNIX_TIMESTAMP();", 'sim_battle_reports'); + $DisallowView = true; + $Reason = 'deleted'; + } + } + else + { + if($ReportHash === false) + { + $ReportOwners1 = explode(',', $Report['id_owner1']); + $ReportOwners2 = explode(',', $Report['id_owner2']); + foreach($ReportOwners1 as $UserID) + { + $AllowedOwners[] = trim($UserID); + } + foreach($ReportOwners2 as $UserID) + { + $AllowedOwners[] = trim($UserID); + } + if(!in_array($_User['id'], $AllowedOwners) AND !CheckAuth('supportadmin')) + { + $DisallowView = true; + $Reason = 'notyour'; + } + } + } + if($DisallowView !== true) + { + include($_EnginePath.'includes/functions/ReadBattleReport.php'); + $ParsePage['Content'] = ReadBattleReport($Report); + } + else + { + $ParsePage['Content'] = parsetemplate($TPL_Error, array('Error' => $_Lang['BattleReportReader_CannotRead'].'
'.$_Lang['BattleReportReader_'.$Reason])); + } + } + else + { + $ParsePage['Content'] = parsetemplate($TPL_Error, array('Error' => $_Lang['BattleReport_DoesntExist'])); + } +} +else +{ + $ParsePage['Content'] = parsetemplate($TPL_Error, array('Error' => $_Lang['BattleReport_NoIDGiven'])); +} + +display(parsetemplate($TPL_Body, $ParsePage), $_Lang['BattleReport_title'], false); + +?> diff --git a/buddy.php b/buddy.php index 76ca48a51..d39ae9dc3 100644 --- a/buddy.php +++ b/buddy.php @@ -1,407 +1,407 @@ - 0) - { - doquery("UPDATE {{table}} SET `active` = 1 WHERE `sender` = {$UID} AND `owner` = {$_User['id']} AND `active` = 0;", 'buddy'); - if(mysql_affected_rows() == 1) - { - $Message['msg_id'] = '090'; - $Message['args'] = array($_User['id'], $_User['username']); - $Message = json_encode($Message); - Cache_Message($UID, 0, NULL, 70, '007', '021', $Message); - - CheckJobsDone('BUDDY_OR_ALLY_TASK', $_User['id']); - CheckJobsDone('BUDDY_OR_ALLY_TASK', $UID); - - $Parse['Insert_MsgBoxText'] = $_Lang['Success_Accepted']; - $Parse['Insert_MsgBoxColor'] = 'lime'; - } - else - { - $Parse['Insert_MsgBoxText'] = $_Lang['Error_BadElement']; - $Parse['Insert_MsgBoxColor'] = 'red'; - } - } - else - { - $Parse['Insert_MsgBoxText'] = $_Lang['Error_ElementIDBad']; - $Parse['Insert_MsgBoxColor'] = 'red'; - } - } - else if($Command == 'refuse') - { - $Command = ''; - if($UID > 0) - { - doquery("DELETE FROM {{table}} WHERE `sender` = {$UID} AND `owner` = {$_User['id']} AND `active` = 0;", 'buddy'); - if(mysql_affected_rows() == 1) - { - $Message['msg_id'] = '091'; - $Message['args'] = array($_User['id'], $_User['username']); - $Message = json_encode($Message); - Cache_Message($UID, 0, NULL, 70, '007', '021', $Message); - - $Parse['Insert_MsgBoxText'] = $_Lang['Success_Refused']; - $Parse['Insert_MsgBoxColor'] = 'lime'; - } - else - { - $Parse['Insert_MsgBoxText'] = $_Lang['Error_BadElement']; - $Parse['Insert_MsgBoxColor'] = 'red'; - } - } - else - { - $Parse['Insert_MsgBoxText'] = $_Lang['Error_ElementIDBad']; - $Parse['Insert_MsgBoxColor'] = 'red'; - } - } - else if($Command == 'rmv') - { - $Command = ''; - if($UID > 0) - { - doquery("DELETE FROM {{table}} WHERE ((`sender` = {$UID} AND `owner` = {$_User['id']}) OR (`owner` = {$UID} AND `sender` = {$_User['id']})) AND `active` = 1;", 'buddy'); - if(mysql_affected_rows() == 1) - { - $Message['msg_id'] = '092'; - $Message['args'] = array($_User['id'], $_User['username']); - $Message = json_encode($Message); - Cache_Message($UID, 0, NULL, 70, '007', '021', $Message); - - $Parse['Insert_MsgBoxText'] = $_Lang['Success_Removed']; - $Parse['Insert_MsgBoxColor'] = 'lime'; - } - else - { - $Parse['Insert_MsgBoxText'] = $_Lang['Error_BadElement']; - $Parse['Insert_MsgBoxColor'] = 'red'; - } - } - else - { - $Parse['Insert_MsgBoxText'] = $_Lang['Error_ElementIDBad']; - $Parse['Insert_MsgBoxColor'] = 'red'; - } - } - else if($Command == 'del') - { - $Command = ''; - if($UID > 0) - { - doquery("DELETE FROM {{table}} WHERE `owner` = {$UID} AND `sender` = {$_User['id']} AND `active` = 0;", 'buddy'); - if(mysql_affected_rows() == 1) - { - $Parse['Insert_MsgBoxText'] = $_Lang['Success_Deleted']; - $Parse['Insert_MsgBoxColor'] = 'lime'; - } - else - { - $Parse['Insert_MsgBoxText'] = $_Lang['Error_BadElement']; - $Parse['Insert_MsgBoxColor'] = 'red'; - } - } - else - { - $Parse['Insert_MsgBoxText'] = $_Lang['Error_ElementIDBad']; - $Parse['Insert_MsgBoxColor'] = 'red'; - } - } - else if($Command != 'edit' AND $Command != 'add') - { - $Command = ''; - } - - if(empty($Command)) - { - $TPL_Default = gettemplate('buddy_list_body'); - - $Parse['Insert_HideSeparator'] = 'hide'; - $Parse['Insert_HideWithBuddyList'] = ''; - $Parse['Insert_HidePagination'] = 'hide'; - - $Get_BuddyCount = doquery("SELECT COUNT(*) AS `Count` FROM {{table}} WHERE `owner` = {$_User['id']} OR `sender` = {$_User['id']};", 'buddy', true); - $BuddyCount = $Get_BuddyCount['Count']; - if($BuddyCount > 0) - { - $TPL_BuddyRow = gettemplate('buddy_list_row'); - - $ThisPage = (isset($_GET['page']) ? intval($_GET['page']) : 0); - if($ThisPage < 1) - { - $ThisPage = 1; - } - $LimitStart = ($ThisPage - 1) * $_PerPage; - if($LimitStart >= $Get_BuddyCount) - { - $ThisPage = 1; - $LimitStart = 0; - } - $AddPage2Link = ''; - if($ThisPage > 1) - { - $AddPage2Link = '&page='.$ThisPage; - } - $LastPage = ceil($BuddyCount / $_PerPage); - - $NeededFields = "`buddy`.*, `users`.`username`, `users`.`onlinetime`, `users`.`galaxy`, `users`.`system`, `users`.`planet`, `users`.`ally_id`, `ally`.`ally_name`, `stats`.`total_rank`, `stats`.`total_points` "; - $Query = ''; - $Query .= "SELECT {$NeededFields} FROM {{table}} AS `buddy` "; - $Query .= "LEFT JOIN `{{prefix}}users` AS `users` ON `users`.`id` = IF(`buddy`.`owner` = {$_User['id']}, `buddy`.`sender`, `buddy`.`owner`) "; - $Query .= "LEFT JOIN `{{prefix}}alliance` AS `ally` ON `ally`.`id` = `users`.`ally_id` "; - $Query .= "LEFT JOIN `{{prefix}}statpoints` AS `stats` ON `users`.`id` = `stats`.`id_owner` AND `stats`.`stat_type` = '1' "; - $Query .= "WHERE `buddy`.`owner` = {$_User['id']} OR `buddy`.`sender` = {$_User['id']} "; - $Query .= "ORDER BY `buddy`.`active` ASC, `buddy`.`date` DESC LIMIT {$LimitStart}, {$_PerPage};"; - $Get_Buddy = doquery($Query, 'buddy'); - - while($BuddyData = mysql_fetch_assoc($Get_Buddy)) - { - $BuddyData['UID'] = ($BuddyData['owner'] == $_User['id'] ? $BuddyData['sender'] : $BuddyData['owner']); - $BuddyParse = array - ( - 'Insert_UID' => $BuddyData['UID'], - 'Insert_Nick' => $BuddyData['username'], - 'Insert_StatPositionLink' => $BuddyData['total_rank'], - 'Insert_StatPoints' => prettyNumber($BuddyData['total_points']), - 'Insert_StatPosition' => prettyNumber($BuddyData['total_rank']), - 'Insert_AllyID' => $BuddyData['ally_id'], - 'Insert_Ally' => $BuddyData['ally_name'], - 'Insert_PosGalaxy' => $BuddyData['galaxy'], - 'Insert_PosSystem' => $BuddyData['system'], - 'Insert_PosPlanet' => $BuddyData['planet'], - 'Insert_Date' => date('d.m.Y, H:i:s', $BuddyData['date']) - ); - - if($BuddyData['active'] == 1) - { - $OnlineDiff = $Now - $BuddyData['onlinetime']; - if($OnlineDiff <= TIME_ONLINE) - { - $BuddyParse['Insert_State'] = $_Lang['Row_State_Online']; - $BuddyParse['Insert_StateColor'] = 'lime'; - } - else if($OnlineDiff <= TIME_HOUR) - { - $BuddyParse['Insert_State'] = floor($OnlineDiff / 60).' '.$_Lang['Row_State_Minutes']; - $BuddyParse['Insert_StateColor'] = 'orange'; - } - else - { - $BuddyParse['Insert_State'] = $_Lang['Row_State_Offline'].': '.floor($OnlineDiff / TIME_DAY).' '.$_Lang['Row_State_Days']; - $BuddyParse['Insert_StateColor'] = 'red'; - } - $BuddyParse['Insert_Actions'][] = ""; - } - else - { - $BuddyParse['Insert_State'] = $_Lang['Row_State_Awaiting']; - if($BuddyData['sender'] == $_User['id']) - { - $BuddyParse['Insert_StateColor'] = 'orange'; - $BuddyParse['Insert_Actions'][] = ""; - $BuddyParse['Insert_Actions'][] = ""; - } - else - { - $BuddyParse['Insert_StateColor'] = 'lime'; - $BuddyParse['Insert_Actions'][] = ""; - $BuddyParse['Insert_Actions'][] = ""; - } - } - if(!empty($BuddyParse['Insert_Actions'])) - { - $BuddyParse['Insert_Actions'] = implode(' ', $BuddyParse['Insert_Actions']); - } - else - { - $BuddyParse['Insert_Actions'] = ' '; - } - - $BuddyParse = parsetemplate($TPL_BuddyRow, $BuddyParse); - if($BuddyData['active'] == 1) - { - $BuddyRows['active'][] = $BuddyParse; - } - else - { - $BuddyRows['awaiting'][] = $BuddyParse; - } - } - - if(!empty($BuddyRows['awaiting'])) - { - $Parse['Insert_AwaitingList'] = implode('', $BuddyRows['awaiting']); - $Parse['Insert_HideSeparator'] = ''; - } - if(!empty($BuddyRows['active'])) - { - $Parse['Insert_BuddyList'] = implode('', $BuddyRows['active']); - $Parse['Insert_HideWithBuddyList'] = 'hide'; - } - else - { - $Parse['Insert_HideSeparator'] = ''; - if($LastPage != $ThisPage) - { - $Parse['Insert_HideSeparator'] = 'hide'; - $Parse['Insert_HideWithBuddyList'] = 'hide'; - } - } - - if($BuddyCount > $_PerPage) - { - include_once($_EnginePath.'includes/functions/Pagination.php'); - $Pagination = CreatePaginationArray($BuddyCount, $_PerPage, $ThisPage, 7); - $PaginationTPL = "{\$ShowValue}"; - $PaginationViewOpt = array('CurrentPage_Classes' => 'orange', 'Breaker_View' => '...'); - $Pagination = ParsePaginationArray($Pagination, $ThisPage, $PaginationTPL, $PaginationViewOpt); - $Parse['Insert_Pagination'] = implode(' ', $Pagination); - $Parse['Insert_HidePagination'] = ''; - } - } - } - else if($Command == 'edit' OR $Command == 'add') - { - $TPL_Default = gettemplate('buddy_form'); - - if($Command == 'add') - { - if($UID < 1) - { - message($_Lang['Error_BadUID'], $_Lang['Title'], 'buddy.php', 3); - } - $GetUserdata = doquery("SELECT `username` FROM {{table}} WHERE `id` = {$UID} LIMIT 1;", 'users', true); - if(empty($GetUserdata['username'])) - { - message($_Lang['Error_BadUser'], $_Lang['Title'], 'buddy.php', 3); - } - $CheckBuddy = doquery("SELECT COUNT(*) AS `Count` FROM {{table}} WHERE (`sender` = {$_User['id']} AND `owner` = {$UID}) OR (`sender` = {$UID} AND `owner` = {$_User['id']}) LIMIT 1;", 'buddy', true); - if($CheckBuddy['Count'] > 0) - { - message($_Lang['Error_LinkExists'], $_Lang['Title'], 'buddy.php', 3); - } - - $Parse['Insert_Username'] = $GetUserdata['username']; - } - else - { - if($UID < 1) - { - message($_Lang['Error_ElementIDBad'], $_Lang['Title'], 'buddy.php', 3); - } - - $Query = ''; - $Query .= "SELECT `buddy`.*, `users`.`username` FROM {{table}} AS `buddy` "; - $Query .= "LEFT JOIN {{prefix}}users AS `users` ON `users`.`id` = `buddy`.`owner` "; - $Query .= "WHERE (`buddy`.`sender` = {$UID} AND `buddy`.`owner` = {$_User['id']}) OR (`buddy`.`sender` = {$_User['id']} AND `buddy`.`owner` = {$UID}) "; - $Query .= "LIMIT 1;"; - $CheckBuddy = doquery($Query, 'buddy', true); - if(empty($CheckBuddy)) - { - message($_Lang['Error_RowNoExists'], $_Lang['Title'], 'buddy.php', 3); - } - if($CheckBuddy['sender'] != $_User['id']) - { - message($_Lang['Error_CantEdit'], $_Lang['Title'], 'buddy.php', 3); - } - if($CheckBuddy['active'] == 1) - { - message($_Lang['Error_AlreadyActive'], $_Lang['Title'], 'buddy.php', 3); - } - - $Parse['Insert_Username'] = $CheckBuddy['username']; - $Parse['Insert_Text'] = $CheckBuddy['text']; - } - - if(isset($_POST['send']) && $_POST['send'] == '1') - { - $InsertClean['Text'] = substr(trim(stripslashes($_POST['text'])), 0, $_MaxLength); - $Insert['Text'] = mysql_real_escape_string($InsertClean['Text']); - - if(!empty($Insert['Text'])) - { - if($Command == 'add') - { - doquery("INSERT INTO {{table}} SET `sender` = {$_User['id']}, `owner` = {$UID}, `text` = '{$Insert['Text']}', `date` = UNIX_TIMESTAMP();", 'buddy'); - - header('Location: ?msg=add'); - safeDie(); - } - else if($Command == 'edit') - { - doquery("UPDATE {{table}} SET `text` = '{$Insert['Text']}', `date` = UNIX_TIMESTAMP() WHERE `sender` = {$CheckBuddy['sender']} AND `owner` = {$CheckBuddy['owner']} LIMIT 1;", 'buddy'); - - $Parse['Insert_MsgBoxText'] = $_Lang['Success_Edited']; - $Parse['Insert_MsgBoxColor'] = 'lime'; - } - } - else - { - $Parse['Insert_MsgBoxText'] = $_Lang['Error_EmptyText']; - $Parse['Insert_MsgBoxColor'] = 'red'; - } - - $Parse['Insert_Text'] = $InsertClean['Text']; - } - - $Parse['Insert_MaxLength'] = $_MaxLength; - } - - if(isset($_GET['msg']) && $_GET['msg'] == 'add') - { - $Parse['Insert_MsgBoxText'] = $_Lang['Success_Sent']; - $Parse['Insert_MsgBoxColor'] = 'lime'; - } - - if(empty($Parse['Insert_MsgBoxText'])) - { - $Parse['Insert_MsgBoxHide'] = 'hide'; - } - - display(parsetemplate($TPL_Default, $Parse), $_Lang['Title'], false); - -?> \ No newline at end of file + 0) + { + doquery("UPDATE {{table}} SET `active` = 1 WHERE `sender` = {$UID} AND `owner` = {$_User['id']} AND `active` = 0;", 'buddy'); + if(mysql_affected_rows() == 1) + { + $Message['msg_id'] = '090'; + $Message['args'] = array($_User['id'], $_User['username']); + $Message = json_encode($Message); + Cache_Message($UID, 0, NULL, 70, '007', '021', $Message); + + CheckJobsDone('BUDDY_OR_ALLY_TASK', $_User['id']); + CheckJobsDone('BUDDY_OR_ALLY_TASK', $UID); + + $Parse['Insert_MsgBoxText'] = $_Lang['Success_Accepted']; + $Parse['Insert_MsgBoxColor'] = 'lime'; + } + else + { + $Parse['Insert_MsgBoxText'] = $_Lang['Error_BadElement']; + $Parse['Insert_MsgBoxColor'] = 'red'; + } + } + else + { + $Parse['Insert_MsgBoxText'] = $_Lang['Error_ElementIDBad']; + $Parse['Insert_MsgBoxColor'] = 'red'; + } +} +else if($Command == 'refuse') +{ + $Command = ''; + if($UID > 0) + { + doquery("DELETE FROM {{table}} WHERE `sender` = {$UID} AND `owner` = {$_User['id']} AND `active` = 0;", 'buddy'); + if(mysql_affected_rows() == 1) + { + $Message['msg_id'] = '091'; + $Message['args'] = array($_User['id'], $_User['username']); + $Message = json_encode($Message); + Cache_Message($UID, 0, NULL, 70, '007', '021', $Message); + + $Parse['Insert_MsgBoxText'] = $_Lang['Success_Refused']; + $Parse['Insert_MsgBoxColor'] = 'lime'; + } + else + { + $Parse['Insert_MsgBoxText'] = $_Lang['Error_BadElement']; + $Parse['Insert_MsgBoxColor'] = 'red'; + } + } + else + { + $Parse['Insert_MsgBoxText'] = $_Lang['Error_ElementIDBad']; + $Parse['Insert_MsgBoxColor'] = 'red'; + } +} +else if($Command == 'rmv') +{ + $Command = ''; + if($UID > 0) + { + doquery("DELETE FROM {{table}} WHERE ((`sender` = {$UID} AND `owner` = {$_User['id']}) OR (`owner` = {$UID} AND `sender` = {$_User['id']})) AND `active` = 1;", 'buddy'); + if(mysql_affected_rows() == 1) + { + $Message['msg_id'] = '092'; + $Message['args'] = array($_User['id'], $_User['username']); + $Message = json_encode($Message); + Cache_Message($UID, 0, NULL, 70, '007', '021', $Message); + + $Parse['Insert_MsgBoxText'] = $_Lang['Success_Removed']; + $Parse['Insert_MsgBoxColor'] = 'lime'; + } + else + { + $Parse['Insert_MsgBoxText'] = $_Lang['Error_BadElement']; + $Parse['Insert_MsgBoxColor'] = 'red'; + } + } + else + { + $Parse['Insert_MsgBoxText'] = $_Lang['Error_ElementIDBad']; + $Parse['Insert_MsgBoxColor'] = 'red'; + } +} +else if($Command == 'del') +{ + $Command = ''; + if($UID > 0) + { + doquery("DELETE FROM {{table}} WHERE `owner` = {$UID} AND `sender` = {$_User['id']} AND `active` = 0;", 'buddy'); + if(mysql_affected_rows() == 1) + { + $Parse['Insert_MsgBoxText'] = $_Lang['Success_Deleted']; + $Parse['Insert_MsgBoxColor'] = 'lime'; + } + else + { + $Parse['Insert_MsgBoxText'] = $_Lang['Error_BadElement']; + $Parse['Insert_MsgBoxColor'] = 'red'; + } + } + else + { + $Parse['Insert_MsgBoxText'] = $_Lang['Error_ElementIDBad']; + $Parse['Insert_MsgBoxColor'] = 'red'; + } +} +else if($Command != 'edit' AND $Command != 'add') +{ + $Command = ''; +} + +if(empty($Command)) +{ + $TPL_Default = gettemplate('buddy_list_body'); + + $Parse['Insert_HideSeparator'] = 'hide'; + $Parse['Insert_HideWithBuddyList'] = ''; + $Parse['Insert_HidePagination'] = 'hide'; + + $Get_BuddyCount = doquery("SELECT COUNT(*) AS `Count` FROM {{table}} WHERE `owner` = {$_User['id']} OR `sender` = {$_User['id']};", 'buddy', true); + $BuddyCount = $Get_BuddyCount['Count']; + if($BuddyCount > 0) + { + $TPL_BuddyRow = gettemplate('buddy_list_row'); + + $ThisPage = (isset($_GET['page']) ? intval($_GET['page']) : 0); + if($ThisPage < 1) + { + $ThisPage = 1; + } + $LimitStart = ($ThisPage - 1) * $_PerPage; + if($LimitStart >= $Get_BuddyCount) + { + $ThisPage = 1; + $LimitStart = 0; + } + $AddPage2Link = ''; + if($ThisPage > 1) + { + $AddPage2Link = '&page='.$ThisPage; + } + $LastPage = ceil($BuddyCount / $_PerPage); + + $NeededFields = "`buddy`.*, `users`.`username`, `users`.`onlinetime`, `users`.`galaxy`, `users`.`system`, `users`.`planet`, `users`.`ally_id`, `ally`.`ally_name`, `stats`.`total_rank`, `stats`.`total_points` "; + $Query = ''; + $Query .= "SELECT {$NeededFields} FROM {{table}} AS `buddy` "; + $Query .= "LEFT JOIN `{{prefix}}users` AS `users` ON `users`.`id` = IF(`buddy`.`owner` = {$_User['id']}, `buddy`.`sender`, `buddy`.`owner`) "; + $Query .= "LEFT JOIN `{{prefix}}alliance` AS `ally` ON `ally`.`id` = `users`.`ally_id` "; + $Query .= "LEFT JOIN `{{prefix}}statpoints` AS `stats` ON `users`.`id` = `stats`.`id_owner` AND `stats`.`stat_type` = '1' "; + $Query .= "WHERE `buddy`.`owner` = {$_User['id']} OR `buddy`.`sender` = {$_User['id']} "; + $Query .= "ORDER BY `buddy`.`active` ASC, `buddy`.`date` DESC LIMIT {$LimitStart}, {$_PerPage};"; + $Get_Buddy = doquery($Query, 'buddy'); + + while($BuddyData = mysql_fetch_assoc($Get_Buddy)) + { + $BuddyData['UID'] = ($BuddyData['owner'] == $_User['id'] ? $BuddyData['sender'] : $BuddyData['owner']); + $BuddyParse = array + ( + 'Insert_UID' => $BuddyData['UID'], + 'Insert_Nick' => $BuddyData['username'], + 'Insert_StatPositionLink' => $BuddyData['total_rank'], + 'Insert_StatPoints' => prettyNumber($BuddyData['total_points']), + 'Insert_StatPosition' => prettyNumber($BuddyData['total_rank']), + 'Insert_AllyID' => $BuddyData['ally_id'], + 'Insert_Ally' => $BuddyData['ally_name'], + 'Insert_PosGalaxy' => $BuddyData['galaxy'], + 'Insert_PosSystem' => $BuddyData['system'], + 'Insert_PosPlanet' => $BuddyData['planet'], + 'Insert_Date' => date('d.m.Y, H:i:s', $BuddyData['date']) + ); + + if($BuddyData['active'] == 1) + { + $OnlineDiff = $Now - $BuddyData['onlinetime']; + if($OnlineDiff <= TIME_ONLINE) + { + $BuddyParse['Insert_State'] = $_Lang['Row_State_Online']; + $BuddyParse['Insert_StateColor'] = 'lime'; + } + else if($OnlineDiff <= TIME_HOUR) + { + $BuddyParse['Insert_State'] = floor($OnlineDiff / 60).' '.$_Lang['Row_State_Minutes']; + $BuddyParse['Insert_StateColor'] = 'orange'; + } + else + { + $BuddyParse['Insert_State'] = $_Lang['Row_State_Offline'].': '.floor($OnlineDiff / TIME_DAY).' '.$_Lang['Row_State_Days']; + $BuddyParse['Insert_StateColor'] = 'red'; + } + $BuddyParse['Insert_Actions'][] = ""; + } + else + { + $BuddyParse['Insert_State'] = $_Lang['Row_State_Awaiting']; + if($BuddyData['sender'] == $_User['id']) + { + $BuddyParse['Insert_StateColor'] = 'orange'; + $BuddyParse['Insert_Actions'][] = ""; + $BuddyParse['Insert_Actions'][] = ""; + } + else + { + $BuddyParse['Insert_StateColor'] = 'lime'; + $BuddyParse['Insert_Actions'][] = ""; + $BuddyParse['Insert_Actions'][] = ""; + } + } + if(!empty($BuddyParse['Insert_Actions'])) + { + $BuddyParse['Insert_Actions'] = implode(' ', $BuddyParse['Insert_Actions']); + } + else + { + $BuddyParse['Insert_Actions'] = ' '; + } + + $BuddyParse = parsetemplate($TPL_BuddyRow, $BuddyParse); + if($BuddyData['active'] == 1) + { + $BuddyRows['active'][] = $BuddyParse; + } + else + { + $BuddyRows['awaiting'][] = $BuddyParse; + } + } + + if(!empty($BuddyRows['awaiting'])) + { + $Parse['Insert_AwaitingList'] = implode('', $BuddyRows['awaiting']); + $Parse['Insert_HideSeparator'] = ''; + } + if(!empty($BuddyRows['active'])) + { + $Parse['Insert_BuddyList'] = implode('', $BuddyRows['active']); + $Parse['Insert_HideWithBuddyList'] = 'hide'; + } + else + { + $Parse['Insert_HideSeparator'] = ''; + if($LastPage != $ThisPage) + { + $Parse['Insert_HideSeparator'] = 'hide'; + $Parse['Insert_HideWithBuddyList'] = 'hide'; + } + } + + if($BuddyCount > $_PerPage) + { + include_once($_EnginePath.'includes/functions/Pagination.php'); + $Pagination = CreatePaginationArray($BuddyCount, $_PerPage, $ThisPage, 7); + $PaginationTPL = "{\$ShowValue}"; + $PaginationViewOpt = array('CurrentPage_Classes' => 'orange', 'Breaker_View' => '...'); + $Pagination = ParsePaginationArray($Pagination, $ThisPage, $PaginationTPL, $PaginationViewOpt); + $Parse['Insert_Pagination'] = implode(' ', $Pagination); + $Parse['Insert_HidePagination'] = ''; + } + } +} +else if($Command == 'edit' OR $Command == 'add') +{ + $TPL_Default = gettemplate('buddy_form'); + + if($Command == 'add') + { + if($UID < 1) + { + message($_Lang['Error_BadUID'], $_Lang['Title'], 'buddy.php', 3); + } + $GetUserdata = doquery("SELECT `username` FROM {{table}} WHERE `id` = {$UID} LIMIT 1;", 'users', true); + if(empty($GetUserdata['username'])) + { + message($_Lang['Error_BadUser'], $_Lang['Title'], 'buddy.php', 3); + } + $CheckBuddy = doquery("SELECT COUNT(*) AS `Count` FROM {{table}} WHERE (`sender` = {$_User['id']} AND `owner` = {$UID}) OR (`sender` = {$UID} AND `owner` = {$_User['id']}) LIMIT 1;", 'buddy', true); + if($CheckBuddy['Count'] > 0) + { + message($_Lang['Error_LinkExists'], $_Lang['Title'], 'buddy.php', 3); + } + + $Parse['Insert_Username'] = $GetUserdata['username']; + } + else + { + if($UID < 1) + { + message($_Lang['Error_ElementIDBad'], $_Lang['Title'], 'buddy.php', 3); + } + + $Query = ''; + $Query .= "SELECT `buddy`.*, `users`.`username` FROM {{table}} AS `buddy` "; + $Query .= "LEFT JOIN {{prefix}}users AS `users` ON `users`.`id` = `buddy`.`owner` "; + $Query .= "WHERE (`buddy`.`sender` = {$UID} AND `buddy`.`owner` = {$_User['id']}) OR (`buddy`.`sender` = {$_User['id']} AND `buddy`.`owner` = {$UID}) "; + $Query .= "LIMIT 1;"; + $CheckBuddy = doquery($Query, 'buddy', true); + if(empty($CheckBuddy)) + { + message($_Lang['Error_RowNoExists'], $_Lang['Title'], 'buddy.php', 3); + } + if($CheckBuddy['sender'] != $_User['id']) + { + message($_Lang['Error_CantEdit'], $_Lang['Title'], 'buddy.php', 3); + } + if($CheckBuddy['active'] == 1) + { + message($_Lang['Error_AlreadyActive'], $_Lang['Title'], 'buddy.php', 3); + } + + $Parse['Insert_Username'] = $CheckBuddy['username']; + $Parse['Insert_Text'] = $CheckBuddy['text']; + } + + if(isset($_POST['send']) && $_POST['send'] == '1') + { + $InsertClean['Text'] = substr(trim(stripslashes($_POST['text'])), 0, $_MaxLength); + $Insert['Text'] = mysql_real_escape_string($InsertClean['Text']); + + if(!empty($Insert['Text'])) + { + if($Command == 'add') + { + doquery("INSERT INTO {{table}} SET `sender` = {$_User['id']}, `owner` = {$UID}, `text` = '{$Insert['Text']}', `date` = UNIX_TIMESTAMP();", 'buddy'); + + header('Location: ?msg=add'); + safeDie(); + } + else if($Command == 'edit') + { + doquery("UPDATE {{table}} SET `text` = '{$Insert['Text']}', `date` = UNIX_TIMESTAMP() WHERE `sender` = {$CheckBuddy['sender']} AND `owner` = {$CheckBuddy['owner']} LIMIT 1;", 'buddy'); + + $Parse['Insert_MsgBoxText'] = $_Lang['Success_Edited']; + $Parse['Insert_MsgBoxColor'] = 'lime'; + } + } + else + { + $Parse['Insert_MsgBoxText'] = $_Lang['Error_EmptyText']; + $Parse['Insert_MsgBoxColor'] = 'red'; + } + + $Parse['Insert_Text'] = $InsertClean['Text']; + } + + $Parse['Insert_MaxLength'] = $_MaxLength; +} + +if(isset($_GET['msg']) && $_GET['msg'] == 'add') +{ + $Parse['Insert_MsgBoxText'] = $_Lang['Success_Sent']; + $Parse['Insert_MsgBoxColor'] = 'lime'; +} + +if(empty($Parse['Insert_MsgBoxText'])) +{ + $Parse['Insert_MsgBoxHide'] = 'hide'; +} + +display(parsetemplate($TPL_Default, $Parse), $_Lang['Title'], false); + +?> diff --git a/buildings.php b/buildings.php index ec9b82197..9b6eeae6c 100644 --- a/buildings.php +++ b/buildings.php @@ -1,109 +1,109 @@ - $_User['settings_DevelopmentOld'], - 'PHP_ViewText' => $_Lang['ViewSel_ViewText'], - 'PHP_Mode0' => $_Lang['ViewSel_Mode0'], - 'PHP_Mode1' => $_Lang['ViewSel_Mode1'], - 'PHP_ChangeView' => $_Lang['ViewSel_ChangeView'] - ); - GlobalTemplate_AppendToBottomMenuInjection(parsetemplate(gettemplate('buildings_compact_viewselector_body'), $ViewSelectorPHP)); - - if(!isset($_Planet)) - { - $_Planet = array(); - } - HandleFullUserUpdate($_User, $_Planet, $GetLabPlanet); - if(isset($_User['techQueue_EndTime']) && $_User['techQueue_EndTime'] > 0) - { - $InResearch = true; - $ResearchPlanet = &$GetLabPlanet; - } - else - { - $InResearch = false; - $ResearchPlanet = false; - } - - $OldViewMode = ($_User['settings_DevelopmentOld'] == 1 ? true : false); - - if(!isset($_GET['mode'])) - { - $_GET['mode'] = ''; - } - switch($_GET['mode']) - { - case 'fleet': - if($OldViewMode) - { - include($_EnginePath.'includes/functions/FleetBuildingPage.php'); - FleetBuildingPage($_Planet, $_User); - } - else - { - include($_EnginePath.'includes/functions/ShipyardPage.php'); - ShipyardPage($_Planet, $_User); - } - break; - case 'research': - if($OldViewMode) - { - include($_EnginePath.'includes/functions/ResearchBuildingPage.php'); - ResearchBuildingPage($_Planet, $_User, $InResearch, $ResearchPlanet); - } - else - { - include($_EnginePath.'includes/functions/LaboratoryPage.php'); - LaboratoryPage($_Planet, $_User, $InResearch, $ResearchPlanet); - } - break; - case 'defense': - if($OldViewMode) - { - include($_EnginePath.'includes/functions/DefensesBuildingPage.php'); - DefensesBuildingPage($_Planet, $_User); - } - else - { - include($_EnginePath.'includes/functions/ShipyardPage.php'); - ShipyardPage($_Planet, $_User, 'defense'); - } - break; - default: - if($OldViewMode) - { - include($_EnginePath.'includes/functions/BatimentBuildingPage.php'); - BatimentBuildingPage($_Planet, $_User); - } - else - { - include($_EnginePath.'includes/functions/StructuresBuildingPage.php'); - StructuresBuildingPage($_Planet, $_User); - } - break; - } - -?> \ No newline at end of file + $_User['settings_DevelopmentOld'], + 'PHP_ViewText' => $_Lang['ViewSel_ViewText'], + 'PHP_Mode0' => $_Lang['ViewSel_Mode0'], + 'PHP_Mode1' => $_Lang['ViewSel_Mode1'], + 'PHP_ChangeView' => $_Lang['ViewSel_ChangeView'] +); +GlobalTemplate_AppendToBottomMenuInjection(parsetemplate(gettemplate('buildings_compact_viewselector_body'), $ViewSelectorPHP)); + +if(!isset($_Planet)) +{ + $_Planet = array(); +} +HandleFullUserUpdate($_User, $_Planet, $GetLabPlanet); +if(isset($_User['techQueue_EndTime']) && $_User['techQueue_EndTime'] > 0) +{ + $InResearch = true; + $ResearchPlanet = &$GetLabPlanet; +} +else +{ + $InResearch = false; + $ResearchPlanet = false; +} + +$OldViewMode = ($_User['settings_DevelopmentOld'] == 1 ? true : false); + +if(!isset($_GET['mode'])) +{ + $_GET['mode'] = ''; +} +switch($_GET['mode']) +{ + case 'fleet': + if($OldViewMode) + { + include($_EnginePath.'includes/functions/FleetBuildingPage.php'); + FleetBuildingPage($_Planet, $_User); + } + else + { + include($_EnginePath.'includes/functions/ShipyardPage.php'); + ShipyardPage($_Planet, $_User); + } + break; + case 'research': + if($OldViewMode) + { + include($_EnginePath.'includes/functions/ResearchBuildingPage.php'); + ResearchBuildingPage($_Planet, $_User, $InResearch, $ResearchPlanet); + } + else + { + include($_EnginePath.'includes/functions/LaboratoryPage.php'); + LaboratoryPage($_Planet, $_User, $InResearch, $ResearchPlanet); + } + break; + case 'defense': + if($OldViewMode) + { + include($_EnginePath.'includes/functions/DefensesBuildingPage.php'); + DefensesBuildingPage($_Planet, $_User); + } + else + { + include($_EnginePath.'includes/functions/ShipyardPage.php'); + ShipyardPage($_Planet, $_User, 'defense'); + } + break; + default: + if($OldViewMode) + { + include($_EnginePath.'includes/functions/BatimentBuildingPage.php'); + BatimentBuildingPage($_Planet, $_User); + } + else + { + include($_EnginePath.'includes/functions/StructuresBuildingPage.php'); + StructuresBuildingPage($_Planet, $_User); + } + break; +} + +?> diff --git a/cache/data/index.php b/cache/data/index.php index 2c5d40047..bc99142d1 100644 --- a/cache/data/index.php +++ b/cache/data/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/cache/img/index.php b/cache/img/index.php index 2c5d40047..bc99142d1 100644 --- a/cache/img/index.php +++ b/cache/img/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/cache/img/signatures/en/index.php b/cache/img/signatures/en/index.php index 2c5d40047..bc99142d1 100644 --- a/cache/img/signatures/en/index.php +++ b/cache/img/signatures/en/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/cache/img/signatures/index.php b/cache/img/signatures/index.php index 2c5d40047..bc99142d1 100644 --- a/cache/img/signatures/index.php +++ b/cache/img/signatures/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/cache/img/signatures/pl/index.php b/cache/img/signatures/pl/index.php index 2c5d40047..bc99142d1 100644 --- a/cache/img/signatures/pl/index.php +++ b/cache/img/signatures/pl/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/cache/img/signatures/static/index.php b/cache/img/signatures/static/index.php index 2c5d40047..bc99142d1 100644 --- a/cache/img/signatures/static/index.php +++ b/cache/img/signatures/static/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/cache/index.php b/cache/index.php index 2c5d40047..bc99142d1 100644 --- a/cache/index.php +++ b/cache/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/changelog.php b/changelog.php index 277a31d38..12d231ccd 100644 --- a/changelog.php +++ b/changelog.php @@ -1,45 +1,45 @@ - $Desc) - { - $parse['version_number'] = $Version; - $parse['description'] = nl2br($Desc); - - $ChangesList .= parsetemplate($template, $parse); - } - - $parse = $_Lang; - $parse['InfoTable'] = $SubFrame; - $parse['ChangesList'] = $ChangesList; - - display(parsetemplate(gettemplate('changelog_body'), $parse), 'ChangeLog', false); - -?> \ No newline at end of file + $Desc) +{ + $parse['version_number'] = $Version; + $parse['description'] = nl2br($Desc); + + $ChangesList .= parsetemplate($template, $parse); +} + +$parse = $_Lang; +$parse['InfoTable'] = $SubFrame; +$parse['ChangesList'] = $ChangesList; + +display(parsetemplate(gettemplate('changelog_body'), $parse), 'ChangeLog', false); + +?> diff --git a/chat.php b/chat.php index e1609dad0..42a0128de 100644 --- a/chat.php +++ b/chat.php @@ -1,83 +1,83 @@ -= $Query_GetRoom['AccessCheck']) - { - $_ChatTitle = sprintf($_Lang['ChatTitle_String'], $_Lang['ChatTitle_GameTeam']); - } - } - } - - $Query_GetFirstID = ''; - $Query_GetFirstID .= "SELECT `msg`.`ID` FROM {{table}} AS `msg` "; - $Query_GetFirstID .= "LEFT JOIN `{{prefix}}chat_online` AS `visit` ON `visit`.`RID` = {$RoomID} AND `visit`.`UID` = {$_User['id']} "; - $Query_GetFirstID .= "WHERE `msg`.`TimeStamp_Add` <= `visit`.`LastOnline` AND `msg`.`RID` = {$RoomID} "; - $Query_GetFirstID .= "ORDER BY `msg`.`ID` DESC LIMIT 1;"; - $GetFirstID = doquery($Query_GetFirstID, 'chat_messages', true); - - foreach($_Lang['months_variant1'] as $monthID => $monthText) - { - $MonthLangString[($monthID+1)] = $monthText; - } - $_Lang['Online_You_ID'] = $_User['id']; - $_Lang['Online_You_Color'] = (string)GetAuthLabel($_User); - $_Lang['Online_You_Name'] = $_User['username']; - - $_Lang['MonthLangString'] = json_encode($MonthLangString); - $_Lang['LastSeenID'] = (string)($GetFirstID['ID'] + 0); - $_Lang['ServerStamp'] = SERVER_MAINOPEN_TSTAMP; - $_Lang['UserAuth'] = (string)($_User['authlevel'] + 0); - $_Lang['RoomID'] = (string)($RoomID + 0); - $_Lang['Insert_JSLang_Errors'] = json_encode($_Lang['jsLang_Errors']); - - if($_User['chat_GhostMode'] == 1) - { - $_Lang['Online_You_Invisible'] = 'usrInv'; - $_Lang['Insert_CheckedGhostMode'] = 'checked'; - } - if($_User['chat_GhostMode_DontCount'] == 1) - { - $_Lang['Insert_CheckedGhostMode_DontCount'] = 'checked'; - } - if(!CheckAuth('supportadmin')) - { - $_Lang['Insert_Hide_GhostMode_DontCount'] = 'hide'; - } - $_Lang['Insert_Settings'] = parsetemplate(gettemplate('chat_body_settings'), $_Lang); - - $_DisplaySettings['dontShow_MainChat_MsgCount'] = true; - $_DisplaySettings['dontShow_AllyChat_MsgCount'] = true; - - display(parsetemplate($BodyTPL, $_Lang), $_ChatTitle, false); - -?> \ No newline at end of file += $Query_GetRoom['AccessCheck']) + { + $_ChatTitle = sprintf($_Lang['ChatTitle_String'], $_Lang['ChatTitle_GameTeam']); + } + } +} + +$Query_GetFirstID = ''; +$Query_GetFirstID .= "SELECT `msg`.`ID` FROM {{table}} AS `msg` "; +$Query_GetFirstID .= "LEFT JOIN `{{prefix}}chat_online` AS `visit` ON `visit`.`RID` = {$RoomID} AND `visit`.`UID` = {$_User['id']} "; +$Query_GetFirstID .= "WHERE `msg`.`TimeStamp_Add` <= `visit`.`LastOnline` AND `msg`.`RID` = {$RoomID} "; +$Query_GetFirstID .= "ORDER BY `msg`.`ID` DESC LIMIT 1;"; +$GetFirstID = doquery($Query_GetFirstID, 'chat_messages', true); + +foreach($_Lang['months_variant1'] as $monthID => $monthText) +{ + $MonthLangString[($monthID+1)] = $monthText; +} +$_Lang['Online_You_ID'] = $_User['id']; +$_Lang['Online_You_Color'] = (string)GetAuthLabel($_User); +$_Lang['Online_You_Name'] = $_User['username']; + +$_Lang['MonthLangString'] = json_encode($MonthLangString); +$_Lang['LastSeenID'] = (string)($GetFirstID['ID'] + 0); +$_Lang['ServerStamp'] = SERVER_MAINOPEN_TSTAMP; +$_Lang['UserAuth'] = (string)($_User['authlevel'] + 0); +$_Lang['RoomID'] = (string)($RoomID + 0); +$_Lang['Insert_JSLang_Errors'] = json_encode($_Lang['jsLang_Errors']); + +if($_User['chat_GhostMode'] == 1) +{ + $_Lang['Online_You_Invisible'] = 'usrInv'; + $_Lang['Insert_CheckedGhostMode'] = 'checked'; +} +if($_User['chat_GhostMode_DontCount'] == 1) +{ + $_Lang['Insert_CheckedGhostMode_DontCount'] = 'checked'; +} +if(!CheckAuth('supportadmin')) +{ + $_Lang['Insert_Hide_GhostMode_DontCount'] = 'hide'; +} +$_Lang['Insert_Settings'] = parsetemplate(gettemplate('chat_body_settings'), $_Lang); + +$_DisplaySettings['dontShow_MainChat_MsgCount'] = true; +$_DisplaySettings['dontShow_AllyChat_MsgCount'] = true; + +display(parsetemplate($BodyTPL, $_Lang), $_ChatTitle, false); + +?> diff --git a/chat_edit.php b/chat_edit.php index d6976da2c..2ad7b179d 100644 --- a/chat_edit.php +++ b/chat_edit.php @@ -7,36 +7,36 @@ $_EnginePath = './'; include($_EnginePath.'common.php'); - loggedCheck(); - - includeLang('chat'); - $BodyTPL = gettemplate('chat_edit'); - - if(!CheckAuth('supportadmin')) - { - message($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); - } - - $EditID = (isset($_GET['mode']) ? round($_GET['mode']) : 0); - if($EditID > 0 && isset($_GET['save'])) - { - $NewMessage = mysql_real_escape_string($_POST['message']); - doquery("UPDATE {{table}} SET `Text` = '{$NewMessage}', `TimeStamp_Edit` = UNIX_TIMESTAMP() WHERE `ID` = {$EditID} LIMIT 1;", 'chat_messages'); - header('Location: chat.php'); - } - else if($EditID > 0) - { - $GetMessage = doquery("SELECT `Text` FROM {{table}} WHERE `ID` = {$EditID} LIMIT 1;", "chat_messages", true); - $_Lang['EditID'] = $EditID; - $_Lang['OldText'] = stripslashes($GetMessage['Text']); - $_Lang['SubmitButton'] = $_Lang['chat_save']; - } - else - { - header('Location: chat.php'); - } - - $page = parsetemplate($BodyTPL, $_Lang); - display($page, $_Lang['Chat'], false); - -?> \ No newline at end of file +loggedCheck(); + +includeLang('chat'); +$BodyTPL = gettemplate('chat_edit'); + +if(!CheckAuth('supportadmin')) +{ + message($_Lang['sys_noalloaw'], $_Lang['sys_noaccess']); +} + +$EditID = (isset($_GET['mode']) ? round($_GET['mode']) : 0); +if($EditID > 0 && isset($_GET['save'])) +{ + $NewMessage = mysql_real_escape_string($_POST['message']); + doquery("UPDATE {{table}} SET `Text` = '{$NewMessage}', `TimeStamp_Edit` = UNIX_TIMESTAMP() WHERE `ID` = {$EditID} LIMIT 1;", 'chat_messages'); + header('Location: chat.php'); +} +else if($EditID > 0) +{ + $GetMessage = doquery("SELECT `Text` FROM {{table}} WHERE `ID` = {$EditID} LIMIT 1;", "chat_messages", true); + $_Lang['EditID'] = $EditID; + $_Lang['OldText'] = stripslashes($GetMessage['Text']); + $_Lang['SubmitButton'] = $_Lang['chat_save']; +} +else +{ + header('Location: chat.php'); +} + +$page = parsetemplate($BodyTPL, $_Lang); +display($page, $_Lang['Chat'], false); + +?> diff --git a/class/UniEngine_Cache.class.php b/class/UniEngine_Cache.class.php index e323bbdfb..a88498812 100644 --- a/class/UniEngine_Cache.class.php +++ b/class/UniEngine_Cache.class.php @@ -1,62 +1,62 @@ -APCCache_Key = UNIENGINE_UNIID.'_APCCache'; - } - } - - public function __get($name) - { - if(UNIENGINE_HASAPC) - { - return apc_fetch($this->APCCache_Key.'__'.$name); - } - return null; - } - - public function __set($name, $value) - { - if(UNIENGINE_HASAPC) - { - return apc_store($this->APCCache_Key.'__'.$name, $value); - } - return false; - } - - public function __isset($name) - { - if(UNIENGINE_HASAPC) - { - return apc_exists($this->APCCache_Key.'__'.$name); - } - return false; - } - - public function __unset($name) - { - if(UNIENGINE_HASAPC) - { - return apc_delete($this->APCCache_Key.'__'.$name); - } - return false; - } -} - -?> \ No newline at end of file +APCCache_Key = UNIENGINE_UNIID.'_APCCache'; + } + } + + public function __get($name) + { + if(UNIENGINE_HASAPC) + { + return apc_fetch($this->APCCache_Key.'__'.$name); + } + return null; + } + + public function __set($name, $value) + { + if(UNIENGINE_HASAPC) + { + return apc_store($this->APCCache_Key.'__'.$name, $value); + } + return false; + } + + public function __isset($name) + { + if(UNIENGINE_HASAPC) + { + return apc_exists($this->APCCache_Key.'__'.$name); + } + return false; + } + + public function __unset($name) + { + if(UNIENGINE_HASAPC) + { + return apc_delete($this->APCCache_Key.'__'.$name); + } + return false; + } +} + +?> diff --git a/class/index.php b/class/index.php index ee150fd01..bc99142d1 100644 --- a/class/index.php +++ b/class/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/common.php b/common.php index 81a43e161..64b813ad9 100644 --- a/common.php +++ b/common.php @@ -1,487 +1,488 @@ -simpleCountStart(false, 'telemetry__c'); } - -session_start(); -if($_SERVER['SERVER_ADDR'] == '127.0.0.1' OR $_SERVER['SERVER_ADDR'] == '::1') -{ - // We are on Localhost - define('LOCALHOST', TRUE); - define('TESTSERVER', FALSE); -} -else -{ - // We are not on Localhost - define('LOCALHOST', FALSE); - if($_SERVER['HTTP_HOST'] === GAMEURL_REMOTE_TESTSERVERHOST) - { - define('TESTSERVER', TRUE); - } - else - { - define('TESTSERVER', FALSE); - } -} - -ini_set('default_charset', 'UTF-8'); -$_GameConfig = array(); -$_User = array(); -$_Lang = array(); -$_DBLink = ''; -$ForceIPnUALog = false; -$Common_TimeNow = time(); - -define('DEFAULT_SKINPATH' , 'skins/epicblue/'); -define('TEMPLATE_DIR' , 'templates/'); -define('TEMPLATE_NAME' , 'default_template'); -define('DEFAULT_LANG' , 'pl'); - -include($_EnginePath.'includes/constants.php'); -if(defined('INSTALL_NOTDONE')) -{ - header('Location: ./install/'); - die(); -} -include($_EnginePath.'includes/functions.php'); -include($_EnginePath.'includes/unlocalised.php'); -include($_EnginePath.'includes/ingamefunctions.php'); -include($_EnginePath.'class/UniEngine_Cache.class.php'); - -$_MemCache = new UniEngine_Cache(); - -$_POST = SecureInput($_POST); -$_GET = SecureInput($_GET); - -include($_EnginePath.'includes/vars.php'); -include($_EnginePath.'includes/db.php'); -include($_EnginePath.'includes/strings.php'); - -// Load game configuration -if(isset($_MemCache->GameConfig)) -{ - $_GameConfig = $_MemCache->GameConfig; -} -else -{ - $Query_GetGameConfig = "SELECT * FROM {{table}};"; - $Result_GetGameConfig = doquery($Query_GetGameConfig, 'config'); - while($FetchData = mysql_fetch_assoc($Result_GetGameConfig)) - { - $_GameConfig[$FetchData['config_name']] = $FetchData['config_value']; - } - $_MemCache->GameConfig = $_GameConfig; -} - -define('VERSION', $_GameConfig['EngineInfo_Version']); -define('REVISION' , $_GameConfig['EngineInfo_BuildNo']); - -if(!defined('UEC_INLOGIN')) -{ - $_User = CheckUserSession(); -} - -if(defined('IN_ADMIN')) -{ - if(empty($_User['skinpath'])) - { - $UsePath = DEFAULT_SKINPATH; - } - else - { - $UsePath = $_User['skinpath']; - } - if(strstr($UsePath, 'http:') === false) - { - $_SkinPath = $_EnginePath.$UsePath; - } - else - { - $_SkinPath = $UsePath; - } -} -else -{ - $_SkinPath = (empty($_User['skinpath'])) ? DEFAULT_SKINPATH : $_User['skinpath']; -} - -includeLang('tech'); -includeLang('system'); - -if($_GameConfig['game_disable'] AND !CheckAuth('supportadmin')) -{ - $_DontShowMenus = true; - if(!empty($_CommonSettings['gamedisable_callback'])) - { - $_CommonSettings['gamedisable_callback'](); - } - message(($_GameConfig['close_reason'] ? nl2br($_Lang['ServerIsClosed'].'
'.$_GameConfig['close_reason']) : $_Lang['ServerIsClosed']), $_GameConfig['game_name']); -} - -if(!isset($_SetAccessLogPath)) -{ - $_SetAccessLogPath = ''; -} -if(!isset($_SetAccessLogPreFilename)) -{ - $_SetAccessLogPreFilename = ''; -} -CreateAccessLog($_SetAccessLogPath, $_SetAccessLogPreFilename); - -if(!empty($_GameConfig['banned_ip_list'])) -{ - $BannedIPs = explode('|',$_GameConfig['banned_ip_list']); - if(!empty($BannedIPs) AND (array)$BannedIPs === $BannedIPs) - { - if(!empty($_SERVER['REMOTE_ADDR']) AND in_array($_SERVER['REMOTE_ADDR'], $BannedIPs)) - { - message($_Lang['Game_blocked_for_this_IP'], $_GameConfig['game_name']); - } - } -} - -if(isLogged()) -{ - if(TESTSERVER === TRUE) - { - if($_User['allowTestServer'] != 1 AND $_User['id'] != 1) - { - message($_Lang['sys_noaccess'], $_Lang['Title_System'], GAMEURL_STRICT, 3); - } - } - - if($_User['onlinetime'] > 0 AND $_User['onlinetime'] < ($Common_TimeNow - TIME_ONLINE)) - { - $ForceIPnUALog = true; - } - - if(empty($_SESSION['IP_check'])) - { - $_SESSION['IP_check'] = $_SERVER['REMOTE_ADDR']; - } - else - { - if($_SERVER['REMOTE_ADDR'] != $_SESSION['IP_check']) - { - if($_User['noipcheck'] != 1) - { - unset($_SESSION['IP_check']); - header('Location: logout.php?badip=1'); - safeDie(); - } - else - { - $_SESSION['IP_check'] = $_SERVER['REMOTE_ADDR']; - $ForceIPnUALog = true; - } - } - } - - if($ForceIPnUALog) - { - include("{$_EnginePath}includes/functions/IPandUA_Logger.php"); - IPandUA_Logger($_User); - } - - if(LOCALHOST === FALSE AND TESTSERVER === FALSE) - { - if($Common_TimeNow < SERVER_MAINOPEN_TSTAMP) - { - message(sprintf($_Lang['ServerStart_NotReached'], prettyDate('d m Y', SERVER_MAINOPEN_TSTAMP, 1), date('H:i:s', SERVER_MAINOPEN_TSTAMP)), $_Lang['Title_System']); - } - } - - if(!empty($_User['activation_code']) AND $_User['first_login'] > 0 AND ($Common_TimeNow - $_User['first_login']) > NONACTIVE_PLAYTIME) - { - $_DontShowMenus = true; - message($_Lang['NonActiveBlock'], $_GameConfig['game_name']); - } - - // Cookie Blockade - $ShowBlockadeInfo_CookieStyle = false; - if(!empty($_COOKIE[COOKIE_BLOCK])) - { - if($_COOKIE[COOKIE_BLOCK] === (COOKIE_BLOCK_VAL.md5($_User['id'])) AND $_User['block_cookies'] == 0) - { - setcookie(COOKIE_BLOCK, '', $Common_TimeNow - 100000, '', '', false, true); - $_COOKIE[COOKIE_BLOCK] = ''; - } - else - { - $ShowBlockadeInfo_CookieStyle = true; - } - } - else - { - if($_User['block_cookies'] == 1) - { - setcookie(COOKIE_BLOCK, (COOKIE_BLOCK_VAL.md5($_User['id'])), $Common_TimeNow + (3 * TIME_YEAR), "", "", false, true); - $ShowBlockadeInfo_CookieStyle = true; - } - } - if($ShowBlockadeInfo_CookieStyle === true) - { - $_DontShowMenus = true; - message($_Lang['GameBlock_CookieStyle'], $_GameConfig['game_name']); - } - - if($_User['dokick'] == 1) - { - setcookie($_GameConfig['COOKIE_NAME'], '', $Common_TimeNow - 100000, '/', '', 0); - doquery("UPDATE {{table}} SET `dokick` = 0 WHERE `id` = {$_User['id']};", 'users'); - - header('Location: logout.php?kicked=1'); - safeDie(); - } - - // --- Handle Tasks --- - if(!isset($_UseMinimalCommon) || $_UseMinimalCommon !== true) - { - if(!isset($_DontShowMenus) || $_DontShowMenus !== true) - { - if(!empty($_User['tasks_done_parsed']['locked'])) - { - $TaskBoxParseData = includeLang('tasks_infobox', true); - $DoneTasks = 0; - - foreach($_User['tasks_done_parsed']['locked'] as $CatID => $CatTasks) - { - if(strstr($CatID, 's')) - { - $CatID = str_replace('s', '', $CatID); - $ThisCatSkiped = true; - } - else - { - $ThisCatSkiped = false; - } - foreach($CatTasks as $TaskID) - { - unset($_User['tasks_done_parsed']['jobs'][$CatID][$TaskID]); - if($ThisCatSkiped === false OR ($ThisCatSkiped === true AND $_Vars_TasksData[$CatID]['skip']['tasksrew'] === true)) - { - $TaskBoxLinks[$CatID] = 'cat='.$CatID.'&showtask='.$TaskID; - foreach($_Vars_TasksData[$CatID]['tasks'][$TaskID]['reward'] as $RewardData) - { - Tasks_ParseRewards($RewardData, $_Vars_TasksDataUpdate); - } - } - $DoneTasks += 1; - } - if(Tasks_IsCatDone($CatID, $_User)) - { - unset($_User['tasks_done_parsed']['jobs'][$CatID]); - if($ThisCatSkiped === false OR ($ThisCatSkiped === true AND $_Vars_TasksData[$CatID]['skip']['catrew'] === true)) - { - $TaskBoxLinks[$CatID] = 'mode=log&cat='.$CatID; - foreach($_Vars_TasksData[$CatID]['reward'] as $RewardData) - { - Tasks_ParseRewards($RewardData, $_Vars_TasksDataUpdate); - } - } - } - else - { - if(empty($_User['tasks_done_parsed']['jobs'])) - { - unset($_User['tasks_done_parsed']['jobs']); - } - } - } - - if(empty($_User['tasks_done_parsed']['jobs'])) - { - unset($_User['tasks_done_parsed']['jobs']); - } - - if(!empty($TaskBoxLinks)) - { - if($DoneTasks > 1) - { - $TaskBoxParseData['Task'] = $TaskBoxParseData['MoreTasks']; - } - else - { - $TaskBoxParseData['Task'] = $TaskBoxParseData['OneTask']; - } - foreach($TaskBoxLinks as $CatID => $LinkData) - { - $TaskBoxParseData['CatLinks'][] = sprintf($TaskBoxParseData['CatLink'], $LinkData, $TaskBoxParseData['Names'][$CatID]); - } - $TaskBoxParseData['CatLinks'] = implode(', ', $TaskBoxParseData['CatLinks']); - GlobalTemplate_AppendToTaskBox(parsetemplate(gettemplate('tasks_infobox'), $TaskBoxParseData)); - } - - unset($_User['tasks_done_parsed']['locked']); - $_User['tasks_done'] = json_encode($_User['tasks_done_parsed']); - - GlobalTemplate_AppendToTaskBox(parsetemplate(gettemplate('tasks_infobox'), $TaskBoxParseData)); - - if(!empty($_Vars_TasksDataUpdate['planet'])) - { - foreach($_Vars_TasksDataUpdate['planet'] as $Key => $Value2Add) - { - $_Vars_TasksDataUpdate['planet_array'][] = "`{$Key}` = `{$Key}` + {$Value2Add}"; - } - doquery("UPDATE {{table}} SET ".implode(', ', $_Vars_TasksDataUpdate['planet_array'])." WHERE `id` = {$_User['id_planet']} LIMIT 1;", 'planets'); - - if(!empty($_Vars_TasksDataUpdate['devlog'])) - { - foreach($_Vars_TasksDataUpdate['devlog'] as $DevLogKey => $DevLogRow) - { - $Insert2DevLog[] = "{$DevLogKey},{$DevLogRow}"; - } - $UserDev_Log[] = array('PlanetID' => $_User['id_planet'], 'Date' => $Common_TimeNow, 'Place' => 30, 'Code' => '0', 'ElementID' => '0', 'AdditionalData' => implode(';', $Insert2DevLog)); - unset($Insert2DevLog); - } - } - if(!empty($_Vars_TasksDataUpdate['free_premium'])) - { - foreach($_Vars_TasksDataUpdate['free_premium'] as $ItemID) - { - $_Vars_TasksDataUpdate['free_premium_array'][] = "(NULL, {$_User['id']}, UNIX_TIMESTAMP(), 0, 0, {$ItemID}, 0)"; - } - doquery("INSERT INTO {{table}} VALUES ".implode(', ', $_Vars_TasksDataUpdate['free_premium_array']).";", 'premium_free'); - } - if(!empty($_Vars_TasksDataUpdate['user'])) - { - foreach($_Vars_TasksDataUpdate['user'] as $Key => $Value2Add) - { - $_Vars_TasksDataUpdate['user_var'][] = "`{$Key}` = `{$Key}` + {$Value2Add}"; - $_User[$Key] += $Value2Add; - } - } - - $_Vars_TasksDataUpdate['user_var'][] = "`tasks_done` = '{$_User['tasks_done']}'"; - doquery("UPDATE {{table}} SET ".implode(',', $_Vars_TasksDataUpdate['user_var'])." WHERE `id` = {$_User['id']};", 'users'); - } - } - } - // --- Handling Tasks ends here --- - - if(!isset($_AllowInVacationMode) || $_AllowInVacationMode != true) - { - // If this place do not allow User to be in VacationMode, show him a message if it's necessary - if(isOnVacation()) - { - $MinimalVacationTime = ($_User['pro_time'] > $_User['vacation_starttime'] ? MINURLOP_PRO : MINURLOP_FREE) + $_User['vacation_starttime']; - $VacationMessage = sprintf($_Lang['VacationTill'], date('d.m.Y H:i:s', $MinimalVacationTime)); - if($MinimalVacationTime <= $Common_TimeNow) - { - $VacationMessage .= $_Lang['VacationSetOff']; - } - message($VacationMessage, $_Lang['Vacation']); - } - } - - if(!isset($_UseMinimalCommon) || $_UseMinimalCommon !== true) - { - // Change Planet (if user wants to do this) - SetSelectedPlanet($_User); - - // Get PlanetRow - $_Planet = doquery("SELECT * FROM {{table}} WHERE `id` = {$_User['current_planet']};", 'planets', true); - if($_Planet['id'] <= 0 OR $_Planet['id_owner'] != $_User['id']) - { - // If this planet doesn't exist, try to go back to MotherPlanet - SetSelectedPlanet($_User, $_User['id_planet']); - $_Planet = doquery("SELECT * FROM {{table}} WHERE `id` = {$_User['id_planet']};", 'planets', true); - if($_Planet['id'] <= 0) - { - // If MotherPlanet doesn't exist, ThrowError and don't allow go further - message($_Lang['FatalError_PlanetRowEmpty'], 'FatalError'); - } - } - CheckPlanetUsedFields($_Planet); - - if($_Planet['planet_type'] == 1) - { - $GalaxyRowWhere = "`id_planet` = {$_Planet['id']}"; - } - else - { - $GalaxyRowWhere = "`id_moon` = {$_Planet['id']}"; - } - $_GalaxyRow = doquery("SELECT * FROM {{table}} WHERE {$GalaxyRowWhere};", 'galaxy', true); - - if(!isset($_BlockFleetHandler) || $_BlockFleetHandler !== true) - { - $FleetHandlerReturn = FlyingFleetHandler($_Planet); - if(isset($FleetHandlerReturn['ThisMoonDestroyed']) && $FleetHandlerReturn['ThisMoonDestroyed']) - { - // Redirect User to Planet (from Destroyed Moon) - SetSelectedPlanet($_User, $_User['id_planet']); - $_Planet = doquery("SELECT * FROM {{table}} WHERE `id` = {$_User['id_planet']};", 'planets', true); - if($_Planet['id'] <= 0) - { - message($_Lang['FatalError_PlanetRowEmpty'], 'FatalError'); - } - else - { - if($_GalaxyRow['id_planet'] != $_Planet['id']) - { - $_GalaxyRow = doquery("SELECT * FROM {{table}} WHERE `id_planet` = {$_Planet['id']};", 'galaxy', true); - } - } - } - } - - if(!isset($_DontForceRulesAcceptance) || $_DontForceRulesAcceptance !== true) - { - if($_GameConfig['enforceRulesAcceptance'] == '1' AND $_GameConfig['last_rules_changes'] > 0 AND $_User['rules_accept_stamp'] < $_GameConfig['last_rules_changes']) - { - if(isset($_DontShowRulesBox) && $_DontShowRulesBox === true) - { - message($_Lang['RulesAcceptBox_CantUseFunction'], $_Lang['SystemInfo']); - } - else - { - if(IN_RULES !== true) - { - header('Location: rules.php'); - safeDie(); - } - else - { - $_ForceRulesAcceptBox = true; - } - } - } - } - - if(!isset($_DontCheckPolls) || $_DontCheckPolls !== true) - { - if($_User['isAI'] != 1 AND $_User['register_time'] < ($Common_TimeNow - TIME_DAY)) - { - $Query_SelectPolls = ''; - $Query_SelectPolls .= "SELECT `votes`.`id` AS `vote_id` FROM {{table}} AS `polls` "; - $Query_SelectPolls .= "LEFT JOIN `{{prefix}}poll_votes` AS `votes` ON `votes`.`poll_id` = `polls`.`id` AND `votes`.`user_id` = {$_User['id']} "; - $Query_SelectPolls .= "WHERE `polls`.`open` = 1 AND `polls`.`obligatory` = 1;"; - $SelectObligatoryPolls = doquery($Query_SelectPolls, 'polls'); - if(mysql_num_rows($SelectObligatoryPolls) > 0) - { - $PollsCount = 0; - while($SelectObligatoryPollsData = mysql_fetch_assoc($SelectObligatoryPolls)) - { - if($SelectObligatoryPollsData['vote_id'] <= 0) - { - $PollsCount += 1; - } - } - if($PollsCount > 0) - { - message(sprintf($_Lang['YouHaveToVoteInSurveys'], $PollsCount), $_Lang['SystemInfo'], 'polls.php', 10); - } - } - } - } - } -} -else -{ - $_DontShowMenus = true; -} - -if(!empty($_BenchTool)){ $_BenchTool->simpleCountStop(); } - -?> \ No newline at end of file +simpleCountStart(false, 'telemetry__c'); } + +session_start(); +if($_SERVER['SERVER_ADDR'] == '127.0.0.1' OR $_SERVER['SERVER_ADDR'] == '::1') +{ + // We are on Localhost + define('LOCALHOST', TRUE); + define('TESTSERVER', FALSE); +} +else +{ + // We are not on Localhost + define('LOCALHOST', FALSE); + if($_SERVER['HTTP_HOST'] === GAMEURL_REMOTE_TESTSERVERHOST) + { + define('TESTSERVER', TRUE); + } + else + { + define('TESTSERVER', FALSE); + } +} + +ini_set('default_charset', 'UTF-8'); + +$_GameConfig = array(); +$_User = array(); +$_Lang = array(); +$_DBLink = ''; +$ForceIPnUALog = false; +$Common_TimeNow = time(); + +define('DEFAULT_SKINPATH', 'skins/epicblue/'); +define('TEMPLATE_DIR', 'templates/'); +define('TEMPLATE_NAME', 'default_template'); +define('DEFAULT_LANG', 'pl'); + +include($_EnginePath.'includes/constants.php'); +if(defined('INSTALL_NOTDONE')) +{ + header('Location: ./install/'); + die(); +} +include($_EnginePath.'includes/functions.php'); +include($_EnginePath.'includes/unlocalised.php'); +include($_EnginePath.'includes/ingamefunctions.php'); +include($_EnginePath.'class/UniEngine_Cache.class.php'); + +$_MemCache = new UniEngine_Cache(); + +$_POST = SecureInput($_POST); +$_GET = SecureInput($_GET); + +include($_EnginePath.'includes/vars.php'); +include($_EnginePath.'includes/db.php'); +include($_EnginePath.'includes/strings.php'); + +// Load game configuration +if(isset($_MemCache->GameConfig)) +{ + $_GameConfig = $_MemCache->GameConfig; +} +else +{ + $Query_GetGameConfig = "SELECT * FROM {{table}};"; + $Result_GetGameConfig = doquery($Query_GetGameConfig, 'config'); + while($FetchData = mysql_fetch_assoc($Result_GetGameConfig)) + { + $_GameConfig[$FetchData['config_name']] = $FetchData['config_value']; + } + $_MemCache->GameConfig = $_GameConfig; +} + +define('VERSION', $_GameConfig['EngineInfo_Version']); +define('REVISION', $_GameConfig['EngineInfo_BuildNo']); + +if(!defined('UEC_INLOGIN')) +{ + $_User = CheckUserSession(); +} + +if(defined('IN_ADMIN')) +{ + if(empty($_User['skinpath'])) + { + $UsePath = DEFAULT_SKINPATH; + } + else + { + $UsePath = $_User['skinpath']; + } + if(strstr($UsePath, 'http:') === false) + { + $_SkinPath = $_EnginePath.$UsePath; + } + else + { + $_SkinPath = $UsePath; + } +} +else +{ + $_SkinPath = (empty($_User['skinpath'])) ? DEFAULT_SKINPATH : $_User['skinpath']; +} + +includeLang('tech'); +includeLang('system'); + +if($_GameConfig['game_disable'] AND !CheckAuth('supportadmin')) +{ + $_DontShowMenus = true; + if(!empty($_CommonSettings['gamedisable_callback'])) + { + $_CommonSettings['gamedisable_callback'](); + } + message(($_GameConfig['close_reason'] ? nl2br($_Lang['ServerIsClosed'].'
'.$_GameConfig['close_reason']) : $_Lang['ServerIsClosed']), $_GameConfig['game_name']); +} + +if(!isset($_SetAccessLogPath)) +{ + $_SetAccessLogPath = ''; +} +if(!isset($_SetAccessLogPreFilename)) +{ + $_SetAccessLogPreFilename = ''; +} +CreateAccessLog($_SetAccessLogPath, $_SetAccessLogPreFilename); + +if(!empty($_GameConfig['banned_ip_list'])) +{ + $BannedIPs = explode('|',$_GameConfig['banned_ip_list']); + if(!empty($BannedIPs) AND (array)$BannedIPs === $BannedIPs) + { + if(!empty($_SERVER['REMOTE_ADDR']) AND in_array($_SERVER['REMOTE_ADDR'], $BannedIPs)) + { + message($_Lang['Game_blocked_for_this_IP'], $_GameConfig['game_name']); + } + } +} + +if(isLogged()) +{ + if(TESTSERVER === TRUE) + { + if($_User['allowTestServer'] != 1 AND $_User['id'] != 1) + { + message($_Lang['sys_noaccess'], $_Lang['Title_System'], GAMEURL_STRICT, 3); + } + } + + if($_User['onlinetime'] > 0 AND $_User['onlinetime'] < ($Common_TimeNow - TIME_ONLINE)) + { + $ForceIPnUALog = true; + } + + if(empty($_SESSION['IP_check'])) + { + $_SESSION['IP_check'] = $_SERVER['REMOTE_ADDR']; + } + else + { + if($_SERVER['REMOTE_ADDR'] != $_SESSION['IP_check']) + { + if($_User['noipcheck'] != 1) + { + unset($_SESSION['IP_check']); + header('Location: logout.php?badip=1'); + safeDie(); + } + else + { + $_SESSION['IP_check'] = $_SERVER['REMOTE_ADDR']; + $ForceIPnUALog = true; + } + } + } + + if($ForceIPnUALog) + { + include("{$_EnginePath}includes/functions/IPandUA_Logger.php"); + IPandUA_Logger($_User); + } + + if(LOCALHOST === FALSE AND TESTSERVER === FALSE) + { + if($Common_TimeNow < SERVER_MAINOPEN_TSTAMP) + { + message(sprintf($_Lang['ServerStart_NotReached'], prettyDate('d m Y', SERVER_MAINOPEN_TSTAMP, 1), date('H:i:s', SERVER_MAINOPEN_TSTAMP)), $_Lang['Title_System']); + } + } + + if(!empty($_User['activation_code']) AND $_User['first_login'] > 0 AND ($Common_TimeNow - $_User['first_login']) > NONACTIVE_PLAYTIME) + { + $_DontShowMenus = true; + message($_Lang['NonActiveBlock'], $_GameConfig['game_name']); + } + + // Cookie Blockade + $ShowBlockadeInfo_CookieStyle = false; + if(!empty($_COOKIE[COOKIE_BLOCK])) + { + if($_COOKIE[COOKIE_BLOCK] === (COOKIE_BLOCK_VAL.md5($_User['id'])) AND $_User['block_cookies'] == 0) + { + setcookie(COOKIE_BLOCK, '', $Common_TimeNow - 100000, '', '', false, true); + $_COOKIE[COOKIE_BLOCK] = ''; + } + else + { + $ShowBlockadeInfo_CookieStyle = true; + } + } + else + { + if($_User['block_cookies'] == 1) + { + setcookie(COOKIE_BLOCK, (COOKIE_BLOCK_VAL.md5($_User['id'])), $Common_TimeNow + (3 * TIME_YEAR), "", "", false, true); + $ShowBlockadeInfo_CookieStyle = true; + } + } + if($ShowBlockadeInfo_CookieStyle === true) + { + $_DontShowMenus = true; + message($_Lang['GameBlock_CookieStyle'], $_GameConfig['game_name']); + } + + if($_User['dokick'] == 1) + { + setcookie($_GameConfig['COOKIE_NAME'], '', $Common_TimeNow - 100000, '/', '', 0); + doquery("UPDATE {{table}} SET `dokick` = 0 WHERE `id` = {$_User['id']};", 'users'); + + header('Location: logout.php?kicked=1'); + safeDie(); + } + + // --- Handle Tasks --- + if(!isset($_UseMinimalCommon) || $_UseMinimalCommon !== true) + { + if(!isset($_DontShowMenus) || $_DontShowMenus !== true) + { + if(!empty($_User['tasks_done_parsed']['locked'])) + { + $TaskBoxParseData = includeLang('tasks_infobox', true); + $DoneTasks = 0; + + foreach($_User['tasks_done_parsed']['locked'] as $CatID => $CatTasks) + { + if(strstr($CatID, 's')) + { + $CatID = str_replace('s', '', $CatID); + $ThisCatSkiped = true; + } + else + { + $ThisCatSkiped = false; + } + foreach($CatTasks as $TaskID) + { + unset($_User['tasks_done_parsed']['jobs'][$CatID][$TaskID]); + if($ThisCatSkiped === false OR ($ThisCatSkiped === true AND $_Vars_TasksData[$CatID]['skip']['tasksrew'] === true)) + { + $TaskBoxLinks[$CatID] = 'cat='.$CatID.'&showtask='.$TaskID; + foreach($_Vars_TasksData[$CatID]['tasks'][$TaskID]['reward'] as $RewardData) + { + Tasks_ParseRewards($RewardData, $_Vars_TasksDataUpdate); + } + } + $DoneTasks += 1; + } + if(Tasks_IsCatDone($CatID, $_User)) + { + unset($_User['tasks_done_parsed']['jobs'][$CatID]); + if($ThisCatSkiped === false OR ($ThisCatSkiped === true AND $_Vars_TasksData[$CatID]['skip']['catrew'] === true)) + { + $TaskBoxLinks[$CatID] = 'mode=log&cat='.$CatID; + foreach($_Vars_TasksData[$CatID]['reward'] as $RewardData) + { + Tasks_ParseRewards($RewardData, $_Vars_TasksDataUpdate); + } + } + } + else + { + if(empty($_User['tasks_done_parsed']['jobs'])) + { + unset($_User['tasks_done_parsed']['jobs']); + } + } + } + + if(empty($_User['tasks_done_parsed']['jobs'])) + { + unset($_User['tasks_done_parsed']['jobs']); + } + + if(!empty($TaskBoxLinks)) + { + if($DoneTasks > 1) + { + $TaskBoxParseData['Task'] = $TaskBoxParseData['MoreTasks']; + } + else + { + $TaskBoxParseData['Task'] = $TaskBoxParseData['OneTask']; + } + foreach($TaskBoxLinks as $CatID => $LinkData) + { + $TaskBoxParseData['CatLinks'][] = sprintf($TaskBoxParseData['CatLink'], $LinkData, $TaskBoxParseData['Names'][$CatID]); + } + $TaskBoxParseData['CatLinks'] = implode(', ', $TaskBoxParseData['CatLinks']); + GlobalTemplate_AppendToTaskBox(parsetemplate(gettemplate('tasks_infobox'), $TaskBoxParseData)); + } + + unset($_User['tasks_done_parsed']['locked']); + $_User['tasks_done'] = json_encode($_User['tasks_done_parsed']); + + GlobalTemplate_AppendToTaskBox(parsetemplate(gettemplate('tasks_infobox'), $TaskBoxParseData)); + + if(!empty($_Vars_TasksDataUpdate['planet'])) + { + foreach($_Vars_TasksDataUpdate['planet'] as $Key => $Value2Add) + { + $_Vars_TasksDataUpdate['planet_array'][] = "`{$Key}` = `{$Key}` + {$Value2Add}"; + } + doquery("UPDATE {{table}} SET ".implode(', ', $_Vars_TasksDataUpdate['planet_array'])." WHERE `id` = {$_User['id_planet']} LIMIT 1;", 'planets'); + + if(!empty($_Vars_TasksDataUpdate['devlog'])) + { + foreach($_Vars_TasksDataUpdate['devlog'] as $DevLogKey => $DevLogRow) + { + $Insert2DevLog[] = "{$DevLogKey},{$DevLogRow}"; + } + $UserDev_Log[] = array('PlanetID' => $_User['id_planet'], 'Date' => $Common_TimeNow, 'Place' => 30, 'Code' => '0', 'ElementID' => '0', 'AdditionalData' => implode(';', $Insert2DevLog)); + unset($Insert2DevLog); + } + } + if(!empty($_Vars_TasksDataUpdate['free_premium'])) + { + foreach($_Vars_TasksDataUpdate['free_premium'] as $ItemID) + { + $_Vars_TasksDataUpdate['free_premium_array'][] = "(NULL, {$_User['id']}, UNIX_TIMESTAMP(), 0, 0, {$ItemID}, 0)"; + } + doquery("INSERT INTO {{table}} VALUES ".implode(', ', $_Vars_TasksDataUpdate['free_premium_array']).";", 'premium_free'); + } + if(!empty($_Vars_TasksDataUpdate['user'])) + { + foreach($_Vars_TasksDataUpdate['user'] as $Key => $Value2Add) + { + $_Vars_TasksDataUpdate['user_var'][] = "`{$Key}` = `{$Key}` + {$Value2Add}"; + $_User[$Key] += $Value2Add; + } + } + + $_Vars_TasksDataUpdate['user_var'][] = "`tasks_done` = '{$_User['tasks_done']}'"; + doquery("UPDATE {{table}} SET ".implode(',', $_Vars_TasksDataUpdate['user_var'])." WHERE `id` = {$_User['id']};", 'users'); + } + } + } + // --- Handling Tasks ends here --- + + if(!isset($_AllowInVacationMode) || $_AllowInVacationMode != true) + { + // If this place do not allow User to be in VacationMode, show him a message if it's necessary + if(isOnVacation()) + { + $MinimalVacationTime = ($_User['pro_time'] > $_User['vacation_starttime'] ? MINURLOP_PRO : MINURLOP_FREE) + $_User['vacation_starttime']; + $VacationMessage = sprintf($_Lang['VacationTill'], date('d.m.Y H:i:s', $MinimalVacationTime)); + if($MinimalVacationTime <= $Common_TimeNow) + { + $VacationMessage .= $_Lang['VacationSetOff']; + } + message($VacationMessage, $_Lang['Vacation']); + } + } + + if(!isset($_UseMinimalCommon) || $_UseMinimalCommon !== true) + { + // Change Planet (if user wants to do this) + SetSelectedPlanet($_User); + + // Get PlanetRow + $_Planet = doquery("SELECT * FROM {{table}} WHERE `id` = {$_User['current_planet']};", 'planets', true); + if($_Planet['id'] <= 0 OR $_Planet['id_owner'] != $_User['id']) + { + // If this planet doesn't exist, try to go back to MotherPlanet + SetSelectedPlanet($_User, $_User['id_planet']); + $_Planet = doquery("SELECT * FROM {{table}} WHERE `id` = {$_User['id_planet']};", 'planets', true); + if($_Planet['id'] <= 0) + { + // If MotherPlanet doesn't exist, ThrowError and don't allow go further + message($_Lang['FatalError_PlanetRowEmpty'], 'FatalError'); + } + } + CheckPlanetUsedFields($_Planet); + + if($_Planet['planet_type'] == 1) + { + $GalaxyRowWhere = "`id_planet` = {$_Planet['id']}"; + } + else + { + $GalaxyRowWhere = "`id_moon` = {$_Planet['id']}"; + } + $_GalaxyRow = doquery("SELECT * FROM {{table}} WHERE {$GalaxyRowWhere};", 'galaxy', true); + + if(!isset($_BlockFleetHandler) || $_BlockFleetHandler !== true) + { + $FleetHandlerReturn = FlyingFleetHandler($_Planet); + if(isset($FleetHandlerReturn['ThisMoonDestroyed']) && $FleetHandlerReturn['ThisMoonDestroyed']) + { + // Redirect User to Planet (from Destroyed Moon) + SetSelectedPlanet($_User, $_User['id_planet']); + $_Planet = doquery("SELECT * FROM {{table}} WHERE `id` = {$_User['id_planet']};", 'planets', true); + if($_Planet['id'] <= 0) + { + message($_Lang['FatalError_PlanetRowEmpty'], 'FatalError'); + } + else + { + if($_GalaxyRow['id_planet'] != $_Planet['id']) + { + $_GalaxyRow = doquery("SELECT * FROM {{table}} WHERE `id_planet` = {$_Planet['id']};", 'galaxy', true); + } + } + } + } + + if(!isset($_DontForceRulesAcceptance) || $_DontForceRulesAcceptance !== true) + { + if($_GameConfig['enforceRulesAcceptance'] == '1' AND $_GameConfig['last_rules_changes'] > 0 AND $_User['rules_accept_stamp'] < $_GameConfig['last_rules_changes']) + { + if(isset($_DontShowRulesBox) && $_DontShowRulesBox === true) + { + message($_Lang['RulesAcceptBox_CantUseFunction'], $_Lang['SystemInfo']); + } + else + { + if(IN_RULES !== true) + { + header('Location: rules.php'); + safeDie(); + } + else + { + $_ForceRulesAcceptBox = true; + } + } + } + } + + if(!isset($_DontCheckPolls) || $_DontCheckPolls !== true) + { + if($_User['isAI'] != 1 AND $_User['register_time'] < ($Common_TimeNow - TIME_DAY)) + { + $Query_SelectPolls = ''; + $Query_SelectPolls .= "SELECT `votes`.`id` AS `vote_id` FROM {{table}} AS `polls` "; + $Query_SelectPolls .= "LEFT JOIN `{{prefix}}poll_votes` AS `votes` ON `votes`.`poll_id` = `polls`.`id` AND `votes`.`user_id` = {$_User['id']} "; + $Query_SelectPolls .= "WHERE `polls`.`open` = 1 AND `polls`.`obligatory` = 1;"; + $SelectObligatoryPolls = doquery($Query_SelectPolls, 'polls'); + if(mysql_num_rows($SelectObligatoryPolls) > 0) + { + $PollsCount = 0; + while($SelectObligatoryPollsData = mysql_fetch_assoc($SelectObligatoryPolls)) + { + if($SelectObligatoryPollsData['vote_id'] <= 0) + { + $PollsCount += 1; + } + } + if($PollsCount > 0) + { + message(sprintf($_Lang['YouHaveToVoteInSurveys'], $PollsCount), $_Lang['SystemInfo'], 'polls.php', 10); + } + } + } + } + } +} +else +{ + $_DontShowMenus = true; +} + +if(!empty($_BenchTool)){ $_BenchTool->simpleCountStop(); } + +?> diff --git a/config.localhost.php b/config.localhost.php index e9892945c..294d43864 100644 --- a/config.localhost.php +++ b/config.localhost.php @@ -1,4 +1,4 @@ \ No newline at end of file +?> diff --git a/config.php b/config.php index 071f563d4..033442d76 100644 --- a/config.php +++ b/config.php @@ -1,4 +1,12 @@ - \ No newline at end of file + 'mysql', + 'user' => 'root', + 'pass' => '123456', + 'name' => 'uniengine', + 'prefix' => 'uni3_', + 'secretword' => 'SzkzxlxJd3r9h4Xb8MNm' +); +?> diff --git a/config.testserver.php b/config.testserver.php index 55719125a..d2a38d07c 100644 --- a/config.testserver.php +++ b/config.testserver.php @@ -1,4 +1,4 @@ \ No newline at end of file +?> diff --git a/contact.php b/contact.php index c8323bd36..5c2e07715 100644 --- a/contact.php +++ b/contact.php @@ -1,42 +1,42 @@ - 0 ORDER BY `authlevel` DESC;"; - $GetData = doquery($QrySelectUser, 'users'); - - while($DataRow = mysql_fetch_assoc($GetData)) - { - $Row['Username'] = $DataRow['username']; - $Row['Authlabel'] = $_Lang['user_level'][GetAuthLabel($DataRow)]; - $Row['Email'] = $DataRow['email']; - $parse['InsertRows'] .= parsetemplate($RowsTPL, $Row); - } - - $page = parsetemplate($BodyTPL, $parse); - - display($page, $_Lang['Title'], false); - -?> \ No newline at end of file + 0 ORDER BY `authlevel` DESC;"; +$GetData = doquery($QrySelectUser, 'users'); + +while($DataRow = mysql_fetch_assoc($GetData)) +{ + $Row['Username'] = $DataRow['username']; + $Row['Authlabel'] = $_Lang['user_level'][GetAuthLabel($DataRow)]; + $Row['Email'] = $DataRow['email']; + $parse['InsertRows'] .= parsetemplate($RowsTPL, $Row); +} + +$page = parsetemplate($BodyTPL, $parse); + +display($page, $_Lang['Title'], false); + +?> diff --git a/converter.php b/converter.php index 35e206bdb..8e30cf231 100644 --- a/converter.php +++ b/converter.php @@ -1,58 +1,58 @@ - 0) - { - $Report = doquery("SELECT * FROM {{table}} WHERE `ID` = {$ReportID};", 'battle_reports', true); - if($Report) - { - $Owners = array_merge(explode(',', $Report['id_owner1']), explode(',', $Report['id_owner2'])); - if(in_array($_User['id'], $Owners)) - { - includeLang('converter'); - include_once($_EnginePath.'includes/functions/ConvertBattleReport.php'); - $_Lang['Title'] = $_Lang['BattleConverter_title']; - - $Settings = array - ( - 'colorTheme' => (isset($_POST['colorTheme']) && $_POST['colorTheme'] == '2' ? 2 : 1), - 'colorArray' => null - ); - $Settings['colorArray'] = $_Lang['Conv_Colors'][$Settings['colorTheme']]; - $_Lang['Set_ColorTheme_'.$Settings['colorTheme'].'_Check'] = 'selected'; - - $_Lang['ReportCode'] = ConvertBattleReport($Report, $Settings); - $Page = parsetemplate(gettemplate('converter'), $_Lang); - } - else - { - message("{$_Lang['BattleReportConverter_CannotConvert']}", $Title); - } - } - else - { - message("{$_Lang['BattleReport_DoesntExist']}", $Title); - } - } - else - { - message("{$_Lang['BattleReport_NoIDGiven']}", $Title); - } - - display($Page, $_Lang['BattleConverter_title'], false); - -?> \ No newline at end of file + 0) +{ + $Report = doquery("SELECT * FROM {{table}} WHERE `ID` = {$ReportID};", 'battle_reports', true); + if($Report) + { + $Owners = array_merge(explode(',', $Report['id_owner1']), explode(',', $Report['id_owner2'])); + if(in_array($_User['id'], $Owners)) + { + includeLang('converter'); + include_once($_EnginePath.'includes/functions/ConvertBattleReport.php'); + $_Lang['Title'] = $_Lang['BattleConverter_title']; + + $Settings = array + ( + 'colorTheme' => (isset($_POST['colorTheme']) && $_POST['colorTheme'] == '2' ? 2 : 1), + 'colorArray' => null + ); + $Settings['colorArray'] = $_Lang['Conv_Colors'][$Settings['colorTheme']]; + $_Lang['Set_ColorTheme_'.$Settings['colorTheme'].'_Check'] = 'selected'; + + $_Lang['ReportCode'] = ConvertBattleReport($Report, $Settings); + $Page = parsetemplate(gettemplate('converter'), $_Lang); + } + else + { + message("{$_Lang['BattleReportConverter_CannotConvert']}", $Title); + } + } + else + { + message("{$_Lang['BattleReport_DoesntExist']}", $Title); + } +} +else +{ + message("{$_Lang['BattleReport_NoIDGiven']}", $Title); +} + +display($Page, $_Lang['BattleConverter_title'], false); + +?> diff --git a/css/admin/index.php b/css/admin/index.php index 58f7bb163..bc99142d1 100644 --- a/css/admin/index.php +++ b/css/admin/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file +?> diff --git a/css/index.php b/css/index.php index 58f7bb163..bc99142d1 100644 --- a/css/index.php +++ b/css/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file +?> diff --git a/declaration.php b/declaration.php index cfe4be588..2c14db80c 100644 --- a/declaration.php +++ b/declaration.php @@ -1,302 +1,302 @@ - 0) - { - $IsInValidationProcess = doquery("SELECT `users`, `status` FROM {{table}} WHERE `id` = '{$_User['multiIP_DeclarationID']}' AND `status` != -2 LIMIT 1;", 'declarations'); - if(mysql_num_rows($IsInValidationProcess) != 0) - { - $Validating = true; - $IsInValidationProcess = mysql_fetch_assoc($IsInValidationProcess); - $ExplodeUsers = explode(',', $IsInValidationProcess['users']); - - $DeclarationOwner = false; - foreach($ExplodeUsers as $UserID) - { - $UserID = str_replace('|', '', $UserID); - if($UserID > 0) - { - $DeclarationUsers[] = $UserID; - if($DeclarationOwner === false) - { - $DeclarationOwner = $UserID; - } - } - } - if($DeclarationOwner == $_User['id']) - { - $IsDeclarationOwner = true; - } - else - { - $IsDeclarationOwner = false; - $GetUsername = doquery("SELECT `username` FROM {{table}} WHERE `id` = '{$DeclarationOwner}' LIMIT 1;", 'users', true); - $GetUsername = $GetUsername['username']; - } - } - } - - $parse['ShowError'] = 'display: none;'; - - if(isset($_GET['cmd']) && $_GET['cmd'] == 'rmv') - { - if($Validating === true AND ($IsInValidationProcess['status'] == 0 OR $IsInValidationProcess['status'] == 1)) - { - if($IsDeclarationOwner === true) - { - doquery("UPDATE {{table}} SET `multi_validated` = 0 WHERE `id` IN (".implode(', ', $DeclarationUsers).");", 'users'); - doquery("UPDATE {{table}} SET `status` = -2 WHERE `id` = {$_User['multiIP_DeclarationID']};", 'declarations'); - $parse['ShowError'] = ''; - $parse['ErrorText'] = $_Lang['Msg_DeclarationRemoved']; - $parse['ErrorColor'] = 'lime'; - - $SendDeleteMessage = true; - foreach($DeclarationUsers as $UserID) - { - if($UserID != $_User['id']) - { - $SendDeleteMessageUsers[] = $UserID; - } - } - } - else - { - foreach($DeclarationUsers as $UserID) - { - if($UserID != $_User['id']) - { - $NewArray[] = "|{$UserID}|"; - } - } - if(count($NewArray) <= 1) - { - doquery("UPDATE {{table}} SET `multi_validated` = 0 WHERE `id` IN (".implode(', ', $DeclarationUsers).");", 'users'); - doquery("UPDATE {{table}} SET `status` = -2 WHERE `id` = {$_User['multiIP_DeclarationID']};", 'declarations'); - - $SendDeleteMessage = true; - foreach($DeclarationUsers as $UserID) - { - if($UserID != $_User['id']) - { - $SendDeleteMessageUsers[] = $UserID; - } - } - } - else - { - doquery("UPDATE {{table}} SET `users` = '".implode(',', $NewArray)."' WHERE `id` = {$_User['multiIP_DeclarationID']};", 'declarations'); - doquery("UPDATE {{table}} SET `multi_validated` = 0, `multiIP_DeclarationID` = 0 WHERE `id` = {$_User['id']};", 'users'); - } - $parse['ShowError'] = ''; - $parse['ErrorText'] = $_Lang['Msg_DeclarationLeft']; - $parse['ErrorColor'] = 'lime'; - } - $Validating = false; - $IsInValidationProcess = array(); - - if($SendDeleteMessage === true) - { - $Message = false; - $Message['msg_id'] = '079'; - $Message['args'] = array(); - $Message = json_encode($Message); - Cache_Message($SendDeleteMessageUsers, 0, time(), 70, '007', '020', $Message); - } - } - } - - if(isset($_POST['mode']) && $_POST['mode'] == 'addit') - { - if($_User['multi_validated'] !== 1) - { - if($Validating === false || (isset($IsInValidationProcess['status']) && $IsInValidationProcess['status'] == -1)) - { - if(empty($_POST['userslist'])) - { - message($_Lang['Error_Empty_Userlist'], $_Lang['Title'], 'declaration.php', 3); - } - if(!isset($_POST['declaration_type']) || $_POST['declaration_type'] <= 0) - { - message($_Lang['Error_Type_NotSelected'], $_Lang['Title'], 'declaration.php', 3); - } - $DeclarationType = intval($_POST['declaration_type']); - if($DeclarationType > 5) - { - message($_Lang['Error_Bad_DeclarationType'], $_Lang['Title'], 'declaration.php', 3); - } - - $UserList = explode(',', $_POST['userslist']); - if((array)$UserList !== $UserList) - { - message($_Lang['Error_BadUserlist_Sent'], $_Lang['Title'], 'declaration.php', 3); - } - - $BadUsernames = array(); - $SearchUsers = array(); - foreach($UserList as $ThisUser) - { - $ThisUser = strtolower(trim($ThisUser)); - if($ThisUser == strtolower($_User['username'])) - { - $FoundOwn = true; - continue; - } - if(!preg_match(REGEXP_USERNAME_ABSOLUTE, $ThisUser)) - { - if(!in_array($ThisUser, $BadUsernames)) - { - $BadUsernames[] = $ThisUser; - } - } - else - { - if(!in_array($ThisUser, $SearchUsers)) - { - $BadUsernames[] = $ThisUser; - $SearchUsers[] = "'{$ThisUser}'"; - } - } - } - - if(!empty($SearchUsers)) - { - $DoSearch = doquery("SELECT `user`.`id`, `user`.`username` FROM {{table}} AS `user` LEFT JOIN {{prefix}}declarations AS `decl` ON `decl`.`id` = `user`.`multiIP_DeclarationID` WHERE `user`.`username` IN (".implode(', ', $SearchUsers).") AND (`user`.`multiIP_DeclarationID` = 0 OR `decl`.`status` = -2 OR `decl`.`status` = -1);", 'users'); - while($Result = mysql_fetch_assoc($DoSearch)) - { - $FoundUsers[] = "|{$Result['id']}|"; - $SearchNDestroy = array_search(strtolower($Result['username']), $BadUsernames); - if((int)$SearchNDestroy === $SearchNDestroy) - { - unset($BadUsernames[$SearchNDestroy]); - } - else - { - foreach($SearchNDestroy as $Value) - { - unset($BadUsernames[$Value]); - } - } - } - } - - if(!empty($BadUsernames)) - { - $parse['ShowBadUsers'] = implode(', ', $BadUsernames); - $parse['ShowError'] = ''; - $parse['ErrorText'] = sprintf($_Lang['Error_BadUsernames'], $parse['ShowBadUsers']); - $parse['ErrorColor'] = 'red'; - } - else - { - if(!empty($FoundUsers)) - { - $QryCreateDeclaration = "INSERT INTO {{table}} SET `users` = '|{$_User['id']}|,".implode(',', $FoundUsers)."', `all_present_users` = `users`, `time` = UNIX_TIMESTAMP(), `reason` = '{$DeclarationType}';"; - doquery($QryCreateDeclaration, 'declarations'); - foreach($FoundUsers as &$UserID) - { - $UserID =str_replace('|', '', $UserID); - } - doquery("UPDATE {{table}} SET `multi_validated` = 0, `multiIP_DeclarationID` = LAST_INSERT_ID() WHERE `id` IN ({$_User['id']}, ".implode(',', $FoundUsers).");", 'users'); - message($_Lang['Declaration_added'], $_Lang['Title']); - } - else - { - if($FoundOwn) - { - message($_Lang['Error_OnlyUFound'], $_Lang['Title'], 'declaration.php', 3); - } - else - { - message($_Lang['Error_UsersNotFound'], $_Lang['Title'], 'declaration.php', 3); - } - } - } - } - else - { - if($IsDeclarationOwner === false) - { - $Message = $_Lang['Cannot_add_second_declare_other']; - } - else - { - $Message = $_Lang['Cannot_add_second_declare']; - } - message($Message, $_Lang['Title']); - } - } - else - { - message($_Lang['Multi_validated'], $_Lang['Title'], 'declaration.php', 3); - } - } - - if($Validating === false || $IsInValidationProcess['status'] == -1) - { - if(isset($IsInValidationProcess['status']) && $IsInValidationProcess['status'] == -1 && empty($BadUsernames)) - { - $parse['ShowError'] = ''; - if($IsDeclarationOwner === false) - { - $parse['ErrorText'] = $_Lang['Error_DeclarationRejected_other']; - } - else - { - $parse['ErrorText'] = $_Lang['Error_DeclarationRejected']; - } - $parse['ErrorColor'] = 'orange'; - } - - $parse['InsertUserslist'] = (isset($_POST['userslist']) ? $_POST['userslist'] : null); - if(isset($_POST['declaration_type'])) - { - $parse['InsertType_'.$_POST['declaration_type']] = 'checked'; - } - - $Page = parsetemplate($PageTpl, $parse); - } - else - { - if($IsInValidationProcess['status'] == 1) - { - // Validation Done - if($IsDeclarationOwner === true) - { - $Message = $_Lang['Multi_validated']; - } - else - { - $Message = sprintf($_Lang['Multi_validated_other'], $GetUsername); - } - message($Message, $_Lang['Title']); - } - else if($IsInValidationProcess['status'] == 0) - { - // Validation Awaiting - if($IsDeclarationOwner === true) - { - $Message = $_Lang['Declaration_awaiting']; - } - else - { - $Message = sprintf($_Lang['Declaration_awaiting_other'], $GetUsername); - } - message($Message, $_Lang['Title']); - } - } - - display($Page, $_Lang['Title'], false); - -?> \ No newline at end of file + 0) +{ + $IsInValidationProcess = doquery("SELECT `users`, `status` FROM {{table}} WHERE `id` = '{$_User['multiIP_DeclarationID']}' AND `status` != -2 LIMIT 1;", 'declarations'); + if(mysql_num_rows($IsInValidationProcess) != 0) + { + $Validating = true; + $IsInValidationProcess = mysql_fetch_assoc($IsInValidationProcess); + $ExplodeUsers = explode(',', $IsInValidationProcess['users']); + + $DeclarationOwner = false; + foreach($ExplodeUsers as $UserID) + { + $UserID = str_replace('|', '', $UserID); + if($UserID > 0) + { + $DeclarationUsers[] = $UserID; + if($DeclarationOwner === false) + { + $DeclarationOwner = $UserID; + } + } + } + if($DeclarationOwner == $_User['id']) + { + $IsDeclarationOwner = true; + } + else + { + $IsDeclarationOwner = false; + $GetUsername = doquery("SELECT `username` FROM {{table}} WHERE `id` = '{$DeclarationOwner}' LIMIT 1;", 'users', true); + $GetUsername = $GetUsername['username']; + } + } +} + +$parse['ShowError'] = 'display: none;'; + +if(isset($_GET['cmd']) && $_GET['cmd'] == 'rmv') +{ + if($Validating === true AND ($IsInValidationProcess['status'] == 0 OR $IsInValidationProcess['status'] == 1)) + { + if($IsDeclarationOwner === true) + { + doquery("UPDATE {{table}} SET `multi_validated` = 0 WHERE `id` IN (".implode(', ', $DeclarationUsers).");", 'users'); + doquery("UPDATE {{table}} SET `status` = -2 WHERE `id` = {$_User['multiIP_DeclarationID']};", 'declarations'); + $parse['ShowError'] = ''; + $parse['ErrorText'] = $_Lang['Msg_DeclarationRemoved']; + $parse['ErrorColor'] = 'lime'; + + $SendDeleteMessage = true; + foreach($DeclarationUsers as $UserID) + { + if($UserID != $_User['id']) + { + $SendDeleteMessageUsers[] = $UserID; + } + } + } + else + { + foreach($DeclarationUsers as $UserID) + { + if($UserID != $_User['id']) + { + $NewArray[] = "|{$UserID}|"; + } + } + if(count($NewArray) <= 1) + { + doquery("UPDATE {{table}} SET `multi_validated` = 0 WHERE `id` IN (".implode(', ', $DeclarationUsers).");", 'users'); + doquery("UPDATE {{table}} SET `status` = -2 WHERE `id` = {$_User['multiIP_DeclarationID']};", 'declarations'); + + $SendDeleteMessage = true; + foreach($DeclarationUsers as $UserID) + { + if($UserID != $_User['id']) + { + $SendDeleteMessageUsers[] = $UserID; + } + } + } + else + { + doquery("UPDATE {{table}} SET `users` = '".implode(',', $NewArray)."' WHERE `id` = {$_User['multiIP_DeclarationID']};", 'declarations'); + doquery("UPDATE {{table}} SET `multi_validated` = 0, `multiIP_DeclarationID` = 0 WHERE `id` = {$_User['id']};", 'users'); + } + $parse['ShowError'] = ''; + $parse['ErrorText'] = $_Lang['Msg_DeclarationLeft']; + $parse['ErrorColor'] = 'lime'; + } + $Validating = false; + $IsInValidationProcess = array(); + + if($SendDeleteMessage === true) + { + $Message = false; + $Message['msg_id'] = '079'; + $Message['args'] = array(); + $Message = json_encode($Message); + Cache_Message($SendDeleteMessageUsers, 0, time(), 70, '007', '020', $Message); + } + } +} + +if(isset($_POST['mode']) && $_POST['mode'] == 'addit') +{ + if($_User['multi_validated'] !== 1) + { + if($Validating === false || (isset($IsInValidationProcess['status']) && $IsInValidationProcess['status'] == -1)) + { + if(empty($_POST['userslist'])) + { + message($_Lang['Error_Empty_Userlist'], $_Lang['Title'], 'declaration.php', 3); + } + if(!isset($_POST['declaration_type']) || $_POST['declaration_type'] <= 0) + { + message($_Lang['Error_Type_NotSelected'], $_Lang['Title'], 'declaration.php', 3); + } + $DeclarationType = intval($_POST['declaration_type']); + if($DeclarationType > 5) + { + message($_Lang['Error_Bad_DeclarationType'], $_Lang['Title'], 'declaration.php', 3); + } + + $UserList = explode(',', $_POST['userslist']); + if((array)$UserList !== $UserList) + { + message($_Lang['Error_BadUserlist_Sent'], $_Lang['Title'], 'declaration.php', 3); + } + + $BadUsernames = array(); + $SearchUsers = array(); + foreach($UserList as $ThisUser) + { + $ThisUser = strtolower(trim($ThisUser)); + if($ThisUser == strtolower($_User['username'])) + { + $FoundOwn = true; + continue; + } + if(!preg_match(REGEXP_USERNAME_ABSOLUTE, $ThisUser)) + { + if(!in_array($ThisUser, $BadUsernames)) + { + $BadUsernames[] = $ThisUser; + } + } + else + { + if(!in_array($ThisUser, $SearchUsers)) + { + $BadUsernames[] = $ThisUser; + $SearchUsers[] = "'{$ThisUser}'"; + } + } + } + + if(!empty($SearchUsers)) + { + $DoSearch = doquery("SELECT `user`.`id`, `user`.`username` FROM {{table}} AS `user` LEFT JOIN {{prefix}}declarations AS `decl` ON `decl`.`id` = `user`.`multiIP_DeclarationID` WHERE `user`.`username` IN (".implode(', ', $SearchUsers).") AND (`user`.`multiIP_DeclarationID` = 0 OR `decl`.`status` = -2 OR `decl`.`status` = -1);", 'users'); + while($Result = mysql_fetch_assoc($DoSearch)) + { + $FoundUsers[] = "|{$Result['id']}|"; + $SearchNDestroy = array_search(strtolower($Result['username']), $BadUsernames); + if((int)$SearchNDestroy === $SearchNDestroy) + { + unset($BadUsernames[$SearchNDestroy]); + } + else + { + foreach($SearchNDestroy as $Value) + { + unset($BadUsernames[$Value]); + } + } + } + } + + if(!empty($BadUsernames)) + { + $parse['ShowBadUsers'] = implode(', ', $BadUsernames); + $parse['ShowError'] = ''; + $parse['ErrorText'] = sprintf($_Lang['Error_BadUsernames'], $parse['ShowBadUsers']); + $parse['ErrorColor'] = 'red'; + } + else + { + if(!empty($FoundUsers)) + { + $QryCreateDeclaration = "INSERT INTO {{table}} SET `users` = '|{$_User['id']}|,".implode(',', $FoundUsers)."', `all_present_users` = `users`, `time` = UNIX_TIMESTAMP(), `reason` = '{$DeclarationType}';"; + doquery($QryCreateDeclaration, 'declarations'); + foreach($FoundUsers as &$UserID) + { + $UserID =str_replace('|', '', $UserID); + } + doquery("UPDATE {{table}} SET `multi_validated` = 0, `multiIP_DeclarationID` = LAST_INSERT_ID() WHERE `id` IN ({$_User['id']}, ".implode(',', $FoundUsers).");", 'users'); + message($_Lang['Declaration_added'], $_Lang['Title']); + } + else + { + if($FoundOwn) + { + message($_Lang['Error_OnlyUFound'], $_Lang['Title'], 'declaration.php', 3); + } + else + { + message($_Lang['Error_UsersNotFound'], $_Lang['Title'], 'declaration.php', 3); + } + } + } + } + else + { + if($IsDeclarationOwner === false) + { + $Message = $_Lang['Cannot_add_second_declare_other']; + } + else + { + $Message = $_Lang['Cannot_add_second_declare']; + } + message($Message, $_Lang['Title']); + } + } + else + { + message($_Lang['Multi_validated'], $_Lang['Title'], 'declaration.php', 3); + } +} + +if($Validating === false || $IsInValidationProcess['status'] == -1) +{ + if(isset($IsInValidationProcess['status']) && $IsInValidationProcess['status'] == -1 && empty($BadUsernames)) + { + $parse['ShowError'] = ''; + if($IsDeclarationOwner === false) + { + $parse['ErrorText'] = $_Lang['Error_DeclarationRejected_other']; + } + else + { + $parse['ErrorText'] = $_Lang['Error_DeclarationRejected']; + } + $parse['ErrorColor'] = 'orange'; + } + + $parse['InsertUserslist'] = (isset($_POST['userslist']) ? $_POST['userslist'] : null); + if(isset($_POST['declaration_type'])) + { + $parse['InsertType_'.$_POST['declaration_type']] = 'checked'; + } + + $Page = parsetemplate($PageTpl, $parse); +} +else +{ + if($IsInValidationProcess['status'] == 1) + { + // Validation Done + if($IsDeclarationOwner === true) + { + $Message = $_Lang['Multi_validated']; + } + else + { + $Message = sprintf($_Lang['Multi_validated_other'], $GetUsername); + } + message($Message, $_Lang['Title']); + } + else if($IsInValidationProcess['status'] == 0) + { + // Validation Awaiting + if($IsDeclarationOwner === true) + { + $Message = $_Lang['Declaration_awaiting']; + } + else + { + $Message = sprintf($_Lang['Declaration_awaiting_other'], $GetUsername); + } + message($Message, $_Lang['Title']); + } +} + +display($Page, $_Lang['Title'], false); + +?> diff --git a/destroy_rockets.php b/destroy_rockets.php index 1b8f5a52a..b122a6ad0 100644 --- a/destroy_rockets.php +++ b/destroy_rockets.php @@ -1,69 +1,69 @@ - $_Planet['antiballistic_missile']) - { - $destroy[502] = $_Planet['antiballistic_missile']; - } - if($destroy[503] > $_Planet['interplanetary_missile']) - { - $destroy[503] = $_Planet['interplanetary_missile']; - } - - if($destroy[502] == 0 && $destroy[503] == 0) - { - message($_Lang['NothingDestroyed'], $_Lang['Title'], 'infos.php?gid=44', 3); - } - - $_Planet[$_Vars_GameElements[502]] -= $destroy[502]; - $_Planet[$_Vars_GameElements[503]] -= $destroy[503]; - if($destroy[502] > 0) - { - $CreateLogArray[] = '502,'.$destroy[502]; - } - if($destroy[503] > 0) - { - $CreateLogArray[] = '503,'.$destroy[503]; - } - - $UserDev_Log[] = array('PlanetID' => $_User['current_planet'], 'Date' => time(), 'Place' => 28, 'Code' => '0', 'ElementID' => '0', 'AdditionalData' => implode(';', $CreateLogArray)); - - $Query_DeleteMissiles = ''; - $Query_DeleteMissiles .= "UPDATE {{table}} SET "; - $Query_DeleteMissiles .= "`antiballistic_missile` = `antiballistic_missile` - {$destroy[502]}, "; - $Query_DeleteMissiles .= "`interplanetary_missile` = `interplanetary_missile` - {$destroy[503]} "; - $Query_DeleteMissiles .= "WHERE `id` = {$_User['current_planet']} LIMIT 1;"; - doquery($Query_DeleteMissiles, 'planets'); - - message( - sprintf - ( - $_Lang['RocketsDestroyed'], - prettyNumber($destroy[502]), prettyNumber($destroy[503]), $_Planet['name'], - $_Planet['galaxy'], $_Planet['system'], $_Planet['planet'] - ), - $_Lang['Title'], 'infos.php?gid=44', 3 - ); - -?> \ No newline at end of file + $_Planet['antiballistic_missile']) +{ + $destroy[502] = $_Planet['antiballistic_missile']; +} +if($destroy[503] > $_Planet['interplanetary_missile']) +{ + $destroy[503] = $_Planet['interplanetary_missile']; +} + +if($destroy[502] == 0 && $destroy[503] == 0) +{ + message($_Lang['NothingDestroyed'], $_Lang['Title'], 'infos.php?gid=44', 3); +} + +$_Planet[$_Vars_GameElements[502]] -= $destroy[502]; +$_Planet[$_Vars_GameElements[503]] -= $destroy[503]; +if($destroy[502] > 0) +{ + $CreateLogArray[] = '502,'.$destroy[502]; +} +if($destroy[503] > 0) +{ + $CreateLogArray[] = '503,'.$destroy[503]; +} + +$UserDev_Log[] = array('PlanetID' => $_User['current_planet'], 'Date' => time(), 'Place' => 28, 'Code' => '0', 'ElementID' => '0', 'AdditionalData' => implode(';', $CreateLogArray)); + +$Query_DeleteMissiles = ''; +$Query_DeleteMissiles .= "UPDATE {{table}} SET "; +$Query_DeleteMissiles .= "`antiballistic_missile` = `antiballistic_missile` - {$destroy[502]}, "; +$Query_DeleteMissiles .= "`interplanetary_missile` = `interplanetary_missile` - {$destroy[503]} "; +$Query_DeleteMissiles .= "WHERE `id` = {$_User['current_planet']} LIMIT 1;"; +doquery($Query_DeleteMissiles, 'planets'); + +message( + sprintf + ( + $_Lang['RocketsDestroyed'], + prettyNumber($destroy[502]), prettyNumber($destroy[503]), $_Planet['name'], + $_Planet['galaxy'], $_Planet['system'], $_Planet['planet'] + ), + $_Lang['Title'], 'infos.php?gid=44', 3 +); + +?> diff --git a/disassembler.php b/disassembler.php index c8dac0cfb..6dbe99c1d 100644 --- a/disassembler.php +++ b/disassembler.php @@ -1,223 +1,223 @@ - $Count) - { - $ID = intval($ID); - $Count = floor(floatval(str_replace('.', '', $Count))); - if($Count > 0) - { - $SomethinkAdded = true; - if(in_array($ID, $_Vars_ElementCategories['fleet']) OR in_array($ID, $_Vars_ElementCategories['defense'])) - { - if($CurrentPlanet[$_Vars_GameElements[$ID]] > 0) - { - if($CurrentPlanet[$_Vars_GameElements[$ID]] < $Count) - { - $Count = $CurrentPlanet[$_Vars_GameElements[$ID]]; - } - $Disassemble[$ID] = $Count; - } - } - } - } - } - - if($SomethinkAdded) - { - if(!empty($Disassemble)) - { - $AddMet = 0; - $AddCry = 0; - $AddDeu = 0; - foreach($Disassemble as $ID => $Count) - { - $AddMet += $_Vars_Prices[$ID]['metal'] * $Count * DISASSEMBLER_PERCENT; - $AddCry += $_Vars_Prices[$ID]['crystal'] * $Count * DISASSEMBLER_PERCENT; - $AddDeu += $_Vars_Prices[$ID]['deuterium'] * $Count * DISASSEMBLER_PERCENT; - $CurrentPlanet[$_Vars_GameElements[$ID]] -= $Count; - $PlanetUpdate[] = "`{$_Vars_GameElements[$ID]}` = `{$_Vars_GameElements[$ID]}` - {$Count}"; - - $DevLog_Array[] = "{$ID},{$Count}"; - } - - $CurrentPlanet['metal'] += $AddMet; - $CurrentPlanet['crystal'] += $AddCry; - $CurrentPlanet['deuterium'] += $AddDeu; - $QryPlanetUpdate = "UPDATE {{table}} SET "; - $QryPlanetUpdate .= implode(',', $PlanetUpdate); - $QryPlanetUpdate .= " WHERE `id` = {$CurrentPlanet['id']};"; - doquery($QryPlanetUpdate, 'planets'); - $UserDev_Log[] = array('PlanetID' => $CurrentPlanet['id'], 'Date' => time(), 'Place' => 24, 'Code' => '0', 'ElementID' => '0', 'AdditionalData' => 'P,'.(DISASSEMBLER_PERCENT * 100).';'.implode(';', $DevLog_Array)); - - $Parse['Create_DisassembleResult'] = sprintf($_Lang['Disassembler_Sold_units'], prettyNumber($AddMet), prettyNumber($AddCry), prettyNumber($AddDeu)); - $Parse['Create_DisassembleResult_Color'] = 'lime'; - } - else - { - $Parse['Create_DisassembleResult'] = sprintf($_Lang['Disassembler_NoUnits_on_that_planet'], (($CurrentPlanet['planet_type'] == 1) ? $_Lang['on_this_planet'] : $_Lang['on_this_moon'])); - $Parse['Create_DisassembleResult_Color'] = 'red'; - } - } - else - { - $Parse['Create_DisassembleResult_Color'] = 'orange'; - $Parse['Create_DisassembleResult'] = $_Lang['Disassembler_Nothink_in_post']; - } - } - - if(empty($Parse['Create_DisassembleResult'])) - { - $Parse['HideDisassembleResult'] = 'hide'; - } - - // Generate ElementsList - $TPL['list_element'] = gettemplate('buildings_compact_list_element_shipyard'); - $TPL['list_hidden'] = gettemplate('buildings_compact_list_hidden'); - $TPL['list_row'] = gettemplate('buildings_compact_list_row'); - $TPL['list_breakrow'] = gettemplate('buildings_compact_list_breakrow'); - $TPL['list_disabled'] = gettemplate('buildings_compact_list_disabled'); - $TPL['list_disabled'] = parsetemplate($TPL['list_disabled'], array('AddOpacity' => '')); - - $ElementParserDefault = array - ( - 'SkinPath' => $_SkinPath, - 'InfoBox_Count' => $_Lang['InfoBox_Count'], - 'InfoBox_Build' => $_Lang['InfoBox_DoResearch'], - ); - - $TabIndex = 1; - - $CombineReslist = array_merge($_Vars_ElementCategories['fleet'], $_Vars_ElementCategories['defense']); - foreach($CombineReslist as $ElementID) - { - if(in_array($ElementID, $_Vars_ElementCategories['fleet'])) - { - $Type = 'fleet'; - } - else - { - $Type = 'defense'; - } - $ElementParser = $ElementParserDefault; - - $BlockZeroCount = ($CurrentPlanet[$_Vars_GameElements[$ElementID]] > 0 ? false : true); - - $ElementParser['ElementCount'] = prettyNumber($CurrentPlanet[$_Vars_GameElements[$ElementID]]); - if(strlen($ElementParser['ElementCount']) > 10) - { - $ElementParser['IsBigNum'] = 'bignum'; - } - $ElementParser['ElementName'] = $_Lang['tech'][$ElementID]; - $ElementParser['ElementID'] = $ElementID; - - if(!$BlockZeroCount) - { - $ElementParser['ElementPrice'] = GetBuildingPrice($_User, $CurrentPlanet, $ElementID, true, false, true); - foreach($ElementParser['ElementPrice'] as $Key => $Value) - { - if($Value > 0) - { - $ElementPriceArray[$ElementID][$Key] = $Value * DISASSEMBLER_PERCENT; - } - } - } - - $BlockReason = array(); - if($BlockZeroCount) - { - $BlockReason[] = $_Lang['ListBox_Disallow_NoElements']; - } - if(!empty($BlockReason)) - { - $ElementParser['ElementDisabled'] = $TPL['list_disabled']; - $ElementParser['ElementDisableInv'] = 'inv'; - $ElementParser['ElementDisableReason'] = end($BlockReason); - } - else - { - $ElementParser['TabIndex'] = $TabIndex; - $TabIndex += 1; - } - - $StructuresList[$Type][] = parsetemplate($TPL['list_element'], $ElementParser); - } - - // Create List - foreach($StructuresList as $Type => $Rows) - { - $ThisRowIndex = 0; - $InRowCount = 0; - foreach($Rows as $ParsedData) - { - if($InRowCount == $ElementsPerRow) - { - $ParsedRows[$Type][($ThisRowIndex + 1)] = $TPL['list_breakrow']; - $ThisRowIndex += 2; - $InRowCount = 0; - } - - if(!isset($StructureRows[$Type][$ThisRowIndex]['Elements'])) - { - $StructureRows[$Type][$ThisRowIndex]['Elements'] = ''; - } - $StructureRows[$Type][$ThisRowIndex]['Elements'] .= $ParsedData; - $InRowCount += 1; - } - if($InRowCount < $ElementsPerRow) - { - $StructureRows[$Type][$ThisRowIndex]['Elements'] .= str_repeat($TPL['list_hidden'], ($ElementsPerRow - $InRowCount)); - } - foreach($StructureRows[$Type] as $Index => $Data) - { - $ParsedRows[$Type][$Index] = parsetemplate($TPL['list_row'], $Data); - } - ksort($ParsedRows[$Type], SORT_ASC); - } - - $Parse['Create_StructuresList_Ships'] = implode('', $ParsedRows['fleet']); - $Parse['Create_StructuresList_Defense'] = implode('', $ParsedRows['defense']); - $Parse['Create_InsertPrices'] = json_encode($ElementPriceArray); - $Parse['Create_DisassemblerPercent'] = sprintf($_Lang['Disassembler_ReturnTip'], (DISASSEMBLER_PERCENT * 100)); - if($_User['settings_useprettyinputbox'] == 1) - { - $Parse['P_AllowPrettyInputBox'] = 'true'; - } - else - { - $Parse['P_AllowPrettyInputBox'] = 'false'; - } - // End of - Parse all available ships - - $page = parsetemplate(gettemplate('disassembler_body'), $Parse); - - display($page, $_Lang['Disassembler_Title']); - -?> \ No newline at end of file + $Count) + { + $ID = intval($ID); + $Count = floor(floatval(str_replace('.', '', $Count))); + if($Count > 0) + { + $SomethinkAdded = true; + if(in_array($ID, $_Vars_ElementCategories['fleet']) OR in_array($ID, $_Vars_ElementCategories['defense'])) + { + if($CurrentPlanet[$_Vars_GameElements[$ID]] > 0) + { + if($CurrentPlanet[$_Vars_GameElements[$ID]] < $Count) + { + $Count = $CurrentPlanet[$_Vars_GameElements[$ID]]; + } + $Disassemble[$ID] = $Count; + } + } + } + } + } + + if($SomethinkAdded) + { + if(!empty($Disassemble)) + { + $AddMet = 0; + $AddCry = 0; + $AddDeu = 0; + foreach($Disassemble as $ID => $Count) + { + $AddMet += $_Vars_Prices[$ID]['metal'] * $Count * DISASSEMBLER_PERCENT; + $AddCry += $_Vars_Prices[$ID]['crystal'] * $Count * DISASSEMBLER_PERCENT; + $AddDeu += $_Vars_Prices[$ID]['deuterium'] * $Count * DISASSEMBLER_PERCENT; + $CurrentPlanet[$_Vars_GameElements[$ID]] -= $Count; + $PlanetUpdate[] = "`{$_Vars_GameElements[$ID]}` = `{$_Vars_GameElements[$ID]}` - {$Count}"; + + $DevLog_Array[] = "{$ID},{$Count}"; + } + + $CurrentPlanet['metal'] += $AddMet; + $CurrentPlanet['crystal'] += $AddCry; + $CurrentPlanet['deuterium'] += $AddDeu; + $QryPlanetUpdate = "UPDATE {{table}} SET "; + $QryPlanetUpdate .= implode(',', $PlanetUpdate); + $QryPlanetUpdate .= " WHERE `id` = {$CurrentPlanet['id']};"; + doquery($QryPlanetUpdate, 'planets'); + $UserDev_Log[] = array('PlanetID' => $CurrentPlanet['id'], 'Date' => time(), 'Place' => 24, 'Code' => '0', 'ElementID' => '0', 'AdditionalData' => 'P,'.(DISASSEMBLER_PERCENT * 100).';'.implode(';', $DevLog_Array)); + + $Parse['Create_DisassembleResult'] = sprintf($_Lang['Disassembler_Sold_units'], prettyNumber($AddMet), prettyNumber($AddCry), prettyNumber($AddDeu)); + $Parse['Create_DisassembleResult_Color'] = 'lime'; + } + else + { + $Parse['Create_DisassembleResult'] = sprintf($_Lang['Disassembler_NoUnits_on_that_planet'], (($CurrentPlanet['planet_type'] == 1) ? $_Lang['on_this_planet'] : $_Lang['on_this_moon'])); + $Parse['Create_DisassembleResult_Color'] = 'red'; + } + } + else + { + $Parse['Create_DisassembleResult_Color'] = 'orange'; + $Parse['Create_DisassembleResult'] = $_Lang['Disassembler_Nothink_in_post']; + } +} + +if(empty($Parse['Create_DisassembleResult'])) +{ + $Parse['HideDisassembleResult'] = 'hide'; +} + +// Generate ElementsList +$TPL['list_element'] = gettemplate('buildings_compact_list_element_shipyard'); +$TPL['list_hidden'] = gettemplate('buildings_compact_list_hidden'); +$TPL['list_row'] = gettemplate('buildings_compact_list_row'); +$TPL['list_breakrow'] = gettemplate('buildings_compact_list_breakrow'); +$TPL['list_disabled'] = gettemplate('buildings_compact_list_disabled'); +$TPL['list_disabled'] = parsetemplate($TPL['list_disabled'], array('AddOpacity' => '')); + +$ElementParserDefault = array +( + 'SkinPath' => $_SkinPath, + 'InfoBox_Count' => $_Lang['InfoBox_Count'], + 'InfoBox_Build' => $_Lang['InfoBox_DoResearch'], +); + +$TabIndex = 1; + +$CombineReslist = array_merge($_Vars_ElementCategories['fleet'], $_Vars_ElementCategories['defense']); +foreach($CombineReslist as $ElementID) +{ + if(in_array($ElementID, $_Vars_ElementCategories['fleet'])) + { + $Type = 'fleet'; + } + else + { + $Type = 'defense'; + } + $ElementParser = $ElementParserDefault; + + $BlockZeroCount = ($CurrentPlanet[$_Vars_GameElements[$ElementID]] > 0 ? false : true); + + $ElementParser['ElementCount'] = prettyNumber($CurrentPlanet[$_Vars_GameElements[$ElementID]]); + if(strlen($ElementParser['ElementCount']) > 10) + { + $ElementParser['IsBigNum'] = 'bignum'; + } + $ElementParser['ElementName'] = $_Lang['tech'][$ElementID]; + $ElementParser['ElementID'] = $ElementID; + + if(!$BlockZeroCount) + { + $ElementParser['ElementPrice'] = GetBuildingPrice($_User, $CurrentPlanet, $ElementID, true, false, true); + foreach($ElementParser['ElementPrice'] as $Key => $Value) + { + if($Value > 0) + { + $ElementPriceArray[$ElementID][$Key] = $Value * DISASSEMBLER_PERCENT; + } + } + } + + $BlockReason = array(); + if($BlockZeroCount) + { + $BlockReason[] = $_Lang['ListBox_Disallow_NoElements']; + } + if(!empty($BlockReason)) + { + $ElementParser['ElementDisabled'] = $TPL['list_disabled']; + $ElementParser['ElementDisableInv'] = 'inv'; + $ElementParser['ElementDisableReason'] = end($BlockReason); + } + else + { + $ElementParser['TabIndex'] = $TabIndex; + $TabIndex += 1; + } + + $StructuresList[$Type][] = parsetemplate($TPL['list_element'], $ElementParser); +} + +// Create List +foreach($StructuresList as $Type => $Rows) +{ + $ThisRowIndex = 0; + $InRowCount = 0; + foreach($Rows as $ParsedData) + { + if($InRowCount == $ElementsPerRow) + { + $ParsedRows[$Type][($ThisRowIndex + 1)] = $TPL['list_breakrow']; + $ThisRowIndex += 2; + $InRowCount = 0; + } + + if(!isset($StructureRows[$Type][$ThisRowIndex]['Elements'])) + { + $StructureRows[$Type][$ThisRowIndex]['Elements'] = ''; + } + $StructureRows[$Type][$ThisRowIndex]['Elements'] .= $ParsedData; + $InRowCount += 1; + } + if($InRowCount < $ElementsPerRow) + { + $StructureRows[$Type][$ThisRowIndex]['Elements'] .= str_repeat($TPL['list_hidden'], ($ElementsPerRow - $InRowCount)); + } + foreach($StructureRows[$Type] as $Index => $Data) + { + $ParsedRows[$Type][$Index] = parsetemplate($TPL['list_row'], $Data); + } + ksort($ParsedRows[$Type], SORT_ASC); +} + +$Parse['Create_StructuresList_Ships'] = implode('', $ParsedRows['fleet']); +$Parse['Create_StructuresList_Defense'] = implode('', $ParsedRows['defense']); +$Parse['Create_InsertPrices'] = json_encode($ElementPriceArray); +$Parse['Create_DisassemblerPercent'] = sprintf($_Lang['Disassembler_ReturnTip'], (DISASSEMBLER_PERCENT * 100)); +if($_User['settings_useprettyinputbox'] == 1) +{ + $Parse['P_AllowPrettyInputBox'] = 'true'; +} +else +{ + $Parse['P_AllowPrettyInputBox'] = 'false'; +} +// End of - Parse all available ships + +$page = parsetemplate(gettemplate('disassembler_body'), $Parse); + +display($page, $_Lang['Disassembler_Title']); + +?> diff --git a/email_change.php b/email_change.php index 8bf6e1b6c..b142040db 100644 --- a/email_change.php +++ b/email_change.php @@ -1,173 +1,173 @@ - \ No newline at end of file + diff --git a/empire.php b/empire.php index 4da73075a..70907ed2f 100644 --- a/empire.php +++ b/empire.php @@ -1,263 +1,263 @@ - 0) - { - $production_level = 0; - } - else if($p['energy_max'] > 0 AND abs($p['energy_used']) > $p['energy_max']) - { - $production_level = floor(($p['energy_max'] * 100) / abs($p['energy_used'])); - } - else - { - $production_level = 100; - } - if($production_level > 100) - { - $production_level = 100; - } - $production_level = 0.01 * $production_level; - - $StoreColor = array('metal' => '', 'crystal' => '', 'deuterium' => ''); - $AddSign = array('metal' => '', 'crystal' => '', 'deuterium' => ''); - $BaseProduct = array('metal' => 0, 'crystal' => 0, 'deuterium' => 0); - if($p['planet_type'] == 1) - { - $BaseProduct['metal'] = ($p['metal_perhour'] * $production_level) + $BasicIncome['metal']; - $BaseProduct['crystal'] = ($p['crystal_perhour'] * $production_level) + $BasicIncome['crystal']; - $BaseProduct['deuterium'] = ($p['deuterium_perhour'] * $production_level) + $BasicIncome['deuterium']; - foreach($BaseProduct as $Type => $Value) - { - if($Value > 0) - { - $ProductColor[$Type] = 'lime'; - $AddSign[$Type] = '+'; - } - else if($Value == 0) - { - $ProductColor[$Type] = 'orange'; - } - else - { - $ProductColor[$Type] = 'red'; - $AddSign[$Type] = '-'; - $BaseProduct[$Type] *= -1; - } - } - $StoreColor['metal'] = ($p['metal'] >= ($p['metal_max'] * MAX_OVERFLOW) ? $TPL_Addon_Overflow : ''); - $StoreColor['crystal'] = ($p['crystal'] >= ($p['crystal_max'] * MAX_OVERFLOW) ? $TPL_Addon_Overflow : ''); - $StoreColor['deuterium'] = ($p['deuterium'] >= ($p['deuterium_max'] * MAX_OVERFLOW) ? $TPL_Addon_Overflow : ''); - } - else - { - $ProductColor['metal'] = 'orange'; - $ProductColor['crystal'] = 'orange'; - $ProductColor['deuterium'] = 'orange'; - } - - $EnergyTotal = $p['energy_max'] + $p['energy_used']; - if($EnergyTotal > 0) - { - $EnergyColor = 'lime'; - } - else if($EnergyTotal == 0) - { - $EnergyColor = 'orange'; - } - else - { - $EnergyColor = 'red'; - } - - if($p['id'] == $_User['current_planet']) - { - $data['AddCurrent'] = 'select'; - } - else - { - $data['AddCurrent'] = ''; - } - $ElementTHStart = ""; - - $datat = array - ( - array('ID' => $p['id'], 'skinpath' => $_SkinPath, 'Img' => $p['image']), - array('Name' => $p['name']), - array('G' => $p['galaxy'], 'S' => $p['system'], 'P' => $p['planet']), - array('Current' => $p['field_current'], 'Max' => $p['field_max']), - array - ( - 'ID' => $p['id'], - 'res' => prettyNumber($p['metal']), - 'overflow' => $StoreColor['metal'], - 'color' => $ProductColor['metal'], - 'sign' => $AddSign['metal'], - 'production' => prettyNumber($BaseProduct['metal']) - ), - array - ( - 'ID' => $p['id'], - 'res' => prettyNumber($p['crystal']), - 'overflow' => $StoreColor['crystal'], - 'color' => $ProductColor['crystal'], - 'sign' => $AddSign['crystal'], - 'production' => prettyNumber($BaseProduct['crystal']) - ), - array - ( - 'ID' => $p['id'], - 'res' => prettyNumber($p['deuterium']), - 'overflow' => $StoreColor['deuterium'], - 'color' => $ProductColor['deuterium'], - 'sign' => $AddSign['deuterium'], - 'production' => prettyNumber($BaseProduct['deuterium']) - ), - array - ( - 'color' => $EnergyColor, - 'val' => prettyNumber($EnergyTotal) - ) - ); - $f = array - ( - 'img', 'name', 'coords', 'fields', 'metal', 'crystal', 'deuterium', 'energy' - ); - for($k = 0; $k < 8; $k += 1) - { - if(!isset($parse['row_'.$f[$k]])) - { - $parse['row_'.$f[$k]] = ''; - } - $data['parsed'] = parsetemplate($TPL_Row_StdInfo[$f[$k]], $datat[$k]); - $parse['row_'.$f[$k]] .= parsetemplate($TPL_Row_PlanetCell, $data); - } - - foreach($_Vars_ElementCategories['allowedBuild'] as $ElementID) - { - if(!isset($r[$ElementID])) - { - $r[$ElementID] = ''; - } - $data['text'] = prettyNumber($p[$_Vars_GameElements[$ElementID]])." +"; - $r[$ElementID] .= $ElementTHStart.$data['text'].''; - } - foreach($_Vars_ElementCategories['fleetNdef'] as $ElementID) - { - if(!isset($r[$ElementID])) - { - $r[$ElementID] = ''; - } - if(in_array($ElementID, $_Vars_ElementCategories['fleet'])) - { - $restype = 'fleet'; - } - else - { - $restype = 'defense'; - } - $data['text'] = "".prettyNumber($p[$_Vars_GameElements[$ElementID]]).""; - $r[$ElementID] .= $ElementTHStart.$data['text'].''; - } - } - - $m = array('allowedBuild', 'fleet', 'defense'); - $n = array('row_buildings', 'row_ships', 'row_defense'); - for($j = 0; $j < 3; $j += 1) - { - foreach($_Vars_ElementCategories[$m[$j]] as $i) - { - if(!isset($parse[$n[$j]])) - { - $parse[$n[$j]] = ''; - } - $data['ElementID'] = $i; - $data['ElementName'] = $_Lang['tech'][$i]; - $data['PlanetsCells'] = $r[$i]; - $parse[$n[$j]] .= parsetemplate($TPL_Row, $data); - } - } - - display(parsetemplate(gettemplate('empire_table'), $parse), $_Lang['empire_vision'], false); - -?> \ No newline at end of file + 0) + { + $production_level = 0; + } + else if($p['energy_max'] > 0 AND abs($p['energy_used']) > $p['energy_max']) + { + $production_level = floor(($p['energy_max'] * 100) / abs($p['energy_used'])); + } + else + { + $production_level = 100; + } + if($production_level > 100) + { + $production_level = 100; + } + $production_level = 0.01 * $production_level; + + $StoreColor = array('metal' => '', 'crystal' => '', 'deuterium' => ''); + $AddSign = array('metal' => '', 'crystal' => '', 'deuterium' => ''); + $BaseProduct = array('metal' => 0, 'crystal' => 0, 'deuterium' => 0); + if($p['planet_type'] == 1) + { + $BaseProduct['metal'] = ($p['metal_perhour'] * $production_level) + $BasicIncome['metal']; + $BaseProduct['crystal'] = ($p['crystal_perhour'] * $production_level) + $BasicIncome['crystal']; + $BaseProduct['deuterium'] = ($p['deuterium_perhour'] * $production_level) + $BasicIncome['deuterium']; + foreach($BaseProduct as $Type => $Value) + { + if($Value > 0) + { + $ProductColor[$Type] = 'lime'; + $AddSign[$Type] = '+'; + } + else if($Value == 0) + { + $ProductColor[$Type] = 'orange'; + } + else + { + $ProductColor[$Type] = 'red'; + $AddSign[$Type] = '-'; + $BaseProduct[$Type] *= -1; + } + } + $StoreColor['metal'] = ($p['metal'] >= ($p['metal_max'] * MAX_OVERFLOW) ? $TPL_Addon_Overflow : ''); + $StoreColor['crystal'] = ($p['crystal'] >= ($p['crystal_max'] * MAX_OVERFLOW) ? $TPL_Addon_Overflow : ''); + $StoreColor['deuterium'] = ($p['deuterium'] >= ($p['deuterium_max'] * MAX_OVERFLOW) ? $TPL_Addon_Overflow : ''); + } + else + { + $ProductColor['metal'] = 'orange'; + $ProductColor['crystal'] = 'orange'; + $ProductColor['deuterium'] = 'orange'; + } + + $EnergyTotal = $p['energy_max'] + $p['energy_used']; + if($EnergyTotal > 0) + { + $EnergyColor = 'lime'; + } + else if($EnergyTotal == 0) + { + $EnergyColor = 'orange'; + } + else + { + $EnergyColor = 'red'; + } + + if($p['id'] == $_User['current_planet']) + { + $data['AddCurrent'] = 'select'; + } + else + { + $data['AddCurrent'] = ''; + } + $ElementTHStart = ""; + + $datat = array + ( + array('ID' => $p['id'], 'skinpath' => $_SkinPath, 'Img' => $p['image']), + array('Name' => $p['name']), + array('G' => $p['galaxy'], 'S' => $p['system'], 'P' => $p['planet']), + array('Current' => $p['field_current'], 'Max' => $p['field_max']), + array + ( + 'ID' => $p['id'], + 'res' => prettyNumber($p['metal']), + 'overflow' => $StoreColor['metal'], + 'color' => $ProductColor['metal'], + 'sign' => $AddSign['metal'], + 'production' => prettyNumber($BaseProduct['metal']) + ), + array + ( + 'ID' => $p['id'], + 'res' => prettyNumber($p['crystal']), + 'overflow' => $StoreColor['crystal'], + 'color' => $ProductColor['crystal'], + 'sign' => $AddSign['crystal'], + 'production' => prettyNumber($BaseProduct['crystal']) + ), + array + ( + 'ID' => $p['id'], + 'res' => prettyNumber($p['deuterium']), + 'overflow' => $StoreColor['deuterium'], + 'color' => $ProductColor['deuterium'], + 'sign' => $AddSign['deuterium'], + 'production' => prettyNumber($BaseProduct['deuterium']) + ), + array + ( + 'color' => $EnergyColor, + 'val' => prettyNumber($EnergyTotal) + ) + ); + $f = array + ( + 'img', 'name', 'coords', 'fields', 'metal', 'crystal', 'deuterium', 'energy' + ); + for($k = 0; $k < 8; $k += 1) + { + if(!isset($parse['row_'.$f[$k]])) + { + $parse['row_'.$f[$k]] = ''; + } + $data['parsed'] = parsetemplate($TPL_Row_StdInfo[$f[$k]], $datat[$k]); + $parse['row_'.$f[$k]] .= parsetemplate($TPL_Row_PlanetCell, $data); + } + + foreach($_Vars_ElementCategories['allowedBuild'] as $ElementID) + { + if(!isset($r[$ElementID])) + { + $r[$ElementID] = ''; + } + $data['text'] = prettyNumber($p[$_Vars_GameElements[$ElementID]])." +"; + $r[$ElementID] .= $ElementTHStart.$data['text'].''; + } + foreach($_Vars_ElementCategories['fleetNdef'] as $ElementID) + { + if(!isset($r[$ElementID])) + { + $r[$ElementID] = ''; + } + if(in_array($ElementID, $_Vars_ElementCategories['fleet'])) + { + $restype = 'fleet'; + } + else + { + $restype = 'defense'; + } + $data['text'] = "".prettyNumber($p[$_Vars_GameElements[$ElementID]]).""; + $r[$ElementID] .= $ElementTHStart.$data['text'].''; + } +} + +$m = array('allowedBuild', 'fleet', 'defense'); +$n = array('row_buildings', 'row_ships', 'row_defense'); +for($j = 0; $j < 3; $j += 1) +{ + foreach($_Vars_ElementCategories[$m[$j]] as $i) + { + if(!isset($parse[$n[$j]])) + { + $parse[$n[$j]] = ''; + } + $data['ElementID'] = $i; + $data['ElementName'] = $_Lang['tech'][$i]; + $data['PlanetsCells'] = $r[$i]; + $parse[$n[$j]] .= parsetemplate($TPL_Row, $data); + } +} + +display(parsetemplate(gettemplate('empire_table'), $parse), $_Lang['empire_vision'], false); + +?> diff --git a/fleet.php b/fleet.php index 29dbaa595..f08707114 100644 --- a/fleet.php +++ b/fleet.php @@ -1,1153 +1,1165 @@ - $_Lang['type_mission'][1], - 2 => $_Lang['type_mission'][2], - 3 => $_Lang['type_mission'][3], - 4 => $_Lang['type_mission'][4], - 5 => $_Lang['type_mission'][5], - 6 => $_Lang['type_mission'][6], - 7 => $_Lang['type_mission'][7], - 8 => $_Lang['type_mission'][8], - 9 => $_Lang['type_mission'][9], - 15 => $_Lang['type_mission'][15] - ); - - if($_User['settings_useprettyinputbox'] == 1) - { - $_Lang['P_AllowPrettyInputBox'] = 'true'; - } - else - { - $_Lang['P_AllowPrettyInputBox'] = 'false'; - } - $_Lang['InsertACSUsers'] = 'new Object()'; - $_Lang['InsertACSUsersMax'] = MAX_ACS_JOINED_PLAYERS; - - // Fleet Blockade Info (here, only for Global Block) - $GetSFBData = doquery("SELECT `ID`, `EndTime`, `BlockMissions`, `DontBlockIfIdle`, `Reason` FROM {{table}} WHERE `Type` = 1 AND `StartTime` <= UNIX_TIMESTAMP() AND (`EndTime` > UNIX_TIMESTAMP() OR `PostEndTime` > UNIX_TIMESTAMP()) ORDER BY `EndTime` DESC LIMIT 1;", 'smart_fleet_blockade', true); - if($GetSFBData['ID'] > 0) - { - // Fleet Blockade is Active - include($_EnginePath.'includes/functions/CreateSFBInfobox.php'); - $_Lang['P_SFBInfobox'] = CreateSFBInfobox($GetSFBData, array('standAlone' => true, 'Width' => 750, 'MarginBottom' => 10)); - } - - // Show RetreatBox (when fleet was retreated) - if(isset($_GET['ret'])) - { - if(!isset($_GET['m'])) - { - $_GET['m'] = 0; - } - switch($_GET['m']) - { - case 1: - $RetreatMessage = $_Lang['fl_notback']; - break; - case 2: - $RetreatMessage = $_Lang['fl_isback']; - break; - case 3: - $RetreatMessage = $_Lang['fl_isback2']; - break; - case 4: - $RetreatMessage = $_Lang['fl_missiles_cannot_go_back']; - break; - case 5: - $RetreatMessage = $_Lang['fl_onlyyours']; - break; - default: - $RetreatMessage = $_Lang['fl_notback']; - break; - } - if(!isset($_GET['c'])) - { - $_GET['c'] = 0; - } - switch($_GET['c']) - { - case 1: - $RetreatColor = 'red'; - break; - case 2: - $RetreatColor = 'lime'; - break; - default: - $RetreatColor = 'red'; - break; - } - - $_Lang['RetreatBox_Color'] = $RetreatColor; - $_Lang['RetreatBox_Text'] = $RetreatMessage; - } - else - { - $_Lang['P_HideRetreatBox'] = $Hide; - } - - // Get FlyingFleets Count - $Fleets = doquery("SELECT `fleet_mission` FROM {{table}} WHERE `fleet_owner` = {$_User['id']};", 'fleets'); - while($FleetData = mysql_fetch_assoc($Fleets)) - { - $FlyingFleetsCount += 1; - if($FleetData['fleet_mission'] == 15) - { - $FlyingExpeditions += 1; - } - } - - // Get Available Slots for Fleets (1 + ComputerTech + 2 on Admiral) - // Get Available Slots for Expeditions (1 + floor(ExpeditionTech / 3)) - $_Lang['P_MaxFleetSlots'] = 1 + $_User[$_Vars_GameElements[108]] + (($_User['admiral_time'] > $Now) ? 2 : 0); - $_Lang['P_MaxExpedSlots'] = 1 + floor($_User[$_Vars_GameElements[124]] / 3); - $_Lang['P_FlyingFleetsCount'] = (string)($FlyingFleetsCount + 0); - $_Lang['P_FlyingExpeditions'] = (string)($FlyingExpeditions + 0); - - // Get own fleets - $FL = 'fleet_'; - $FS = $FL.'start_'; - $FE = $FL.'end_'; - $FR = $FL.'resource_'; - $Query_GetFleets = ''; - $Query_GetFleets .= "SELECT `{$FL}id`, `{$FL}mess`, `{$FL}mission`, `{$FL}start_time`, `{$FL}end_time`, `{$FL}end_stay`, `{$FL}send_time`, `{$FL}array`, `{$FL}amount`, "; - $Query_GetFleets .= "`{$FS}galaxy`, `{$FS}system`, `{$FS}planet`, `{$FS}type`, "; - $Query_GetFleets .= "`{$FE}stay`, `{$FE}galaxy`, `{$FE}system`, `{$FE}planet`, `{$FE}type`, "; - $Query_GetFleets .= "`{$FR}metal`, `{$FR}crystal`, `{$FR}deuterium` "; - $Query_GetFleets .= "FROM {{table}} WHERE `fleet_owner` = {$_User['id']} ORDER BY `{$FS}time` ASC, `fleet_id` ASC;"; - $Result_GetFleets = doquery($Query_GetFleets, 'fleets'); - - $i = 0; - $ACSCounter = 1; - - $CheckACSFields = '`t`.`id`, `t`.`main_fleet_id`, `t`.`owner_id`, `t`.`fleets_id`, `t`.`start_time`, `t`.`end_galaxy`, `t`.`end_system`, `t`.`end_planet`, `t`.`end_type`, `userst`.`username`, `fleets`.`fleet_amount`, `fleets`.`fleet_array`, `fleet_start_galaxy`, `fleet_start_system`, `fleet_start_planet`, `fleet_start_type`, `fleet_start_time`'; - $CheckACS = doquery("SELECT {$CheckACSFields} FROM {{table}} AS `t` LEFT JOIN {{prefix}}users as `userst` ON `owner_id` = `userst`.`id` LEFT JOIN {{prefix}}fleets as `fleets` ON `main_fleet_id` = `fleets`.`fleet_id` WHERE (`users` LIKE '%|{$_User['id']}|%' OR `owner_id` = {$_User['id']}) AND `t`.`start_time` > UNIX_TIMESTAMP();", 'acs'); - $AddJoinButton = array(); - - if(mysql_num_rows($CheckACS) > 0) - { - $CheckACSForFleets = doquery("SELECT `main_fleet_id`, `fleets_id` FROM {{table}} WHERE (`users` LIKE '%|{$_User['id']}|%' OR `owner_id` = {$_User['id']}) AND `start_time` > UNIX_TIMESTAMP();", 'acs'); - if(mysql_num_rows($CheckACSForFleets) > 0) - { - while($ACSFleetsData = mysql_fetch_assoc($CheckACSForFleets)) - { - if(!empty($ACSFleetsData['fleets_id'])) - { - $ACSFleetsID[$ACSFleetsData['main_fleet_id']] = explode(',', str_replace('|', '', $ACSFleetsData['fleets_id'])); - foreach($ACSFleetsID[$ACSFleetsData['main_fleet_id']] as $GetFleetID) - { - $ACSFleetsIDIn[] = $GetFleetID; - $ACSFleetsIDs[$GetFleetID] = $ACSFleetsData['main_fleet_id']; - } - } - } - } - - if(!empty($ACSFleetsIDIn)) - { - $CheckACSFleets = doquery("SELECT `fleet_id`, `fleet_array`, `fleet_amount` FROM {{table}} WHERE `fleet_id` IN (".implode(', ', $ACSFleetsIDIn).");", 'fleets'); - if(mysql_num_rows($CheckACSFleets) > 0) - { - while($ACSFleetsData = mysql_fetch_assoc($CheckACSFleets)) - { - $ACSFleetsFillData[$ACSFleetsIDs[$ACSFleetsData['fleet_id']]][] = array('array' => $ACSFleetsData['fleet_array'], 'count' => $ACSFleetsData['fleet_amount']); - } - } - } - - while($ACSData = mysql_fetch_assoc($CheckACS)) - { - if($ACSData['owner_id'] == $_User['id']) - { - $AddJoinButton[$ACSData['id']] = $ACSData['main_fleet_id']; - if(!empty($ACSData['fleets_id'])) - { - $ChangeMission[$ACSData['main_fleet_id']] = true; - } - continue; - } - - $AdditionalFleets = array(); - $AdditionalFleetsCount = 0; - - $FleetRow = array(); - $FleetRow['FleetDetails'] = ''; - - $i += 1; - $FleetRow['FleetNo'] = $i; - $FleetRow['FleetMissionColor'] = 'orange'; - $FleetRow['FleetMission'] = $missiontype[2]; - $FleetRow['ACSOwner'] = '
('.$ACSData['username'].')'; - - $ACSNoCounters[$ACSData['main_fleet_id']] = $ACSCounter; - $FleetRow['FleetMission'] .= " #{$ACSCounter}"; - $ACSCounter += 1; - - if($ACSData['fleet_start_time'] < $Now) - { - if($ACSData['fleet_end_stay'] > 0 AND $ACSData['fleet_end_stay'] > $Now) - { - if($ACSData['fleet_mission'] == 15) - { - $FleetRow['FleetBehaviour'] = $_Lang['fl_explore_to_ttl']; - $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_explore_to']; - } - else - { - $FleetRow['FleetBehaviour'] = $_Lang['fl_stay_to_ttl']; - $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_stay_to']; - } - } - else - { - if($ACSData['fleet_end_time'] > $Now) - { - $FleetRow['FleetBehaviour'] = $_Lang['fl_back_to_ttl']; - $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_back_to']; - } - else - { - $FleetRow['FleetBehaviour'] = $_Lang['fl_cameback_ttl']; - $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_cameback']; - } - } - } - else - { - $FleetRow['FleetBehaviour'] = $_Lang['fl_get_to_ttl']; - $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_get_to']; - } - - if(!empty($ACSFleetsFillData[$ACSData['main_fleet_id']])) - { - foreach($ACSFleetsFillData[$ACSData['main_fleet_id']] as $FData) - { - $FDataArray = explode(';', $FData['array']); - foreach($FDataArray as $Ships) - { - if(!empty($Ships)) - { - $Ships = explode(',', $Ships); - if(!isset($AdditionalFleets[$Ships[0]])) - { - $AdditionalFleets[$Ships[0]] = 0; - } - $AdditionalFleets[$Ships[0]] += $Ships[1]; - } - } - $AdditionalFleetsCount += $FData['count']; - } - } - - $FleetArray = explode(';', $ACSData['fleet_array']); - foreach($FleetArray as $Ships) - { - if(!empty($Ships)) - { - $Ships = explode(',', $Ships); - if(!isset($AdditionalFleets[$Ships[0]])) - { - $AdditionalFleets[$Ships[0]] = 0; - } - $AdditionalFleets[$Ships[0]] += $Ships[1]; - } - } - - foreach($AdditionalFleets as $Ship => $Count) - { - $FleetRow['FleetDetails'] .= parsetemplate($FleetDetTPL, array('Ship' => $_Lang['tech'][$Ship], 'Count' => prettyNumber($Count))); - } - - $FleetRow['FleetCount'] = prettyNumber($ACSData['fleet_amount'] + $AdditionalFleetsCount); - $FleetRow['FleetOriGalaxy'] = $ACSData['fleet_start_galaxy']; - $FleetRow['FleetOriSystem'] = $ACSData['fleet_start_system']; - $FleetRow['FleetOriPlanet'] = $ACSData['fleet_start_planet']; - $FleetRow['FleetOriStart'] = date('d.m.Y<\b\r/>H:i:s', $ACSData['start_time']); - $FleetRow['FleetOriType'] = ($ACSData['fleet_start_type'] == 1 ? 'planet' : ($ACSData['fleet_start_type'] == 3 ? 'moon' : 'debris')); - - $FleetRow['FleetDesGalaxy'] = $ACSData['end_galaxy']; - $FleetRow['FleetDesSystem'] = $ACSData['end_system']; - $FleetRow['FleetDesPlanet'] = $ACSData['end_planet']; - $FleetRow['FleetDesArrive'] = date('d.m.Y<\b\r/>H:i:s', $ACSData['fleet_start_time']); - $FleetRow['FleetDesType'] = ($ACSData['end_type'] == 1 ? 'planet' : ($ACSData['end_type'] == 3 ? 'moon' : 'debris')); - - $FleetRow['FleetEndTime'] = '-'; - - $FleetRow['FleetFlyTargetTime'] = $ACSData['fleet_start_time'] - $Now; - $InsertChronoApplets .= InsertJavaScriptChronoApplet('ft_', $i, $FleetRow['FleetFlyTargetTime']); - $FleetRow['FleetFlyTargetTime'] = ''.pretty_time($FleetRow['FleetFlyTargetTime'], true, 'D').''; - $FleetRow['FleetHideComeBackTime'] = $FleetRow['FleetHideTargetorBackTime'] = $FleetRow['FleetHideStayTime'] = $FleetRow['FleetHideRetreatTime'] = $Hide; - - - $JoinThisACS = ''; - if((isset($_GET['joinacs']) && $_GET['joinacs'] == $ACSData['id']) || (isset($_POST['getacsdata']) && $_POST['getacsdata'] > 0 && isset($_POST['getacsdata']) && $_POST['getacsdata'] == $ACSData['id'])) - { - $JoinThisACS = ' checked'; - $_Lang['SetJoiningACSID'] = $ACSData['id']; - } - $FleetRow['FleetOrders'] = "
{$_Lang['fl_acs_joinnow']}"; - - - $_Lang['FlyingFleetsRows'] .= parsetemplate($FleetRowTPL, $FleetRow); - } - } - - while($f = mysql_fetch_assoc($Result_GetFleets)) - { - $FleetRow = array(); - $FleetRow['FleetDetails'] = ''; - $AdditionalFleets = array(); - $AdditionalFleetsCount = 0; - $Orders = ''; - - $i += 1; - $FleetRow['FleetNo'] = $i; - if(in_array($f['fleet_id'], $AddJoinButton)) - { - $FleetRow['FleetMissionColor']= 'orange'; - } - if(isset($ChangeMission[$f['fleet_id']])) - { - $f['fleet_mission'] = 2; - } - $FleetRow['FleetMission'] = $missiontype[$f['fleet_mission']]; - - if($f['fleet_start_time'] < $Now) - { - if($f['fleet_end_stay'] > 0 AND $f['fleet_end_stay'] > $Now) - { - if($f['fleet_mission'] == 15) - { - $FleetRow['FleetBehaviour'] = $_Lang['fl_explore_to_ttl']; - $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_explore_to']; - } - else - { - $FleetRow['FleetBehaviour'] = $_Lang['fl_stay_to_ttl']; - $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_stay_to']; - } - } - else - { - if($f['fleet_end_time'] > $Now) - { - $FleetRow['FleetBehaviour'] = $_Lang['fl_back_to_ttl']; - $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_back_to']; - } - else - { - $FleetRow['FleetBehaviour'] = $_Lang['fl_cameback_ttl']; - $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_cameback']; - } - } - } - else - { - $FleetRow['FleetBehaviour'] = $_Lang['fl_get_to_ttl']; - $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_get_to']; - } - - if(isset($ChangeMission[$f['fleet_id']])) - { - $f['fleet_mission'] = 1; - } - - if(!empty($ACSFleetsFillData[$f['fleet_id']])) - { - $ACSNoCounters[$f['fleet_id']] = $ACSCounter; - $FleetRow['FleetMission'] .= " #{$ACSCounter}"; - $ACSCounter += 1; - - foreach($ACSFleetsFillData[$f['fleet_id']] as $FData) - { - $FDataArray = explode(';', $FData['array']); - foreach($FDataArray as $Ships) - { - if(!empty($Ships)) - { - $Ships = explode(',', $Ships); - if(!isset($AdditionalFleets[$Ships[0]])) - { - $AdditionalFleets[$Ships[0]] = 0; - } - $AdditionalFleets[$Ships[0]] += $Ships[1]; - } - } - $AdditionalFleetsCount += $FData['count']; - } - } - else - { - if($f['fleet_mission'] == 2) - { - $FleetRow['FleetMission'] .= " #{$ACSNoCounters[$ACSFleetsIDs[$f['fleet_id']]]}"; - } - } - - $FleetArray = explode(';', $f['fleet_array']); - foreach($FleetArray as $Ships) - { - if(!empty($Ships)) - { - $Ships = explode(',', $Ships); - $FleetRow['FleetDetails'] .= parsetemplate($FleetDetTPL, array('Ship' => $_Lang['tech'][$Ships[0]], 'Count' => prettyNumber($Ships[1]))); - } - } - $FleetRow['FleetResInfo'] = parsetemplate($FleetResTPL, array('FleetMetal' => prettyNumber($f['fleet_resource_metal']), 'FleetCrystal' => prettyNumber($f['fleet_resource_crystal']), 'FleetDeuterium' => prettyNumber($f['fleet_resource_deuterium']))); - - if(!empty($AdditionalFleets)) - { - $FleetRow['FleetAddShipsInfo'] = $FleetAddTPL; - foreach($AdditionalFleets as $Ship => $Count) - { - $FleetRow['FleetAddShipsInfo'] .= parsetemplate($FleetDetTPL, array('Ship' => $_Lang['tech'][$Ship], 'Count' => prettyNumber($Count))); - } - } - - $FleetRow['FleetCount'] = prettyNumber($f['fleet_amount'] + $AdditionalFleetsCount); - $FleetRow['FleetOriGalaxy'] = $f['fleet_start_galaxy']; - $FleetRow['FleetOriSystem'] = $f['fleet_start_system']; - $FleetRow['FleetOriPlanet'] = $f['fleet_start_planet']; - $FleetRow['FleetOriStart'] = date('d.m.Y<\b\r/>H:i:s', $f['fleet_send_time']); - $FleetRow['FleetOriType'] = ($f['fleet_start_type'] == 1 ? 'planet' : ($f['fleet_start_type'] == 3 ? 'moon' : 'debris')); - - $FleetRow['FleetDesGalaxy'] = $f['fleet_end_galaxy']; - $FleetRow['FleetDesSystem'] = $f['fleet_end_system']; - $FleetRow['FleetDesPlanet'] = $f['fleet_end_planet']; - $FleetRow['FleetDesArrive'] = date('d.m.Y<\b\r/>H:i:s', $f['fleet_start_time']); - $FleetRow['FleetDesType'] = ($f['fleet_end_type'] == 1 ? 'planet' : ($f['fleet_end_type'] == 3 ? 'moon' : 'debris')); - - $FleetRow['FleetEndTime'] = date('d.m.Y<\b\r/>H:i:s', $f['fleet_end_time']); - - $FleetTargetIn = $f['fleet_start_time'] - $Now; - if($FleetTargetIn <= 0) - { - $FleetTargetInT = '-'; - $FleetRow['FleetHideTargetTime'] = $FleetRow['FleetHideTargetorBackTime'] = $Hide; - } - else - { - if($f['fleet_mission'] != 5) - { - $FleetRow['AddToJSChronoAppletCallback'] = 'document.getElementById(\'bxxfr_'.$i.'\').innerHTML = \'-\';'; - } - $InsertChronoApplets .= InsertJavaScriptChronoApplet('ft_', $i, $FleetTargetIn, false, false, 'function(){ clearInterval(ChronoIntervalfr_'.$i.'); '.$FleetRow['AddToJSChronoAppletCallback'].' }'); - $FleetTargetInT = ''.pretty_time($FleetTargetIn, true, 'D').''; - $FleetRow['FleetFlyTargetTime'] = $FleetTargetInT; - } - - if($f['fleet_mission'] == 4 AND $f['fleet_mess'] == 0) - { - $FleetRow['FleetHideComeBackTime'] = $FleetRow['FleetHideTargetorBackTime'] = $Hide; - } - else - { - $FleetBackIn = $f['fleet_end_time'] - $Now; - if($FleetBackIn <= 0) - { - $FleetBackInT = ''.$_Lang['fl_already_cameback'].''; - } - else - { - $InsertChronoApplets .= InsertJavaScriptChronoApplet('fb_', $i, $FleetBackIn); - $FleetBackInT = ''.pretty_time($FleetBackIn, true, 'D').''; - } - $FleetRow['FleetFlyBackTime'] = $FleetBackInT; - } - - if($f['fleet_end_stay'] > 0 AND $f['fleet_end_stay'] > $Now) - { - $InsertChronoApplets .= InsertJavaScriptChronoApplet('fs_', $i, $f['fleet_end_stay'] - $Now); - $FleetRow['FleetFlyStayTime'] = ''.pretty_time($f['fleet_end_stay'] - $Now, true, 'D').''; - } - else - { - $FleetRow['FleetHideStayTime'] = $Hide; - } - - if($f['fleet_mess'] == 0) - { - $FleetRow['AllowRetreat'] = true; - $FleetRow['RetreatType'] = 1; - $Orders = ''; - $Orders .= parsetemplate($TPL_Orders_Retreat, array('FleetID' => $f['fleet_id'], 'ButtonText' => $_Lang['fl_sback'])); - if($f['fleet_mission'] == 1) - { - $Orders .= parsetemplate($TPL_Orders_ACS, array('FleetID' => $f['fleet_id'], 'ButtonText' => $_Lang['fl_associate'])); - } - if(in_array($f['fleet_id'], $AddJoinButton)) - { - $ACS_GetID = array_keys($AddJoinButton, $f['fleet_id']); - if(isset($_POST['getacsdata']) && $_POST['getacsdata'] > 0 && $_POST['getacsdata'] == $ACS_GetID[0]) - { - $JoinThisACS = ' checked'; - } - else - { - $JoinThisACS = ''; - } - $Orders .= parsetemplate($TPL_Orders_JoinToACS, array('ACS_ID' => $ACS_GetID[0], 'checked' => $JoinThisACS, 'Text' => $_Lang['fl_acs_joinnow'])); - } - else - { - $Orders .= "{AddACSJoin_{$f['fleet_id']}}"; - } - } - else - { - if($f['fleet_mission'] == 5 AND $f['fleet_end_stay'] > $Now) - { - $FleetRow['AllowRetreat'] = true; - $FleetRow['RetreatType'] = 2; - $Orders = ''; - $Orders .= parsetemplate($TPL_Orders_Retreat, array('FleetID' => $f['fleet_id'], 'ButtonText' => $_Lang['fl_back_from_stay'])); - } - else - { - $Orders = ' '; - } - } - if(isset($FleetRow['AllowRetreat']) && $FleetRow['AllowRetreat'] === true) - { - if($FleetRow['RetreatType'] == 1 AND $FleetTargetIn > 0) - { - $InsertChronoApplets .= InsertJavaScriptChronoApplet('fr_', $i, $f['fleet_send_time'], true, true); - $FleetRow['FleetRetreatTime'] = ''.pretty_time($Now - $f['fleet_send_time'], true, 'D').''; - } - else - { - $FleetRow['FleetRetreatTime'] = ''.pretty_time($f['fleet_start_time'] - $f['fleet_send_time'], true, 'D').''; - } - } - else - { - $FleetRow['FleetHideRetreatTime'] = $Hide; - } - $FleetRow['FleetOrders'] = $Orders; - - $_Lang['FlyingFleetsRows'] .= parsetemplate($FleetRowTPL, $FleetRow); - } - - $_Lang['P_HideNoFreeSlots'] = $Hide; - if($i == 0) - { - $_Lang['FlyingFleetsRows'] = '-'; - } - else - { - if($FlyingFleetsCount >= $_Lang['P_MaxFleetSlots']) - { - $_Lang['P_HideNoFreeSlots'] = ''; - } - } - - if(isset($_POST['acsmanage']) && $_POST['acsmanage'] == 'open') - { - $ACSMsgCol = 'red'; - $_Lang['P_HideACSBoxOnError'] = $Hide; - $FleetID = intval($_POST['fleet_id']); - $_Lang['FleetID'] = $FleetID; - if($FleetID > 0) - { - $QryGetFleet4ACSFields = '`fleet`.*, `planet`.`name`'; - $QryGetFleet4ACS = "SELECT {$QryGetFleet4ACSFields} FROM {{table}} AS `fleet` LEFT JOIN {{prefix}}planets AS `planet` ON `planet`.`id` = `fleet`.`fleet_end_id` WHERE `fleet`.`fleet_id` = {$FleetID} LIMIT 1;"; - $Fleet4ACS = doquery($QryGetFleet4ACS, 'fleets', true); - if($Fleet4ACS['fleet_id'] == $FleetID AND $Fleet4ACS['fleet_owner'] == $_User['id']) - { - if($Fleet4ACS['fleet_mission'] == 1 AND $Fleet4ACS['fleet_mess'] == 0) - { - if($Fleet4ACS['fleet_start_time'] > $Now) - { - $_Lang['P_HideACSBoxOnError'] = ''; - - $GetACSRow = doquery("SELECT * FROM {{table}} WHERE `main_fleet_id` = {$FleetID} LIMIT 1;", 'acs', true); - if($GetACSRow['id'] <= 0) - { - $ACSJustCreated = true; - - $CreateACSName = substr($_User['username'].' '.date('d.m.Y H:i', $Now), 0, 50); - $QryCreateACSRow = ''; - $QryCreateACSRow .= "INSERT INTO {{table}} SET `name` = '{$CreateACSName}', `main_fleet_id` = {$FleetID}, `owner_id` = {$_User['id']}, "; - $QryCreateACSRow .= "`start_time_org` = {$Fleet4ACS['fleet_start_time']}, `start_time` = `start_time_org`, `end_target_id` = {$Fleet4ACS['fleet_end_id']}, "; - $QryCreateACSRow .= "`end_galaxy` = {$Fleet4ACS['fleet_end_galaxy']}, `end_system` = {$Fleet4ACS['fleet_end_system']}, `end_planet` = {$Fleet4ACS['fleet_end_planet']}, `end_type` = {$Fleet4ACS['fleet_end_type']};"; - doquery($QryCreateACSRow, 'acs'); - - $GetLastID = doquery("SELECT LAST_INSERT_ID() AS `ID`;", '', true); - $GetLastID = $GetLastID['ID']; - $GetACSRow = array - ( - 'id' => $GetLastID, 'name' => $CreateACSName, 'main_fleet_id' => $FleetID, 'owner_id' => $_User['id'], - 'start_time_org' => $Fleet4ACS['fleet_start_time'], 'start_time' => $Fleet4ACS['fleet_start_time'], 'end_target_id' => $Fleet4ACS['fleet_end_id'], - 'end_galaxy' => $Fleet4ACS['fleet_end_galaxy'], 'end_system' => $Fleet4ACS['fleet_end_system'], 'end_planet' => $Fleet4ACS['fleet_end_planet'], 'end_type' => $Fleet4ACS['fleet_end_type'], - ); - - doquery("UPDATE {{table}} SET `Fleet_ACSID` = {$GetLastID} WHERE `Fleet_ID` = {$FleetID};", 'fleet_archive'); - - if(strstr($_Lang['FlyingFleetsRows'], 'AddACSJoin_') !== false) - { - $_Lang['FlyingFleetsRows'] = str_replace('{AddACSJoin_'.$FleetID.'}', "
{$_Lang['fl_acs_joinnow']}", $_Lang['FlyingFleetsRows']); - } - } - - $JSACSUsers[$_User['id']] = array('name' => $_User['username'], 'status' => $_Lang['fl_acs_leader'], 'canmove' => false, 'place' => 1); - - if($_User['ally_id'] > 0) - { - $Data_GetInvitableUsers['AllyID'][] = $_User['ally_id']; - - $Query_GetAllyPacts = ''; - $Query_GetAllyPacts .= "SELECT IF(`AllyID_Sender` = {$_User['ally_id']}, `AllyID_Owner`, `AllyID_Sender`) AS `AllyID`, `Type` "; - $Query_GetAllyPacts .= "FROM {{table}} WHERE "; - $Query_GetAllyPacts .= "(`AllyID_Sender` = {$_User['ally_id']} OR `AllyID_Owner` = {$_User['ally_id']}) AND `Active` = 1 AND `Type` >= ".ALLYPACT_MILITARY; - $Query_GetAllyPacts .= "; -- fleet.php|GetAllyPacts"; - $Result_GetAllyPacts = doquery($Query_GetAllyPacts, 'ally_pacts'); - if(mysql_num_rows($Result_GetAllyPacts) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_GetAllyPacts)) - { - $Data_GetInvitableUsers['AllyID'][] = $FetchData['AllyID']; - } - } - - $Data_GetInvitableUsers['AllyID'] = implode(', ', $Data_GetInvitableUsers['AllyID']); - $Query_GetInvitableUsers[0] = ''; - $Query_GetInvitableUsers[0] .= "("; - $Query_GetInvitableUsers[0] .= "SELECT `id`, `username` FROM `{{prefix}}users` "; - $Query_GetInvitableUsers[0] .= "WHERE `ally_id` IN ({$Data_GetInvitableUsers['AllyID']}) AND `id` != {$_User['id']}"; - $Query_GetInvitableUsers[0] .= ")"; - } - - $Query_GetInvitableUsers[1] = ''; - $Query_GetInvitableUsers[1] .= "("; - $Query_GetInvitableUsers[1] .= "SELECT "; - $Query_GetInvitableUsers[1] .= "IF(`buddy`.`sender` = {$_User['id']}, `buddy`.`owner`, `buddy`.`sender`) AS `id`, "; - $Query_GetInvitableUsers[1] .= "`user`.`username` AS `username` "; - $Query_GetInvitableUsers[1] .= "FROM `{{prefix}}buddy` AS `buddy` "; - $Query_GetInvitableUsers[1] .= "LEFT JOIN `{{prefix}}users` AS `user` ON "; - $Query_GetInvitableUsers[1] .= "`user`.`id` = IF(`buddy`.`sender` = {$_User['id']}, `buddy`.`owner`, `buddy`.`sender`) "; - $Query_GetInvitableUsers[1] .= "WHERE (`buddy`.`sender` = {$_User['id']} OR `buddy`.`owner` = {$_User['id']}) AND `active` = 1"; - $Query_GetInvitableUsers[1] .= ")"; - - $Query_GetInvitableUsers = implode(' UNION ', $Query_GetInvitableUsers); - $Query_GetInvitableUsers .= "; -- fleet.php|GetInvitableUsers"; - $GetInvitableUsers = doquery($Query_GetInvitableUsers, 'users'); - if(mysql_num_rows($GetInvitableUsers) > 0) - { - while($InvitableUser = mysql_fetch_assoc($GetInvitableUsers)) - { - $InvitableUsers[$InvitableUser['id']] = $InvitableUser; - $JSACSUsers[$InvitableUser['id']] = array('name' => $InvitableUser['username'], 'status' => '', 'canmove' => true, 'place' => 2); - } - } - - if(!isset($ACSJustCreated) || $ACSJustCreated !== true) - { - if(!empty($GetACSRow['users'])) - { - $Users = str_replace('|', '', $GetACSRow['users']); - $Users = explode(',', $Users); - foreach($Users as $UsersID) - { - if($UsersID > 0) - { - if(empty($JSACSUsers[$UsersID]['name'])) - { - $Data_GetEmptyUsernames['ids'][] = $UsersID; - } - $Status = ((strstr($GetACSRow['user_joined'], "|{$UsersID}|") !== FALSE) ? $_Lang['fl_acs_joined'] : $_Lang['fl_acs_invited']); - $JSACSUsers[$UsersID]['status'] = $Status; - $JSACSUsers[$UsersID]['place'] = 1; - if($Status == $_Lang['fl_acs_joined']) - { - $HasToBeInNewArray[] = $UsersID; - } - } - } - } - - if(!empty($Data_GetEmptyUsernames)) - { - $Data_GetEmptyUsernames['count'] = count($Data_GetEmptyUsernames['ids']); - $Data_GetEmptyUsernames['ids'] = implode(',', $Data_GetEmptyUsernames['ids']); - $Query_GetEmptyUsernames = ''; - $Query_GetEmptyUsernames .= "SELECT `id`, `username` FROM {{table}} "; - $Query_GetEmptyUsernames .= "WHERE `id` IN ({$Data_GetEmptyUsernames['ids']}) "; - $Query_GetEmptyUsernames .= "LIMIT {$Data_GetEmptyUsernames['count']}; -- fleet.php|GetEmptyUsernames"; - $Result_GetEmptyUsernames = doquery($Query_GetEmptyUsernames, 'users'); - if(mysql_num_rows($Result_GetEmptyUsernames) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_GetEmptyUsernames)) - { - $JSACSUsers[$FetchData['id']]['name'] = $FetchData['username']; - } - } - } - - if(!empty($_POST['acs_name'])) - { - $NewName = trim($_POST['acs_name']); - $NewName = preg_replace('#[^a-zA-Z'.REGEXP_POLISHSIGNS.'0-9\_\-\.\ \:]#si', '', $NewName); - if($NewName != $GetACSRow['name']) - { - if(strlen($NewName) > 3) - { - doquery("UPDATE {{table}} SET `name` = '{$NewName}' WHERE `id` = {$GetACSRow['id']};", 'acs'); - $GetACSRow['name'] = $NewName; - $ACSMsgCol = 'lime'; - $ACSMsg = $_Lang['fl_acs_changesSaved']; - } - else - { - $ACSMsgCol = 'red'; - $ACSMsg = $_Lang['fl_acs_error_shortname']; - } - } - } - if(isset($_POST['acsuserschanged']) && $_POST['acsuserschanged'] == '1') - { - if(!empty($_POST['acs_users'])) - { - $NewUsersArray = array(); - $ExplodeUsers = explode(',', $_POST['acs_users']); - $UsersCount = 0; - foreach($ExplodeUsers as $ACSUserID) - { - $ACSUserID = intval($ACSUserID); - if(isset($InvitableUsers[$ACSUserID]['id']) && $InvitableUsers[$ACSUserID]['id'] > 0) - { - if($UsersCount < MAX_ACS_JOINED_PLAYERS) - { - $NewUsersArray[$ACSUserID] = $ACSUserID; - $UsersCount += 1; - } - else - { - break; - } - } - } - if(!empty($HasToBeInNewArray)) - { - foreach($HasToBeInNewArray as $UsersID) - { - if(!in_array($UsersID, $NewUsersArray)) - { - $BreakUsersUpdate = true; - $ACSMsg = $_Lang['fl_acs_cantkick_joined']; - break; - } - } - } - if(!isset($BreakUsersUpdate) || $BreakUsersUpdate !== true) - { - foreach($JSACSUsers as $UserID => $UserData) - { - if($UserData['canmove'] === false) - { - continue; - } - if(!in_array($UserID, $NewUsersArray)) - { - if($UserData['place'] != 2) - { - $ChangedInUserArray = true; - $JSACSUsers[$UserID]['place'] = 2; - $JSACSUsers[$UserID]['status'] = ''; - } - } - else - { - if($UserData['place'] == 2) - { - $ChangedInUserArray = true; - $JSACSUsers[$UserID]['place'] = 1; - $JSACSUsers[$UserID]['status'] = $_Lang['fl_acs_invited']; - $MessagesToSend[] = $UserID; - } - } - } - if($ChangedInUserArray === true) - { - foreach($NewUsersArray as $UserID) - { - $NewUserList[] = "|{$UserID}|"; - } - if(!empty($NewUserList)) - { - $NewUserList = implode(',', $NewUserList); - $NewUserCount = count($NewUsersArray); - } - else - { - $NewUserList = ''; - $NewUserCount = '0'; - } - doquery("UPDATE {{table}} SET `users` = '{$NewUserList}', `invited_users` = '{$NewUserCount}' WHERE `id` = {$GetACSRow['id']};", 'acs'); - if(!empty($MessagesToSend)) - { - $Message = false; - $Message['msg_id'] = '069'; - $Message['args'] = array - ( - $_User['username'], (($Fleet4ACS['fleet_end_type'] == 1) ? $_Lang['to_planet'] : $_Lang['to_moon']), - $Fleet4ACS['name'], $Fleet4ACS['fleet_end_galaxy'], $Fleet4ACS['fleet_end_system'], - $Fleet4ACS['fleet_end_galaxy'], $Fleet4ACS['fleet_end_system'], $Fleet4ACS['fleet_end_planet'], - (($Fleet4ACS['fleet_end_type'] == 1) ? $_Lang['to_this_planet'] : $_Lang['to_this_moon']), - $Fleet4ACS['fleet_end_galaxy'], $Fleet4ACS['fleet_end_system'], $Fleet4ACS['fleet_end_planet'], $Fleet4ACS['fleet_end_type'], - $GetACSRow['id'], $GetACSRow['name'] - ); - $Message = json_encode($Message); - Cache_Message($MessagesToSend, 0, '', 1, '007', '018', $Message); - } - - $ACSMsgCol = 'lime'; - $ACSMsg = $_Lang['fl_acs_changesSaved']; - } - } - } - } - } - - if(!empty($JSACSUsers)) - { - $_Lang['InsertACSUsers'] = json_encode($JSACSUsers); - foreach($JSACSUsers as $UserID => $UserData) - { - if($UserData['place'] == 1) - { - $Pointer = &$_Lang['UsersInvited']; - } - else - { - $Pointer = &$_Lang['Users2Invite']; - } - if($UserData['canmove'] === false OR $UserData['status'] == $_Lang['fl_acs_joined']) - { - $IsDisabled = ' disabled'; - } - else - { - $IsDisabled = ''; - } - if(!empty($UserData['status'])) - { - $Status = " ({$UserData['status']})"; - } - else - { - $Status = ''; - } - $Pointer .= ""; - } - } - - if(empty($GetACSRow['name'])) - { - $_Lang['ACSName'] = $_Lang['fl_acs_noname']; - } - else - { - $_Lang['ACSName'] = $GetACSRow['name']; - } - } - else - { - $ACSMsg = $_Lang['fl_acs_timeup']; - } - } - else - { - $ACSMsg = $_Lang['fl_acs_badmission']; - } - } - else - { - $ACSMsg = $_Lang['fl_acs_noexist']; - } - } - else - { - $ACSMsg = $_Lang['fl_acs_noid']; - } - - if(!empty($ACSMsg)) - { - $_Lang['P_HideACSMSG'] = ''; - $_Lang['P_ACSMSG'] = $ACSMsg; - $_Lang['P_ACSMSGCOL']= $ACSMsgCol; - } - else - { - $_Lang['P_HideACSMSG'] = $Hide; - } - - $_Lang['Insert_ACSForm'] = parsetemplate(gettemplate('fleet_acsform'), $_Lang); - } - - $_Lang['FlyingFleetsRows'] = preg_replace('#\{AddACSJoin\_[0-9]+\}#si', '', $_Lang['FlyingFleetsRows']); - - $_Lang['InsertJSShipSet'] = "var JSShipSet = false;"; - if(!isPro()) - { - // Don't Allow to use this function to NonPro Players - $_GET['quickres'] = 0; - } - if(isset($_GET['quickres']) && $_GET['quickres'] == 1) - { - $_Lang['P_SetQuickRes'] = '1'; - $TotalResStorage = floor($_Planet['metal']) + floor($_Planet['crystal']) + floor($_Planet['deuterium']); - $TotalShipsStorage[217] = $_Planet[$_Vars_GameElements[217]] * $_Vars_Prices[217]['capacity']; - $TotalShipsStorage[203] = $_Planet[$_Vars_GameElements[203]] * $_Vars_Prices[203]['capacity']; - $TotalShipsStorage[202] = $_Planet[$_Vars_GameElements[202]] * $_Vars_Prices[202]['capacity']; - $TotalShipsStorage['all'] = array_sum($TotalShipsStorage); - if($TotalResStorage >= $TotalShipsStorage['all']) - { - $JSSetShipsCount[217] = 'max'; - $JSSetShipsCount[203] = 'max'; - $JSSetShipsCount[202] = 'max'; - } - else - { - if($TotalResStorage >= $TotalShipsStorage[217]) - { - $JSSetShipsCount[217] = 'max'; - $TotalResStorage -= $TotalShipsStorage[217]; - if($TotalResStorage >= $TotalShipsStorage[203]) - { - $JSSetShipsCount[203] = 'max'; - $TotalResStorage -= $TotalShipsStorage[203]; - if($TotalResStorage >= $TotalShipsStorage[202]) - { - $JSSetShipsCount[202] = 'max'; - } - else - { - $JSSetShipsCount[202] = $TotalResStorage / $_Vars_Prices[202]['capacity']; - } - } - else - { - $JSSetShipsCount[203] = $TotalResStorage / $_Vars_Prices[203]['capacity']; - } - } - else - { - $JSSetShipsCount[217] = $TotalResStorage / $_Vars_Prices[217]['capacity']; - } - } - - if(!empty($JSSetShipsCount)) - { - $_Lang['InsertJSShipSet'] = "var JSShipSet = new Object;\n"; - foreach($JSSetShipsCount as $ShipID => $ShipCount) - { - $ShipCount = ceil($ShipCount); - if($_Planet[$_Vars_GameElements[$ShipID]] > 0) - { - if($ShipCount == 'max') - { - $ShipCount = $_Planet[$_Vars_GameElements[$ShipID]]; - } - else if($ShipCount > $_Planet[$_Vars_GameElements[$ShipID]]) - { - $ShipCount = $_Planet[$_Vars_GameElements[$ShipID]]; - } - $_Lang['InsertJSShipSet'] .= "JSShipSet['{$ShipID}'] = {$ShipCount};\n"; - } - } - } - } - else - { - $_Lang['P_SetQuickRes'] = '0'; - } - - if(isset($_POST['gobackUsed'])) - { - if(!empty($_POST['FleetArray'])) - { - $PostFleet = explode(';', $_POST['FleetArray']); - foreach($PostFleet as $Data) - { - if(!empty($Data)) - { - $Data = explode(',', $Data); - if(in_array($Data[0], $_Vars_ElementCategories['fleet'])) - { - $InsertShipCount[$Data[0]] = prettyNumber($Data[1]); - } - } - } - } - } - - foreach($_Vars_ElementCategories['fleet'] as $ID) - { - if($_Planet[$_Vars_GameElements[$ID]] > 0) - { - if(empty($_Vars_Prices[$ID]['engine'])) - { - continue; - } - $ThisShip = array(); - - $ThisShip['ID'] = $ID; - $ThisShip['Speed'] = prettyNumber(GetFleetMaxSpeed(array(), $ID, $_User)); - $ThisShip['Name'] = $_Lang['tech'][$ID]; - $ThisShip['Count'] = prettyNumber($_Planet[$_Vars_GameElements[$ID]]); - if($ID == 210) - { - $ShipsData['storage'][$ID] = 0; - } - else - { - $ShipsData['storage'][$ID] = $_Vars_Prices[$ID]['capacity']; - } - $ShipsData['count'][$ID] = $_Planet[$_Vars_GameElements[$ID]]; - - $ThisShip['MaxCount'] = explode('.', sprintf('%f', floor($_Planet[$_Vars_GameElements[$ID]]))); - $ThisShip['MaxCount'] = (string)$ThisShip['MaxCount'][0]; - - if(!empty($InsertShipCount[$ID])) - { - $ThisShip['InsertShipCount'] = $InsertShipCount[$ID]; - } - else - { - $ThisShip['InsertShipCount'] = '0'; - } - - $_Lang['ShipsRow'] .= parsetemplate($ShipRowTPL, $ThisShip); - } - } - $_Lang['Insert_ShipsData'] = json_encode(isset($ShipsData) ? $ShipsData : null); - - $_Lang['P_HideNoSlotsInfo'] = $Hide; - $_Lang['P_HideSendShips'] = $Hide; - $_Lang['P_HideNoShipsInfo'] = $Hide; - if(!empty($_Lang['ShipsRow'])) - { - if($FlyingFleetsCount >= $_Lang['P_MaxFleetSlots']) - { - $_Lang['P_HideNoSlotsInfo'] = ''; - } - else - { - $_Lang['P_HideSendShips'] = ''; - } - } - else - { - $_Lang['P_HideNoShipsInfo'] = ''; - } - - $_Lang['ChronoAppletsScripts'] = $InsertChronoApplets; - - if(isset($_POST['gobackUsed'])) - { - $GoBackVars = array - ( - 'speed' => $_POST['speed'], - ); - if(!empty($_POST['gobackVars'])) - { - $_Lang['P_GoBackVars'] = json_decode(base64_decode($_POST['gobackVars']), true); - if((array)$_Lang['P_GoBackVars'] === $_Lang['P_GoBackVars']) - { - $GoBackVars = array_merge($_Lang['P_GoBackVars'], $GoBackVars); - } - } - - $_Lang['SetJoiningACSID'] = (isset($_POST['getacsdata']) ? $_POST['getacsdata'] : null); - $_Lang['P_Galaxy'] = (isset($_POST['galaxy']) ? $_POST['galaxy'] : null); - $_Lang['P_System'] = (isset($_POST['system']) ? $_POST['system'] : null); - $_Lang['P_Planet'] = (isset($_POST['planet']) ? $_POST['planet'] : null); - $_Lang['P_PlType'] = (isset($_POST['planettype']) ? $_POST['planettype'] : null); - $_Lang['P_Mission'] = (isset($_POST['target_mission']) ? $_POST['target_mission'] : null); - $_Lang['P_SetQuickRes'] = (isset($_POST['quickres']) ? $_POST['quickres'] : null); - $_Lang['P_GoBackVars'] = base64_encode(json_encode($GoBackVars)); - } - else - { - $_Lang['P_Galaxy'] = (isset($_GET['galaxy']) ? intval($_GET['galaxy']) : null); - $_Lang['P_System'] = (isset($_GET['system']) ? intval($_GET['system']) : null); - $_Lang['P_Planet'] = (isset($_GET['planet']) ? intval($_GET['planet']) : null); - $_Lang['P_PlType'] = (isset($_GET['planettype']) ? intval($_GET['planettype']) : null); - $_Lang['P_Mission'] = (isset($_GET['target_mission']) ? intval($_GET['target_mission']) : null); - if(isset($_GET['quickres'])) - { - if(isset($_GET['target_mission']) && $_GET['target_mission'] != 3) - { - if($_User['settings_mainPlanetID'] != $_Planet['id']) - { - $GetQuickResPlanet = doquery("SELECT `galaxy`, `system`, `planet` FROM {{table}} WHERE `id` = {$_User['settings_mainPlanetID']};", 'planets', true); - } - $_Lang['P_Galaxy'] = $GetQuickResPlanet['galaxy']; - $_Lang['P_System'] = $GetQuickResPlanet['system']; - $_Lang['P_Planet'] = $GetQuickResPlanet['planet']; - $_Lang['P_PlType'] = 1; - $_Lang['P_Mission'] = 3; - } - } - } - - if(!isPro()) - { - $_Lang['P_HideQuickRes'] = 'hide'; - } - - $_Lang['P_TotalPlanetResources'] = (string)(floor($_Planet['metal']) + floor($_Planet['crystal']) + floor($_Planet['deuterium']) + 0); - if($_Lang['P_TotalPlanetResources'] == '0') - { - $_Lang['P_StorageColor'] = 'lime'; - } - else - { - $_Lang['P_StorageColor'] = 'orange'; - } - - $Page = parsetemplate($BodyTPL, $_Lang); - display($Page, $_Lang['fl_title']); - -?> \ No newline at end of file + $_Lang['type_mission'][1], + 2 => $_Lang['type_mission'][2], + 3 => $_Lang['type_mission'][3], + 4 => $_Lang['type_mission'][4], + 5 => $_Lang['type_mission'][5], + 6 => $_Lang['type_mission'][6], + 7 => $_Lang['type_mission'][7], + 8 => $_Lang['type_mission'][8], + 9 => $_Lang['type_mission'][9], + 15 => $_Lang['type_mission'][15] +); + +if($_User['settings_useprettyinputbox'] == 1) +{ + $_Lang['P_AllowPrettyInputBox'] = 'true'; +} +else +{ + $_Lang['P_AllowPrettyInputBox'] = 'false'; +} +$_Lang['InsertACSUsers'] = 'new Object()'; +$_Lang['InsertACSUsersMax'] = MAX_ACS_JOINED_PLAYERS; + +// Fleet Blockade Info (here, only for Global Block) +$GetSFBData = doquery("SELECT `ID`, `EndTime`, `BlockMissions`, `DontBlockIfIdle`, `Reason` FROM {{table}} WHERE `Type` = 1 AND `StartTime` <= UNIX_TIMESTAMP() AND (`EndTime` > UNIX_TIMESTAMP() OR `PostEndTime` > UNIX_TIMESTAMP()) ORDER BY `EndTime` DESC LIMIT 1;", 'smart_fleet_blockade', true); +if($GetSFBData['ID'] > 0) +{ + // Fleet Blockade is Active + include($_EnginePath.'includes/functions/CreateSFBInfobox.php'); + $_Lang['P_SFBInfobox'] = CreateSFBInfobox($GetSFBData, array('standAlone' => true, 'Width' => 750, 'MarginBottom' => 10)); +} + +// Show RetreatBox (when fleet was retreated) +if(isset($_GET['ret'])) +{ + if(!isset($_GET['m'])) + { + $_GET['m'] = 0; + } + switch($_GET['m']) + { + case 1: + $RetreatMessage = $_Lang['fl_notback']; + break; + case 2: + $RetreatMessage = $_Lang['fl_isback']; + break; + case 3: + $RetreatMessage = $_Lang['fl_isback2']; + break; + case 4: + $RetreatMessage = $_Lang['fl_missiles_cannot_go_back']; + break; + case 5: + $RetreatMessage = $_Lang['fl_onlyyours']; + break; + default: + $RetreatMessage = $_Lang['fl_notback']; + break; + } + if(!isset($_GET['c'])) + { + $_GET['c'] = 0; + } + switch($_GET['c']) + { + case 1: + $RetreatColor = 'red'; + break; + case 2: + $RetreatColor = 'lime'; + break; + default: + $RetreatColor = 'red'; + break; + } + + $_Lang['RetreatBox_Color'] = $RetreatColor; + $_Lang['RetreatBox_Text'] = $RetreatMessage; +} +else +{ + $_Lang['P_HideRetreatBox'] = $Hide; +} + +// Get FlyingFleets Count +$Fleets = doquery("SELECT `fleet_mission` FROM {{table}} WHERE `fleet_owner` = {$_User['id']};", 'fleets'); +while($FleetData = mysql_fetch_assoc($Fleets)) +{ + $FlyingFleetsCount += 1; + if($FleetData['fleet_mission'] == 15) + { + $FlyingExpeditions += 1; + } +} + +// Get Available Slots for Fleets (1 + ComputerTech + 2 on Admiral) +// Get Available Slots for Expeditions (1 + floor(ExpeditionTech / 3)) +$_Lang['P_MaxFleetSlots'] = 1 + $_User[$_Vars_GameElements[108]] + (($_User['admiral_time'] > $Now) ? 2 : 0); +$_Lang['P_MaxExpedSlots'] = 1 + floor($_User[$_Vars_GameElements[124]] / 3); +$_Lang['P_FlyingFleetsCount'] = (string)($FlyingFleetsCount + 0); +$_Lang['P_FlyingExpeditions'] = (string)($FlyingExpeditions + 0); + +// Get own fleets +$FL = 'fleet_'; +$FS = $FL.'start_'; +$FE = $FL.'end_'; +$FR = $FL.'resource_'; +$Query_GetFleets = ''; +$Query_GetFleets .= "SELECT `{$FL}id`, `{$FL}mess`, `{$FL}mission`, `{$FL}start_time`, `{$FL}end_time`, `{$FL}end_stay`, `{$FL}send_time`, `{$FL}array`, `{$FL}amount`, "; +$Query_GetFleets .= "`{$FS}galaxy`, `{$FS}system`, `{$FS}planet`, `{$FS}type`, "; +$Query_GetFleets .= "`{$FE}stay`, `{$FE}galaxy`, `{$FE}system`, `{$FE}planet`, `{$FE}type`, "; +$Query_GetFleets .= "`{$FR}metal`, `{$FR}crystal`, `{$FR}deuterium` "; +$Query_GetFleets .= "FROM {{table}} WHERE `fleet_owner` = {$_User['id']} ORDER BY `{$FS}time` ASC, `fleet_id` ASC;"; +$Result_GetFleets = doquery($Query_GetFleets, 'fleets'); + +$i = 0; +$ACSCounter = 1; + +$CheckACSFields = '`t`.`id`, `t`.`main_fleet_id`, `t`.`owner_id`, `t`.`fleets_id`, `t`.`start_time`, `t`.`end_galaxy`, `t`.`end_system`, `t`.`end_planet`, `t`.`end_type`, `userst`.`username`, `fleets`.`fleet_amount`, `fleets`.`fleet_array`, `fleet_start_galaxy`, `fleet_start_system`, `fleet_start_planet`, `fleet_start_type`, `fleet_start_time`'; +$CheckACS = doquery("SELECT {$CheckACSFields} FROM {{table}} AS `t` LEFT JOIN {{prefix}}users as `userst` ON `owner_id` = `userst`.`id` LEFT JOIN {{prefix}}fleets as `fleets` ON `main_fleet_id` = `fleets`.`fleet_id` WHERE (`users` LIKE '%|{$_User['id']}|%' OR `owner_id` = {$_User['id']}) AND `t`.`start_time` > UNIX_TIMESTAMP();", 'acs'); +$AddJoinButton = array(); + +if(mysql_num_rows($CheckACS) > 0) +{ + $CheckACSForFleets = doquery("SELECT `main_fleet_id`, `fleets_id` FROM {{table}} WHERE (`users` LIKE '%|{$_User['id']}|%' OR `owner_id` = {$_User['id']}) AND `start_time` > UNIX_TIMESTAMP();", 'acs'); + if(mysql_num_rows($CheckACSForFleets) > 0) + { + while($ACSFleetsData = mysql_fetch_assoc($CheckACSForFleets)) + { + if(!empty($ACSFleetsData['fleets_id'])) + { + $ACSFleetsID[$ACSFleetsData['main_fleet_id']] = explode(',', str_replace('|', '', $ACSFleetsData['fleets_id'])); + foreach($ACSFleetsID[$ACSFleetsData['main_fleet_id']] as $GetFleetID) + { + $ACSFleetsIDIn[] = $GetFleetID; + $ACSFleetsIDs[$GetFleetID] = $ACSFleetsData['main_fleet_id']; + } + } + } + } + + if(!empty($ACSFleetsIDIn)) + { + $CheckACSFleets = doquery("SELECT `fleet_id`, `fleet_array`, `fleet_amount` FROM {{table}} WHERE `fleet_id` IN (".implode(', ', $ACSFleetsIDIn).");", 'fleets'); + if(mysql_num_rows($CheckACSFleets) > 0) + { + while($ACSFleetsData = mysql_fetch_assoc($CheckACSFleets)) + { + $ACSFleetsFillData[$ACSFleetsIDs[$ACSFleetsData['fleet_id']]][] = array('array' => $ACSFleetsData['fleet_array'], 'count' => $ACSFleetsData['fleet_amount']); + } + } + } + + while($ACSData = mysql_fetch_assoc($CheckACS)) + { + if($ACSData['owner_id'] == $_User['id']) + { + $AddJoinButton[$ACSData['id']] = $ACSData['main_fleet_id']; + if(!empty($ACSData['fleets_id'])) + { + $ChangeMission[$ACSData['main_fleet_id']] = true; + } + continue; + } + + $AdditionalFleets = array(); + $AdditionalFleetsCount = 0; + + $FleetRow = array(); + $FleetRow['FleetDetails'] = ''; + + $i += 1; + $FleetRow['FleetNo'] = $i; + $FleetRow['FleetMissionColor'] = 'orange'; + $FleetRow['FleetMission'] = $missiontype[2]; + $FleetRow['ACSOwner'] = '
('.$ACSData['username'].')'; + + $ACSNoCounters[$ACSData['main_fleet_id']] = $ACSCounter; + $FleetRow['FleetMission'] .= " #{$ACSCounter}"; + $ACSCounter += 1; + + if($ACSData['fleet_start_time'] < $Now) + { + if($ACSData['fleet_end_stay'] > 0 AND $ACSData['fleet_end_stay'] > $Now) + { + if($ACSData['fleet_mission'] == 15) + { + $FleetRow['FleetBehaviour'] = $_Lang['fl_explore_to_ttl']; + $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_explore_to']; + } + else + { + $FleetRow['FleetBehaviour'] = $_Lang['fl_stay_to_ttl']; + $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_stay_to']; + } + } + else + { + if($ACSData['fleet_end_time'] > $Now) + { + $FleetRow['FleetBehaviour'] = $_Lang['fl_back_to_ttl']; + $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_back_to']; + } + else + { + $FleetRow['FleetBehaviour'] = $_Lang['fl_cameback_ttl']; + $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_cameback']; + } + } + } + else + { + $FleetRow['FleetBehaviour'] = $_Lang['fl_get_to_ttl']; + $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_get_to']; + } + + if(!empty($ACSFleetsFillData[$ACSData['main_fleet_id']])) + { + foreach($ACSFleetsFillData[$ACSData['main_fleet_id']] as $FData) + { + $FDataArray = explode(';', $FData['array']); + foreach($FDataArray as $Ships) + { + if(!empty($Ships)) + { + $Ships = explode(',', $Ships); + if(!isset($AdditionalFleets[$Ships[0]])) + { + $AdditionalFleets[$Ships[0]] = 0; + } + $AdditionalFleets[$Ships[0]] += $Ships[1]; + } + } + $AdditionalFleetsCount += $FData['count']; + } + } + + $FleetArray = explode(';', $ACSData['fleet_array']); + foreach($FleetArray as $Ships) + { + if(!empty($Ships)) + { + $Ships = explode(',', $Ships); + if(!isset($AdditionalFleets[$Ships[0]])) + { + $AdditionalFleets[$Ships[0]] = 0; + } + $AdditionalFleets[$Ships[0]] += $Ships[1]; + } + } + + foreach($AdditionalFleets as $Ship => $Count) + { + $FleetRow['FleetDetails'] .= parsetemplate($FleetDetTPL, array('Ship' => $_Lang['tech'][$Ship], 'Count' => prettyNumber($Count))); + } + + $FleetRow['FleetCount'] = prettyNumber($ACSData['fleet_amount'] + $AdditionalFleetsCount); + $FleetRow['FleetOriGalaxy'] = $ACSData['fleet_start_galaxy']; + $FleetRow['FleetOriSystem'] = $ACSData['fleet_start_system']; + $FleetRow['FleetOriPlanet'] = $ACSData['fleet_start_planet']; + $FleetRow['FleetOriStart'] = date('d.m.Y<\b\r/>H:i:s', $ACSData['start_time']); + $FleetRow['FleetOriType'] = ($ACSData['fleet_start_type'] == 1 ? 'planet' : ($ACSData['fleet_start_type'] == 3 ? 'moon' : 'debris')); + + $FleetRow['FleetDesGalaxy'] = $ACSData['end_galaxy']; + $FleetRow['FleetDesSystem'] = $ACSData['end_system']; + $FleetRow['FleetDesPlanet'] = $ACSData['end_planet']; + $FleetRow['FleetDesArrive'] = date('d.m.Y<\b\r/>H:i:s', $ACSData['fleet_start_time']); + $FleetRow['FleetDesType'] = ($ACSData['end_type'] == 1 ? 'planet' : ($ACSData['end_type'] == 3 ? 'moon' : 'debris')); + + $FleetRow['FleetEndTime'] = '-'; + + $FleetRow['FleetFlyTargetTime'] = $ACSData['fleet_start_time'] - $Now; + $InsertChronoApplets .= InsertJavaScriptChronoApplet('ft_', $i, $FleetRow['FleetFlyTargetTime']); + $FleetRow['FleetFlyTargetTime'] = ''.pretty_time($FleetRow['FleetFlyTargetTime'], true, 'D').''; + $FleetRow['FleetHideComeBackTime'] = $FleetRow['FleetHideTargetorBackTime'] = $FleetRow['FleetHideStayTime'] = $FleetRow['FleetHideRetreatTime'] = $Hide; + + + $JoinThisACS = ''; + if((isset($_GET['joinacs']) && $_GET['joinacs'] == $ACSData['id']) || (isset($_POST['getacsdata']) && $_POST['getacsdata'] > 0 && isset($_POST['getacsdata']) && $_POST['getacsdata'] == $ACSData['id'])) + { + $JoinThisACS = ' checked'; + $_Lang['SetJoiningACSID'] = $ACSData['id']; + } + $FleetRow['FleetOrders'] = "
{$_Lang['fl_acs_joinnow']}"; + + + $_Lang['FlyingFleetsRows'] .= parsetemplate($FleetRowTPL, $FleetRow); + } +} + +while($f = mysql_fetch_assoc($Result_GetFleets)) +{ + $FleetRow = array(); + $FleetRow['FleetDetails'] = ''; + $AdditionalFleets = array(); + $AdditionalFleetsCount = 0; + $Orders = ''; + + $i += 1; + $FleetRow['FleetNo'] = $i; + if(in_array($f['fleet_id'], $AddJoinButton)) + { + $FleetRow['FleetMissionColor']= 'orange'; + } + if(isset($ChangeMission[$f['fleet_id']])) + { + $f['fleet_mission'] = 2; + } + $FleetRow['FleetMission'] = $missiontype[$f['fleet_mission']]; + + if($f['fleet_start_time'] < $Now) + { + if($f['fleet_end_stay'] > 0 AND $f['fleet_end_stay'] > $Now) + { + if($f['fleet_mission'] == 15) + { + $FleetRow['FleetBehaviour'] = $_Lang['fl_explore_to_ttl']; + $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_explore_to']; + } + else + { + $FleetRow['FleetBehaviour'] = $_Lang['fl_stay_to_ttl']; + $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_stay_to']; + } + } + else + { + if($f['fleet_end_time'] > $Now) + { + $FleetRow['FleetBehaviour'] = $_Lang['fl_back_to_ttl']; + $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_back_to']; + } + else + { + $FleetRow['FleetBehaviour'] = $_Lang['fl_cameback_ttl']; + $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_cameback']; + } + } + } + else + { + $FleetRow['FleetBehaviour'] = $_Lang['fl_get_to_ttl']; + $FleetRow['FleetBehaviourTxt'] = $_Lang['fl_get_to']; + } + + if(isset($ChangeMission[$f['fleet_id']])) + { + $f['fleet_mission'] = 1; + } + + if(!empty($ACSFleetsFillData[$f['fleet_id']])) + { + $ACSNoCounters[$f['fleet_id']] = $ACSCounter; + $FleetRow['FleetMission'] .= " #{$ACSCounter}"; + $ACSCounter += 1; + + foreach($ACSFleetsFillData[$f['fleet_id']] as $FData) + { + $FDataArray = explode(';', $FData['array']); + foreach($FDataArray as $Ships) + { + if(!empty($Ships)) + { + $Ships = explode(',', $Ships); + if(!isset($AdditionalFleets[$Ships[0]])) + { + $AdditionalFleets[$Ships[0]] = 0; + } + $AdditionalFleets[$Ships[0]] += $Ships[1]; + } + } + $AdditionalFleetsCount += $FData['count']; + } + } + else + { + if($f['fleet_mission'] == 2) + { + $FleetRow['FleetMission'] .= " #{$ACSNoCounters[$ACSFleetsIDs[$f['fleet_id']]]}"; + } + } + + $FleetArray = explode(';', $f['fleet_array']); + foreach($FleetArray as $Ships) + { + if(!empty($Ships)) + { + $Ships = explode(',', $Ships); + $FleetRow['FleetDetails'] .= parsetemplate($FleetDetTPL, array('Ship' => $_Lang['tech'][$Ships[0]], 'Count' => prettyNumber($Ships[1]))); + } + } + $FleetRow['FleetResInfo'] = parsetemplate($FleetResTPL, array('FleetMetal' => prettyNumber($f['fleet_resource_metal']), 'FleetCrystal' => prettyNumber($f['fleet_resource_crystal']), 'FleetDeuterium' => prettyNumber($f['fleet_resource_deuterium']))); + + if(!empty($AdditionalFleets)) + { + $FleetRow['FleetAddShipsInfo'] = $FleetAddTPL; + foreach($AdditionalFleets as $Ship => $Count) + { + $FleetRow['FleetAddShipsInfo'] .= parsetemplate($FleetDetTPL, array('Ship' => $_Lang['tech'][$Ship], 'Count' => prettyNumber($Count))); + } + } + + $FleetRow['FleetCount'] = prettyNumber($f['fleet_amount'] + $AdditionalFleetsCount); + $FleetRow['FleetOriGalaxy'] = $f['fleet_start_galaxy']; + $FleetRow['FleetOriSystem'] = $f['fleet_start_system']; + $FleetRow['FleetOriPlanet'] = $f['fleet_start_planet']; + $FleetRow['FleetOriStart'] = date('d.m.Y<\b\r/>H:i:s', $f['fleet_send_time']); + $FleetRow['FleetOriType'] = ($f['fleet_start_type'] == 1 ? 'planet' : ($f['fleet_start_type'] == 3 ? 'moon' : 'debris')); + + $FleetRow['FleetDesGalaxy'] = $f['fleet_end_galaxy']; + $FleetRow['FleetDesSystem'] = $f['fleet_end_system']; + $FleetRow['FleetDesPlanet'] = $f['fleet_end_planet']; + $FleetRow['FleetDesArrive'] = date('d.m.Y<\b\r/>H:i:s', $f['fleet_start_time']); + $FleetRow['FleetDesType'] = ($f['fleet_end_type'] == 1 ? 'planet' : ($f['fleet_end_type'] == 3 ? 'moon' : 'debris')); + + $FleetRow['FleetEndTime'] = date('d.m.Y<\b\r/>H:i:s', $f['fleet_end_time']); + + $FleetTargetIn = $f['fleet_start_time'] - $Now; + if($FleetTargetIn <= 0) + { + $FleetTargetInT = '-'; + $FleetRow['FleetHideTargetTime'] = $FleetRow['FleetHideTargetorBackTime'] = $Hide; + } + else + { + if($f['fleet_mission'] != 5) + { + $FleetRow['AddToJSChronoAppletCallback'] = 'document.getElementById(\'bxxfr_'.$i.'\').innerHTML = \'-\';'; + } + $InsertChronoApplets .= InsertJavaScriptChronoApplet('ft_', $i, $FleetTargetIn, false, false, 'function(){ clearInterval(ChronoIntervalfr_'.$i.'); '.$FleetRow['AddToJSChronoAppletCallback'].' }'); + $FleetTargetInT = ''.pretty_time($FleetTargetIn, true, 'D').''; + $FleetRow['FleetFlyTargetTime'] = $FleetTargetInT; + } + + if($f['fleet_mission'] == 4 AND $f['fleet_mess'] == 0) + { + $FleetRow['FleetHideComeBackTime'] = $FleetRow['FleetHideTargetorBackTime'] = $Hide; + } + else + { + $FleetBackIn = $f['fleet_end_time'] - $Now; + if($FleetBackIn <= 0) + { + $FleetBackInT = ''.$_Lang['fl_already_cameback'].''; + } + else + { + $InsertChronoApplets .= InsertJavaScriptChronoApplet('fb_', $i, $FleetBackIn); + $FleetBackInT = ''.pretty_time($FleetBackIn, true, 'D').''; + } + $FleetRow['FleetFlyBackTime'] = $FleetBackInT; + } + + if($f['fleet_end_stay'] > 0 AND $f['fleet_end_stay'] > $Now) + { + $InsertChronoApplets .= InsertJavaScriptChronoApplet('fs_', $i, $f['fleet_end_stay'] - $Now); + $FleetRow['FleetFlyStayTime'] = ''.pretty_time($f['fleet_end_stay'] - $Now, true, 'D').''; + } + else + { + $FleetRow['FleetHideStayTime'] = $Hide; + } + + if($f['fleet_mess'] == 0) + { + $FleetRow['AllowRetreat'] = true; + $FleetRow['RetreatType'] = 1; + $Orders = ''; + $Orders .= parsetemplate($TPL_Orders_Retreat, array('FleetID' => $f['fleet_id'], 'ButtonText' => $_Lang['fl_sback'])); + if($f['fleet_mission'] == 1) + { + $Orders .= parsetemplate($TPL_Orders_ACS, array('FleetID' => $f['fleet_id'], 'ButtonText' => $_Lang['fl_associate'])); + } + if(in_array($f['fleet_id'], $AddJoinButton)) + { + $ACS_GetID = array_keys($AddJoinButton, $f['fleet_id']); + if(isset($_POST['getacsdata']) && $_POST['getacsdata'] > 0 && $_POST['getacsdata'] == $ACS_GetID[0]) + { + $JoinThisACS = ' checked'; + } + else + { + $JoinThisACS = ''; + } + $Orders .= parsetemplate($TPL_Orders_JoinToACS, array('ACS_ID' => $ACS_GetID[0], 'checked' => $JoinThisACS, 'Text' => $_Lang['fl_acs_joinnow'])); + } + else + { + $Orders .= "{AddACSJoin_{$f['fleet_id']}}"; + } + } + else + { + if($f['fleet_mission'] == 5 AND $f['fleet_end_stay'] > $Now) + { + $FleetRow['AllowRetreat'] = true; + $FleetRow['RetreatType'] = 2; + $Orders = ''; + $Orders .= parsetemplate($TPL_Orders_Retreat, array('FleetID' => $f['fleet_id'], 'ButtonText' => $_Lang['fl_back_from_stay'])); + } + else + { + $Orders = ' '; + } + } + if(isset($FleetRow['AllowRetreat']) && $FleetRow['AllowRetreat'] === true) + { + if($FleetRow['RetreatType'] == 1 AND $FleetTargetIn > 0) + { + $InsertChronoApplets .= InsertJavaScriptChronoApplet('fr_', $i, $f['fleet_send_time'], true, true); + $FleetRow['FleetRetreatTime'] = ''.pretty_time($Now - $f['fleet_send_time'], true, 'D').''; + } + else + { + $FleetRow['FleetRetreatTime'] = ''.pretty_time($f['fleet_start_time'] - $f['fleet_send_time'], true, 'D').''; + } + } + else + { + $FleetRow['FleetHideRetreatTime'] = $Hide; + } + $FleetRow['FleetOrders'] = $Orders; + + $_Lang['FlyingFleetsRows'] .= parsetemplate($FleetRowTPL, $FleetRow); +} + +$_Lang['P_HideNoFreeSlots'] = $Hide; +if($i == 0) +{ + $_Lang['FlyingFleetsRows'] = '-'; +} +else +{ + if($FlyingFleetsCount >= $_Lang['P_MaxFleetSlots']) + { + $_Lang['P_HideNoFreeSlots'] = ''; + } +} + +if(isset($_POST['acsmanage']) && $_POST['acsmanage'] == 'open') +{ + $ACSMsgCol = 'red'; + $_Lang['P_HideACSBoxOnError'] = $Hide; + $FleetID = intval($_POST['fleet_id']); + $_Lang['FleetID'] = $FleetID; + if($FleetID > 0) + { + $QryGetFleet4ACSFields = '`fleet`.*, `planet`.`name`'; + $QryGetFleet4ACS = "SELECT {$QryGetFleet4ACSFields} FROM {{table}} AS `fleet` LEFT JOIN {{prefix}}planets AS `planet` ON `planet`.`id` = `fleet`.`fleet_end_id` WHERE `fleet`.`fleet_id` = {$FleetID} LIMIT 1;"; + $Fleet4ACS = doquery($QryGetFleet4ACS, 'fleets', true); + if($Fleet4ACS['fleet_id'] == $FleetID AND $Fleet4ACS['fleet_owner'] == $_User['id']) + { + if($Fleet4ACS['fleet_mission'] == 1 AND $Fleet4ACS['fleet_mess'] == 0) + { + if($Fleet4ACS['fleet_start_time'] > $Now) + { + $_Lang['P_HideACSBoxOnError'] = ''; + + $GetACSRow = doquery("SELECT * FROM {{table}} WHERE `main_fleet_id` = {$FleetID} LIMIT 1;", 'acs', true); + if($GetACSRow['id'] <= 0) + { + $ACSJustCreated = true; + + $CreateACSName = substr($_User['username'].' '.date('d.m.Y H:i', $Now), 0, 50); + $QryCreateACSRow = ''; + $QryCreateACSRow .= "INSERT INTO {{table}} SET `name` = '{$CreateACSName}', `main_fleet_id` = {$FleetID}, `owner_id` = {$_User['id']}, "; + $QryCreateACSRow .= "`start_time_org` = {$Fleet4ACS['fleet_start_time']}, `start_time` = `start_time_org`, `end_target_id` = {$Fleet4ACS['fleet_end_id']}, "; + $QryCreateACSRow .= "`end_galaxy` = {$Fleet4ACS['fleet_end_galaxy']}, `end_system` = {$Fleet4ACS['fleet_end_system']}, `end_planet` = {$Fleet4ACS['fleet_end_planet']}, `end_type` = {$Fleet4ACS['fleet_end_type']};"; + doquery($QryCreateACSRow, 'acs'); + + $GetLastID = doquery("SELECT LAST_INSERT_ID() AS `ID`;", '', true); + $GetLastID = $GetLastID['ID']; + $GetACSRow = array + ( + 'id' => $GetLastID, 'name' => $CreateACSName, 'main_fleet_id' => $FleetID, 'owner_id' => $_User['id'], + 'start_time_org' => $Fleet4ACS['fleet_start_time'], 'start_time' => $Fleet4ACS['fleet_start_time'], 'end_target_id' => $Fleet4ACS['fleet_end_id'], + 'end_galaxy' => $Fleet4ACS['fleet_end_galaxy'], 'end_system' => $Fleet4ACS['fleet_end_system'], 'end_planet' => $Fleet4ACS['fleet_end_planet'], 'end_type' => $Fleet4ACS['fleet_end_type'], + ); + + doquery("UPDATE {{table}} SET `Fleet_ACSID` = {$GetLastID} WHERE `Fleet_ID` = {$FleetID};", 'fleet_archive'); + + if(strstr($_Lang['FlyingFleetsRows'], 'AddACSJoin_') !== false) + { + $_Lang['FlyingFleetsRows'] = str_replace('{AddACSJoin_'.$FleetID.'}', "
{$_Lang['fl_acs_joinnow']}", $_Lang['FlyingFleetsRows']); + } + } + + $JSACSUsers[$_User['id']] = array('name' => $_User['username'], 'status' => $_Lang['fl_acs_leader'], 'canmove' => false, 'place' => 1); + + if($_User['ally_id'] > 0) + { + $Data_GetInvitableUsers['AllyID'][] = $_User['ally_id']; + + $Query_GetAllyPacts = ''; + $Query_GetAllyPacts .= "SELECT IF(`AllyID_Sender` = {$_User['ally_id']}, `AllyID_Owner`, `AllyID_Sender`) AS `AllyID`, `Type` "; + $Query_GetAllyPacts .= "FROM {{table}} WHERE "; + $Query_GetAllyPacts .= "(`AllyID_Sender` = {$_User['ally_id']} OR `AllyID_Owner` = {$_User['ally_id']}) AND `Active` = 1 AND `Type` >= ".ALLYPACT_MILITARY; + $Query_GetAllyPacts .= "; -- fleet.php|GetAllyPacts"; + $Result_GetAllyPacts = doquery($Query_GetAllyPacts, 'ally_pacts'); + if(mysql_num_rows($Result_GetAllyPacts) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_GetAllyPacts)) + { + $Data_GetInvitableUsers['AllyID'][] = $FetchData['AllyID']; + } + } + + $Data_GetInvitableUsers['AllyID'] = implode(', ', $Data_GetInvitableUsers['AllyID']); + $Query_GetInvitableUsers[0] = ''; + $Query_GetInvitableUsers[0] .= "("; + $Query_GetInvitableUsers[0] .= "SELECT `id`, `username` FROM `{{prefix}}users` "; + $Query_GetInvitableUsers[0] .= "WHERE `ally_id` IN ({$Data_GetInvitableUsers['AllyID']}) AND `id` != {$_User['id']}"; + $Query_GetInvitableUsers[0] .= ")"; + } + + $Query_GetInvitableUsers[1] = ''; + $Query_GetInvitableUsers[1] .= "("; + $Query_GetInvitableUsers[1] .= "SELECT "; + $Query_GetInvitableUsers[1] .= "IF(`buddy`.`sender` = {$_User['id']}, `buddy`.`owner`, `buddy`.`sender`) AS `id`, "; + $Query_GetInvitableUsers[1] .= "`user`.`username` AS `username` "; + $Query_GetInvitableUsers[1] .= "FROM `{{prefix}}buddy` AS `buddy` "; + $Query_GetInvitableUsers[1] .= "LEFT JOIN `{{prefix}}users` AS `user` ON "; + $Query_GetInvitableUsers[1] .= "`user`.`id` = IF(`buddy`.`sender` = {$_User['id']}, `buddy`.`owner`, `buddy`.`sender`) "; + $Query_GetInvitableUsers[1] .= "WHERE (`buddy`.`sender` = {$_User['id']} OR `buddy`.`owner` = {$_User['id']}) AND `active` = 1"; + $Query_GetInvitableUsers[1] .= ")"; + + $Query_GetInvitableUsers = implode(' UNION ', $Query_GetInvitableUsers); + $Query_GetInvitableUsers .= "; -- fleet.php|GetInvitableUsers"; + $GetInvitableUsers = doquery($Query_GetInvitableUsers, 'users'); + if(mysql_num_rows($GetInvitableUsers) > 0) + { + while($InvitableUser = mysql_fetch_assoc($GetInvitableUsers)) + { + $InvitableUsers[$InvitableUser['id']] = $InvitableUser; + $JSACSUsers[$InvitableUser['id']] = array('name' => $InvitableUser['username'], 'status' => '', 'canmove' => true, 'place' => 2); + } + } + + if(!isset($ACSJustCreated) || $ACSJustCreated !== true) + { + if(!empty($GetACSRow['users'])) + { + $Users = str_replace('|', '', $GetACSRow['users']); + $Users = explode(',', $Users); + foreach($Users as $UsersID) + { + if($UsersID > 0) + { + if(empty($JSACSUsers[$UsersID]['name'])) + { + $Data_GetEmptyUsernames['ids'][] = $UsersID; + } + $Status = ((strstr($GetACSRow['user_joined'], "|{$UsersID}|") !== FALSE) ? $_Lang['fl_acs_joined'] : $_Lang['fl_acs_invited']); + $JSACSUsers[$UsersID]['status'] = $Status; + $JSACSUsers[$UsersID]['place'] = 1; + if($Status == $_Lang['fl_acs_joined']) + { + $HasToBeInNewArray[] = $UsersID; + } + } + } + } + + if(!empty($Data_GetEmptyUsernames)) + { + $Data_GetEmptyUsernames['count'] = count($Data_GetEmptyUsernames['ids']); + $Data_GetEmptyUsernames['ids'] = implode(',', $Data_GetEmptyUsernames['ids']); + $Query_GetEmptyUsernames = ''; + $Query_GetEmptyUsernames .= "SELECT `id`, `username` FROM {{table}} "; + $Query_GetEmptyUsernames .= "WHERE `id` IN ({$Data_GetEmptyUsernames['ids']}) "; + $Query_GetEmptyUsernames .= "LIMIT {$Data_GetEmptyUsernames['count']}; -- fleet.php|GetEmptyUsernames"; + $Result_GetEmptyUsernames = doquery($Query_GetEmptyUsernames, 'users'); + if(mysql_num_rows($Result_GetEmptyUsernames) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_GetEmptyUsernames)) + { + $JSACSUsers[$FetchData['id']]['name'] = $FetchData['username']; + } + } + } + + if(!empty($_POST['acs_name'])) + { + $NewName = trim($_POST['acs_name']); + $NewName = preg_replace('#[^a-zA-Z'.REGEXP_POLISHSIGNS.'0-9\_\-\.\ \:]#si', '', $NewName); + if($NewName != $GetACSRow['name']) + { + if(strlen($NewName) > 3) + { + doquery("UPDATE {{table}} SET `name` = '{$NewName}' WHERE `id` = {$GetACSRow['id']};", 'acs'); + $GetACSRow['name'] = $NewName; + $ACSMsgCol = 'lime'; + $ACSMsg = $_Lang['fl_acs_changesSaved']; + } + else + { + $ACSMsgCol = 'red'; + $ACSMsg = $_Lang['fl_acs_error_shortname']; + } + } + } + if(isset($_POST['acsuserschanged']) && $_POST['acsuserschanged'] == '1') + { + if(!empty($_POST['acs_users'])) + { + $NewUsersArray = array(); + $ExplodeUsers = explode(',', $_POST['acs_users']); + $UsersCount = 0; + foreach($ExplodeUsers as $ACSUserID) + { + $ACSUserID = intval($ACSUserID); + if(isset($InvitableUsers[$ACSUserID]['id']) && $InvitableUsers[$ACSUserID]['id'] > 0) + { + if($UsersCount < MAX_ACS_JOINED_PLAYERS) + { + $NewUsersArray[$ACSUserID] = $ACSUserID; + $UsersCount += 1; + } + else + { + break; + } + } + } + if(!empty($HasToBeInNewArray)) + { + foreach($HasToBeInNewArray as $UsersID) + { + if(!in_array($UsersID, $NewUsersArray)) + { + $BreakUsersUpdate = true; + $ACSMsg = $_Lang['fl_acs_cantkick_joined']; + break; + } + } + } + if(!isset($BreakUsersUpdate) || $BreakUsersUpdate !== true) + { + foreach($JSACSUsers as $UserID => $UserData) + { + if($UserData['canmove'] === false) + { + continue; + } + if(!in_array($UserID, $NewUsersArray)) + { + if($UserData['place'] != 2) + { + $ChangedInUserArray = true; + $JSACSUsers[$UserID]['place'] = 2; + $JSACSUsers[$UserID]['status'] = ''; + } + } + else + { + if($UserData['place'] == 2) + { + $ChangedInUserArray = true; + $JSACSUsers[$UserID]['place'] = 1; + $JSACSUsers[$UserID]['status'] = $_Lang['fl_acs_invited']; + $MessagesToSend[] = $UserID; + } + } + } + if($ChangedInUserArray === true) + { + foreach($NewUsersArray as $UserID) + { + $NewUserList[] = "|{$UserID}|"; + } + if(!empty($NewUserList)) + { + $NewUserList = implode(',', $NewUserList); + $NewUserCount = count($NewUsersArray); + } + else + { + $NewUserList = ''; + $NewUserCount = '0'; + } + doquery("UPDATE {{table}} SET `users` = '{$NewUserList}', `invited_users` = '{$NewUserCount}' WHERE `id` = {$GetACSRow['id']};", 'acs'); + if(!empty($MessagesToSend)) + { + $Message = false; + $Message['msg_id'] = '069'; + $Message['args'] = array + ( + $_User['username'], (($Fleet4ACS['fleet_end_type'] == 1) ? $_Lang['to_planet'] : $_Lang['to_moon']), + $Fleet4ACS['name'], $Fleet4ACS['fleet_end_galaxy'], $Fleet4ACS['fleet_end_system'], + $Fleet4ACS['fleet_end_galaxy'], $Fleet4ACS['fleet_end_system'], $Fleet4ACS['fleet_end_planet'], + (($Fleet4ACS['fleet_end_type'] == 1) ? $_Lang['to_this_planet'] : $_Lang['to_this_moon']), + $Fleet4ACS['fleet_end_galaxy'], $Fleet4ACS['fleet_end_system'], $Fleet4ACS['fleet_end_planet'], $Fleet4ACS['fleet_end_type'], + $GetACSRow['id'], $GetACSRow['name'] + ); + $Message = json_encode($Message); + Cache_Message($MessagesToSend, 0, '', 1, '007', '018', $Message); + } + + $ACSMsgCol = 'lime'; + $ACSMsg = $_Lang['fl_acs_changesSaved']; + } + } + } + } + } + + if(!empty($JSACSUsers)) + { + $_Lang['InsertACSUsers'] = json_encode($JSACSUsers); + foreach($JSACSUsers as $UserID => $UserData) + { + if($UserData['place'] == 1) + { + $Pointer = &$_Lang['UsersInvited']; + } + else + { + $Pointer = &$_Lang['Users2Invite']; + } + if($UserData['canmove'] === false OR $UserData['status'] == $_Lang['fl_acs_joined']) + { + $IsDisabled = ' disabled'; + } + else + { + $IsDisabled = ''; + } + if(!empty($UserData['status'])) + { + $Status = " ({$UserData['status']})"; + } + else + { + $Status = ''; + } + $Pointer .= ""; + } + } + + if(empty($GetACSRow['name'])) + { + $_Lang['ACSName'] = $_Lang['fl_acs_noname']; + } + else + { + $_Lang['ACSName'] = $GetACSRow['name']; + } + } + else + { + $ACSMsg = $_Lang['fl_acs_timeup']; + } + } + else + { + $ACSMsg = $_Lang['fl_acs_badmission']; + } + } + else + { + $ACSMsg = $_Lang['fl_acs_noexist']; + } + } + else + { + $ACSMsg = $_Lang['fl_acs_noid']; + } + + if(!empty($ACSMsg)) + { + $_Lang['P_HideACSMSG'] = ''; + $_Lang['P_ACSMSG'] = $ACSMsg; + $_Lang['P_ACSMSGCOL']= $ACSMsgCol; + } + else + { + $_Lang['P_HideACSMSG'] = $Hide; + } + + $_Lang['Insert_ACSForm'] = parsetemplate(gettemplate('fleet_acsform'), $_Lang); +} + +$_Lang['FlyingFleetsRows'] = preg_replace('#\{AddACSJoin\_[0-9]+\}#si', '', $_Lang['FlyingFleetsRows']); + +$_Lang['InsertJSShipSet'] = "var JSShipSet = false;"; +if(!isPro()) +{ + // Don't Allow to use this function to NonPro Players + $_GET['quickres'] = 0; +} +if(isset($_GET['quickres']) && $_GET['quickres'] == 1) +{ + $_Lang['P_SetQuickRes'] = '1'; + $TotalResStorage = floor($_Planet['metal']) + floor($_Planet['crystal']) + floor($_Planet['deuterium']); + $TotalShipsStorage[217] = $_Planet[$_Vars_GameElements[217]] * $_Vars_Prices[217]['capacity']; + $TotalShipsStorage[203] = $_Planet[$_Vars_GameElements[203]] * $_Vars_Prices[203]['capacity']; + $TotalShipsStorage[202] = $_Planet[$_Vars_GameElements[202]] * $_Vars_Prices[202]['capacity']; + $TotalShipsStorage['all'] = array_sum($TotalShipsStorage); + if($TotalResStorage >= $TotalShipsStorage['all']) + { + $JSSetShipsCount[217] = 'max'; + $JSSetShipsCount[203] = 'max'; + $JSSetShipsCount[202] = 'max'; + } + else + { + if($TotalResStorage >= $TotalShipsStorage[217]) + { + $JSSetShipsCount[217] = 'max'; + $TotalResStorage -= $TotalShipsStorage[217]; + if($TotalResStorage >= $TotalShipsStorage[203]) + { + $JSSetShipsCount[203] = 'max'; + $TotalResStorage -= $TotalShipsStorage[203]; + if($TotalResStorage >= $TotalShipsStorage[202]) + { + $JSSetShipsCount[202] = 'max'; + } + else + { + $JSSetShipsCount[202] = $TotalResStorage / $_Vars_Prices[202]['capacity']; + } + } + else + { + $JSSetShipsCount[203] = $TotalResStorage / $_Vars_Prices[203]['capacity']; + } + } + else + { + $JSSetShipsCount[217] = $TotalResStorage / $_Vars_Prices[217]['capacity']; + } + } + + if(!empty($JSSetShipsCount)) + { + $_Lang['InsertJSShipSet'] = "var JSShipSet = new Object;\n"; + foreach($JSSetShipsCount as $ShipID => $ShipCount) + { + $ShipCount = ceil($ShipCount); + if($_Planet[$_Vars_GameElements[$ShipID]] > 0) + { + if($ShipCount == 'max') + { + $ShipCount = $_Planet[$_Vars_GameElements[$ShipID]]; + } + else if($ShipCount > $_Planet[$_Vars_GameElements[$ShipID]]) + { + $ShipCount = $_Planet[$_Vars_GameElements[$ShipID]]; + } + $_Lang['InsertJSShipSet'] .= "JSShipSet['{$ShipID}'] = {$ShipCount};\n"; + } + } + } +} +else +{ + $_Lang['P_SetQuickRes'] = '0'; +} + +if(isset($_POST['gobackUsed'])) +{ + if(!empty($_POST['FleetArray'])) + { + $PostFleet = explode(';', $_POST['FleetArray']); + foreach($PostFleet as $Data) + { + if(!empty($Data)) + { + $Data = explode(',', $Data); + if(in_array($Data[0], $_Vars_ElementCategories['fleet'])) + { + $InsertShipCount[$Data[0]] = prettyNumber($Data[1]); + } + } + } + } +} + +foreach($_Vars_ElementCategories['fleet'] as $ID) +{ + if($_Planet[$_Vars_GameElements[$ID]] > 0) + { + if(empty($_Vars_Prices[$ID]['engine'])) + { + continue; + } + $ThisShip = array(); + + $ThisShip['ID'] = $ID; + $ThisShip['Speed'] = prettyNumber(GetFleetMaxSpeed(array(), $ID, $_User)); + $ThisShip['Name'] = $_Lang['tech'][$ID]; + $ThisShip['Count'] = prettyNumber($_Planet[$_Vars_GameElements[$ID]]); + if($ID == 210) + { + $ShipsData['storage'][$ID] = 0; + } + else + { + $ShipsData['storage'][$ID] = $_Vars_Prices[$ID]['capacity']; + } + $ShipsData['count'][$ID] = $_Planet[$_Vars_GameElements[$ID]]; + + $ThisShip['MaxCount'] = explode('.', sprintf('%f', floor($_Planet[$_Vars_GameElements[$ID]]))); + $ThisShip['MaxCount'] = (string)$ThisShip['MaxCount'][0]; + + if(!empty($InsertShipCount[$ID])) + { + $ThisShip['InsertShipCount'] = $InsertShipCount[$ID]; + } + else + { + $ThisShip['InsertShipCount'] = '0'; + } + + $_Lang['ShipsRow'] .= parsetemplate($ShipRowTPL, $ThisShip); + } +} +$_Lang['Insert_ShipsData'] = json_encode(isset($ShipsData) ? $ShipsData : null); + +$_Lang['P_HideNoSlotsInfo'] = $Hide; +$_Lang['P_HideSendShips'] = $Hide; +$_Lang['P_HideNoShipsInfo'] = $Hide; +if(!empty($_Lang['ShipsRow'])) +{ + if($FlyingFleetsCount >= $_Lang['P_MaxFleetSlots']) + { + $_Lang['P_HideNoSlotsInfo'] = ''; + } + else + { + $_Lang['P_HideSendShips'] = ''; + } +} +else +{ + $_Lang['P_HideNoShipsInfo'] = ''; +} + +$_Lang['ChronoAppletsScripts'] = $InsertChronoApplets; + +if(isset($_POST['gobackUsed'])) +{ + $GoBackVars = array + ( + 'speed' => $_POST['speed'], + ); + if(!empty($_POST['gobackVars'])) + { + $_Lang['P_GoBackVars'] = json_decode(base64_decode($_POST['gobackVars']), true); + if((array)$_Lang['P_GoBackVars'] === $_Lang['P_GoBackVars']) + { + $GoBackVars = array_merge($_Lang['P_GoBackVars'], $GoBackVars); + } + } + + $_Lang['SetJoiningACSID'] = (isset($_POST['getacsdata']) ? $_POST['getacsdata'] : null); + $_Lang['P_Galaxy'] = (isset($_POST['galaxy']) ? $_POST['galaxy'] : null); + $_Lang['P_System'] = (isset($_POST['system']) ? $_POST['system'] : null); + $_Lang['P_Planet'] = (isset($_POST['planet']) ? $_POST['planet'] : null); + $_Lang['P_PlType'] = (isset($_POST['planettype']) ? $_POST['planettype'] : null); + $_Lang['P_Mission'] = (isset($_POST['target_mission']) ? $_POST['target_mission'] : null); + $_Lang['P_SetQuickRes'] = (isset($_POST['quickres']) ? $_POST['quickres'] : null); + $_Lang['P_GoBackVars'] = base64_encode(json_encode($GoBackVars)); +} +else +{ + $_Lang['P_Galaxy'] = (isset($_GET['galaxy']) ? intval($_GET['galaxy']) : null); + $_Lang['P_System'] = (isset($_GET['system']) ? intval($_GET['system']) : null); + $_Lang['P_Planet'] = (isset($_GET['planet']) ? intval($_GET['planet']) : null); + $_Lang['P_PlType'] = (isset($_GET['planettype']) ? intval($_GET['planettype']) : null); + $_Lang['P_Mission'] = (isset($_GET['target_mission']) ? intval($_GET['target_mission']) : null); + if(isset($_GET['quickres'])) + { + if(isset($_GET['target_mission']) && $_GET['target_mission'] != 3) + { + if($_User['settings_mainPlanetID'] != $_Planet['id']) + { + $GetQuickResPlanet = doquery("SELECT `galaxy`, `system`, `planet` FROM {{table}} WHERE `id` = {$_User['settings_mainPlanetID']};", 'planets', true); + } + $_Lang['P_Galaxy'] = $GetQuickResPlanet['galaxy']; + $_Lang['P_System'] = $GetQuickResPlanet['system']; + $_Lang['P_Planet'] = $GetQuickResPlanet['planet']; + $_Lang['P_PlType'] = 1; + $_Lang['P_Mission'] = 3; + } + } +} + +if(!isPro()) +{ + $_Lang['P_HideQuickRes'] = 'hide'; +} + +$_Lang['P_TotalPlanetResources'] = (string)(floor($_Planet['metal']) + floor($_Planet['crystal']) + floor($_Planet['deuterium']) + 0); +if($_Lang['P_TotalPlanetResources'] == '0') +{ + $_Lang['P_StorageColor'] = 'lime'; +} +else +{ + $_Lang['P_StorageColor'] = 'orange'; +} + +$Page = parsetemplate($BodyTPL, $_Lang); +display($Page, $_Lang['fl_title']); + +?> diff --git a/fleet1.php b/fleet1.php index c6230c367..17a2140d4 100644 --- a/fleet1.php +++ b/fleet1.php @@ -1,398 +1,398 @@ - $_POST['resource1'], - 'resource2' => $_POST['resource2'], - 'resource3' => $_POST['resource3'], - 'usequantumgate' => (isset($_POST['usequantumgate']) ? $_POST['usequantumgate'] : null), - 'expeditiontime' => (isset($_POST['expeditiontime']) ? $_POST['expeditiontime'] : null), - 'holdingtime' => (isset($_POST['holdingtime']) ? $_POST['holdingtime'] : null) - ); - } - if(!empty($_POST['gobackVars'])) - { - $_Lang['P_GoBackVars'] = json_decode(base64_decode($_POST['gobackVars']), true); - if((array)$_Lang['P_GoBackVars'] === $_Lang['P_GoBackVars']) - { - if(!empty($GoBackVars)) - { - $GoBackVars = array_merge($GoBackVars, $_Lang['P_GoBackVars']); - } - else - { - $GoBackVars = $_Lang['P_GoBackVars']; - } - } - } - if(!empty($GoBackVars)) - { - $_Lang['P_GoBackVars'] = base64_encode(json_encode($GoBackVars)); - } - - if(!empty($_POST['gobackVars'])) - { - $_POST['gobackVars'] = json_decode(base64_decode($_POST['gobackVars']), true); - $_Set_DefaultSpeed = $_POST['gobackVars']['speed']; - } - - // Management of ShipsList - if(!empty($_POST['ship'])) - { - foreach($_POST['ship'] as $ShipID => $ShipCount) - { - $ShipID = intval($ShipID); - if(in_array($ShipID, $_Vars_ElementCategories['fleet'])) - { - if(!empty($_Vars_Prices[$ShipID]['engine'])) - { - $ShipCount = floor(str_replace('.', '', $ShipCount)); - if($ShipCount > 0) - { - if($_Planet[$_Vars_GameElements[$ShipID]] >= $ShipCount) - { - $Fleet['array'][$ShipID] = $ShipCount; - $Fleet['count'] += $ShipCount; - $ThisStorage = $_Vars_Prices[$ShipID]['capacity'] * $ShipCount; - if($ShipID != 210) - { - $Fleet['storage'] += $ThisStorage; - } - else - { - $Fleet['FuelStorage'] += $ThisStorage; - } - $speedalls[$ShipID] = GetFleetMaxSpeed('', $ShipID, $_User); - $FleetHiddenBlock .= ""; - $FleetHiddenBlock .= ""; - } - else - { - message($_Lang['fl1_NoEnoughShips'], $ErrorTitle, 'fleet.php', 3); - } - } - } - else - { - message($_Lang['fl1_CantSendUnflyable'], $ErrorTitle, 'fleet.php', 3); - } - } - else - { - message($_Lang['fl1_BadShipGiven'], $ErrorTitle, 'fleet.php', 3); - } - } - } - - if($Fleet['count'] <= 0) - { - message($_Lang['fl1_NoShipsGiven'], $ErrorTitle, 'fleet.php', 3); - } - $speedallsmin = min($speedalls); - - // Create SpeedsArray - $SpeedsAvailable = array - ( - 10 => 100, - 9 => 90, - 8 => 80, - 7 => 70, - 6 => 60, - 5 => 50, - 4 => 40, - 3 => 30, - 2 => 20, - 1 => 10 - ); - - if($_User['admiral_time'] > $Now) - { - $SpeedsAvailable[12] = 120; - $SpeedsAvailable[11] = 110; - $SpeedsAvailable['0.5'] = 5; - $SpeedsAvailable['0.25'] = 2.5; - } - if(MORALE_ENABLED) - { - $MaxAvailableSpeed = max($SpeedsAvailable); - if($_User['morale_level'] >= MORALE_BONUS_FLEETSPEEDUP1) - { - $SpeedsAvailable[(string)(($MaxAvailableSpeed + MORALE_BONUS_FLEETSPEEDUP1_VALUE) / 10)] = $MaxAvailableSpeed + MORALE_BONUS_FLEETSPEEDUP1_VALUE; - } - if($_User['morale_level'] >= MORALE_BONUS_FLEETSPEEDUP2) - { - $SpeedsAvailable[(string)(($MaxAvailableSpeed + MORALE_BONUS_FLEETSPEEDUP2_VALUE) / 10)] = $MaxAvailableSpeed + MORALE_BONUS_FLEETSPEEDUP2_VALUE; - } - - if($_User['morale_level'] <= MORALE_PENALTY_FLEETSLOWDOWN) - { - $speedallsmin *= MORALE_PENALTY_FLEETSLOWDOWN_VALUE; - } - } - arsort($SpeedsAvailable); - - $_Lang['P_HideACSJoining'] = $Hide; - $GetACSData = intval($_POST['getacsdata']); - $SetPosNotEmpty = false; - if($GetACSData > 0) - { - $ACSData = doquery("SELECT `id`, `name`, `end_galaxy`, `end_system`, `end_planet`, `end_type`, `start_time` FROM {{table}} WHERE `id` = {$GetACSData};", 'acs', true); - if($ACSData['id'] == $GetACSData) - { - if($ACSData['start_time'] > $Now) - { - $SetPos['g'] = $ACSData['end_galaxy']; - $SetPos['s'] = $ACSData['end_system']; - $SetPos['p'] = $ACSData['end_planet']; - $SetPos['t'] = $ACSData['end_type']; - - $SetPosNotEmpty = true; - $_Lang['P_HideACSJoining'] = ''; - $_Lang['fl1_ACSJoiningFleet'] = sprintf($_Lang['fl1_ACSJoiningFleet'], $ACSData['name'], $ACSData['end_galaxy'], $ACSData['end_system'], $ACSData['end_planet']); - $_Lang['P_DisableCoordSel'] = 'disabled'; - $_Lang['SelectedACSID'] = $GetACSData; - } - else - { - message($_Lang['fl1_ACSTimeUp'], $ErrorTitle, 'fleet.php', 3); - } - } - else - { - message($_Lang['fl1_ACSNoExist'], $ErrorTitle, 'fleet.php', 3); - } - } - - if($SetPosNotEmpty !== true) - { - $SetPos['g'] = intval($_POST['galaxy']); - $SetPos['s'] = intval($_POST['system']); - $SetPos['p'] = intval($_POST['planet']); - $SetPos['t'] = (isset($_POST['planet_type']) ? intval($_POST['planet_type']) : 0); - if(!in_array($SetPos['t'], array(1, 2, 3)) && isset($_POST['planettype'])) - { - $SetPos['t'] = intval($_POST['planettype']); - } - - if($SetPos['g'] < 1 OR $SetPos['g'] > MAX_GALAXY_IN_WORLD) - { - $SetPos['g'] = $_Planet['galaxy']; - } - if($SetPos['s'] < 1 OR $SetPos['s'] > MAX_SYSTEM_IN_GALAXY) - { - $SetPos['s'] = $_Planet['system']; - } - if($SetPos['p'] < 1 OR $SetPos['p'] > MAX_PLANET_IN_SYSTEM) - { - $SetPos['p'] = $_Planet['planet']; - } - if(!in_array($SetPos['t'], array(1, 2, 3))) - { - $SetPos['t'] = $_Planet['planet_type']; - } - - $_Lang['SetTargetMission'] = $_POST['target_mission']; - } - else - { - $_Lang['SetTargetMission'] = 2; - } - - // Fleet Blockade Info (here, only for Global Block) - $GetSFBData = doquery("SELECT `ID`, `EndTime`, `BlockMissions`, `DontBlockIfIdle`, `Reason` FROM {{table}} WHERE `Type` = 1 AND `StartTime` <= UNIX_TIMESTAMP() AND (`EndTime` > UNIX_TIMESTAMP() OR `PostEndTime` > UNIX_TIMESTAMP()) ORDER BY `EndTime` DESC LIMIT 1;", 'smart_fleet_blockade', true); - if($GetSFBData['ID'] > 0) - { - // Fleet Blockade is Active - include($_EnginePath.'includes/functions/CreateSFBInfobox.php'); - $_Lang['P_SFBInfobox'] = CreateSFBInfobox($GetSFBData, array('standAlone' => true, 'Width' => 750, 'MarginBottom' => 10)); - } - - $_Lang['FleetHiddenBlock'] = $FleetHiddenBlock; - $_Lang['speedallsmin'] = $speedallsmin; - $_Lang['MaxSpeedPretty'] = prettyNumber($speedallsmin); - $_Lang['Storage'] = (string)($Fleet['storage'] + 0); - $_Lang['FuelStorage'] = (string)($Fleet['FuelStorage'] + 0); - $_Lang['ThisGalaxy'] = $_Planet['galaxy']; - $_Lang['ThisSystem'] = $_Planet['system']; - $_Lang['ThisPlanet'] = $_Planet['planet']; - $_Lang['GalaxyEnd'] = intval($_POST['galaxy']); - $_Lang['SystemEnd'] = intval($_POST['system']); - $_Lang['PlanetEnd'] = intval($_POST['planet']); - $_Lang['SpeedFactor'] = GetGameSpeedFactor(); - $_Lang['ThisPlanetType'] = $_Planet['planet_type']; - $_Lang['ThisResource3'] = (string)(floor($_Planet['deuterium']) + 0); - foreach($Fleet['array'] as $ID => $Count) - { - $_Lang['FleetArray'][] = $ID.','.$Count; - } - $_Lang['FleetArray'] = implode(';', $_Lang['FleetArray']); - if($_POST['quickres'] == '1') - { - $_Lang['P_SetQuickRes'] = '1'; - } - else - { - $_Lang['P_SetQuickRes'] = '0'; - } - - $_Lang['P_MaxGalaxy'] = MAX_GALAXY_IN_WORLD; - $_Lang['P_MaxSystem'] = MAX_SYSTEM_IN_GALAXY; - $_Lang['P_MaxPlanet'] = MAX_PLANET_IN_SYSTEM + 1; - - foreach($SetPos as $Key => $Value) - { - if($Key == 't') - { - $_Lang['SetPos_Type'.$Value.'Selected'] = 'selected'; - continue; - } - $_Lang['SetPos_'.$Key] = $Value; - } - - if(empty($_Set_DefaultSpeed) OR !in_array($_Set_DefaultSpeed, array_keys($SpeedsAvailable))) - { - $_Set_DefaultSpeed = max(array_keys($SpeedsAvailable)); - } - $_Lang['Insert_SpeedInput'] = $_Set_DefaultSpeed; - - foreach($SpeedsAvailable as $Selector => $Text) - { - $_Lang['Insert_Speeds'][] = "{$Text}"; - } - $_Lang['Insert_Speeds'] = implode('|', $_Lang['Insert_Speeds']); - - // Create Colony List and Shortcuts List (dropdown) - $OtherPlanets = SortUserPlanets($_User); - $Shortcuts = doquery("SELECT {{table}}.*, IF(`planets`.`id` > 0, `planets`.`name`, '') AS `name`, IF(`planets`.`id` > 0, `planets`.`galaxy`, {{table}}.galaxy) AS `galaxy`, IF(`planets`.`id` > 0, `planets`.`system`, {{table}}.system) AS `system`, IF(`planets`.`id` > 0, `planets`.`planet`, {{table}}.planet) AS `planet`, IF(`planets`.`id` > 0, `planets`.`planet_type`, {{table}}.type) AS `planet_type` FROM {{table}} LEFT JOIN {{prefix}}planets as `planets` ON `planets`.`id` = {{table}}.`id_planet` WHERE {{table}}.`id_owner` = {$_User['id']} ORDER BY {{table}}.id ASC;", 'fleet_shortcuts'); - - if(mysql_num_rows($OtherPlanets) > 1) - { - while($PlanetData = mysql_fetch_assoc($OtherPlanets)) - { - if($PlanetData['galaxy'] == $_Planet['galaxy'] AND $PlanetData['system'] == $_Planet['system'] AND $PlanetData['planet'] == $_Planet['planet'] AND $PlanetData['planet_type'] == $_Planet['planet_type']) - { - // Do nothing, we don't want current planet on this list - } - else - { - $OtherPlanetsList[] = array - ( - 'txt' => $PlanetData['name'].' '.(($PlanetData['planet_type'] == 3) ? '('.$_Lang['DropdownList_Moon_sign'].') ' : '')."[{$PlanetData['galaxy']}:{$PlanetData['system']}:{$PlanetData['planet']}]", - 'js' => "{$PlanetData['galaxy']},{$PlanetData['system']},{$PlanetData['planet']},{$PlanetData['planet_type']}" - ); - } - } - } - - if(mysql_num_rows($Shortcuts) > 0) - { - while($Data = mysql_fetch_assoc($Shortcuts)) - { - $ShortcutList[] = array - ( - 'txt' => ((!empty($Data['own_name']) ? $Data['own_name'].' - ' : '')).$Data['name'].(($Data['planet_type'] == 3) ? ' ('.$_Lang['moon_sign'].')' : (($Data['planet_type'] == 2) ? ' ('.$_Lang['debris_sign'].')' : ''))." [{$Data['galaxy']}:{$Data['system']}:{$Data['planet']}]", - 'js' => "{$Data['galaxy']},{$Data['system']},{$Data['planet']},{$Data['planet_type']}" - ); - } - } - - $_Lang['P_HideFastLinks'] = $Hide; - $_Lang['P_HideNoFastLinks'] = $Hide; - - if(!empty($OtherPlanetsList) OR !empty($ShortcutList)) - { - $_Lang['P_HideFastLinks'] = ''; - - if(!empty($OtherPlanetsList)) - { - $_Lang['FastLinks_Planets'] = ''; - } - else - { - $_Lang['FastLinks_Planets'] = $_Lang['fl_no_planets']; - } - - if(!empty($ShortcutList)) - { - $_Lang['FastLinks_ShortCuts'] = ''; - } - else - { - $_Lang['FastLinks_ShortCuts'] = $_Lang['fl_no_shortcuts']; - } - } - else - { - $_Lang['P_HideNoFastLinks'] = ''; - } - - $Page = parsetemplate(gettemplate('fleet1_body'), $_Lang); - display($Page, $_Lang['fl_title']); - -?> \ No newline at end of file + $_POST['resource1'], + 'resource2' => $_POST['resource2'], + 'resource3' => $_POST['resource3'], + 'usequantumgate' => (isset($_POST['usequantumgate']) ? $_POST['usequantumgate'] : null), + 'expeditiontime' => (isset($_POST['expeditiontime']) ? $_POST['expeditiontime'] : null), + 'holdingtime' => (isset($_POST['holdingtime']) ? $_POST['holdingtime'] : null) + ); +} +if(!empty($_POST['gobackVars'])) +{ + $_Lang['P_GoBackVars'] = json_decode(base64_decode($_POST['gobackVars']), true); + if((array)$_Lang['P_GoBackVars'] === $_Lang['P_GoBackVars']) + { + if(!empty($GoBackVars)) + { + $GoBackVars = array_merge($GoBackVars, $_Lang['P_GoBackVars']); + } + else + { + $GoBackVars = $_Lang['P_GoBackVars']; + } + } +} +if(!empty($GoBackVars)) +{ + $_Lang['P_GoBackVars'] = base64_encode(json_encode($GoBackVars)); +} + +if(!empty($_POST['gobackVars'])) +{ + $_POST['gobackVars'] = json_decode(base64_decode($_POST['gobackVars']), true); + $_Set_DefaultSpeed = $_POST['gobackVars']['speed']; +} + +// Management of ShipsList +if(!empty($_POST['ship'])) +{ + foreach($_POST['ship'] as $ShipID => $ShipCount) + { + $ShipID = intval($ShipID); + if(in_array($ShipID, $_Vars_ElementCategories['fleet'])) + { + if(!empty($_Vars_Prices[$ShipID]['engine'])) + { + $ShipCount = floor(str_replace('.', '', $ShipCount)); + if($ShipCount > 0) + { + if($_Planet[$_Vars_GameElements[$ShipID]] >= $ShipCount) + { + $Fleet['array'][$ShipID] = $ShipCount; + $Fleet['count'] += $ShipCount; + $ThisStorage = $_Vars_Prices[$ShipID]['capacity'] * $ShipCount; + if($ShipID != 210) + { + $Fleet['storage'] += $ThisStorage; + } + else + { + $Fleet['FuelStorage'] += $ThisStorage; + } + $speedalls[$ShipID] = GetFleetMaxSpeed('', $ShipID, $_User); + $FleetHiddenBlock .= ""; + $FleetHiddenBlock .= ""; + } + else + { + message($_Lang['fl1_NoEnoughShips'], $ErrorTitle, 'fleet.php', 3); + } + } + } + else + { + message($_Lang['fl1_CantSendUnflyable'], $ErrorTitle, 'fleet.php', 3); + } + } + else + { + message($_Lang['fl1_BadShipGiven'], $ErrorTitle, 'fleet.php', 3); + } + } +} + +if($Fleet['count'] <= 0) +{ + message($_Lang['fl1_NoShipsGiven'], $ErrorTitle, 'fleet.php', 3); +} +$speedallsmin = min($speedalls); + +// Create SpeedsArray +$SpeedsAvailable = array +( + 10 => 100, + 9 => 90, + 8 => 80, + 7 => 70, + 6 => 60, + 5 => 50, + 4 => 40, + 3 => 30, + 2 => 20, + 1 => 10 +); + +if($_User['admiral_time'] > $Now) +{ + $SpeedsAvailable[12] = 120; + $SpeedsAvailable[11] = 110; + $SpeedsAvailable['0.5'] = 5; + $SpeedsAvailable['0.25'] = 2.5; +} +if(MORALE_ENABLED) +{ + $MaxAvailableSpeed = max($SpeedsAvailable); + if($_User['morale_level'] >= MORALE_BONUS_FLEETSPEEDUP1) + { + $SpeedsAvailable[(string)(($MaxAvailableSpeed + MORALE_BONUS_FLEETSPEEDUP1_VALUE) / 10)] = $MaxAvailableSpeed + MORALE_BONUS_FLEETSPEEDUP1_VALUE; + } + if($_User['morale_level'] >= MORALE_BONUS_FLEETSPEEDUP2) + { + $SpeedsAvailable[(string)(($MaxAvailableSpeed + MORALE_BONUS_FLEETSPEEDUP2_VALUE) / 10)] = $MaxAvailableSpeed + MORALE_BONUS_FLEETSPEEDUP2_VALUE; + } + + if($_User['morale_level'] <= MORALE_PENALTY_FLEETSLOWDOWN) + { + $speedallsmin *= MORALE_PENALTY_FLEETSLOWDOWN_VALUE; + } +} +arsort($SpeedsAvailable); + +$_Lang['P_HideACSJoining'] = $Hide; +$GetACSData = intval($_POST['getacsdata']); +$SetPosNotEmpty = false; +if($GetACSData > 0) +{ + $ACSData = doquery("SELECT `id`, `name`, `end_galaxy`, `end_system`, `end_planet`, `end_type`, `start_time` FROM {{table}} WHERE `id` = {$GetACSData};", 'acs', true); + if($ACSData['id'] == $GetACSData) + { + if($ACSData['start_time'] > $Now) + { + $SetPos['g'] = $ACSData['end_galaxy']; + $SetPos['s'] = $ACSData['end_system']; + $SetPos['p'] = $ACSData['end_planet']; + $SetPos['t'] = $ACSData['end_type']; + + $SetPosNotEmpty = true; + $_Lang['P_HideACSJoining'] = ''; + $_Lang['fl1_ACSJoiningFleet'] = sprintf($_Lang['fl1_ACSJoiningFleet'], $ACSData['name'], $ACSData['end_galaxy'], $ACSData['end_system'], $ACSData['end_planet']); + $_Lang['P_DisableCoordSel'] = 'disabled'; + $_Lang['SelectedACSID'] = $GetACSData; + } + else + { + message($_Lang['fl1_ACSTimeUp'], $ErrorTitle, 'fleet.php', 3); + } + } + else + { + message($_Lang['fl1_ACSNoExist'], $ErrorTitle, 'fleet.php', 3); + } +} + +if($SetPosNotEmpty !== true) +{ + $SetPos['g'] = intval($_POST['galaxy']); + $SetPos['s'] = intval($_POST['system']); + $SetPos['p'] = intval($_POST['planet']); + $SetPos['t'] = (isset($_POST['planet_type']) ? intval($_POST['planet_type']) : 0); + if(!in_array($SetPos['t'], array(1, 2, 3)) && isset($_POST['planettype'])) + { + $SetPos['t'] = intval($_POST['planettype']); + } + + if($SetPos['g'] < 1 OR $SetPos['g'] > MAX_GALAXY_IN_WORLD) + { + $SetPos['g'] = $_Planet['galaxy']; + } + if($SetPos['s'] < 1 OR $SetPos['s'] > MAX_SYSTEM_IN_GALAXY) + { + $SetPos['s'] = $_Planet['system']; + } + if($SetPos['p'] < 1 OR $SetPos['p'] > MAX_PLANET_IN_SYSTEM) + { + $SetPos['p'] = $_Planet['planet']; + } + if(!in_array($SetPos['t'], array(1, 2, 3))) + { + $SetPos['t'] = $_Planet['planet_type']; + } + + $_Lang['SetTargetMission'] = $_POST['target_mission']; +} +else +{ + $_Lang['SetTargetMission'] = 2; +} + +// Fleet Blockade Info (here, only for Global Block) +$GetSFBData = doquery("SELECT `ID`, `EndTime`, `BlockMissions`, `DontBlockIfIdle`, `Reason` FROM {{table}} WHERE `Type` = 1 AND `StartTime` <= UNIX_TIMESTAMP() AND (`EndTime` > UNIX_TIMESTAMP() OR `PostEndTime` > UNIX_TIMESTAMP()) ORDER BY `EndTime` DESC LIMIT 1;", 'smart_fleet_blockade', true); +if($GetSFBData['ID'] > 0) +{ + // Fleet Blockade is Active + include($_EnginePath.'includes/functions/CreateSFBInfobox.php'); + $_Lang['P_SFBInfobox'] = CreateSFBInfobox($GetSFBData, array('standAlone' => true, 'Width' => 750, 'MarginBottom' => 10)); +} + +$_Lang['FleetHiddenBlock'] = $FleetHiddenBlock; +$_Lang['speedallsmin'] = $speedallsmin; +$_Lang['MaxSpeedPretty'] = prettyNumber($speedallsmin); +$_Lang['Storage'] = (string)($Fleet['storage'] + 0); +$_Lang['FuelStorage'] = (string)($Fleet['FuelStorage'] + 0); +$_Lang['ThisGalaxy'] = $_Planet['galaxy']; +$_Lang['ThisSystem'] = $_Planet['system']; +$_Lang['ThisPlanet'] = $_Planet['planet']; +$_Lang['GalaxyEnd'] = intval($_POST['galaxy']); +$_Lang['SystemEnd'] = intval($_POST['system']); +$_Lang['PlanetEnd'] = intval($_POST['planet']); +$_Lang['SpeedFactor'] = GetGameSpeedFactor(); +$_Lang['ThisPlanetType'] = $_Planet['planet_type']; +$_Lang['ThisResource3'] = (string)(floor($_Planet['deuterium']) + 0); +foreach($Fleet['array'] as $ID => $Count) +{ + $_Lang['FleetArray'][] = $ID.','.$Count; +} +$_Lang['FleetArray'] = implode(';', $_Lang['FleetArray']); +if($_POST['quickres'] == '1') +{ + $_Lang['P_SetQuickRes'] = '1'; +} +else +{ + $_Lang['P_SetQuickRes'] = '0'; +} + +$_Lang['P_MaxGalaxy'] = MAX_GALAXY_IN_WORLD; +$_Lang['P_MaxSystem'] = MAX_SYSTEM_IN_GALAXY; +$_Lang['P_MaxPlanet'] = MAX_PLANET_IN_SYSTEM + 1; + +foreach($SetPos as $Key => $Value) +{ + if($Key == 't') + { + $_Lang['SetPos_Type'.$Value.'Selected'] = 'selected'; + continue; + } + $_Lang['SetPos_'.$Key] = $Value; +} + +if(empty($_Set_DefaultSpeed) OR !in_array($_Set_DefaultSpeed, array_keys($SpeedsAvailable))) +{ + $_Set_DefaultSpeed = max(array_keys($SpeedsAvailable)); +} +$_Lang['Insert_SpeedInput'] = $_Set_DefaultSpeed; + +foreach($SpeedsAvailable as $Selector => $Text) +{ + $_Lang['Insert_Speeds'][] = "{$Text}"; +} +$_Lang['Insert_Speeds'] = implode('|', $_Lang['Insert_Speeds']); + +// Create Colony List and Shortcuts List (dropdown) +$OtherPlanets = SortUserPlanets($_User); +$Shortcuts = doquery("SELECT {{table}}.*, IF(`planets`.`id` > 0, `planets`.`name`, '') AS `name`, IF(`planets`.`id` > 0, `planets`.`galaxy`, {{table}}.galaxy) AS `galaxy`, IF(`planets`.`id` > 0, `planets`.`system`, {{table}}.system) AS `system`, IF(`planets`.`id` > 0, `planets`.`planet`, {{table}}.planet) AS `planet`, IF(`planets`.`id` > 0, `planets`.`planet_type`, {{table}}.type) AS `planet_type` FROM {{table}} LEFT JOIN {{prefix}}planets as `planets` ON `planets`.`id` = {{table}}.`id_planet` WHERE {{table}}.`id_owner` = {$_User['id']} ORDER BY {{table}}.id ASC;", 'fleet_shortcuts'); + +if(mysql_num_rows($OtherPlanets) > 1) +{ + while($PlanetData = mysql_fetch_assoc($OtherPlanets)) + { + if($PlanetData['galaxy'] == $_Planet['galaxy'] AND $PlanetData['system'] == $_Planet['system'] AND $PlanetData['planet'] == $_Planet['planet'] AND $PlanetData['planet_type'] == $_Planet['planet_type']) + { + // Do nothing, we don't want current planet on this list + } + else + { + $OtherPlanetsList[] = array + ( + 'txt' => $PlanetData['name'].' '.(($PlanetData['planet_type'] == 3) ? '('.$_Lang['DropdownList_Moon_sign'].') ' : '')."[{$PlanetData['galaxy']}:{$PlanetData['system']}:{$PlanetData['planet']}]", + 'js' => "{$PlanetData['galaxy']},{$PlanetData['system']},{$PlanetData['planet']},{$PlanetData['planet_type']}" + ); + } + } +} + +if(mysql_num_rows($Shortcuts) > 0) +{ + while($Data = mysql_fetch_assoc($Shortcuts)) + { + $ShortcutList[] = array + ( + 'txt' => ((!empty($Data['own_name']) ? $Data['own_name'].' - ' : '')).$Data['name'].(($Data['planet_type'] == 3) ? ' ('.$_Lang['moon_sign'].')' : (($Data['planet_type'] == 2) ? ' ('.$_Lang['debris_sign'].')' : ''))." [{$Data['galaxy']}:{$Data['system']}:{$Data['planet']}]", + 'js' => "{$Data['galaxy']},{$Data['system']},{$Data['planet']},{$Data['planet_type']}" + ); + } +} + +$_Lang['P_HideFastLinks'] = $Hide; +$_Lang['P_HideNoFastLinks'] = $Hide; + +if(!empty($OtherPlanetsList) OR !empty($ShortcutList)) +{ + $_Lang['P_HideFastLinks'] = ''; + + if(!empty($OtherPlanetsList)) + { + $_Lang['FastLinks_Planets'] = ''; + } + else + { + $_Lang['FastLinks_Planets'] = $_Lang['fl_no_planets']; + } + + if(!empty($ShortcutList)) + { + $_Lang['FastLinks_ShortCuts'] = ''; + } + else + { + $_Lang['FastLinks_ShortCuts'] = $_Lang['fl_no_shortcuts']; + } +} +else +{ + $_Lang['P_HideNoFastLinks'] = ''; +} + +$Page = parsetemplate(gettemplate('fleet1_body'), $_Lang); +display($Page, $_Lang['fl_title']); + +?> diff --git a/fleet2.php b/fleet2.php index 43c2ee2f4..549f7242f 100644 --- a/fleet2.php +++ b/fleet2.php @@ -1,663 +1,663 @@ - (isset($_POST['gobackVars']['resource1']) ? $_POST['gobackVars']['resource1'] : null), - 'resource2' => (isset($_POST['gobackVars']['resource2']) ? $_POST['gobackVars']['resource2'] : null), - 'resource3' => (isset($_POST['gobackVars']['resource3']) ? $_POST['gobackVars']['resource3'] : null) - )); - if(isset($_POST['gobackVars']['usequantumgate']) && $_POST['gobackVars']['usequantumgate'] == 'on') - { - $_Lang['SelectQuantumGate'] = 'true'; - } - } - - includeLang('fleet'); - - $QuantumGateInterval = QUANTUMGATE_INTERVAL_HOURS; - $Now = time(); - $ErrorTitle = &$_Lang['fl_error']; - $Hide = ' class="hide"'; - - $_Lang['MissionSelectors'] = ''; - - if(MORALE_ENABLED) - { - Morale_ReCalculate($_User, $Now); - } - - // Check, if Target Data are correct - $Target['galaxy'] = (isset($_POST['galaxy']) ? intval($_POST['galaxy']) : null); - $Target['system'] = (isset($_POST['system']) ? intval($_POST['system']) : null); - $Target['planet'] = (isset($_POST['planet']) ? intval($_POST['planet']) : null); - $Target['type'] = (isset($_POST['planettype']) ? intval($_POST['planettype']) : null); - - $GetACSData = intval($_POST['getacsdata']); - if($GetACSData > 0) - { - $ACSData = doquery("SELECT `id`, `name`, `end_galaxy`, `end_system`, `end_planet`, `end_type`, `start_time` FROM {{table}} WHERE `id` = {$GetACSData};", 'acs', true); - if($ACSData['id'] == $GetACSData) - { - if($ACSData['start_time'] > $Now) - { - $Target['galaxy'] = $ACSData['end_galaxy']; - $Target['system'] = $ACSData['end_system']; - $Target['planet'] = $ACSData['end_planet']; - $Target['type'] = $ACSData['end_type']; - } - else - { - message($_Lang['fl1_ACSTimeUp'], $ErrorTitle, 'fleet.php', 3); - } - } - else - { - message($_Lang['fl1_ACSNoExist'], $ErrorTitle, 'fleet.php', 3); - } - } - - if($Target['galaxy'] == $_Planet['galaxy'] AND $Target['system'] == $_Planet['system'] AND $Target['planet'] == $_Planet['planet'] AND $Target['type'] == $_Planet['planet_type']) - { - message($_Lang['fl2_cantsendsamecoords'], $ErrorTitle, 'fleet.php', 3); - } - - foreach($Target as $Type => $Value) - { - if($Value < 1) - { - $TargetError = true; - break; - } - switch($Type) - { - case 'galaxy': - $CheckValue = MAX_GALAXY_IN_WORLD; - break; - case 'system': - $CheckValue = MAX_SYSTEM_IN_GALAXY; - break; - case 'planet': - $CheckValue = MAX_PLANET_IN_SYSTEM + 1; - break; - case 'type': - $CheckValue = 3; - break; - } - if($Value > $CheckValue) - { - $TargetError = true; - break; - } - // Set Positions for Inputs - $_Lang['Target_'.$Type] = $Value; - } - if(isset($TargetError)) - { - message($_Lang['fl2_targeterror'], $ErrorTitle, 'fleet.php', 3); - } - - // Create SpeedsArray - $SpeedsAvailable = array(10, 9, 8, 7, 6, 5, 4, 3, 2, 1); - - if($_User['admiral_time'] > $Now) - { - $SpeedsAvailable[] = 12; - $SpeedsAvailable[] = 11; - $SpeedsAvailable[] = 0.5; - $SpeedsAvailable[] = 0.25; - } - if(MORALE_ENABLED) - { - $MaxAvailableSpeed = max($SpeedsAvailable); - if($_User['morale_level'] >= MORALE_BONUS_FLEETSPEEDUP1) - { - $SpeedsAvailable[] = $MaxAvailableSpeed + (MORALE_BONUS_FLEETSPEEDUP1_VALUE / 10); - } - if($_User['morale_level'] >= MORALE_BONUS_FLEETSPEEDUP2) - { - $SpeedsAvailable[] = $MaxAvailableSpeed + (MORALE_BONUS_FLEETSPEEDUP2_VALUE / 10); - } - } - if(!in_array($_POST['speed'], $SpeedsAvailable)) - { - message($_Lang['fl_bad_fleet_speed'], $ErrorTitle, 'fleet.php', 3); - } - - // Check PlanetOwner - $YourPlanet = false; - $UsedPlanet = false; - $OwnerFriend = false; - $OwnerHasMarcantilePact = false; - $AllyPactWarning = false; - $CheckPlanetOwnerQuery = ''; - $CheckPlanetOwnerQuery .= "SELECT `planets`.`id`, `planets`.`id_owner` AS `owner`, `planets`.`name` AS `name`, `quantumgate`, "; - $CheckPlanetOwnerQuery .= "`users`.`ally_id`, `users`.`username` as `username`, `buddy1`.`active` AS `active1`, `buddy2`.`active` AS `active2` "; - if($_User['ally_id'] > 0) - { - $CheckPlanetOwnerQuery .= ", `apact1`.`Type` AS `AllyPact1`, `apact2`.`Type` AS `AllyPact2` "; - } - $CheckPlanetOwnerQuery .= "FROM {{table}} AS `planets` "; - $CheckPlanetOwnerQuery .= "LEFT JOIN `{{prefix}}buddy` AS `buddy1` ON (`planets`.`id_owner` = `buddy1`.`sender` AND `buddy1`.`owner` = {$_User['id']}) "; - $CheckPlanetOwnerQuery .= "LEFT JOIN `{{prefix}}buddy` AS `buddy2` ON (`planets`.`id_owner` = `buddy2`.`owner` AND `buddy2`.`sender` = {$_User['id']}) "; - $CheckPlanetOwnerQuery .= "LEFT JOIN `{{prefix}}users` AS `users` ON `planets`.`id_owner` = `users`.`id` "; - if($_User['ally_id'] > 0) - { - $CheckPlanetOwnerQuery .= "LEFT JOIN `{{prefix}}ally_pacts` AS `apact1` ON (`apact1`.`AllyID_Sender` = {$_User['ally_id']} AND `apact1`.`AllyID_Owner` = `users`.`ally_id` AND `apact1`.`Active` = 1) "; - $CheckPlanetOwnerQuery .= "LEFT JOIN `{{prefix}}ally_pacts` AS `apact2` ON (`apact2`.`AllyID_Sender` = `users`.`ally_id` AND `apact2`.`AllyID_Owner` = {$_User['ally_id']} AND `apact2`.`Active` = 1) "; - } - $CheckPlanetOwnerQuery .= "WHERE `planets`.`galaxy` = {$Target['galaxy']} AND `planets`.`system` = {$Target['system']} AND `planets`.`planet` = {$Target['planet']} AND `planets`.`planet_type` = {$Target['type']} "; - $CheckPlanetOwnerQuery .= "LIMIT 1;"; - $CheckPlanetOwner = doquery($CheckPlanetOwnerQuery, 'planets'); - - if(mysql_num_rows($CheckPlanetOwner) == 1) - { - $CheckPlanetOwner = mysql_fetch_assoc($CheckPlanetOwner); - $UsedPlanet = true; - if($CheckPlanetOwner['owner'] == $_User['id']) - { - $YourPlanet = true; - } - else - { - if(!empty($_GameConfig['TestUsersIDs'])) - { - $TestUsersArray = explode(',', $_GameConfig['TestUsersIDs']); - if(in_array($CheckPlanetOwner['owner'], $TestUsersArray)) - { - $EnableTestAccWarning = true; - } - } - if((isset($CheckPlanetOwner['AllyPact1']) && $CheckPlanetOwner['AllyPact1'] >= ALLYPACT_NONAGGRESSION) || (isset($CheckPlanetOwner['AllyPact2']) && $CheckPlanetOwner['AllyPact2'] >= ALLYPACT_NONAGGRESSION)) - { - $AllyPactWarning = true; - } - if((isset($CheckPlanetOwner['AllyPact1']) && $CheckPlanetOwner['AllyPact1'] >= ALLYPACT_MERCANTILE) || (isset($CheckPlanetOwner['AllyPact2']) && $CheckPlanetOwner['AllyPact2'] >= ALLYPACT_MERCANTILE)) - { - $OwnerHasMarcantilePact = true; - } - if(($CheckPlanetOwner['active1'] == 1 OR $CheckPlanetOwner['active2'] == 1) OR ($CheckPlanetOwner['ally_id'] == $_User['ally_id'] AND $_User['ally_id'] > 0) OR ((isset($CheckPlanetOwner['AllyPact1']) && $CheckPlanetOwner['AllyPact1'] >= ALLYPACT_DEFENSIVE) || (isset($CheckPlanetOwner['AllyPact2']) && $CheckPlanetOwner['AllyPact2'] >= ALLYPACT_DEFENSIVE))) - { - $OwnerFriend = true; - } - } - } - - // Parse Fleet Array - $Fleet['count'] = 0; - $Fleet['storage'] = 0; - $Fleet['FuelStorage'] = 0; - - $Fleet['array'] = explode(';', $_POST['FleetArray']); - $FleetArray = array(); - if(!empty($Fleet['array']) AND (array)$Fleet['array'] === $Fleet['array']) - { - foreach($Fleet['array'] as $ShipData) - { - $ShipData = explode(',', $ShipData); - $ShipID = intval($ShipData[0]); - if(in_array($ShipID, $_Vars_ElementCategories['fleet'])) - { - if(!empty($_Vars_Prices[$ShipID]['engine'])) - { - $ShipCount = floor($ShipData[1]); - if($ShipCount > 0) - { - if($_Planet[$_Vars_GameElements[$ShipID]] >= $ShipCount) - { - $FleetArray[$ShipID] = $ShipCount; - $Fleet['count'] += $ShipCount; - $ThisStorage = $_Vars_Prices[$ShipID]['capacity'] * $ShipCount; - if($ShipID != 210) - { - $Fleet['storage'] += $ThisStorage; - } - else - { - $Fleet['FuelStorage'] += $ThisStorage; - } - } - else - { - message($_Lang['fl1_NoEnoughShips'], $ErrorTitle, 'fleet.php', 3); - } - } - else - { - message($_Lang['fl2_ShipCountCantBe0'], $ErrorTitle, 'fleet.php', 3); - } - } - else - { - message($_Lang['fl1_CantSendUnflyable'], $ErrorTitle, 'fleet.php', 3); - } - } - else - { - message($_Lang['fl1_BadShipGiven'], $ErrorTitle, 'fleet.php', 3); - } - } - } - else - { - message($_Lang['fl2_FleetArrayPostEmpty'], $ErrorTitle, 'fleet.php', 3); - } - if($Fleet['count'] <= 0) - { - message($_Lang['fl2_ZeroShips'], $ErrorTitle, 'fleet.php', 3); - } - $Fleet['array'] = $FleetArray; - unset($FleetArray); - - // Create Array of Available Missions - $AvailableMissions = array(); - if($Target['type'] == 2) - { - if($Fleet['array'][209] > 0) - { - $AvailableMissions[] = 8; - } - } - else - { - if($UsedPlanet) - { - if(!isset($Fleet['array'][210]) || $Fleet['count'] > $Fleet['array'][210]) - { - $AvailableMissions[] = 3; - } - if(!$YourPlanet) - { - $AvailableMissions[] = 1; - if($OwnerFriend) - { - $AvailableMissions[] = 5; - } - if(isset($Fleet['array'][210]) && $Fleet['count'] == $Fleet['array'][210]) - { - $AvailableMissions[] = 6; - } - if($Target['type'] == 3 && isset($Fleet['array'][214]) && $Fleet['array'][214] > 0) - { - $AvailableMissions[] = 9; - } - } - else - { - $AvailableMissions[] = 4; - } - } - else - { - if($Target['planet'] == (MAX_PLANET_IN_SYSTEM + 1)) - { - $AvailableMissions[] = 15; - } - else - { - if($Fleet['array'][208] > 0 AND $Target['type'] == 1) - { - $AvailableMissions[] = 7; - } - } - } - } - - if(in_array(1, $AvailableMissions)) - { - $CheckACS = doquery("SELECT * FROM {{table}} WHERE (`users` LIKE '%|{$_User['id']}|%' OR `owner_id` = {$_User['id']}) AND `end_target_id` = {$CheckPlanetOwner['id']} AND `start_time` > UNIX_TIMESTAMP();", 'acs'); - if(mysql_num_rows($CheckACS) > 0) - { - while($ACSData = mysql_fetch_assoc($CheckACS)) - { - $ACSData['fleets_count'] += 1; - $ACSList[$ACSData['id']] = "{$ACSData['name']} ({$_Lang['fl_acs_fleets']}: {$ACSData['fleets_count']})"; - } - $AvailableMissions[] = 2; - } - } - - $allowUseQuantumGate = false; - if(!empty($AvailableMissions)) - { - if($_Planet['quantumgate'] == 1) - { - if(($YourPlanet OR $OwnerFriend OR $OwnerHasMarcantilePact) AND $CheckPlanetOwner['quantumgate'] == 1 AND (in_array(3, $AvailableMissions) OR in_array(4, $AvailableMissions) OR in_array(5, $AvailableMissions))) - { - $allowUseQuantumGate = true; - $allowGateJump = true; - } - else - { - if($_Planet['galaxy'] == $Target['galaxy']) - { - if(($_Planet['quantumgate_lastuse'] + ($QuantumGateInterval * 3600)) <= $Now) - { - $allowUseQuantumGate = true; - } - } - } - } - } - - $PreSelectedMission = intval($_POST['target_mission']); - $SpeedFactor = GetGameSpeedFactor(); - $AllFleetSpeed = GetFleetMaxSpeed($Fleet['array'], 0, $_User); - $GenFleetSpeed = $_POST['speed']; - $MaxFleetSpeed = min($AllFleetSpeed); - if(MORALE_ENABLED) - { - if($_User['morale_level'] <= MORALE_PENALTY_FLEETSLOWDOWN) - { - $MaxFleetSpeed *= MORALE_PENALTY_FLEETSLOWDOWN_VALUE; - } - } - $distance = GetTargetDistance($_Planet['galaxy'], $Target['galaxy'], $_Planet['system'], $Target['system'], $_Planet['planet'], $Target['planet']); - $duration = GetMissionDuration($GenFleetSpeed, $MaxFleetSpeed, $distance, $SpeedFactor); - $consumption = GetFleetConsumption($Fleet['array'], $SpeedFactor, $duration, $distance, $_User); - - if($_Planet['deuterium'] < $consumption) - { - if($allowUseQuantumGate) - { - if($allowGateJump OR $_Planet['deuterium'] > ($consumption / 2)) - { - $AllowNoEnoughDeuterium = true; - $_Lang['P_UserHave2UseQuantumGate'] = '1'; - } - } - if(!isset($AllowNoEnoughDeuterium)) - { - message($_Lang['fl2_NoEnoughFuel'], $ErrorTitle, 'fleet.php', 3); - } - } - if(($Fleet['storage'] + $Fleet['FuelStorage']) < $consumption) - { - if($allowUseQuantumGate) - { - if($allowGateJump OR ($Fleet['storage'] + $Fleet['FuelStorage']) > ($consumption / 2)) - { - $AllowNoEnoughFreeStorage = true; - $_Lang['P_UserHave2UseQuantumGate'] = '1'; - } - } - if($AllowNoEnoughFreeStorage !== true) - { - message($_Lang['fl2_NoEnoughStorage'], $ErrorTitle, 'fleet.php', 3); - } - } - - // Fleet Blockade Info (here, only for Global Block) - $GetSFBData = doquery("SELECT `ID`, `EndTime`, `BlockMissions`, `DontBlockIfIdle`, `Reason` FROM {{table}} WHERE `Type` = 1 AND `StartTime` <= UNIX_TIMESTAMP() AND (`EndTime` > UNIX_TIMESTAMP() OR `PostEndTime` > UNIX_TIMESTAMP()) ORDER BY `EndTime` DESC LIMIT 1;", 'smart_fleet_blockade', true); - if($GetSFBData['ID'] > 0) - { - // Fleet Blockade is Active - include($_EnginePath.'includes/functions/CreateSFBInfobox.php'); - $_Lang['P_SFBInfobox'] = CreateSFBInfobox($GetSFBData, array('standAlone' => true, 'Width' => 750, 'MarginBottom' => 10)); - } - - $_Lang['TitlePos'] = ($_Planet['planet_type'] == 1 ? $_Lang['fl2_sendfromplanet'] : $_Lang['fl2_sendfrommoon'])." {$_Planet['name']} [{$_Planet['galaxy']}:{$_Planet['system']}:{$_Planet['planet']}]"; - - $_Lang['FleetArray'] = $_POST['FleetArray']; - if($_POST['quickres'] == '1') - { - $_Lang['P_SetQuickRes']= '1'; - } - else - { - $_Lang['P_SetQuickRes']= '0'; - } - $_Lang['Now'] = $Now; - $_Lang['This_metal'] = explode('.', sprintf('%f', floor($_Planet['metal']))); - $_Lang['This_metal'] = (string)$_Lang['This_metal'][0]; - $_Lang['This_crystal'] = explode('.', sprintf('%f', floor($_Planet['crystal']))); - $_Lang['This_crystal'] = (string)$_Lang['This_crystal'][0]; - $_Lang['This_deuterium'] = explode('.', sprintf('%f', floor($_Planet['deuterium']))); - $_Lang['This_deuterium'] = (string)$_Lang['This_deuterium'][0]; - $_Lang['P_FlightDuration'] = (string)($duration + 0); - $_Lang['FlightTimeShow'] = pretty_time($duration, true); - $_Lang['consumption'] = (string)($consumption + 0); - $_Lang['ShowConsumption'] = prettyNumber($consumption); - $_Lang['totalstorage'] = (string)($Fleet['storage'] + 0); - if($Fleet['FuelStorage'] >= $consumption) - { - $_Lang['FuelStorageReduce'] = $consumption; - } - else - { - $_Lang['FuelStorageReduce'] = $Fleet['FuelStorage']; - } - $TempCeil = ceil($consumption / 2); - if($Fleet['FuelStorage'] >= $TempCeil) - { - $_Lang['FuelStorageReduceH'] = $TempCeil; - } - else - { - $_Lang['FuelStorageReduceH'] = $Fleet['FuelStorage']; - } - $_Lang['freeStorage'] = (string)($Fleet['storage'] - $consumption + $_Lang['FuelStorageReduce'] + 0); - $_Lang['FuelStorageReduce'] = (string)($_Lang['FuelStorageReduce'] + 0); - $_Lang['FuelStorageReduceH'] = (string)($_Lang['FuelStorageReduceH'] + 0); - if((float)$_Lang['freeStorage'] > 0) - { - $_Lang['SetDefaultFreeStorageColor'] = 'lime'; - } - elseif((float)$_Lang['freeStorage'] < 0) - { - $_Lang['SetDefaultFreeStorageColor'] = 'red'; - } - else - { - $_Lang['SetDefaultFreeStorageColor'] = 'orange'; - } - $_Lang['SetDefaultFreeStorage'] = prettyNumber($_Lang['freeStorage']); - $_Lang['ShowTargetPos'] = "[{$Target['galaxy']}:{$Target['system']}:{$Target['planet']}]
"; - if(!empty($CheckPlanetOwner['name'])) - { - if($CheckPlanetOwner['owner'] > 0) - { - $_Lang['ShowTargetPos'] .= ''.$CheckPlanetOwner['name'].''; - } - else - { - $_Lang['ShowTargetPos'] .= ''.$_Lang['fl2_target_abandoned_'.$Target['type']].''; - } - } - else - { - if($Target['type'] == 2) - { - $_Lang['ShowTargetPos'] .= $_Lang['fl2_debrisfield']; - } - else - { - $_Lang['ShowTargetPos'] .= $_Lang['fl2_emptyplanet']; - } - } - if($CheckPlanetOwner['owner'] > 0) - { - $_Lang['ShowTargetOwner'] = "{$CheckPlanetOwner['username']}"; - } - else - { - $_Lang['ShowTargetOwner'] = '-'; - } - $_Lang['SetSpeed'] = $_POST['speed']; - - if($_User['settings_useprettyinputbox'] == 1) - { - $_Lang['P_AllowPrettyInputBox'] = 'true'; - } - else - { - $_Lang['P_AllowPrettyInputBox'] = 'false'; - } - $_User['settings_resSortArray'] = explode(',', $_User['settings_resSortArray']); - foreach($_User['settings_resSortArray'] as $ResSortData) - { - switch($ResSortData) - { - case 'met': - $Temp[] = "'1'"; - break; - case 'cry': - $Temp[] = "'2'"; - break; - case 'deu': - $Temp[] = "'3'"; - break; - } - - $Temp[] = "'{$ResSortData}'"; - if($ResSortData != 'deu') - { - $Temp2[] = "'{$ResSortData}'"; - } - } - $_Lang['ResSortArrayAll'] = '['.implode(', ', $Temp).']'; - $_Lang['ResSortArrayNoDeu'] = '['.implode(', ', $Temp2).']'; - - if($allowUseQuantumGate) - { - $NextUseTimestamp = ($_Planet['quantumgate_lastuse'] + ($QuantumGateInterval * 3600)) - $Now; - if($NextUseTimestamp < 0) - { - $NextUseTimestamp = 0; - } - if($NextUseTimestamp == 0) - { - $_Lang['P_HideQuantumGateReady2UseIn'] = 'hide'; - } - else - { - include("{$_EnginePath}/includes/functions/InsertJavaScriptChronoApplet.php"); - $_Lang['InsertQuantumGateChronoApplet'] = InsertJavaScriptChronoApplet('quantum', '0', $NextUseTimestamp); - $_Lang['P_QuantumGateNextUse'] = pretty_time($NextUseTimestamp, true); - $_Lang['P_HideQuantumGateReady2Use'] = 'hide'; - } - } - else - { - $_Lang['P_HideQuantumGate'] = $Hide; - } - - if(!empty($AvailableMissions)) - { - $MissionRowTPL = gettemplate('fleet2_missionrow'); - foreach($AvailableMissions as $MID) - { - $ThisMission = array(); - $ThisMission['MID'] = $MID; - if($PreSelectedMission == $MID) - { - $ThisMission['CheckThisMission'] = ' checked'; - } - $ThisMission['ThisMissionName'] = $_Lang['type_mission'][$MID]; - - $_Lang['MissionSelectors'] .= parsetemplate($MissionRowTPL, $ThisMission); - if($allowUseQuantumGate) - { - if($MID == 1 OR $MID == 2 OR $MID == 6 OR $MID == 9) - { - $SetValue = '0'; - } - else - { - if($allowGateJump AND ($MID == 3 OR $MID == 4 OR $MID == 5)) - { - $SetValue = '2'; - } - else - { - $SetValue = '1'; - } - } - } - else - { - $SetValue = '0'; - } - $_Lang['QuantumGateJSArray'][] = $MID.': '.$SetValue; - } - if(!empty($_Lang['QuantumGateJSArray'])) - { - $_Lang['QuantumGateJSArray'] = 'var QuantumGateDeuteriumUse = {'.implode(', ', $_Lang['QuantumGateJSArray']).'}'; - } - $_Lang['P_HideNoMissionInfo'] = $Hide; - } - - if(isset($EnableTestAccWarning)) - { - $_Lang['CreateTestACCAlert'] = 'alert("'.$_Lang['fl2_testacctarget'].'");'; - } - - if($Target['planet'] != (MAX_PLANET_IN_SYSTEM + 1)) - { - $_Lang['P_HideExpeditionTimers'] = $Hide; - } - if(!in_array(5, $AvailableMissions)) - { - $_Lang['P_HideHoldingTimers'] = $Hide; - } - if(in_array(2, $AvailableMissions)) - { - $_Lang['CreateACSList'] = ''; - foreach($ACSList as $ID => $Name) - { - $_Lang['CreateACSList'] .= ''; - } - } - else - { - $_Lang['P_HideACSJoinList'] = $Hide; - } - if($AllyPactWarning === true) - { - $_Lang['Insert_AllyPact_AttackWarn'] = 'true'; - } - else - { - $_Lang['Insert_AllyPact_AttackWarn'] = 'false'; - } - - display(parsetemplate(gettemplate('fleet2_body'), $_Lang), $_Lang['fl_title']); - -?> \ No newline at end of file + (isset($_POST['gobackVars']['resource1']) ? $_POST['gobackVars']['resource1'] : null), + 'resource2' => (isset($_POST['gobackVars']['resource2']) ? $_POST['gobackVars']['resource2'] : null), + 'resource3' => (isset($_POST['gobackVars']['resource3']) ? $_POST['gobackVars']['resource3'] : null) + )); + if(isset($_POST['gobackVars']['usequantumgate']) && $_POST['gobackVars']['usequantumgate'] == 'on') + { + $_Lang['SelectQuantumGate'] = 'true'; + } +} + +includeLang('fleet'); + +$QuantumGateInterval = QUANTUMGATE_INTERVAL_HOURS; +$Now = time(); +$ErrorTitle = &$_Lang['fl_error']; +$Hide = ' class="hide"'; + +$_Lang['MissionSelectors'] = ''; + +if(MORALE_ENABLED) +{ + Morale_ReCalculate($_User, $Now); +} + +// Check, if Target Data are correct +$Target['galaxy'] = (isset($_POST['galaxy']) ? intval($_POST['galaxy']) : null); +$Target['system'] = (isset($_POST['system']) ? intval($_POST['system']) : null); +$Target['planet'] = (isset($_POST['planet']) ? intval($_POST['planet']) : null); +$Target['type'] = (isset($_POST['planettype']) ? intval($_POST['planettype']) : null); + +$GetACSData = intval($_POST['getacsdata']); +if($GetACSData > 0) +{ + $ACSData = doquery("SELECT `id`, `name`, `end_galaxy`, `end_system`, `end_planet`, `end_type`, `start_time` FROM {{table}} WHERE `id` = {$GetACSData};", 'acs', true); + if($ACSData['id'] == $GetACSData) + { + if($ACSData['start_time'] > $Now) + { + $Target['galaxy'] = $ACSData['end_galaxy']; + $Target['system'] = $ACSData['end_system']; + $Target['planet'] = $ACSData['end_planet']; + $Target['type'] = $ACSData['end_type']; + } + else + { + message($_Lang['fl1_ACSTimeUp'], $ErrorTitle, 'fleet.php', 3); + } + } + else + { + message($_Lang['fl1_ACSNoExist'], $ErrorTitle, 'fleet.php', 3); + } +} + +if($Target['galaxy'] == $_Planet['galaxy'] AND $Target['system'] == $_Planet['system'] AND $Target['planet'] == $_Planet['planet'] AND $Target['type'] == $_Planet['planet_type']) +{ + message($_Lang['fl2_cantsendsamecoords'], $ErrorTitle, 'fleet.php', 3); +} + +foreach($Target as $Type => $Value) +{ + if($Value < 1) + { + $TargetError = true; + break; + } + switch($Type) + { + case 'galaxy': + $CheckValue = MAX_GALAXY_IN_WORLD; + break; + case 'system': + $CheckValue = MAX_SYSTEM_IN_GALAXY; + break; + case 'planet': + $CheckValue = MAX_PLANET_IN_SYSTEM + 1; + break; + case 'type': + $CheckValue = 3; + break; + } + if($Value > $CheckValue) + { + $TargetError = true; + break; + } + // Set Positions for Inputs + $_Lang['Target_'.$Type] = $Value; +} +if(isset($TargetError)) +{ + message($_Lang['fl2_targeterror'], $ErrorTitle, 'fleet.php', 3); +} + +// Create SpeedsArray +$SpeedsAvailable = array(10, 9, 8, 7, 6, 5, 4, 3, 2, 1); + +if($_User['admiral_time'] > $Now) +{ + $SpeedsAvailable[] = 12; + $SpeedsAvailable[] = 11; + $SpeedsAvailable[] = 0.5; + $SpeedsAvailable[] = 0.25; +} +if(MORALE_ENABLED) +{ + $MaxAvailableSpeed = max($SpeedsAvailable); + if($_User['morale_level'] >= MORALE_BONUS_FLEETSPEEDUP1) + { + $SpeedsAvailable[] = $MaxAvailableSpeed + (MORALE_BONUS_FLEETSPEEDUP1_VALUE / 10); + } + if($_User['morale_level'] >= MORALE_BONUS_FLEETSPEEDUP2) + { + $SpeedsAvailable[] = $MaxAvailableSpeed + (MORALE_BONUS_FLEETSPEEDUP2_VALUE / 10); + } +} +if(!in_array($_POST['speed'], $SpeedsAvailable)) +{ + message($_Lang['fl_bad_fleet_speed'], $ErrorTitle, 'fleet.php', 3); +} + +// Check PlanetOwner +$YourPlanet = false; +$UsedPlanet = false; +$OwnerFriend = false; +$OwnerHasMarcantilePact = false; +$AllyPactWarning = false; +$CheckPlanetOwnerQuery = ''; +$CheckPlanetOwnerQuery .= "SELECT `planets`.`id`, `planets`.`id_owner` AS `owner`, `planets`.`name` AS `name`, `quantumgate`, "; +$CheckPlanetOwnerQuery .= "`users`.`ally_id`, `users`.`username` as `username`, `buddy1`.`active` AS `active1`, `buddy2`.`active` AS `active2` "; +if($_User['ally_id'] > 0) +{ + $CheckPlanetOwnerQuery .= ", `apact1`.`Type` AS `AllyPact1`, `apact2`.`Type` AS `AllyPact2` "; +} +$CheckPlanetOwnerQuery .= "FROM {{table}} AS `planets` "; +$CheckPlanetOwnerQuery .= "LEFT JOIN `{{prefix}}buddy` AS `buddy1` ON (`planets`.`id_owner` = `buddy1`.`sender` AND `buddy1`.`owner` = {$_User['id']}) "; +$CheckPlanetOwnerQuery .= "LEFT JOIN `{{prefix}}buddy` AS `buddy2` ON (`planets`.`id_owner` = `buddy2`.`owner` AND `buddy2`.`sender` = {$_User['id']}) "; +$CheckPlanetOwnerQuery .= "LEFT JOIN `{{prefix}}users` AS `users` ON `planets`.`id_owner` = `users`.`id` "; +if($_User['ally_id'] > 0) +{ + $CheckPlanetOwnerQuery .= "LEFT JOIN `{{prefix}}ally_pacts` AS `apact1` ON (`apact1`.`AllyID_Sender` = {$_User['ally_id']} AND `apact1`.`AllyID_Owner` = `users`.`ally_id` AND `apact1`.`Active` = 1) "; + $CheckPlanetOwnerQuery .= "LEFT JOIN `{{prefix}}ally_pacts` AS `apact2` ON (`apact2`.`AllyID_Sender` = `users`.`ally_id` AND `apact2`.`AllyID_Owner` = {$_User['ally_id']} AND `apact2`.`Active` = 1) "; +} +$CheckPlanetOwnerQuery .= "WHERE `planets`.`galaxy` = {$Target['galaxy']} AND `planets`.`system` = {$Target['system']} AND `planets`.`planet` = {$Target['planet']} AND `planets`.`planet_type` = {$Target['type']} "; +$CheckPlanetOwnerQuery .= "LIMIT 1;"; +$CheckPlanetOwner = doquery($CheckPlanetOwnerQuery, 'planets'); + +if(mysql_num_rows($CheckPlanetOwner) == 1) +{ + $CheckPlanetOwner = mysql_fetch_assoc($CheckPlanetOwner); + $UsedPlanet = true; + if($CheckPlanetOwner['owner'] == $_User['id']) + { + $YourPlanet = true; + } + else + { + if(!empty($_GameConfig['TestUsersIDs'])) + { + $TestUsersArray = explode(',', $_GameConfig['TestUsersIDs']); + if(in_array($CheckPlanetOwner['owner'], $TestUsersArray)) + { + $EnableTestAccWarning = true; + } + } + if((isset($CheckPlanetOwner['AllyPact1']) && $CheckPlanetOwner['AllyPact1'] >= ALLYPACT_NONAGGRESSION) || (isset($CheckPlanetOwner['AllyPact2']) && $CheckPlanetOwner['AllyPact2'] >= ALLYPACT_NONAGGRESSION)) + { + $AllyPactWarning = true; + } + if((isset($CheckPlanetOwner['AllyPact1']) && $CheckPlanetOwner['AllyPact1'] >= ALLYPACT_MERCANTILE) || (isset($CheckPlanetOwner['AllyPact2']) && $CheckPlanetOwner['AllyPact2'] >= ALLYPACT_MERCANTILE)) + { + $OwnerHasMarcantilePact = true; + } + if(($CheckPlanetOwner['active1'] == 1 OR $CheckPlanetOwner['active2'] == 1) OR ($CheckPlanetOwner['ally_id'] == $_User['ally_id'] AND $_User['ally_id'] > 0) OR ((isset($CheckPlanetOwner['AllyPact1']) && $CheckPlanetOwner['AllyPact1'] >= ALLYPACT_DEFENSIVE) || (isset($CheckPlanetOwner['AllyPact2']) && $CheckPlanetOwner['AllyPact2'] >= ALLYPACT_DEFENSIVE))) + { + $OwnerFriend = true; + } + } +} + +// Parse Fleet Array +$Fleet['count'] = 0; +$Fleet['storage'] = 0; +$Fleet['FuelStorage'] = 0; + +$Fleet['array'] = explode(';', $_POST['FleetArray']); +$FleetArray = array(); +if(!empty($Fleet['array']) AND (array)$Fleet['array'] === $Fleet['array']) +{ + foreach($Fleet['array'] as $ShipData) + { + $ShipData = explode(',', $ShipData); + $ShipID = intval($ShipData[0]); + if(in_array($ShipID, $_Vars_ElementCategories['fleet'])) + { + if(!empty($_Vars_Prices[$ShipID]['engine'])) + { + $ShipCount = floor($ShipData[1]); + if($ShipCount > 0) + { + if($_Planet[$_Vars_GameElements[$ShipID]] >= $ShipCount) + { + $FleetArray[$ShipID] = $ShipCount; + $Fleet['count'] += $ShipCount; + $ThisStorage = $_Vars_Prices[$ShipID]['capacity'] * $ShipCount; + if($ShipID != 210) + { + $Fleet['storage'] += $ThisStorage; + } + else + { + $Fleet['FuelStorage'] += $ThisStorage; + } + } + else + { + message($_Lang['fl1_NoEnoughShips'], $ErrorTitle, 'fleet.php', 3); + } + } + else + { + message($_Lang['fl2_ShipCountCantBe0'], $ErrorTitle, 'fleet.php', 3); + } + } + else + { + message($_Lang['fl1_CantSendUnflyable'], $ErrorTitle, 'fleet.php', 3); + } + } + else + { + message($_Lang['fl1_BadShipGiven'], $ErrorTitle, 'fleet.php', 3); + } + } +} +else +{ + message($_Lang['fl2_FleetArrayPostEmpty'], $ErrorTitle, 'fleet.php', 3); +} +if($Fleet['count'] <= 0) +{ + message($_Lang['fl2_ZeroShips'], $ErrorTitle, 'fleet.php', 3); +} +$Fleet['array'] = $FleetArray; +unset($FleetArray); + +// Create Array of Available Missions +$AvailableMissions = array(); +if($Target['type'] == 2) +{ + if($Fleet['array'][209] > 0) + { + $AvailableMissions[] = 8; + } +} +else +{ + if($UsedPlanet) + { + if(!isset($Fleet['array'][210]) || $Fleet['count'] > $Fleet['array'][210]) + { + $AvailableMissions[] = 3; + } + if(!$YourPlanet) + { + $AvailableMissions[] = 1; + if($OwnerFriend) + { + $AvailableMissions[] = 5; + } + if(isset($Fleet['array'][210]) && $Fleet['count'] == $Fleet['array'][210]) + { + $AvailableMissions[] = 6; + } + if($Target['type'] == 3 && isset($Fleet['array'][214]) && $Fleet['array'][214] > 0) + { + $AvailableMissions[] = 9; + } + } + else + { + $AvailableMissions[] = 4; + } + } + else + { + if($Target['planet'] == (MAX_PLANET_IN_SYSTEM + 1)) + { + $AvailableMissions[] = 15; + } + else + { + if($Fleet['array'][208] > 0 AND $Target['type'] == 1) + { + $AvailableMissions[] = 7; + } + } + } +} + +if(in_array(1, $AvailableMissions)) +{ + $CheckACS = doquery("SELECT * FROM {{table}} WHERE (`users` LIKE '%|{$_User['id']}|%' OR `owner_id` = {$_User['id']}) AND `end_target_id` = {$CheckPlanetOwner['id']} AND `start_time` > UNIX_TIMESTAMP();", 'acs'); + if(mysql_num_rows($CheckACS) > 0) + { + while($ACSData = mysql_fetch_assoc($CheckACS)) + { + $ACSData['fleets_count'] += 1; + $ACSList[$ACSData['id']] = "{$ACSData['name']} ({$_Lang['fl_acs_fleets']}: {$ACSData['fleets_count']})"; + } + $AvailableMissions[] = 2; + } +} + +$allowUseQuantumGate = false; +if(!empty($AvailableMissions)) +{ + if($_Planet['quantumgate'] == 1) + { + if(($YourPlanet OR $OwnerFriend OR $OwnerHasMarcantilePact) AND $CheckPlanetOwner['quantumgate'] == 1 AND (in_array(3, $AvailableMissions) OR in_array(4, $AvailableMissions) OR in_array(5, $AvailableMissions))) + { + $allowUseQuantumGate = true; + $allowGateJump = true; + } + else + { + if($_Planet['galaxy'] == $Target['galaxy']) + { + if(($_Planet['quantumgate_lastuse'] + ($QuantumGateInterval * 3600)) <= $Now) + { + $allowUseQuantumGate = true; + } + } + } + } +} + +$PreSelectedMission = intval($_POST['target_mission']); +$SpeedFactor = GetGameSpeedFactor(); +$AllFleetSpeed = GetFleetMaxSpeed($Fleet['array'], 0, $_User); +$GenFleetSpeed = $_POST['speed']; +$MaxFleetSpeed = min($AllFleetSpeed); +if(MORALE_ENABLED) +{ + if($_User['morale_level'] <= MORALE_PENALTY_FLEETSLOWDOWN) + { + $MaxFleetSpeed *= MORALE_PENALTY_FLEETSLOWDOWN_VALUE; + } +} +$distance = GetTargetDistance($_Planet['galaxy'], $Target['galaxy'], $_Planet['system'], $Target['system'], $_Planet['planet'], $Target['planet']); +$duration = GetMissionDuration($GenFleetSpeed, $MaxFleetSpeed, $distance, $SpeedFactor); +$consumption = GetFleetConsumption($Fleet['array'], $SpeedFactor, $duration, $distance, $_User); + +if($_Planet['deuterium'] < $consumption) +{ + if($allowUseQuantumGate) + { + if($allowGateJump OR $_Planet['deuterium'] > ($consumption / 2)) + { + $AllowNoEnoughDeuterium = true; + $_Lang['P_UserHave2UseQuantumGate'] = '1'; + } + } + if(!isset($AllowNoEnoughDeuterium)) + { + message($_Lang['fl2_NoEnoughFuel'], $ErrorTitle, 'fleet.php', 3); + } +} +if(($Fleet['storage'] + $Fleet['FuelStorage']) < $consumption) +{ + if($allowUseQuantumGate) + { + if($allowGateJump OR ($Fleet['storage'] + $Fleet['FuelStorage']) > ($consumption / 2)) + { + $AllowNoEnoughFreeStorage = true; + $_Lang['P_UserHave2UseQuantumGate'] = '1'; + } + } + if($AllowNoEnoughFreeStorage !== true) + { + message($_Lang['fl2_NoEnoughStorage'], $ErrorTitle, 'fleet.php', 3); + } +} + +// Fleet Blockade Info (here, only for Global Block) +$GetSFBData = doquery("SELECT `ID`, `EndTime`, `BlockMissions`, `DontBlockIfIdle`, `Reason` FROM {{table}} WHERE `Type` = 1 AND `StartTime` <= UNIX_TIMESTAMP() AND (`EndTime` > UNIX_TIMESTAMP() OR `PostEndTime` > UNIX_TIMESTAMP()) ORDER BY `EndTime` DESC LIMIT 1;", 'smart_fleet_blockade', true); +if($GetSFBData['ID'] > 0) +{ + // Fleet Blockade is Active + include($_EnginePath.'includes/functions/CreateSFBInfobox.php'); + $_Lang['P_SFBInfobox'] = CreateSFBInfobox($GetSFBData, array('standAlone' => true, 'Width' => 750, 'MarginBottom' => 10)); +} + +$_Lang['TitlePos'] = ($_Planet['planet_type'] == 1 ? $_Lang['fl2_sendfromplanet'] : $_Lang['fl2_sendfrommoon'])." {$_Planet['name']} [{$_Planet['galaxy']}:{$_Planet['system']}:{$_Planet['planet']}]"; + +$_Lang['FleetArray'] = $_POST['FleetArray']; +if($_POST['quickres'] == '1') +{ + $_Lang['P_SetQuickRes']= '1'; +} +else +{ + $_Lang['P_SetQuickRes']= '0'; +} +$_Lang['Now'] = $Now; +$_Lang['This_metal'] = explode('.', sprintf('%f', floor($_Planet['metal']))); +$_Lang['This_metal'] = (string)$_Lang['This_metal'][0]; +$_Lang['This_crystal'] = explode('.', sprintf('%f', floor($_Planet['crystal']))); +$_Lang['This_crystal'] = (string)$_Lang['This_crystal'][0]; +$_Lang['This_deuterium'] = explode('.', sprintf('%f', floor($_Planet['deuterium']))); +$_Lang['This_deuterium'] = (string)$_Lang['This_deuterium'][0]; +$_Lang['P_FlightDuration'] = (string)($duration + 0); +$_Lang['FlightTimeShow'] = pretty_time($duration, true); +$_Lang['consumption'] = (string)($consumption + 0); +$_Lang['ShowConsumption'] = prettyNumber($consumption); +$_Lang['totalstorage'] = (string)($Fleet['storage'] + 0); +if($Fleet['FuelStorage'] >= $consumption) +{ + $_Lang['FuelStorageReduce'] = $consumption; +} +else +{ + $_Lang['FuelStorageReduce'] = $Fleet['FuelStorage']; +} +$TempCeil = ceil($consumption / 2); +if($Fleet['FuelStorage'] >= $TempCeil) +{ + $_Lang['FuelStorageReduceH'] = $TempCeil; +} +else +{ + $_Lang['FuelStorageReduceH'] = $Fleet['FuelStorage']; +} +$_Lang['freeStorage'] = (string)($Fleet['storage'] - $consumption + $_Lang['FuelStorageReduce'] + 0); +$_Lang['FuelStorageReduce'] = (string)($_Lang['FuelStorageReduce'] + 0); +$_Lang['FuelStorageReduceH'] = (string)($_Lang['FuelStorageReduceH'] + 0); +if((float)$_Lang['freeStorage'] > 0) +{ + $_Lang['SetDefaultFreeStorageColor'] = 'lime'; +} +elseif((float)$_Lang['freeStorage'] < 0) +{ + $_Lang['SetDefaultFreeStorageColor'] = 'red'; +} +else +{ + $_Lang['SetDefaultFreeStorageColor'] = 'orange'; +} +$_Lang['SetDefaultFreeStorage'] = prettyNumber($_Lang['freeStorage']); +$_Lang['ShowTargetPos'] = "[{$Target['galaxy']}:{$Target['system']}:{$Target['planet']}]
"; +if(!empty($CheckPlanetOwner['name'])) +{ + if($CheckPlanetOwner['owner'] > 0) + { + $_Lang['ShowTargetPos'] .= ''.$CheckPlanetOwner['name'].''; + } + else + { + $_Lang['ShowTargetPos'] .= ''.$_Lang['fl2_target_abandoned_'.$Target['type']].''; + } +} +else +{ + if($Target['type'] == 2) + { + $_Lang['ShowTargetPos'] .= $_Lang['fl2_debrisfield']; + } + else + { + $_Lang['ShowTargetPos'] .= $_Lang['fl2_emptyplanet']; + } +} +if($CheckPlanetOwner['owner'] > 0) +{ + $_Lang['ShowTargetOwner'] = "{$CheckPlanetOwner['username']}"; +} +else +{ + $_Lang['ShowTargetOwner'] = '-'; +} +$_Lang['SetSpeed'] = $_POST['speed']; + +if($_User['settings_useprettyinputbox'] == 1) +{ + $_Lang['P_AllowPrettyInputBox'] = 'true'; +} +else +{ + $_Lang['P_AllowPrettyInputBox'] = 'false'; +} +$_User['settings_resSortArray'] = explode(',', $_User['settings_resSortArray']); +foreach($_User['settings_resSortArray'] as $ResSortData) +{ + switch($ResSortData) + { + case 'met': + $Temp[] = "'1'"; + break; + case 'cry': + $Temp[] = "'2'"; + break; + case 'deu': + $Temp[] = "'3'"; + break; + } + + $Temp[] = "'{$ResSortData}'"; + if($ResSortData != 'deu') + { + $Temp2[] = "'{$ResSortData}'"; + } +} +$_Lang['ResSortArrayAll'] = '['.implode(', ', $Temp).']'; +$_Lang['ResSortArrayNoDeu'] = '['.implode(', ', $Temp2).']'; + +if($allowUseQuantumGate) +{ + $NextUseTimestamp = ($_Planet['quantumgate_lastuse'] + ($QuantumGateInterval * 3600)) - $Now; + if($NextUseTimestamp < 0) + { + $NextUseTimestamp = 0; + } + if($NextUseTimestamp == 0) + { + $_Lang['P_HideQuantumGateReady2UseIn'] = 'hide'; + } + else + { + include("{$_EnginePath}/includes/functions/InsertJavaScriptChronoApplet.php"); + $_Lang['InsertQuantumGateChronoApplet'] = InsertJavaScriptChronoApplet('quantum', '0', $NextUseTimestamp); + $_Lang['P_QuantumGateNextUse'] = pretty_time($NextUseTimestamp, true); + $_Lang['P_HideQuantumGateReady2Use'] = 'hide'; + } +} +else +{ + $_Lang['P_HideQuantumGate'] = $Hide; +} + +if(!empty($AvailableMissions)) +{ + $MissionRowTPL = gettemplate('fleet2_missionrow'); + foreach($AvailableMissions as $MID) + { + $ThisMission = array(); + $ThisMission['MID'] = $MID; + if($PreSelectedMission == $MID) + { + $ThisMission['CheckThisMission'] = ' checked'; + } + $ThisMission['ThisMissionName'] = $_Lang['type_mission'][$MID]; + + $_Lang['MissionSelectors'] .= parsetemplate($MissionRowTPL, $ThisMission); + if($allowUseQuantumGate) + { + if($MID == 1 OR $MID == 2 OR $MID == 6 OR $MID == 9) + { + $SetValue = '0'; + } + else + { + if($allowGateJump AND ($MID == 3 OR $MID == 4 OR $MID == 5)) + { + $SetValue = '2'; + } + else + { + $SetValue = '1'; + } + } + } + else + { + $SetValue = '0'; + } + $_Lang['QuantumGateJSArray'][] = $MID.': '.$SetValue; + } + if(!empty($_Lang['QuantumGateJSArray'])) + { + $_Lang['QuantumGateJSArray'] = 'var QuantumGateDeuteriumUse = {'.implode(', ', $_Lang['QuantumGateJSArray']).'}'; + } + $_Lang['P_HideNoMissionInfo'] = $Hide; +} + +if(isset($EnableTestAccWarning)) +{ + $_Lang['CreateTestACCAlert'] = 'alert("'.$_Lang['fl2_testacctarget'].'");'; +} + +if($Target['planet'] != (MAX_PLANET_IN_SYSTEM + 1)) +{ + $_Lang['P_HideExpeditionTimers'] = $Hide; +} +if(!in_array(5, $AvailableMissions)) +{ + $_Lang['P_HideHoldingTimers'] = $Hide; +} +if(in_array(2, $AvailableMissions)) +{ + $_Lang['CreateACSList'] = ''; + foreach($ACSList as $ID => $Name) + { + $_Lang['CreateACSList'] .= ''; + } +} +else +{ + $_Lang['P_HideACSJoinList'] = $Hide; +} +if($AllyPactWarning === true) +{ + $_Lang['Insert_AllyPact_AttackWarn'] = 'true'; +} +else +{ + $_Lang['Insert_AllyPact_AttackWarn'] = 'false'; +} + +display(parsetemplate(gettemplate('fleet2_body'), $_Lang), $_Lang['fl_title']); + +?> diff --git a/fleet3.php b/fleet3.php index d09898784..ae3a7172e 100644 --- a/fleet3.php +++ b/fleet3.php @@ -1,1609 +1,1609 @@ -'; - $GoBackForm .= ''; - $GoBackForm .= ''; - $GoBackForm .= ''; - message("
{$Text}
{$GoBackForm}", $Title); - } - - includeLang('fleet'); - - $QuantumGateInterval = QUANTUMGATE_INTERVAL_HOURS; - $Now = time(); - $ErrorTitle = &$_Lang['fl_error']; - - if(MORALE_ENABLED) - { - Morale_ReCalculate($_User, $Now); - } - - // --- Initialize Vars - $Target['galaxy'] = intval($_POST['galaxy']); - $Target['system'] = intval($_POST['system']); - $Target['planet'] = intval($_POST['planet']); - $Target['type'] = intval($_POST['planettype']); - $Fleet['Speed'] = floatval($_POST['speed']); - $Fleet['array'] = explode(';', $_POST['FleetArray']); - $Fleet['UseQuantum'] = (isset($_POST['usequantumgate']) && $_POST['usequantumgate'] == 'on' ? true : false); - $Fleet['resources'] = array('metal' => $_POST['resource1'], 'crystal' => $_POST['resource2'], 'deuterium' => $_POST['resource3']); - $Fleet['ExpeTime'] = intval($_POST['expeditiontime']); - $Fleet['HoldTime'] = intval($_POST['holdingtime']); - $Fleet['ACS_ID'] = isset($_POST['acs_id']) ? floor(floatval($_POST['acs_id'])) : 0; - $Fleet['Mission'] = isset($_POST['mission']) ? intval($_POST['mission']) : 0; - - $Protections['enable'] = (bool) $_GameConfig['noobprotection']; - $Protections['basicLimit'] = $_GameConfig['noobprotectiontime'] * 1000; - $Protections['weakMulti'] = $_GameConfig['noobprotectionmulti']; - $Protections['adminEnable'] = (bool) $_GameConfig['adminprotection']; - $Protections['ally'] = $_GameConfig['allyprotection']; - $Protections['weakLimit'] = $_GameConfig['no_noob_protect'] * 1000; - $Protections['idleTime'] = $_GameConfig['no_idle_protect'] * TIME_DAY; - $Protections['mtypes'] = array(1, 2, 6, 9); - $Protections['newTime'] = $_GameConfig['Protection_NewPlayerTime']; - $Protections['antifarm_enabled'] = (bool) $_GameConfig['Protection_AntiFarmEnabled']; - $Protections['antifarm_rate'] = $_GameConfig['Protection_AntiFarmRate']; - $Protections['antifarm_counttotal'] = $_GameConfig['Protection_AntiFarmCountTotal']; - $Protections['antifarm_countplanet'] = $_GameConfig['Protection_AntiFarmCountPlanet']; - $Protections['bashLimit_enabled'] = (bool) $_GameConfig['Protection_BashLimitEnabled']; - $Protections['bashLimit_interval'] = $_GameConfig['Protection_BashLimitInterval']; - $Protections['bashLimit_counttotal'] = $_GameConfig['Protection_BashLimitCountTotal']; - $Protections['bashLimit_countplanet'] = $_GameConfig['Protection_BashLimitCountPlanet']; - - // --- Check if User's account is activated - if(!empty($_User['activation_code'])) - { - messageRed($_Lang['fl3_BlockAccNotActivated'], $ErrorTitle); - } - - // --- Check if Mission is selected - if($Fleet['Mission'] <= 0) - { - messageRed($_Lang['fl3_NoMissionSelected'], $ErrorTitle); - } - - // --- Get FlyingFleets Count - $FlyingFleetsCount = 0; - $FlyingExpeditions = 0; - - $Query_GetFleets = ''; - $Query_GetFleets .= "SELECT `fleet_mission`, `fleet_target_owner`, `fleet_end_id`, `fleet_mess` FROM {{table}} "; - $Query_GetFleets .= "WHERE `fleet_owner` = {$_User['id']};"; - $Result_GetFleets = doquery($Query_GetFleets, 'fleets'); - while($FleetData = mysql_fetch_assoc($Result_GetFleets)) - { - $FlyingFleetsCount += 1; - if($FleetData['fleet_mission'] == 15) - { - $FlyingExpeditions += 1; - } - if(in_array($FleetData['fleet_mission'], array(1, 2, 9)) AND $FleetData['fleet_mess'] == 0) - { - if(!isset($FlyingFleetsData[$FleetData['fleet_target_owner']]['count'])) - { - $FlyingFleetsData[$FleetData['fleet_target_owner']]['count'] = 0; - } - if(!isset($FlyingFleetsData[$FleetData['fleet_target_owner']][$FleetData['fleet_end_id']])) - { - $FlyingFleetsData[$FleetData['fleet_target_owner']][$FleetData['fleet_end_id']] = 0; - } - $FlyingFleetsData[$FleetData['fleet_target_owner']]['count'] += 1; - $FlyingFleetsData[$FleetData['fleet_target_owner']][$FleetData['fleet_end_id']] += 1; - } - } - - // Get Available Slots for Fleets (1 + ComputerTech + 2 on Admiral) - // Get Available Slots for Expeditions (1 + floor(ExpeditionTech / 3)) - $Slots['MaxFleetSlots'] = 1 + $_User[$_Vars_GameElements[108]] + (($_User['admiral_time'] > $Now) ? 2 : 0); - $Slots['MaxExpedSlots'] = 1 + floor($_User[$_Vars_GameElements[124]] / 3); - $Slots['FlyingFleetsCount'] = $FlyingFleetsCount; - $Slots['FlyingExpeditions'] = $FlyingExpeditions; - if($Slots['FlyingFleetsCount'] >= $Slots['MaxFleetSlots']) - { - messageRed($_Lang['fl3_NoMoreFreeSlots'], $ErrorTitle); - } - if($Slots['FlyingExpeditions'] >= $Slots['MaxExpedSlots'] AND $Fleet['Mission'] == 15) - { - messageRed($_Lang['fl3_NoMoreFreeExpedSlots'], $ErrorTitle); - } - - // --- Switch Off Expeditions - if($Fleet['Mission'] == 15) - { - messageRed($_Lang['fl3_ExpeditionsAreOff'], $ErrorTitle); - } - - // --- Check if all resources are correct (no negative numbers and enough on planet) - foreach($Fleet['resources'] as $Key => $Data) - { - $Fleet['resources'][$Key] = floor(floatval(str_replace('.', '', $Data))); - if($Fleet['resources'][$Key] < 0) - { - messageRed($_Lang['fl3_BadResourcesGiven'], $ErrorTitle); - } - elseif($Fleet['resources'][$Key] > $_Planet[$Key]) - { - messageRed($_Lang['fl3_PlanetNoEnough'.$Key], $ErrorTitle); - } - - if($Fleet['resources'][$Key] == 0) - { - $Fleet['resources'][$Key] = '0'; - } - } - - // --- Check, if Target Data are correct - if($Target['galaxy'] == $_Planet['galaxy'] AND $Target['system'] == $_Planet['system'] AND $Target['planet'] == $_Planet['planet'] AND $Target['type'] == $_Planet['planet_type']) - { - messageRed($_Lang['fl2_cantsendsamecoords'], $ErrorTitle); - } - foreach($Target as $Type => $Value) - { - if($Value < 1) - { - $TargetError = true; - break; - } - switch($Type) - { - case 'galaxy': - $CheckValue = MAX_GALAXY_IN_WORLD; - break; - case 'system': - $CheckValue = MAX_SYSTEM_IN_GALAXY; - break; - case 'planet': - $CheckValue = MAX_PLANET_IN_SYSTEM + 1; - break; - case 'type': - $CheckValue = 3; - break; - } - if($Value > $CheckValue) - { - $TargetError = true; - break; - } - } - if(isset($TargetError)) - { - messageRed($_Lang['fl2_targeterror'], $ErrorTitle); - } - - // Create SpeedsArray - $SpeedsAvailable = array(10, 9, 8, 7, 6, 5, 4, 3, 2, 1); - - if($_User['admiral_time'] > $Now) - { - $SpeedsAvailable[] = 12; - $SpeedsAvailable[] = 11; - $SpeedsAvailable[] = 0.5; - $SpeedsAvailable[] = 0.25; - } - if(MORALE_ENABLED) - { - $MaxAvailableSpeed = max($SpeedsAvailable); - if($_User['morale_level'] >= MORALE_BONUS_FLEETSPEEDUP1) - { - $SpeedsAvailable[] = $MaxAvailableSpeed + (MORALE_BONUS_FLEETSPEEDUP1_VALUE / 10); - } - if($_User['morale_level'] >= MORALE_BONUS_FLEETSPEEDUP2) - { - $SpeedsAvailable[] = $MaxAvailableSpeed + (MORALE_BONUS_FLEETSPEEDUP2_VALUE / 10); - } - } - if(!in_array($Fleet['Speed'], $SpeedsAvailable)) - { - messageRed($_Lang['fl_bad_fleet_speed'], $ErrorTitle); - } - - // --- Check PlanetOwner - $YourPlanet = false; - $UsedPlanet = false; - $OwnerFriend = false; - $OwnerIsBuddyFriend = false; - $OwnerIsAlliedUser = false; - $OwnerHasMarcantilePact = false; - $PlanetAbandoned = false; - - if($Fleet['Mission'] != 8) - { - // This is not a Recycling Mission, so check Planet Data - $Query_CheckPlanetOwner = ''; - $Query_CheckPlanetOwner .= "SELECT `pl`.`id` AS `id`, `pl`.`id_owner` AS `owner`, `pl`.`name` AS `name`, `pl`.`quantumgate`, "; - $Query_CheckPlanetOwner .= "`users`.`ally_id`, `users`.`onlinetime`, `users`.`username` as `username`, `users`.`user_lastip` as `lastip`, `users`.`is_onvacation`, `users`.`is_banned`, `users`.`authlevel`, `users`.`first_login`, `users`.`NoobProtection_EndTime`, `users`.`multiIP_DeclarationID`, "; - $Query_CheckPlanetOwner .= "`stats`.`total_rank`, `stats`.`total_points`, `buddy1`.`active` AS `active1`, `buddy2`.`active` AS `active2` "; - if($_User['ally_id'] > 0) - { - $Query_CheckPlanetOwner .= ", `apact1`.`Type` AS `AllyPact1`, `apact2`.`Type` AS `AllyPact2` "; - } - $Query_CheckPlanetOwner .= "FROM {{table}} as `pl` "; - $Query_CheckPlanetOwner .= "LEFT JOIN {{prefix}}buddy as `buddy1` ON (`pl`.`id_owner` = `buddy1`.`sender` AND `buddy1`.`owner` = {$_User['id']}) "; - $Query_CheckPlanetOwner .= "LEFT JOIN {{prefix}}buddy as `buddy2` ON (`pl`.`id_owner` = `buddy2`.`owner` AND `buddy2`.`sender` = {$_User['id']}) "; - $Query_CheckPlanetOwner .= "LEFT JOIN {{prefix}}users as `users` ON `pl`.`id_owner` = `users`.`id` "; - $Query_CheckPlanetOwner .= "LEFT JOIN {{prefix}}statpoints AS `stats` ON `pl`.`id_owner` = `stats`.`id_owner` AND `stat_type` = '1' "; - if($_User['ally_id'] > 0) - { - $Query_CheckPlanetOwner .= "LEFT JOIN `{{prefix}}ally_pacts` AS `apact1` ON (`apact1`.`AllyID_Sender` = {$_User['ally_id']} AND `apact1`.`AllyID_Owner` = `users`.`ally_id` AND `apact1`.`Active` = 1) "; - $Query_CheckPlanetOwner .= "LEFT JOIN `{{prefix}}ally_pacts` AS `apact2` ON (`apact2`.`AllyID_Sender` = `users`.`ally_id` AND `apact2`.`AllyID_Owner` = {$_User['ally_id']} AND `apact2`.`Active` = 1) "; - } - $Query_CheckPlanetOwner .= "WHERE `pl`.`galaxy` = {$Target['galaxy']} AND `pl`.`system` = {$Target['system']} AND `pl`.`planet` = {$Target['planet']} AND `pl`.`planet_type` = {$Target['type']} "; - $Query_CheckPlanetOwner .= "LIMIT 1;"; - $CheckPlanetOwner = doquery($Query_CheckPlanetOwner, 'planets'); - - if(mysql_num_rows($CheckPlanetOwner) == 1) - { - $CheckGalaxyRow = doquery("SELECT `galaxy_id` FROM {{table}} WHERE `galaxy` = {$Target['galaxy']} AND `system` = {$Target['system']} AND `planet` = {$Target['planet']} LIMIT 1;", 'galaxy', true); - $CheckPlanetOwner = mysql_fetch_assoc($CheckPlanetOwner); - $CheckPlanetOwner['galaxy_id'] = $CheckGalaxyRow['galaxy_id']; - $UsedPlanet = true; - if($CheckPlanetOwner['owner'] > 0) - { - if($CheckPlanetOwner['owner'] == $_User['id']) - { - $YourPlanet = true; - } - else - { - if((isset($CheckPlanetOwner['AllyPact1']) && $CheckPlanetOwner['AllyPact1'] >= ALLYPACT_NONAGGRESSION) || (isset($CheckPlanetOwner['AllyPact2']) && $CheckPlanetOwner['AllyPact2'] >= ALLYPACT_NONAGGRESSION)) - { - $OwnerIsAlliedUser = true; - } - if((isset($CheckPlanetOwner['AllyPact1']) && $CheckPlanetOwner['AllyPact1'] >= ALLYPACT_MERCANTILE) || (isset($CheckPlanetOwner['AllyPact2']) && $CheckPlanetOwner['AllyPact2'] >= ALLYPACT_MERCANTILE)) - { - $OwnerHasMarcantilePact = true; - } - if(($CheckPlanetOwner['active1'] == 1 OR $CheckPlanetOwner['active2'] == 1) OR ($CheckPlanetOwner['ally_id'] == $_User['ally_id'] AND $_User['ally_id'] > 0) OR ((isset($CheckPlanetOwner['AllyPact1']) && $CheckPlanetOwner['AllyPact1'] >= ALLYPACT_DEFENSIVE) || (isset($CheckPlanetOwner['AllyPact2']) && $CheckPlanetOwner['AllyPact2'] >= ALLYPACT_DEFENSIVE))) - { - $OwnerFriend = true; - if($CheckPlanetOwner['active1'] == 1 OR $CheckPlanetOwner['active2'] == 1) - { - $OwnerIsBuddyFriend = true; - } - } - } - } - else - { - $PlanetAbandoned = true; - } - } - else - { - $CheckPlanetOwner = array(); - } - } - else - { - // This is a Recycling Mission, so check Galaxy Data - $CheckDebrisField = doquery("SELECT `galaxy_id`, `metal`, `crystal` FROM {{table}} WHERE galaxy = '{$Target['galaxy']}' AND system = '{$Target['system']}' AND planet = '{$Target['planet']}'", 'galaxy', true); - } - - // Fleet Blockade System - $SFBSelectWhere[] = "(`Type` = 1 AND (`EndTime` > UNIX_TIMESTAMP() OR `PostEndTime` > UNIX_TIMESTAMP()))"; - if($CheckPlanetOwner['owner'] > 0) - { - $SFBSelectWhere[] = "(`Type` = 2 AND `ElementID` = {$CheckPlanetOwner['owner']} AND `EndTime` > UNIX_TIMESTAMP())"; - $SFBSelectWhere[] = "(`Type` = 3 AND `ElementID` = {$CheckPlanetOwner['id']} AND `EndTime` > UNIX_TIMESTAMP())"; - } - $SFBSelectWhere[] = "(`Type` = 2 AND `ElementID` = {$_User['id']} AND `EndTime` > UNIX_TIMESTAMP())"; - $SFBSelectWhere[] = "(`Type` = 3 AND `ElementID` = {$_Planet['id']} AND `EndTime` > UNIX_TIMESTAMP())"; - - $SFBSelect = ''; - $SFBSelect .= "SELECT `Type`, `BlockMissions`, `Reason`, `StartTime`, `EndTime`, `PostEndTime`, `ElementID`, `DontBlockIfIdle` FROM {{table}} WHERE `StartTime` <= UNIX_TIMESTAMP() AND "; - $SFBSelect .= implode(' OR ', $SFBSelectWhere); - $SFBSelect .= " ORDER BY `Type` ASC, `EndTime` DESC;"; - $LoadSFBData = doquery($SFBSelect, 'smart_fleet_blockade'); - if(mysql_num_rows($LoadSFBData) > 0) - { - while($GetSFBData = mysql_fetch_assoc($LoadSFBData)) - { - $BlockedMissions = false; - if($GetSFBData['BlockMissions'] == '0') - { - $BlockedMissions = true; - $AllMissionsBlocked = true; - } - else - { - $BlockedMissions = explode(',', $GetSFBData['BlockMissions']); - } - - if($BlockedMissions === true OR in_array($Fleet['Mission'], $BlockedMissions)) - { - if($GetSFBData['Type'] == 1) - { - // Global Blockade - if($GetSFBData['EndTime'] > $Now) - { - // Normal Blockade - if(!($GetSFBData['DontBlockIfIdle'] == 1 AND in_array($Fleet['Mission'], $_Vars_FleetMissions['military']) AND $CheckPlanetOwner['owner'] > 0 AND $CheckPlanetOwner['onlinetime'] <= ($Now - $Protections['idleTime']))) - { - $BlockFleet = true; - $BlockReason = $_Lang['SFB_Stop_GlobalBlockade']; - } - } - elseif($GetSFBData['PostEndTime'] > $Now) - { - // Post Blockade - if(in_array($Fleet['Mission'], $_Vars_FleetMissions['military']) AND $CheckPlanetOwner['owner'] > 0 AND - ( - ($AllMissionsBlocked !== true AND $CheckPlanetOwner['onlinetime'] > ($Now - $Protections['idleTime']) AND $CheckPlanetOwner['onlinetime'] < $GetSFBData['StartTime']) - OR - ($AllMissionsBlocked === true AND $CheckPlanetOwner['onlinetime'] > ($Now - $Protections['idleTime']) AND $CheckPlanetOwner['onlinetime'] < $GetSFBData['EndTime']) - )) - { - $BlockFleet = true; - $BlockReason = sprintf($_Lang['SFB_Stop_GlobalPostBlockade'], prettyDate('d m Y, H:i:s', $GetSFBData['PostEndTime'], 1)); - } - } - } - elseif($GetSFBData['Type'] == 2) - { - // Per User Blockade - $BlockFleet = true; - $BlockGivenReason = (empty($GetSFBData['Reason']) ? $_Lang['SFB_Stop_ReasonNotGiven'] : "\"{$GetSFBData['Reason']}\""); - $BlockReason = sprintf(($GetSFBData['ElementID'] == $_User['id'] ? $_Lang['SFB_Stop_UserBlockadeOwn'] : $_Lang['SFB_Stop_UserBlockade']), prettyDate('d m Y', $GetSFBData['EndTime'], 1), date('H:i:s', $GetSFBData['EndTime']), $BlockGivenReason); - } - elseif($GetSFBData['Type'] == 3) - { - // Per Planet Blockade - $BlockFleet = true; - $BlockGivenReason = (empty($GetSFBData['Reason']) ? $_Lang['SFB_Stop_ReasonNotGiven'] : "\"{$GetSFBData['Reason']}\""); - if($GetSFBData['ElementID'] == $_Planet['id']) - { - $UseLangVar = ($_Planet['planet_type'] == 1 ? $_Lang['SFB_Stop_PlanetBlockadeOwn_Planet'] : $_Lang['SFB_Stop_PlanetBlockadeOwn_Moon']); - } - else - { - $UseLangVar = ($Target['type'] == 1 ? $_Lang['SFB_Stop_PlanetBlockade_Planet'] : $_Lang['SFB_Stop_PlanetBlockade_Moon']); - } - $BlockReason = sprintf($UseLangVar, prettyDate('d m Y', $GetSFBData['EndTime'], 1), date('H:i:s', $GetSFBData['EndTime']), $BlockGivenReason); - } - } - - if($BlockFleet === true) - { - messageRed($BlockReason.$_Lang['SFB_Stop_LearnMore'], $_Lang['SFB_BoxTitle']); - } - } - } - - // --- Parse Fleet Array - $Fleet['count'] = 0; - $Fleet['storage'] = 0; - $Fleet['FuelStorage'] = 0; - $Fleet['TotalResStorage'] = 0; - - $FleetArray = array(); - if(!empty($Fleet['array']) AND (array)$Fleet['array'] === $Fleet['array']) - { - foreach($Fleet['array'] as $ShipData) - { - $ShipData = explode(',', $ShipData); - $ShipID = intval($ShipData[0]); - if(in_array($ShipID, $_Vars_ElementCategories['fleet'])) - { - if(!empty($_Vars_Prices[$ShipID]['engine'])) - { - $ShipCount = floor($ShipData[1]); - if($ShipCount > 0) - { - if($_Planet[$_Vars_GameElements[$ShipID]] >= $ShipCount) - { - $FleetArray[$ShipID] = $ShipCount; - $Fleet['count'] += $ShipCount; - $ThisStorage = $_Vars_Prices[$ShipID]['capacity'] * $ShipCount; - if($ShipID != 210) - { - $Fleet['storage'] += $ThisStorage; - } - else - { - $Fleet['FuelStorage'] += $ThisStorage; - } - $FleetRemover[] = "`{$_Vars_GameElements[$ShipID]}` = `{$_Vars_GameElements[$ShipID]}` - {$ShipCount}"; - } - else - { - messageRed($_Lang['fl1_NoEnoughShips'], $ErrorTitle); - } - } - else - { - messageRed($_Lang['fl2_ShipCountCantBe0'], $ErrorTitle); - } - } - else - { - messageRed($_Lang['fl1_CantSendUnflyable'], $ErrorTitle); - } - } - else - { - messageRed($_Lang['fl1_BadShipGiven'], $ErrorTitle); - } - } - } - else - { - messageRed($_Lang['fl2_FleetArrayPostEmpty'], $ErrorTitle); - } - if($Fleet['count'] <= 0) - { - messageRed($_Lang['fl2_ZeroShips'], $ErrorTitle); - } - $Fleet['array'] = $FleetArray; - unset($FleetArray); - - // --- Create Array of Available Missions - $AvailableMissions = array(); - if($Target['type'] == 2) - { - if($Fleet['array'][209] > 0) - { - $AvailableMissions[] = 8; - } - } - else - { - if($UsedPlanet) - { - if(!isset($Fleet['array'][210]) || $Fleet['count'] > $Fleet['array'][210]) - { - $AvailableMissions[] = 3; - } - if(!$YourPlanet) - { - $AvailableMissions[] = 1; - $AvailableMissions[] = 2; - if($OwnerFriend) - { - $AvailableMissions[] = 5; - } - if(isset($Fleet['array'][210]) && $Fleet['count'] == $Fleet['array'][210]) - { - $AvailableMissions[] = 6; - } - if($Target['type'] == 3 && isset($Fleet['array'][214]) && $Fleet['array'][214] > 0) - { - $AvailableMissions[] = 9; - } - } - else - { - $AvailableMissions[] = 4; - } - } - else - { - if($Target['planet'] == (MAX_PLANET_IN_SYSTEM + 1)) - { - $AvailableMissions[] = 15; - } - else - { - if($Fleet['array'][208] > 0 AND $Target['type'] == 1) - { - $AvailableMissions[] = 7; - } - } - } - } - - // --- Check if everything is OK with ACS - $Throw = false; - if($Fleet['Mission'] == 2 AND in_array(2, $AvailableMissions)) - { - if($Fleet['ACS_ID'] > 0) - { - $CheckACS = doquery("SELECT {{table}}.*, `fleets`.`fleet_send_time` AS `mf_start_time` FROM {{table}} LEFT JOIN {{prefix}}fleets AS `fleets` ON `fleets`.`fleet_id` = {{table}}.`main_fleet_id` WHERE {{table}}.`id` = {$Fleet['ACS_ID']} LIMIT 1;", 'acs', true); - if($CheckACS) - { - if($CheckACS['owner_id'] == $_User['id'] OR strstr($CheckACS['users'], '|'.$_User['id'].'|') !== FALSE) - { - if($CheckACS['end_target_id'] == $CheckPlanetOwner['id']) - { - if($CheckACS['fleets_count'] < ACS_MAX_JOINED_FLEETS) - { - if($CheckACS['start_time'] > $Now) - { - $UpdateACS = true; - } - else - { - $Throw = $_Lang['fl_acs_cannot_join_time_extended']; - } - } - else - { - $Throw = $_Lang['fl_acs_fleetcount_extended']; - } - } - else - { - $Throw = $_Lang['fl_acs_badcoordinates']; - } - } - else - { - $Throw = $_Lang['fl_acs_cannot_join_this_group']; - } - } - else - { - $Throw = $_Lang['fl_acs_bad_group_id']; - } - } - else - { - $Throw = $_Lang['fl_acs_bad_group_id']; - } - if($Throw) - { - messageRed($Throw, $ErrorTitle); - } - } - - // --- If Mission is not correct, show Error - if(!in_array($Fleet['Mission'], $AvailableMissions)) - { - switch($Fleet['Mission']) - { - case 1: - if($Target['type'] == 2) - { - $Throw = $_Lang['fl3_CantAttackDebris']; - } - else - { - if(!$UsedPlanet) - { - $Throw = $_Lang['fl3_CantAttackNonUsed']; - } - else - { - if($YourPlanet) - { - $Throw = $_Lang['fl3_CantAttackYourself']; - } - } - } - break; - case 2: - if($Target['type'] == 2) - { - $Throw = $_Lang['fl3_CantACSDebris']; - } - else - { - if(!$UsedPlanet) - { - $Throw = $_Lang['fl3_CantACSNonUsed']; - } - else - { - if($YourPlanet) - { - $Throw = $_Lang['fl3_CantACSYourself']; - } - } - } - break; - case 3: - if($Target['type'] == 2) - { - $Throw = $_Lang['fl3_CantTransportDebris']; - } - else - { - if(!$UsedPlanet) - { - $Throw = $_Lang['fl3_CantTransportNonUsed']; - } - else - { - $Throw = $_Lang['fl3_CantTransportSpyProbes']; - } - } - break; - case 4: - if($Target['type'] == 2) - { - $Throw = $_Lang['fl3_CantStayDebris']; - } - else - { - if(!$UsedPlanet) - { - $Throw = $_Lang['fl3_CantStayNonUsed']; - } - else - { - if(!$YourPlanet) - { - $Throw = $_Lang['fl3_CantStayNonYourself']; - } - } - } - break; - case 5: - if($Target['type'] == 2) - { - $Throw = $_Lang['fl3_CantProtectDebris']; - } - else - { - if(!$UsedPlanet) - { - $Throw = $_Lang['fl3_CantProtectNonUsed']; - } - else - { - if($YourPlanet) - { - $Throw = $_Lang['fl3_CantProtectYourself']; - } - else - { - $Throw = $_Lang['fl3_CantProtectNonFriend']; - } - } - } - break; - case 6: - if($Target['type'] == 2) - { - $Throw = $_Lang['fl3_CantSpyDebris']; - } - else - { - if(!$UsedPlanet) - { - $Throw = $_Lang['fl3_CantSpyNonUsed']; - } - else - { - if($YourPlanet) - { - $Throw = $_Lang['fl3_CantSpyYourself']; - } - else - { - $Throw = $_Lang['fl3_CantSpyProbesCount']; - } - } - } - break; - case 7: - if($UsedPlanet) - { - $Throw = $_Lang['fl3_CantSettleOnUsed']; - } - else - { - if($Target['type'] != 1) - { - $Throw = $_Lang['fl3_CantSettleNonPlanet']; - } - else - { - $Throw = $_Lang['fl3_CantSettleNoShips']; - } - } - break; - case 8: - if($Target['type'] != 2) - { - $Throw = $_Lang['fl3_CantRecycleNonDebris']; - } - else - { - $Throw = $_Lang['fl3_CantRecycleNoShip']; - } - break; - case 9: - if($Target['type'] == 2) - { - $Throw = $_Lang['fl3_CantDestroyDebris']; - } - else - { - if(!$UsedPlanet) - { - $Throw = $_Lang['fl3_CantDestroyNonUsed']; - } - else - { - if($YourPlanet) - { - $Throw = $_Lang['fl3_CantDestroyYourself']; - } - else - { - if($Target['type'] != 3) - { - $Throw = $_Lang['fl3_CantDestroyNonMoon']; - } - else - { - $Throw = $_Lang['fl3_CantDestroyNoShip']; - } - } - } - } - break; - } - if($Throw) - { - messageRed($Throw, $ErrorTitle); - } - messageRed($_Lang['fl3_BadMissionSelected'], $ErrorTitle); - } - - // --- If Mission is Recycling and there is no Debris Field, show Error - if($Fleet['Mission'] == 8) - { - if($CheckDebrisField['metal'] <= 0 AND $CheckDebrisField['crystal'] <= 0) - { - messageRed($_Lang['fl3_NoDebrisFieldHere'], $ErrorTitle); - } - } - - // --- Check if Expeditions and HoldingTimes are Correct - $Throw = false; - $Fleet['StayTime'] = 0; - if($Fleet['Mission'] == 15) - { - if($Fleet['ExpeTime'] < 1) - { - $Throw = $_Lang['fl3_Expedition_Min1H']; - } - elseif($Fleet['ExpeTime'] > 12) - { - $Throw = $_Lang['fl3_Expedition_Max12H']; - } - $Fleet['StayTime'] = $Fleet['ExpeTime'] * 3600; - } - elseif($Fleet['Mission'] == 5) - { - if(!in_array($Fleet['HoldTime'], array(1, 2, 4, 8, 16, 32))) - { - $Throw = $_Lang['fl3_Holding_BadTime']; - } - $Fleet['StayTime'] = $Fleet['HoldTime'] * 3600; - } - if($Throw) - { - messageRed($Throw, $ErrorTitle); - } - - // --- Set Variables to better usage - if(!empty($CheckDebrisField)) - { - $TargetData = &$CheckDebrisField; - } - else - { - $TargetData = &$CheckPlanetOwner; - } - - // --- Check if User data are OK - if($UsedPlanet AND !$YourPlanet AND !$PlanetAbandoned) - { - $SaveMyTotalRank = false; - - $StatsData['his'] = ($TargetData['total_points'] > 0 ? $TargetData['total_points'] : 0); - if(!CheckAuth('programmer')) - { - $StatsData['mine'] = ($_User['total_points'] > 0 ? $_User['total_points'] : 0); - } - else - { - $StatsData['mine'] = $StatsData['his']; - if($_User['total_rank'] <= 0) - { - $SaveMyTotalRank = $_User['total_rank']; - $_User['total_rank'] = $TargetData['total_rank']; - } - } - - if(isOnVacation($TargetData)) - { - if($SaveMyTotalRank !== false) - { - $_User['total_rank'] = $SaveMyTotalRank; - } - if($TargetData['is_banned'] == 1) - { - messageRed($_Lang['fl3_CantSendBanned'], $ErrorTitle); - } - else - { - messageRed($_Lang['fl3_CantSendVacation'], $ErrorTitle); - } - } - - if($Protections['ally'] == 1) - { - if($_User['ally_id'] > 0 AND $_User['ally_id'] == $TargetData['ally_id']) - { - if(in_array($Fleet['Mission'], $Protections['mtypes'])) - { - if($SaveMyTotalRank !== false) - { - $_User['total_rank'] = $SaveMyTotalRank; - } - messageRed($_Lang['fl3_CantSendAlly'], $ErrorTitle); - } - } - } - - if($Protections['enable']) - { - $Throw = false; - if(in_array($Fleet['Mission'], $Protections['mtypes'])) - { - if($_User['total_rank'] >= 1) - { - if($TargetData['total_rank'] >= 1) - { - if($_User['NoobProtection_EndTime'] > $Now) - { - $Throw = sprintf($_Lang['fl3_ProtectNewTimeYou'], pretty_time($_User['NoobProtection_EndTime'] - $Now)); - } - else if($TargetData['first_login'] == 0) - { - $Throw = $_Lang['fl3_ProtectNewTimeHe2']; - } - else if($TargetData['NoobProtection_EndTime'] > $Now) - { - $Throw = sprintf($_Lang['fl3_ProtectNewTimeHe'], pretty_time($TargetData['NoobProtection_EndTime'] - $Now)); - } - - if($Throw === false) - { - if($StatsData['mine'] >= $Protections['basicLimit']) - { - if($TargetData['onlinetime'] >= ($Now - $Protections['idleTime'])) - { - if($StatsData['his'] < $Protections['basicLimit']) - { - $Throw = sprintf($_Lang['fl3_ProtectHIWeak'], prettyNumber($Protections['basicLimit'])); - } - else - { - if($StatsData['his'] < $Protections['weakLimit'] OR $StatsData['mine'] < $Protections['weakLimit']) - { - if($StatsData['mine'] > ($StatsData['his'] * $Protections['weakMulti'])) - { - $Throw = sprintf($_Lang['fl3_ProtectUR2Strong'], prettyNumber($Protections['weakMulti'])); - } - elseif(($StatsData['mine'] * $Protections['weakMulti']) < $StatsData['his']) - { - $Throw = sprintf($_Lang['fl3_ProtectHI2Strong'], prettyNumber($Protections['weakMulti'])); - } - } - else - { - if($Protections['antifarm_enabled'] == true AND ($StatsData['mine'] / $StatsData['his']) >= $Protections['antifarm_rate']) - { - $DoFarmCheck = true; - } - } - } - } - } - else - { - $Throw = sprintf($_Lang['fl3_ProtectURWeak'], prettyNumber($Protections['basicLimit'])); - } - } - } - else - { - $Throw = $_Lang['fl3_ProtectHIStatNotCalc']; - } - } - else - { - $Throw = $_Lang['fl3_ProtectURStatNotCalc']; - } - if($Protections['adminEnable']) - { - if(CheckAuth('supportadmin') OR CheckAuth('supportadmin', AUTHCHECK_NORMAL, $TargetData)) - { - if(CheckAuth('supportadmin')) - { - $Throw = $_Lang['fl3_ProtectAdminCant']; - } - else - { - $Throw = $_Lang['fl3_ProtectCantAdmin']; - } - } - } - - if(empty($Throw) AND ($DoFarmCheck === true OR $Protections['bashLimit_enabled'] === true)) - { - if($DoFarmCheck === true) - { - $TodayIs = explode('.', date('d.m.Y')); - $TodayTimestamp = mktime(0, 0, 0, $TodayIs[1], $TodayIs[0], $TodayIs[2]); - if($TodayTimestamp <= 0) - { - $TodayTimestamp = 0; - } - $BashTimestamps[] = array('type' => 'farm', 'key' => 'antifarm', 'stamp' => $TodayTimestamp); - } - if($Protections['bashLimit_enabled'] === true) - { - $BashTimestamps[] = array('type' => 'bash', 'key' => 'bashLimit', 'stamp' => $Now - $Protections['bashLimit_interval']); - } - sort($BashTimestamps, SORT_ASC); - $BashTimestampMinVal = $BashTimestamps[0]['stamp']; - - $GetFleetArchiveRecords = doquery("SELECT * FROM {{table}} WHERE (`Fleet_Time_Start` + `Fleet_Time_ACSAdd`) >= {$BashTimestampMinVal} AND `Fleet_Owner` = {$_User['id']} AND `Fleet_End_Owner` = {$TargetData['owner']} AND `Fleet_Mission` IN (1, 2, 9) AND `Fleet_ReportID` > 0 AND `Fleet_Destroyed_Reason` NOT IN (1, 4, 11);", 'fleet_archive'); - if(mysql_num_rows($GetFleetArchiveRecords) > 0) - { - while($ArchiveRecord = mysql_fetch_assoc($GetFleetArchiveRecords)) - { - foreach($BashTimestamps as $Values) - { - if(($ArchiveRecord['Fleet_Time_Start'] + $ArchiveRecord['Fleet_Time_ACSAdd']) >= $Values['stamp']) - { - $GetEndID = $ArchiveRecord['Fleet_End_ID']; - if($ArchiveRecord['Fleet_End_ID_Changed'] > 0) - { - $GetEndID = $ArchiveRecord['Fleet_End_ID_Changed']; - } - $SaveArchiveData[$Values['type']][$GetEndID] += 1; - } - } - } - } - - foreach($BashTimestamps as $Values) - { - if(!empty($SaveArchiveData)) - { - $FleetArchiveRecordsCount = array_sum($SaveArchiveData[$Values['type']]); - } - if($FleetArchiveRecordsCount >= $Protections[$Values['key'].'_counttotal']) - { - $Throw = sprintf($_Lang['fl3_Protect_AttackLimitTotal'], $_Lang['fl3_Protect_AttackLimit_'.$Values['key']]); - break; - } - elseif(($FleetArchiveRecordsCount + $FlyingFleetsData[$TargetData['owner']]['count']) >= $Protections[$Values['key'].'_counttotal']) - { - $Throw = sprintf($_Lang['fl3_Protect_AttackLimitTotalFly'], $_Lang['fl3_Protect_AttackLimit_'.$Values['key']]); - break; - } - elseif($SaveArchiveData[$Values['type']][$TargetData['id']] >= $Protections[$Values['key'].'_countplanet']) - { - $Throw = sprintf($_Lang['fl3_Protect_AttackLimitSingle'], $_Lang['fl3_Protect_AttackLimit_'.$Values['key']]); - break; - } - elseif(($SaveArchiveData[$Values['type']][$TargetData['id']] + $FlyingFleetsData[$TargetData['owner']][$TargetData['id']]) >= $Protections[$Values['key'].'_countplanet']) - { - $Throw = sprintf($_Lang['fl3_Protect_AttackLimitSingleFly'], $_Lang['fl3_Protect_AttackLimit_'.$Values['key']]); - break; - } - } - } - - if($Throw) - { - if($SaveMyTotalRank !== false) - { - $_User['total_rank'] = $SaveMyTotalRank; - } - messageRed($Throw, $ErrorTitle); - } - } - } - - if($SaveMyTotalRank !== false) - { - $_User['total_rank'] = $SaveMyTotalRank; - } - } - - // --- Calculate Speed and Distance - $AllFleetSpeed = GetFleetMaxSpeed($Fleet['array'], 0, $_User); - $GenFleetSpeed = $Fleet['Speed']; - $SpeedFactor = GetGameSpeedFactor(); - $MaxFleetSpeed = min($AllFleetSpeed); - if(MORALE_ENABLED) - { - if($_User['morale_level'] <= MORALE_PENALTY_FLEETSLOWDOWN) - { - $MaxFleetSpeed *= MORALE_PENALTY_FLEETSLOWDOWN_VALUE; - } - } - $Distance = GetTargetDistance($_Planet['galaxy'], $Target['galaxy'], $_Planet['system'], $Target['system'], $_Planet['planet'], $Target['planet']); - - $Allow_UseQuantumGate = false; - if($Fleet['UseQuantum']) - { - $QuantumGate_Disallow = array(1, 2, 6, 9); - if($_Planet['quantumgate'] == 1) - { - if(!in_array($Fleet['Mission'], $QuantumGate_Disallow)) - { - if($UsedPlanet) - { - if($TargetData['quantumgate'] == 1) - { - if($YourPlanet) - { - $Allow_UseQuantumGate = true; - $QuantumGate_UseType = 1; - } - else - { - if($OwnerFriend OR $OwnerHasMarcantilePact) - { - $Allow_UseQuantumGate = true; - $QuantumGate_UseType = 1; - } - else - { - $Check_SpaceTimeJump = true; - } - } - } - else - { - $Check_SpaceTimeJump = true; - } - } - else - { - $Check_SpaceTimeJump = true; - } - - if($Check_SpaceTimeJump === true) - { - if($_Planet['galaxy'] == $Target['galaxy']) - { - if(($_Planet['quantumgate_lastuse'] + ($QuantumGateInterval * 60 * 60)) <= $Now) - { - $Allow_UseQuantumGate = true; - $QuantumGate_UseType = 2; - } - else - { - $CannotUseTill = $_Planet['quantumgate_lastuse'] + ($QuantumGateInterval * 60 * 60); - messageRed(sprintf($_Lang['CannotUseQuantumGateTill'], prettyDate('d m Y \o H:i:s', $CannotUseTill, 1)), $ErrorTitle); - } - } - else - { - messageRed($_Lang['fl3_SpaceTimeJumpGalaxy'], $ErrorTitle); - } - } - } - else - { - messageRed($_Lang['fl3_QuantumDisallowAttack'], $ErrorTitle); - } - } - else - { - messageRed($_Lang['fl3_NoQuantumGate'], $ErrorTitle); - } - } - - if($Allow_UseQuantumGate) - { - if($QuantumGate_UseType == 1) - { - $DurationTarget = $DurationBack = 1; - $Consumption = 0; - } - elseif($QuantumGate_UseType == 2) - { - $DurationTarget = 1; - $DurationBack = GetMissionDuration($GenFleetSpeed, $MaxFleetSpeed, $Distance, $SpeedFactor); - $Consumption = GetFleetConsumption($Fleet['array'], $SpeedFactor, $DurationBack, $Distance, $_User) / 2; - } - } - else - { - $DurationTarget = $DurationBack = GetMissionDuration($GenFleetSpeed, $MaxFleetSpeed, $Distance, $SpeedFactor); - $Consumption = GetFleetConsumption($Fleet['array'], $SpeedFactor, $DurationTarget, $Distance, $_User); - } - - if($_Planet['deuterium'] < $Consumption) - { - messageRed($_Lang['fl3_NoEnoughFuel'], $ErrorTitle); - } - if($Consumption > ($Fleet['storage'] + $Fleet['FuelStorage'])) - { - messageRed($_Lang['fl3_NoEnoughtStorage4Fuel'], $ErrorTitle); - } - if($_Planet['deuterium'] < ($Consumption + $Fleet['resources']['deuterium'])) - { - messageRed($_Lang['fl3_PlanetNoEnoughdeuterium'], $ErrorTitle); - } - if($Fleet['FuelStorage'] >= $Consumption) - { - $Fleet['storage'] += $Consumption; - } - else - { - $Fleet['storage'] += $Fleet['FuelStorage']; - } - $Fleet['storage'] -= $Consumption; - foreach($Fleet['resources'] as $Value) - { - $Fleet['TotalResStorage'] += $Value; - } - if($Fleet['TotalResStorage'] > $Fleet['storage']) - { - messageRed($_Lang['fl3_NoEnoughStorage4Res'], $ErrorTitle); - } - - $Fleet['SetCalcTime'] = $Now + $DurationTarget; - $Fleet['SetStayTime'] = ($Fleet['StayTime'] > 0 ? $Fleet['SetCalcTime'] + $Fleet['StayTime'] : '0'); - $Fleet['SetBackTime'] = $Fleet['SetCalcTime'] + $Fleet['StayTime'] + $DurationBack; - - if(isset($UpdateACS)) - { - $NewEndTime = $Fleet['SetCalcTime']; - $OldFlightTime = $CheckACS['start_time_org'] - $CheckACS['mf_start_time']; - $FlightDifference = ($NewEndTime - $CheckACS['mf_start_time']) - $OldFlightTime; - - if($OldFlightTime == 0) - { - $OldFlightTime = 1; - } - if($FlightDifference == 0) - { - $FlightDifference = 1; - } - if(($FlightDifference/$OldFlightTime) <= 0.3) - { - if($NewEndTime < $CheckACS['start_time']) - { - $Difference = $CheckACS['start_time'] - $NewEndTime; - $Fleet['SetCalcTime'] += $Difference; - $Fleet['SetBackTime'] += $Difference; - } - elseif($NewEndTime > $CheckACS['start_time']) - { - $Difference = $NewEndTime - $CheckACS['start_time']; - $UpdateACSRow[] = "`start_time` = `start_time` + {$Difference}"; - $UpdateACSFleets[] = "`fleet_start_time` = `fleet_start_time` + {$Difference}"; - $UpdateACSFleets[] = "`fleet_end_time` = `fleet_end_time` + {$Difference}"; - } - } - else - { - messageRed($_Lang['fl3_ACSFleet2Slow'], $ErrorTitle); - } - } - - if($Allow_UseQuantumGate AND $QuantumGate_UseType == 2) - { - $Add2UpdatePlanet[] = "`quantumgate_lastuse` = {$Now}"; - $Add2UpdatePlanetPHP['quantumgate_lastuse'] = $Now; - } - - // MultiAlert System - $SendAlert = false; - $IPIntersectionFound = 'false'; - $IPIntersectionFiltred = 'false'; - $IPIntersectionNow = 'false'; - if($UsedPlanet AND !$YourPlanet AND !$PlanetAbandoned) - { - include($_EnginePath.'includes/functions/AlertSystemUtilities.php'); - $CheckIntersection = AlertUtils_IPIntersect($_User['id'], $TargetData['owner'], array - ( - 'LastTimeDiff' => (TIME_DAY * 30), - 'ThisTimeDiff' => (TIME_DAY * 30), - 'ThisTimeStamp' => ($Now - SERVER_MAINOPEN_TSTAMP) - )); - if($CheckIntersection !== false) - { - $IPIntersectionFound = 'true'; - if($_User['user_lastip'] == $TargetData['lastip']) - { - $IPIntersectionNow = 'true'; - } - - $FiltersData['place'] = 1; - $FiltersData['alertsender'] = 1; - $FiltersData['users'] = array($_User['id'], $TargetData['owner']); - $FiltersData['ips'] = $CheckIntersection['Intersect']; - $FiltersData['sender'] = $_User['id']; - $FiltersData['target'] = $TargetData['owner']; - foreach($CheckIntersection['Intersect'] as $IP) - { - $FiltersData['logcount'][$IP][$_User['id']] = $CheckIntersection['IPLogData'][$_User['id']][$IP]['Count']; - $FiltersData['logcount'][$IP][$TargetData['owner']] = $CheckIntersection['IPLogData'][$TargetData['owner']][$IP]['Count']; - } - - if($_User['multiIP_DeclarationID'] > 0 AND $_User['multiIP_DeclarationID'] == $TargetData['multiIP_DeclarationID']) - { - $Query_CheckDeclaration = ''; - $Query_CheckDeclaration .= "SELECT `id` FROM {{table}} WHERE "; - $Query_CheckDeclaration .= "`status` = 1 AND `id` = {$_User['multiIP_DeclarationID']} "; - $Query_CheckDeclaration .= "LIMIT 1;"; - $CheckDeclaration = doquery($Query_CheckDeclaration, 'declarations', true); - $DeclarationID = $CheckDeclaration['id']; - } - else - { - $DeclarationID = 0; - } - - $FilterResult = AlertUtils_CheckFilters($FiltersData); - if($FilterResult['FilterUsed']) - { - $IPIntersectionFiltred = 'true'; - } - if(!$FilterResult['SendAlert']) - { - $DontSendAlert = true; - } - if(!$FilterResult['ShowAlert']) - { - $DontShowAlert = true; - } - - if(!isset($DontSendAlert)) - { - $SendAlert = true; - } - if(1 == 0 AND $DontShowAlert !== true) - { - // Currently there is no indicator that user wants to get MultiAlert Messages (do disable this code) - $LockFleetSending = true; - $ShowMultiAlert = true; - $_Alert['MultiAlert']['Data']['Blocked'] = true; - } - } - } - - if(!isset($LockFleetSending)) - { - $FleetArray = array(); - foreach($Fleet['array'] as $ShipID => $ShipCount) - { - $FleetArray[] = "{$ShipID},{$ShipCount}"; - } - $FleetArrayCopy = $Fleet['array']; - $Fleet['array'] = implode(';', $FleetArray); - - if(empty($TargetData['id'])) - { - $TargetData['id'] = '0'; - } - if(empty($TargetData['owner'])) - { - $TargetData['owner'] = '0'; - } - if(empty($TargetData['galaxy_id'])) - { - $TargetData['galaxy_id'] = '0'; - } - - $Query_Insert = ''; - $Query_Insert .= "INSERT INTO {{table}} SET "; - $Query_Insert .= "`fleet_owner` = {$_User['id']}, "; - $Query_Insert .= "`fleet_mission` = {$Fleet['Mission']}, "; - $Query_Insert .= "`fleet_amount` = {$Fleet['count']}, "; - $Query_Insert .= "`fleet_array` = '{$Fleet['array']}', "; - $Query_Insert .= "`fleet_start_time` = {$Fleet['SetCalcTime']}, "; - $Query_Insert .= "`fleet_start_id` = {$_Planet['id']}, "; - $Query_Insert .= "`fleet_start_galaxy` = {$_Planet['galaxy']}, "; - $Query_Insert .= "`fleet_start_system` = {$_Planet['system']}, "; - $Query_Insert .= "`fleet_start_planet` = {$_Planet['planet']}, "; - $Query_Insert .= "`fleet_start_type` = {$_Planet['planet_type']}, "; - $Query_Insert .= "`fleet_end_time` = {$Fleet['SetBackTime']}, "; - $Query_Insert .= "`fleet_end_id` = {$TargetData['id']}, "; - $Query_Insert .= "`fleet_end_id_galaxy` = {$TargetData['galaxy_id']}, "; - $Query_Insert .= "`fleet_end_stay` = {$Fleet['SetStayTime']}, "; - $Query_Insert .= "`fleet_end_galaxy` = {$Target['galaxy']}, "; - $Query_Insert .= "`fleet_end_system` = {$Target['system']}, "; - $Query_Insert .= "`fleet_end_planet` = {$Target['planet']}, "; - $Query_Insert .= "`fleet_end_type` = {$Target['type']}, "; - $Query_Insert .= "`fleet_resource_metal` = {$Fleet['resources']['metal']}, "; - $Query_Insert .= "`fleet_resource_crystal` = {$Fleet['resources']['crystal']}, "; - $Query_Insert .= "`fleet_resource_deuterium` = {$Fleet['resources']['deuterium']}, "; - $Query_Insert .= "`fleet_target_owner` = '{$TargetData['owner']}', "; - $Query_Insert .= "`fleet_send_time` = {$Now};"; - doquery($Query_Insert, 'fleets'); - - $LastFleetID = doquery("SELECT LAST_INSERT_ID() as `id`;", '', true); - $LastFleetID = $LastFleetID['id']; - - // PushAlert - if($UsedPlanet AND !$YourPlanet AND !$PlanetAbandoned) - { - if($Fleet['Mission'] == 3) - { - if($StatsData['mine'] < $StatsData['his']) - { - if(!empty($Fleet['resources'])) - { - foreach($Fleet['resources'] as $ThisValue) - { - if($ThisValue > 0) - { - $_Alert['PushAlert']['HasResources'] = true; - break; - } - } - } - if($_Alert['PushAlert']['HasResources'] === true) - { - $FiltersData = array(); - $FiltersData['place'] = 1; - $FiltersData['alertsender'] = 1; - $FiltersData['users'] = array($_User['id'], $TargetData['owner']); - $FiltersData['sender'] = $_User['id']; - $FiltersData['target'] = $TargetData['owner']; - $FilterResult = AlertUtils_CheckFilters($FiltersData, array('DontLoad' => true, 'DontLoad_OnlyIfCacheEmpty' => true)); - - if($FilterResult['SendAlert']) - { - $_Alert['PushAlert']['Data']['TargetUserID'] = $TargetData['owner']; - if($_User['ally_id'] > 0 AND $_User['ally_id'] == $TargetData['ally_id']) - { - $_Alert['PushAlert']['Data']['SameAlly'] = $TargetData['ally_id']; - } - else if($OwnerIsAlliedUser === true) - { - $_Alert['PushAlert']['Data']['AllyPact'] = array - ( - 'SenderAlly' => $_User['ally_id'], - 'TargetAlly' => $TargetData['ally_id'], - ); - } - if($OwnerIsBuddyFriend === true) - { - $_Alert['PushAlert']['Data']['BuddyFriends'] = true; - } - $_Alert['PushAlert']['Data']['FleetID'] = $LastFleetID; - $_Alert['PushAlert']['Data']['Stats']['Sender'] = array('Points' => $StatsData['mine'], 'Position' => $_User['total_rank']); - $_Alert['PushAlert']['Data']['Stats']['Target'] = array('Points' => $StatsData['his'], 'Position' => $TargetData['total_rank']); - $_Alert['PushAlert']['Data']['Resources'] = array - ( - 'Metal' => floatval($Fleet['resources']['metal']), - 'Crystal' => floatval($Fleet['resources']['crystal']), - 'Deuterium' => floatval($Fleet['resources']['deuterium']) - ); - - Alerts_Add(1, $Now, 5, 4, 5, $_User['id'], $_Alert['PushAlert']['Data']); - } - } - } - } - } - } - - if($SendAlert) - { - $_Alert['MultiAlert']['Importance'] = 10; - $_Alert['MultiAlert']['Data']['MissionID'] = $Fleet['Mission']; - if($LastFleetID > 0) - { - $_Alert['MultiAlert']['Data']['FleetID'] = $LastFleetID; - } - $_Alert['MultiAlert']['Data']['TargetUserID'] = $TargetData['owner']; - foreach($CheckIntersection['Intersect'] as $ThisIPID) - { - $_Alert['MultiAlert']['Data']['Intersect'][] = array - ( - 'IPID' => $ThisIPID, - 'SenderData' => $CheckIntersection['IPLogData'][$_User['id']][$ThisIPID], - 'TargetData' => $CheckIntersection['IPLogData'][$TargetData['owner']][$ThisIPID] - ); - } - if($DeclarationID > 0) - { - $_Alert['MultiAlert']['Data']['DeclarationID'] = $DeclarationID; - $_Alert['MultiAlert']['Type'] = 2; - } - else - { - $_Alert['MultiAlert']['Type'] = 1; - } - - $Query_AlertOtherUsers = ''; - $Query_AlertOtherUsers .= "SELECT DISTINCT `User_ID` FROM {{table}} WHERE "; - $Query_AlertOtherUsers .= "`User_ID` NOT IN ({$_User['id']}, {$TargetData['owner']}) AND "; - $Query_AlertOtherUsers .= "`IP_ID` IN (".implode(', ', $CheckIntersection['Intersect']).") AND "; - $Query_AlertOtherUsers .= "`Count` > `FailCount`;"; - $Result_AlertOtherUsers = doquery($Query_AlertOtherUsers, 'user_enterlog'); - if(mysql_num_rows($Result_AlertOtherUsers) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_AlertOtherUsers)) - { - $_Alert['MultiAlert']['Data']['OtherUsers'][] = $FetchData['User_ID']; - } - } - - Alerts_Add(1, $Now, $_Alert['MultiAlert']['Type'], 1, $_Alert['MultiAlert']['Importance'], $_User['id'], $_Alert['MultiAlert']['Data']); - } - - if(isset($ShowMultiAlert)) - { - messageRed($_Lang['MultiAlert'], $_Lang['fl_error']); - } - - if(isset($UpdateACS)) - { - if(!empty($CheckACS['fleets_id'])) - { - $NewFleetsID[] = $CheckACS['fleets_id']; - } - $NewFleetsID[] = '|'.$LastFleetID.'|'; - $UpdateACSRow[] = "`fleets_id` = '".implode(',', $NewFleetsID)."'"; - - if(!empty($CheckACS['user_joined'])) - { - if(strstr($CheckACS['user_joined'], '|'.$_User['id'].'|') === FALSE) - { - $NewUsers[] = $CheckACS['user_joined']; - $NewUsers[] = '|'.$_User['id'].'|'; - $UpdateACSRow[] = "`user_joined` = '".implode(',', $NewUsers)."'"; - } - } - else - { - $UpdateACSRow[] = "`user_joined` = '|{$_User['id']}|'"; - } - - $UpdateACSRow[] = "`fleets_count` = `fleets_count` + 1"; - - if(!empty($UpdateACSRow)) - { - doquery("UPDATE {{table}} SET ".implode(', ', $UpdateACSRow)." WHERE `id` = {$Fleet['ACS_ID']};", 'acs'); - } - - if(!empty($UpdateACSFleets)) - { - $Fleets = $CheckACS['main_fleet_id']; - if(!empty($CheckACS['fleets_id'])) - { - $Fleets .= ','.str_replace('|', '', $CheckACS['fleets_id']); - } - doquery("UPDATE {{table}} SET ".implode(', ', $UpdateACSFleets)." WHERE `fleet_id` IN ({$Fleets});", 'fleets'); - } - } - - if($Allow_UseQuantumGate) - { - $QuantumGate_Used = '1'; - } - else - { - $QuantumGate_Used = '0'; - } - $QryArchive = ''; - $QryArchive .= "INSERT INTO {{table}} (`Fleet_ID`, `Fleet_Owner`, `Fleet_Mission`, `Fleet_Array`, `Fleet_Time_Send`, `Fleet_Time_Start`, `Fleet_Time_Stay`, `Fleet_Time_End`, `Fleet_Start_ID`, `Fleet_Start_Galaxy`, `Fleet_Start_System`, `Fleet_Start_Planet`, `Fleet_Start_Type`, `Fleet_Start_Res_Metal`, `Fleet_Start_Res_Crystal`, `Fleet_Start_Res_Deuterium`, `Fleet_End_ID`, `Fleet_End_ID_Galaxy`, `Fleet_End_Galaxy`, `Fleet_End_System`, `Fleet_End_Planet`, `Fleet_End_Type`, `Fleet_End_Owner`, `Fleet_ACSID`, `Fleet_Info_HadSameIP_Ever`, `Fleet_Info_HadSameIP_Ever_Filtred`, `Fleet_Info_HadSameIP_OnSend`, `Fleet_Info_UsedTeleport`) VALUES "; - $QryArchive .= " ({$LastFleetID}, {$_User['id']}, {$Fleet['Mission']}, '{$Fleet['array']}', {$Now}, {$Fleet['SetCalcTime']}, {$Fleet['SetStayTime']}, {$Fleet['SetBackTime']}, {$_Planet['id']}, {$_Planet['galaxy']}, {$_Planet['system']}, {$_Planet['planet']}, {$_Planet['planet_type']}, {$Fleet['resources']['metal']}, {$Fleet['resources']['crystal']}, {$Fleet['resources']['deuterium']}, '{$TargetData['id']}', '{$TargetData['galaxy_id']}', {$Target['galaxy']}, {$Target['system']}, {$Target['planet']}, {$Target['type']}, '{$TargetData['owner']}', '{$Fleet['ACS_ID']}', {$IPIntersectionFound}, {$IPIntersectionFiltred}, {$IPIntersectionNow}, {$QuantumGate_Used}) "; - - if(!empty($UpdateACSFleets)) - { - $UpdateACSFleetsIDs = explode(',', str_replace('|', '', $CheckACS['fleets_id'])); - $UpdateACSFleetsIDs[] = $CheckACS['main_fleet_id']; - if(!empty($UpdateACSFleetsIDs)) - { - $QryArchive .= ', '; - foreach($UpdateACSFleetsIDs as $FleetID) - { - if(!empty($FleetID)) - { - $QryArchiveA[] = "({$FleetID}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)"; - } - } - $QryArchive .= implode(', ',$QryArchiveA); - $QryArchive .= " ON DUPLICATE KEY UPDATE "; - $QryArchive .= "`Fleet_Time_ACSAdd` = `Fleet_Time_ACSAdd` + {$Difference}"; - } - } - doquery($QryArchive, 'fleet_archive'); - - $_Planet['metal'] -= $Fleet['resources']['metal']; - $_Planet['crystal'] -= $Fleet['resources']['crystal']; - $_Planet['deuterium'] -= ($Fleet['resources']['deuterium'] + $Consumption); - - $_Lang['ShipsRows'] = ''; - foreach($FleetArrayCopy as $ShipID => $ShipCount) - { - $_Planet[$_Vars_GameElements[$ShipID]] -= $ShipCount; - $_Lang['ShipsRows'] .= ''.$_Lang['tech'][$ShipID].''.prettyNumber($ShipCount).''; - } - if(!empty($Add2UpdatePlanetPHP)) - { - foreach($Add2UpdatePlanetPHP as $Key => $Value) - { - $_Planet[$Key] = $Value; - } - } - - $QryUpdatePlanet = ''; - $QryUpdatePlanet .= "UPDATE {{table}} SET "; - $QryUpdatePlanet .= implode(', ', $FleetRemover).', '; - $QryUpdatePlanet .= "`metal` = '{$_Planet['metal']}', "; - $QryUpdatePlanet .= "`crystal` = '{$_Planet['crystal']}', "; - $QryUpdatePlanet .= "`deuterium` = '{$_Planet['deuterium']}' "; - if(!empty($Add2UpdatePlanet)) - { - $QryUpdatePlanet .= ", ".implode(', ', $Add2UpdatePlanet); - } - $QryUpdatePlanet .= " WHERE "; - $QryUpdatePlanet .= "`id` = {$_Planet['id']};"; - - doquery('LOCK TABLE {{table}} WRITE', 'planets'); - doquery($QryUpdatePlanet, 'planets'); - doquery('UNLOCK TABLES', ''); - - // User Development Log - if($Fleet['resources']['metal'] > 0) - { - $Add2UserDev_Log[] = 'M,'.$Fleet['resources']['metal']; - } - if($Fleet['resources']['crystal'] > 0) - { - $Add2UserDev_Log[] = 'C,'.$Fleet['resources']['crystal']; - } - if($Fleet['resources']['deuterium'] > 0) - { - $Add2UserDev_Log[] = 'D,'.$Fleet['resources']['deuterium']; - } - if($Consumption > 0) - { - $Add2UserDev_Log[] = 'F,'.$Consumption; - } - $RTrim = rtrim($Fleet['array'], ';'); - if(!empty($Add2UserDev_Log)) - { - $Add2UserDev_Log = ';'.implode(';', $Add2UserDev_Log); - } - $UserDev_Log[] = array('PlanetID' => $_Planet['id'], 'Date' => $Now, 'Place' => 10, 'Code' => $Fleet['Mission'], 'ElementID' => $LastFleetID, 'AdditionalData' => $RTrim.$Add2UserDev_Log); - // --- - - $_Lang['FleetMission'] = $_Lang['type_mission'][$Fleet['Mission']]; - $_Lang['FleetDistance'] = prettyNumber($Distance); - $_Lang['FleetSpeed'] = prettyNumber($MaxFleetSpeed); - $_Lang['FleetFuel'] = prettyNumber($Consumption); - $_Lang['StartGalaxy'] = $_Planet['galaxy']; - $_Lang['StartSystem'] = $_Planet['system']; - $_Lang['StartPlanet'] = $_Planet['planet']; - $_Lang['StartType'] = ($_Planet['planet_type'] == 1 ? 'planet' : ($_Planet['planet_type'] == 3 ? 'moon' : 'debris')); - $_Lang['TargetGalaxy'] = $Target['galaxy']; - $_Lang['TargetSystem'] = $Target['system']; - $_Lang['TargetPlanet'] = $Target['planet']; - $_Lang['TargetType'] = ($Target['type'] == 1 ? 'planet' : ($Target['type'] == 3 ? 'moon' : 'debris')); - $_Lang['FleetStartTime'] = prettyDate('d m Y H:i:s', $Fleet['SetCalcTime'], 1); - $_Lang['FleetEndTime'] = prettyDate('d m Y H:i:s', $Fleet['SetBackTime'], 1); - $_Lang['useQuickRes'] = ($_POST['useQuickRes'] == '1' ? 'true' : 'false'); - - display(parsetemplate(gettemplate('fleet3_body'), $_Lang), $_Lang['fl_title']); - -?> \ No newline at end of file +'; + $GoBackForm .= ''; + $GoBackForm .= ''; + $GoBackForm .= ''; + message("
{$Text}
{$GoBackForm}", $Title); +} + +includeLang('fleet'); + +$QuantumGateInterval = QUANTUMGATE_INTERVAL_HOURS; +$Now = time(); +$ErrorTitle = &$_Lang['fl_error']; + +if(MORALE_ENABLED) +{ + Morale_ReCalculate($_User, $Now); +} + +// --- Initialize Vars +$Target['galaxy'] = intval($_POST['galaxy']); +$Target['system'] = intval($_POST['system']); +$Target['planet'] = intval($_POST['planet']); +$Target['type'] = intval($_POST['planettype']); +$Fleet['Speed'] = floatval($_POST['speed']); +$Fleet['array'] = explode(';', $_POST['FleetArray']); +$Fleet['UseQuantum'] = (isset($_POST['usequantumgate']) && $_POST['usequantumgate'] == 'on' ? true : false); +$Fleet['resources'] = array('metal' => $_POST['resource1'], 'crystal' => $_POST['resource2'], 'deuterium' => $_POST['resource3']); +$Fleet['ExpeTime'] = intval($_POST['expeditiontime']); +$Fleet['HoldTime'] = intval($_POST['holdingtime']); +$Fleet['ACS_ID'] = isset($_POST['acs_id']) ? floor(floatval($_POST['acs_id'])) : 0; +$Fleet['Mission'] = isset($_POST['mission']) ? intval($_POST['mission']) : 0; + +$Protections['enable'] = (bool) $_GameConfig['noobprotection']; +$Protections['basicLimit'] = $_GameConfig['noobprotectiontime'] * 1000; +$Protections['weakMulti'] = $_GameConfig['noobprotectionmulti']; +$Protections['adminEnable'] = (bool) $_GameConfig['adminprotection']; +$Protections['ally'] = $_GameConfig['allyprotection']; +$Protections['weakLimit'] = $_GameConfig['no_noob_protect'] * 1000; +$Protections['idleTime'] = $_GameConfig['no_idle_protect'] * TIME_DAY; +$Protections['mtypes'] = array(1, 2, 6, 9); +$Protections['newTime'] = $_GameConfig['Protection_NewPlayerTime']; +$Protections['antifarm_enabled'] = (bool) $_GameConfig['Protection_AntiFarmEnabled']; +$Protections['antifarm_rate'] = $_GameConfig['Protection_AntiFarmRate']; +$Protections['antifarm_counttotal'] = $_GameConfig['Protection_AntiFarmCountTotal']; +$Protections['antifarm_countplanet'] = $_GameConfig['Protection_AntiFarmCountPlanet']; +$Protections['bashLimit_enabled'] = (bool) $_GameConfig['Protection_BashLimitEnabled']; +$Protections['bashLimit_interval'] = $_GameConfig['Protection_BashLimitInterval']; +$Protections['bashLimit_counttotal'] = $_GameConfig['Protection_BashLimitCountTotal']; +$Protections['bashLimit_countplanet'] = $_GameConfig['Protection_BashLimitCountPlanet']; + +// --- Check if User's account is activated +if(!empty($_User['activation_code'])) +{ + messageRed($_Lang['fl3_BlockAccNotActivated'], $ErrorTitle); +} + +// --- Check if Mission is selected +if($Fleet['Mission'] <= 0) +{ + messageRed($_Lang['fl3_NoMissionSelected'], $ErrorTitle); +} + +// --- Get FlyingFleets Count +$FlyingFleetsCount = 0; +$FlyingExpeditions = 0; + +$Query_GetFleets = ''; +$Query_GetFleets .= "SELECT `fleet_mission`, `fleet_target_owner`, `fleet_end_id`, `fleet_mess` FROM {{table}} "; +$Query_GetFleets .= "WHERE `fleet_owner` = {$_User['id']};"; +$Result_GetFleets = doquery($Query_GetFleets, 'fleets'); +while($FleetData = mysql_fetch_assoc($Result_GetFleets)) +{ + $FlyingFleetsCount += 1; + if($FleetData['fleet_mission'] == 15) + { + $FlyingExpeditions += 1; + } + if(in_array($FleetData['fleet_mission'], array(1, 2, 9)) AND $FleetData['fleet_mess'] == 0) + { + if(!isset($FlyingFleetsData[$FleetData['fleet_target_owner']]['count'])) + { + $FlyingFleetsData[$FleetData['fleet_target_owner']]['count'] = 0; + } + if(!isset($FlyingFleetsData[$FleetData['fleet_target_owner']][$FleetData['fleet_end_id']])) + { + $FlyingFleetsData[$FleetData['fleet_target_owner']][$FleetData['fleet_end_id']] = 0; + } + $FlyingFleetsData[$FleetData['fleet_target_owner']]['count'] += 1; + $FlyingFleetsData[$FleetData['fleet_target_owner']][$FleetData['fleet_end_id']] += 1; + } +} + +// Get Available Slots for Fleets (1 + ComputerTech + 2 on Admiral) +// Get Available Slots for Expeditions (1 + floor(ExpeditionTech / 3)) +$Slots['MaxFleetSlots'] = 1 + $_User[$_Vars_GameElements[108]] + (($_User['admiral_time'] > $Now) ? 2 : 0); +$Slots['MaxExpedSlots'] = 1 + floor($_User[$_Vars_GameElements[124]] / 3); +$Slots['FlyingFleetsCount'] = $FlyingFleetsCount; +$Slots['FlyingExpeditions'] = $FlyingExpeditions; +if($Slots['FlyingFleetsCount'] >= $Slots['MaxFleetSlots']) +{ + messageRed($_Lang['fl3_NoMoreFreeSlots'], $ErrorTitle); +} +if($Slots['FlyingExpeditions'] >= $Slots['MaxExpedSlots'] AND $Fleet['Mission'] == 15) +{ + messageRed($_Lang['fl3_NoMoreFreeExpedSlots'], $ErrorTitle); +} + +// --- Switch Off Expeditions +if($Fleet['Mission'] == 15) +{ + messageRed($_Lang['fl3_ExpeditionsAreOff'], $ErrorTitle); +} + +// --- Check if all resources are correct (no negative numbers and enough on planet) +foreach($Fleet['resources'] as $Key => $Data) +{ + $Fleet['resources'][$Key] = floor(floatval(str_replace('.', '', $Data))); + if($Fleet['resources'][$Key] < 0) + { + messageRed($_Lang['fl3_BadResourcesGiven'], $ErrorTitle); + } + elseif($Fleet['resources'][$Key] > $_Planet[$Key]) + { + messageRed($_Lang['fl3_PlanetNoEnough'.$Key], $ErrorTitle); + } + + if($Fleet['resources'][$Key] == 0) + { + $Fleet['resources'][$Key] = '0'; + } +} + +// --- Check, if Target Data are correct +if($Target['galaxy'] == $_Planet['galaxy'] AND $Target['system'] == $_Planet['system'] AND $Target['planet'] == $_Planet['planet'] AND $Target['type'] == $_Planet['planet_type']) +{ + messageRed($_Lang['fl2_cantsendsamecoords'], $ErrorTitle); +} +foreach($Target as $Type => $Value) +{ + if($Value < 1) + { + $TargetError = true; + break; + } + switch($Type) + { + case 'galaxy': + $CheckValue = MAX_GALAXY_IN_WORLD; + break; + case 'system': + $CheckValue = MAX_SYSTEM_IN_GALAXY; + break; + case 'planet': + $CheckValue = MAX_PLANET_IN_SYSTEM + 1; + break; + case 'type': + $CheckValue = 3; + break; + } + if($Value > $CheckValue) + { + $TargetError = true; + break; + } +} +if(isset($TargetError)) +{ + messageRed($_Lang['fl2_targeterror'], $ErrorTitle); +} + +// Create SpeedsArray +$SpeedsAvailable = array(10, 9, 8, 7, 6, 5, 4, 3, 2, 1); + +if($_User['admiral_time'] > $Now) +{ + $SpeedsAvailable[] = 12; + $SpeedsAvailable[] = 11; + $SpeedsAvailable[] = 0.5; + $SpeedsAvailable[] = 0.25; +} +if(MORALE_ENABLED) +{ + $MaxAvailableSpeed = max($SpeedsAvailable); + if($_User['morale_level'] >= MORALE_BONUS_FLEETSPEEDUP1) + { + $SpeedsAvailable[] = $MaxAvailableSpeed + (MORALE_BONUS_FLEETSPEEDUP1_VALUE / 10); + } + if($_User['morale_level'] >= MORALE_BONUS_FLEETSPEEDUP2) + { + $SpeedsAvailable[] = $MaxAvailableSpeed + (MORALE_BONUS_FLEETSPEEDUP2_VALUE / 10); + } +} +if(!in_array($Fleet['Speed'], $SpeedsAvailable)) +{ + messageRed($_Lang['fl_bad_fleet_speed'], $ErrorTitle); +} + +// --- Check PlanetOwner +$YourPlanet = false; +$UsedPlanet = false; +$OwnerFriend = false; +$OwnerIsBuddyFriend = false; +$OwnerIsAlliedUser = false; +$OwnerHasMarcantilePact = false; +$PlanetAbandoned = false; + +if($Fleet['Mission'] != 8) +{ + // This is not a Recycling Mission, so check Planet Data + $Query_CheckPlanetOwner = ''; + $Query_CheckPlanetOwner .= "SELECT `pl`.`id` AS `id`, `pl`.`id_owner` AS `owner`, `pl`.`name` AS `name`, `pl`.`quantumgate`, "; + $Query_CheckPlanetOwner .= "`users`.`ally_id`, `users`.`onlinetime`, `users`.`username` as `username`, `users`.`user_lastip` as `lastip`, `users`.`is_onvacation`, `users`.`is_banned`, `users`.`authlevel`, `users`.`first_login`, `users`.`NoobProtection_EndTime`, `users`.`multiIP_DeclarationID`, "; + $Query_CheckPlanetOwner .= "`stats`.`total_rank`, `stats`.`total_points`, `buddy1`.`active` AS `active1`, `buddy2`.`active` AS `active2` "; + if($_User['ally_id'] > 0) + { + $Query_CheckPlanetOwner .= ", `apact1`.`Type` AS `AllyPact1`, `apact2`.`Type` AS `AllyPact2` "; + } + $Query_CheckPlanetOwner .= "FROM {{table}} as `pl` "; + $Query_CheckPlanetOwner .= "LEFT JOIN {{prefix}}buddy as `buddy1` ON (`pl`.`id_owner` = `buddy1`.`sender` AND `buddy1`.`owner` = {$_User['id']}) "; + $Query_CheckPlanetOwner .= "LEFT JOIN {{prefix}}buddy as `buddy2` ON (`pl`.`id_owner` = `buddy2`.`owner` AND `buddy2`.`sender` = {$_User['id']}) "; + $Query_CheckPlanetOwner .= "LEFT JOIN {{prefix}}users as `users` ON `pl`.`id_owner` = `users`.`id` "; + $Query_CheckPlanetOwner .= "LEFT JOIN {{prefix}}statpoints AS `stats` ON `pl`.`id_owner` = `stats`.`id_owner` AND `stat_type` = '1' "; + if($_User['ally_id'] > 0) + { + $Query_CheckPlanetOwner .= "LEFT JOIN `{{prefix}}ally_pacts` AS `apact1` ON (`apact1`.`AllyID_Sender` = {$_User['ally_id']} AND `apact1`.`AllyID_Owner` = `users`.`ally_id` AND `apact1`.`Active` = 1) "; + $Query_CheckPlanetOwner .= "LEFT JOIN `{{prefix}}ally_pacts` AS `apact2` ON (`apact2`.`AllyID_Sender` = `users`.`ally_id` AND `apact2`.`AllyID_Owner` = {$_User['ally_id']} AND `apact2`.`Active` = 1) "; + } + $Query_CheckPlanetOwner .= "WHERE `pl`.`galaxy` = {$Target['galaxy']} AND `pl`.`system` = {$Target['system']} AND `pl`.`planet` = {$Target['planet']} AND `pl`.`planet_type` = {$Target['type']} "; + $Query_CheckPlanetOwner .= "LIMIT 1;"; + $CheckPlanetOwner = doquery($Query_CheckPlanetOwner, 'planets'); + + if(mysql_num_rows($CheckPlanetOwner) == 1) + { + $CheckGalaxyRow = doquery("SELECT `galaxy_id` FROM {{table}} WHERE `galaxy` = {$Target['galaxy']} AND `system` = {$Target['system']} AND `planet` = {$Target['planet']} LIMIT 1;", 'galaxy', true); + $CheckPlanetOwner = mysql_fetch_assoc($CheckPlanetOwner); + $CheckPlanetOwner['galaxy_id'] = $CheckGalaxyRow['galaxy_id']; + $UsedPlanet = true; + if($CheckPlanetOwner['owner'] > 0) + { + if($CheckPlanetOwner['owner'] == $_User['id']) + { + $YourPlanet = true; + } + else + { + if((isset($CheckPlanetOwner['AllyPact1']) && $CheckPlanetOwner['AllyPact1'] >= ALLYPACT_NONAGGRESSION) || (isset($CheckPlanetOwner['AllyPact2']) && $CheckPlanetOwner['AllyPact2'] >= ALLYPACT_NONAGGRESSION)) + { + $OwnerIsAlliedUser = true; + } + if((isset($CheckPlanetOwner['AllyPact1']) && $CheckPlanetOwner['AllyPact1'] >= ALLYPACT_MERCANTILE) || (isset($CheckPlanetOwner['AllyPact2']) && $CheckPlanetOwner['AllyPact2'] >= ALLYPACT_MERCANTILE)) + { + $OwnerHasMarcantilePact = true; + } + if(($CheckPlanetOwner['active1'] == 1 OR $CheckPlanetOwner['active2'] == 1) OR ($CheckPlanetOwner['ally_id'] == $_User['ally_id'] AND $_User['ally_id'] > 0) OR ((isset($CheckPlanetOwner['AllyPact1']) && $CheckPlanetOwner['AllyPact1'] >= ALLYPACT_DEFENSIVE) || (isset($CheckPlanetOwner['AllyPact2']) && $CheckPlanetOwner['AllyPact2'] >= ALLYPACT_DEFENSIVE))) + { + $OwnerFriend = true; + if($CheckPlanetOwner['active1'] == 1 OR $CheckPlanetOwner['active2'] == 1) + { + $OwnerIsBuddyFriend = true; + } + } + } + } + else + { + $PlanetAbandoned = true; + } + } + else + { + $CheckPlanetOwner = array(); + } +} +else +{ + // This is a Recycling Mission, so check Galaxy Data + $CheckDebrisField = doquery("SELECT `galaxy_id`, `metal`, `crystal` FROM {{table}} WHERE galaxy = '{$Target['galaxy']}' AND system = '{$Target['system']}' AND planet = '{$Target['planet']}'", 'galaxy', true); +} + +// Fleet Blockade System +$SFBSelectWhere[] = "(`Type` = 1 AND (`EndTime` > UNIX_TIMESTAMP() OR `PostEndTime` > UNIX_TIMESTAMP()))"; +if($CheckPlanetOwner['owner'] > 0) +{ + $SFBSelectWhere[] = "(`Type` = 2 AND `ElementID` = {$CheckPlanetOwner['owner']} AND `EndTime` > UNIX_TIMESTAMP())"; + $SFBSelectWhere[] = "(`Type` = 3 AND `ElementID` = {$CheckPlanetOwner['id']} AND `EndTime` > UNIX_TIMESTAMP())"; +} +$SFBSelectWhere[] = "(`Type` = 2 AND `ElementID` = {$_User['id']} AND `EndTime` > UNIX_TIMESTAMP())"; +$SFBSelectWhere[] = "(`Type` = 3 AND `ElementID` = {$_Planet['id']} AND `EndTime` > UNIX_TIMESTAMP())"; + +$SFBSelect = ''; +$SFBSelect .= "SELECT `Type`, `BlockMissions`, `Reason`, `StartTime`, `EndTime`, `PostEndTime`, `ElementID`, `DontBlockIfIdle` FROM {{table}} WHERE `StartTime` <= UNIX_TIMESTAMP() AND "; +$SFBSelect .= implode(' OR ', $SFBSelectWhere); +$SFBSelect .= " ORDER BY `Type` ASC, `EndTime` DESC;"; +$LoadSFBData = doquery($SFBSelect, 'smart_fleet_blockade'); +if(mysql_num_rows($LoadSFBData) > 0) +{ + while($GetSFBData = mysql_fetch_assoc($LoadSFBData)) + { + $BlockedMissions = false; + if($GetSFBData['BlockMissions'] == '0') + { + $BlockedMissions = true; + $AllMissionsBlocked = true; + } + else + { + $BlockedMissions = explode(',', $GetSFBData['BlockMissions']); + } + + if($BlockedMissions === true OR in_array($Fleet['Mission'], $BlockedMissions)) + { + if($GetSFBData['Type'] == 1) + { + // Global Blockade + if($GetSFBData['EndTime'] > $Now) + { + // Normal Blockade + if(!($GetSFBData['DontBlockIfIdle'] == 1 AND in_array($Fleet['Mission'], $_Vars_FleetMissions['military']) AND $CheckPlanetOwner['owner'] > 0 AND $CheckPlanetOwner['onlinetime'] <= ($Now - $Protections['idleTime']))) + { + $BlockFleet = true; + $BlockReason = $_Lang['SFB_Stop_GlobalBlockade']; + } + } + elseif($GetSFBData['PostEndTime'] > $Now) + { + // Post Blockade + if(in_array($Fleet['Mission'], $_Vars_FleetMissions['military']) AND $CheckPlanetOwner['owner'] > 0 AND + ( + ($AllMissionsBlocked !== true AND $CheckPlanetOwner['onlinetime'] > ($Now - $Protections['idleTime']) AND $CheckPlanetOwner['onlinetime'] < $GetSFBData['StartTime']) + OR + ($AllMissionsBlocked === true AND $CheckPlanetOwner['onlinetime'] > ($Now - $Protections['idleTime']) AND $CheckPlanetOwner['onlinetime'] < $GetSFBData['EndTime']) + )) + { + $BlockFleet = true; + $BlockReason = sprintf($_Lang['SFB_Stop_GlobalPostBlockade'], prettyDate('d m Y, H:i:s', $GetSFBData['PostEndTime'], 1)); + } + } + } + elseif($GetSFBData['Type'] == 2) + { + // Per User Blockade + $BlockFleet = true; + $BlockGivenReason = (empty($GetSFBData['Reason']) ? $_Lang['SFB_Stop_ReasonNotGiven'] : "\"{$GetSFBData['Reason']}\""); + $BlockReason = sprintf(($GetSFBData['ElementID'] == $_User['id'] ? $_Lang['SFB_Stop_UserBlockadeOwn'] : $_Lang['SFB_Stop_UserBlockade']), prettyDate('d m Y', $GetSFBData['EndTime'], 1), date('H:i:s', $GetSFBData['EndTime']), $BlockGivenReason); + } + elseif($GetSFBData['Type'] == 3) + { + // Per Planet Blockade + $BlockFleet = true; + $BlockGivenReason = (empty($GetSFBData['Reason']) ? $_Lang['SFB_Stop_ReasonNotGiven'] : "\"{$GetSFBData['Reason']}\""); + if($GetSFBData['ElementID'] == $_Planet['id']) + { + $UseLangVar = ($_Planet['planet_type'] == 1 ? $_Lang['SFB_Stop_PlanetBlockadeOwn_Planet'] : $_Lang['SFB_Stop_PlanetBlockadeOwn_Moon']); + } + else + { + $UseLangVar = ($Target['type'] == 1 ? $_Lang['SFB_Stop_PlanetBlockade_Planet'] : $_Lang['SFB_Stop_PlanetBlockade_Moon']); + } + $BlockReason = sprintf($UseLangVar, prettyDate('d m Y', $GetSFBData['EndTime'], 1), date('H:i:s', $GetSFBData['EndTime']), $BlockGivenReason); + } + } + + if($BlockFleet === true) + { + messageRed($BlockReason.$_Lang['SFB_Stop_LearnMore'], $_Lang['SFB_BoxTitle']); + } + } +} + +// --- Parse Fleet Array +$Fleet['count'] = 0; +$Fleet['storage'] = 0; +$Fleet['FuelStorage'] = 0; +$Fleet['TotalResStorage'] = 0; + +$FleetArray = array(); +if(!empty($Fleet['array']) AND (array)$Fleet['array'] === $Fleet['array']) +{ + foreach($Fleet['array'] as $ShipData) + { + $ShipData = explode(',', $ShipData); + $ShipID = intval($ShipData[0]); + if(in_array($ShipID, $_Vars_ElementCategories['fleet'])) + { + if(!empty($_Vars_Prices[$ShipID]['engine'])) + { + $ShipCount = floor($ShipData[1]); + if($ShipCount > 0) + { + if($_Planet[$_Vars_GameElements[$ShipID]] >= $ShipCount) + { + $FleetArray[$ShipID] = $ShipCount; + $Fleet['count'] += $ShipCount; + $ThisStorage = $_Vars_Prices[$ShipID]['capacity'] * $ShipCount; + if($ShipID != 210) + { + $Fleet['storage'] += $ThisStorage; + } + else + { + $Fleet['FuelStorage'] += $ThisStorage; + } + $FleetRemover[] = "`{$_Vars_GameElements[$ShipID]}` = `{$_Vars_GameElements[$ShipID]}` - {$ShipCount}"; + } + else + { + messageRed($_Lang['fl1_NoEnoughShips'], $ErrorTitle); + } + } + else + { + messageRed($_Lang['fl2_ShipCountCantBe0'], $ErrorTitle); + } + } + else + { + messageRed($_Lang['fl1_CantSendUnflyable'], $ErrorTitle); + } + } + else + { + messageRed($_Lang['fl1_BadShipGiven'], $ErrorTitle); + } + } +} +else +{ + messageRed($_Lang['fl2_FleetArrayPostEmpty'], $ErrorTitle); +} +if($Fleet['count'] <= 0) +{ + messageRed($_Lang['fl2_ZeroShips'], $ErrorTitle); +} +$Fleet['array'] = $FleetArray; +unset($FleetArray); + +// --- Create Array of Available Missions +$AvailableMissions = array(); +if($Target['type'] == 2) +{ + if($Fleet['array'][209] > 0) + { + $AvailableMissions[] = 8; + } +} +else +{ + if($UsedPlanet) + { + if(!isset($Fleet['array'][210]) || $Fleet['count'] > $Fleet['array'][210]) + { + $AvailableMissions[] = 3; + } + if(!$YourPlanet) + { + $AvailableMissions[] = 1; + $AvailableMissions[] = 2; + if($OwnerFriend) + { + $AvailableMissions[] = 5; + } + if(isset($Fleet['array'][210]) && $Fleet['count'] == $Fleet['array'][210]) + { + $AvailableMissions[] = 6; + } + if($Target['type'] == 3 && isset($Fleet['array'][214]) && $Fleet['array'][214] > 0) + { + $AvailableMissions[] = 9; + } + } + else + { + $AvailableMissions[] = 4; + } + } + else + { + if($Target['planet'] == (MAX_PLANET_IN_SYSTEM + 1)) + { + $AvailableMissions[] = 15; + } + else + { + if($Fleet['array'][208] > 0 AND $Target['type'] == 1) + { + $AvailableMissions[] = 7; + } + } + } +} + +// --- Check if everything is OK with ACS +$Throw = false; +if($Fleet['Mission'] == 2 AND in_array(2, $AvailableMissions)) +{ + if($Fleet['ACS_ID'] > 0) + { + $CheckACS = doquery("SELECT {{table}}.*, `fleets`.`fleet_send_time` AS `mf_start_time` FROM {{table}} LEFT JOIN {{prefix}}fleets AS `fleets` ON `fleets`.`fleet_id` = {{table}}.`main_fleet_id` WHERE {{table}}.`id` = {$Fleet['ACS_ID']} LIMIT 1;", 'acs', true); + if($CheckACS) + { + if($CheckACS['owner_id'] == $_User['id'] OR strstr($CheckACS['users'], '|'.$_User['id'].'|') !== FALSE) + { + if($CheckACS['end_target_id'] == $CheckPlanetOwner['id']) + { + if($CheckACS['fleets_count'] < ACS_MAX_JOINED_FLEETS) + { + if($CheckACS['start_time'] > $Now) + { + $UpdateACS = true; + } + else + { + $Throw = $_Lang['fl_acs_cannot_join_time_extended']; + } + } + else + { + $Throw = $_Lang['fl_acs_fleetcount_extended']; + } + } + else + { + $Throw = $_Lang['fl_acs_badcoordinates']; + } + } + else + { + $Throw = $_Lang['fl_acs_cannot_join_this_group']; + } + } + else + { + $Throw = $_Lang['fl_acs_bad_group_id']; + } + } + else + { + $Throw = $_Lang['fl_acs_bad_group_id']; + } + if($Throw) + { + messageRed($Throw, $ErrorTitle); + } +} + +// --- If Mission is not correct, show Error +if(!in_array($Fleet['Mission'], $AvailableMissions)) +{ + switch($Fleet['Mission']) + { + case 1: + if($Target['type'] == 2) + { + $Throw = $_Lang['fl3_CantAttackDebris']; + } + else + { + if(!$UsedPlanet) + { + $Throw = $_Lang['fl3_CantAttackNonUsed']; + } + else + { + if($YourPlanet) + { + $Throw = $_Lang['fl3_CantAttackYourself']; + } + } + } + break; + case 2: + if($Target['type'] == 2) + { + $Throw = $_Lang['fl3_CantACSDebris']; + } + else + { + if(!$UsedPlanet) + { + $Throw = $_Lang['fl3_CantACSNonUsed']; + } + else + { + if($YourPlanet) + { + $Throw = $_Lang['fl3_CantACSYourself']; + } + } + } + break; + case 3: + if($Target['type'] == 2) + { + $Throw = $_Lang['fl3_CantTransportDebris']; + } + else + { + if(!$UsedPlanet) + { + $Throw = $_Lang['fl3_CantTransportNonUsed']; + } + else + { + $Throw = $_Lang['fl3_CantTransportSpyProbes']; + } + } + break; + case 4: + if($Target['type'] == 2) + { + $Throw = $_Lang['fl3_CantStayDebris']; + } + else + { + if(!$UsedPlanet) + { + $Throw = $_Lang['fl3_CantStayNonUsed']; + } + else + { + if(!$YourPlanet) + { + $Throw = $_Lang['fl3_CantStayNonYourself']; + } + } + } + break; + case 5: + if($Target['type'] == 2) + { + $Throw = $_Lang['fl3_CantProtectDebris']; + } + else + { + if(!$UsedPlanet) + { + $Throw = $_Lang['fl3_CantProtectNonUsed']; + } + else + { + if($YourPlanet) + { + $Throw = $_Lang['fl3_CantProtectYourself']; + } + else + { + $Throw = $_Lang['fl3_CantProtectNonFriend']; + } + } + } + break; + case 6: + if($Target['type'] == 2) + { + $Throw = $_Lang['fl3_CantSpyDebris']; + } + else + { + if(!$UsedPlanet) + { + $Throw = $_Lang['fl3_CantSpyNonUsed']; + } + else + { + if($YourPlanet) + { + $Throw = $_Lang['fl3_CantSpyYourself']; + } + else + { + $Throw = $_Lang['fl3_CantSpyProbesCount']; + } + } + } + break; + case 7: + if($UsedPlanet) + { + $Throw = $_Lang['fl3_CantSettleOnUsed']; + } + else + { + if($Target['type'] != 1) + { + $Throw = $_Lang['fl3_CantSettleNonPlanet']; + } + else + { + $Throw = $_Lang['fl3_CantSettleNoShips']; + } + } + break; + case 8: + if($Target['type'] != 2) + { + $Throw = $_Lang['fl3_CantRecycleNonDebris']; + } + else + { + $Throw = $_Lang['fl3_CantRecycleNoShip']; + } + break; + case 9: + if($Target['type'] == 2) + { + $Throw = $_Lang['fl3_CantDestroyDebris']; + } + else + { + if(!$UsedPlanet) + { + $Throw = $_Lang['fl3_CantDestroyNonUsed']; + } + else + { + if($YourPlanet) + { + $Throw = $_Lang['fl3_CantDestroyYourself']; + } + else + { + if($Target['type'] != 3) + { + $Throw = $_Lang['fl3_CantDestroyNonMoon']; + } + else + { + $Throw = $_Lang['fl3_CantDestroyNoShip']; + } + } + } + } + break; + } + if($Throw) + { + messageRed($Throw, $ErrorTitle); + } + messageRed($_Lang['fl3_BadMissionSelected'], $ErrorTitle); +} + +// --- If Mission is Recycling and there is no Debris Field, show Error +if($Fleet['Mission'] == 8) +{ + if($CheckDebrisField['metal'] <= 0 AND $CheckDebrisField['crystal'] <= 0) + { + messageRed($_Lang['fl3_NoDebrisFieldHere'], $ErrorTitle); + } +} + +// --- Check if Expeditions and HoldingTimes are Correct +$Throw = false; +$Fleet['StayTime'] = 0; +if($Fleet['Mission'] == 15) +{ + if($Fleet['ExpeTime'] < 1) + { + $Throw = $_Lang['fl3_Expedition_Min1H']; + } + elseif($Fleet['ExpeTime'] > 12) + { + $Throw = $_Lang['fl3_Expedition_Max12H']; + } + $Fleet['StayTime'] = $Fleet['ExpeTime'] * 3600; +} +elseif($Fleet['Mission'] == 5) +{ + if(!in_array($Fleet['HoldTime'], array(1, 2, 4, 8, 16, 32))) + { + $Throw = $_Lang['fl3_Holding_BadTime']; + } + $Fleet['StayTime'] = $Fleet['HoldTime'] * 3600; +} +if($Throw) +{ + messageRed($Throw, $ErrorTitle); +} + +// --- Set Variables to better usage +if(!empty($CheckDebrisField)) +{ + $TargetData = &$CheckDebrisField; +} +else +{ + $TargetData = &$CheckPlanetOwner; +} + +// --- Check if User data are OK +if($UsedPlanet AND !$YourPlanet AND !$PlanetAbandoned) +{ + $SaveMyTotalRank = false; + + $StatsData['his'] = ($TargetData['total_points'] > 0 ? $TargetData['total_points'] : 0); + if(!CheckAuth('programmer')) + { + $StatsData['mine'] = ($_User['total_points'] > 0 ? $_User['total_points'] : 0); + } + else + { + $StatsData['mine'] = $StatsData['his']; + if($_User['total_rank'] <= 0) + { + $SaveMyTotalRank = $_User['total_rank']; + $_User['total_rank'] = $TargetData['total_rank']; + } + } + + if(isOnVacation($TargetData)) + { + if($SaveMyTotalRank !== false) + { + $_User['total_rank'] = $SaveMyTotalRank; + } + if($TargetData['is_banned'] == 1) + { + messageRed($_Lang['fl3_CantSendBanned'], $ErrorTitle); + } + else + { + messageRed($_Lang['fl3_CantSendVacation'], $ErrorTitle); + } + } + + if($Protections['ally'] == 1) + { + if($_User['ally_id'] > 0 AND $_User['ally_id'] == $TargetData['ally_id']) + { + if(in_array($Fleet['Mission'], $Protections['mtypes'])) + { + if($SaveMyTotalRank !== false) + { + $_User['total_rank'] = $SaveMyTotalRank; + } + messageRed($_Lang['fl3_CantSendAlly'], $ErrorTitle); + } + } + } + + if($Protections['enable']) + { + $Throw = false; + if(in_array($Fleet['Mission'], $Protections['mtypes'])) + { + if($_User['total_rank'] >= 1) + { + if($TargetData['total_rank'] >= 1) + { + if($_User['NoobProtection_EndTime'] > $Now) + { + $Throw = sprintf($_Lang['fl3_ProtectNewTimeYou'], pretty_time($_User['NoobProtection_EndTime'] - $Now)); + } + else if($TargetData['first_login'] == 0) + { + $Throw = $_Lang['fl3_ProtectNewTimeHe2']; + } + else if($TargetData['NoobProtection_EndTime'] > $Now) + { + $Throw = sprintf($_Lang['fl3_ProtectNewTimeHe'], pretty_time($TargetData['NoobProtection_EndTime'] - $Now)); + } + + if($Throw === false) + { + if($StatsData['mine'] >= $Protections['basicLimit']) + { + if($TargetData['onlinetime'] >= ($Now - $Protections['idleTime'])) + { + if($StatsData['his'] < $Protections['basicLimit']) + { + $Throw = sprintf($_Lang['fl3_ProtectHIWeak'], prettyNumber($Protections['basicLimit'])); + } + else + { + if($StatsData['his'] < $Protections['weakLimit'] OR $StatsData['mine'] < $Protections['weakLimit']) + { + if($StatsData['mine'] > ($StatsData['his'] * $Protections['weakMulti'])) + { + $Throw = sprintf($_Lang['fl3_ProtectUR2Strong'], prettyNumber($Protections['weakMulti'])); + } + elseif(($StatsData['mine'] * $Protections['weakMulti']) < $StatsData['his']) + { + $Throw = sprintf($_Lang['fl3_ProtectHI2Strong'], prettyNumber($Protections['weakMulti'])); + } + } + else + { + if($Protections['antifarm_enabled'] == true AND ($StatsData['mine'] / $StatsData['his']) >= $Protections['antifarm_rate']) + { + $DoFarmCheck = true; + } + } + } + } + } + else + { + $Throw = sprintf($_Lang['fl3_ProtectURWeak'], prettyNumber($Protections['basicLimit'])); + } + } + } + else + { + $Throw = $_Lang['fl3_ProtectHIStatNotCalc']; + } + } + else + { + $Throw = $_Lang['fl3_ProtectURStatNotCalc']; + } + if($Protections['adminEnable']) + { + if(CheckAuth('supportadmin') OR CheckAuth('supportadmin', AUTHCHECK_NORMAL, $TargetData)) + { + if(CheckAuth('supportadmin')) + { + $Throw = $_Lang['fl3_ProtectAdminCant']; + } + else + { + $Throw = $_Lang['fl3_ProtectCantAdmin']; + } + } + } + + if(empty($Throw) AND ($DoFarmCheck === true OR $Protections['bashLimit_enabled'] === true)) + { + if($DoFarmCheck === true) + { + $TodayIs = explode('.', date('d.m.Y')); + $TodayTimestamp = mktime(0, 0, 0, $TodayIs[1], $TodayIs[0], $TodayIs[2]); + if($TodayTimestamp <= 0) + { + $TodayTimestamp = 0; + } + $BashTimestamps[] = array('type' => 'farm', 'key' => 'antifarm', 'stamp' => $TodayTimestamp); + } + if($Protections['bashLimit_enabled'] === true) + { + $BashTimestamps[] = array('type' => 'bash', 'key' => 'bashLimit', 'stamp' => $Now - $Protections['bashLimit_interval']); + } + sort($BashTimestamps, SORT_ASC); + $BashTimestampMinVal = $BashTimestamps[0]['stamp']; + + $GetFleetArchiveRecords = doquery("SELECT * FROM {{table}} WHERE (`Fleet_Time_Start` + `Fleet_Time_ACSAdd`) >= {$BashTimestampMinVal} AND `Fleet_Owner` = {$_User['id']} AND `Fleet_End_Owner` = {$TargetData['owner']} AND `Fleet_Mission` IN (1, 2, 9) AND `Fleet_ReportID` > 0 AND `Fleet_Destroyed_Reason` NOT IN (1, 4, 11);", 'fleet_archive'); + if(mysql_num_rows($GetFleetArchiveRecords) > 0) + { + while($ArchiveRecord = mysql_fetch_assoc($GetFleetArchiveRecords)) + { + foreach($BashTimestamps as $Values) + { + if(($ArchiveRecord['Fleet_Time_Start'] + $ArchiveRecord['Fleet_Time_ACSAdd']) >= $Values['stamp']) + { + $GetEndID = $ArchiveRecord['Fleet_End_ID']; + if($ArchiveRecord['Fleet_End_ID_Changed'] > 0) + { + $GetEndID = $ArchiveRecord['Fleet_End_ID_Changed']; + } + $SaveArchiveData[$Values['type']][$GetEndID] += 1; + } + } + } + } + + foreach($BashTimestamps as $Values) + { + if(!empty($SaveArchiveData)) + { + $FleetArchiveRecordsCount = array_sum($SaveArchiveData[$Values['type']]); + } + if($FleetArchiveRecordsCount >= $Protections[$Values['key'].'_counttotal']) + { + $Throw = sprintf($_Lang['fl3_Protect_AttackLimitTotal'], $_Lang['fl3_Protect_AttackLimit_'.$Values['key']]); + break; + } + elseif(($FleetArchiveRecordsCount + $FlyingFleetsData[$TargetData['owner']]['count']) >= $Protections[$Values['key'].'_counttotal']) + { + $Throw = sprintf($_Lang['fl3_Protect_AttackLimitTotalFly'], $_Lang['fl3_Protect_AttackLimit_'.$Values['key']]); + break; + } + elseif($SaveArchiveData[$Values['type']][$TargetData['id']] >= $Protections[$Values['key'].'_countplanet']) + { + $Throw = sprintf($_Lang['fl3_Protect_AttackLimitSingle'], $_Lang['fl3_Protect_AttackLimit_'.$Values['key']]); + break; + } + elseif(($SaveArchiveData[$Values['type']][$TargetData['id']] + $FlyingFleetsData[$TargetData['owner']][$TargetData['id']]) >= $Protections[$Values['key'].'_countplanet']) + { + $Throw = sprintf($_Lang['fl3_Protect_AttackLimitSingleFly'], $_Lang['fl3_Protect_AttackLimit_'.$Values['key']]); + break; + } + } + } + + if($Throw) + { + if($SaveMyTotalRank !== false) + { + $_User['total_rank'] = $SaveMyTotalRank; + } + messageRed($Throw, $ErrorTitle); + } + } + } + + if($SaveMyTotalRank !== false) + { + $_User['total_rank'] = $SaveMyTotalRank; + } +} + +// --- Calculate Speed and Distance +$AllFleetSpeed = GetFleetMaxSpeed($Fleet['array'], 0, $_User); +$GenFleetSpeed = $Fleet['Speed']; +$SpeedFactor = GetGameSpeedFactor(); +$MaxFleetSpeed = min($AllFleetSpeed); +if(MORALE_ENABLED) +{ + if($_User['morale_level'] <= MORALE_PENALTY_FLEETSLOWDOWN) + { + $MaxFleetSpeed *= MORALE_PENALTY_FLEETSLOWDOWN_VALUE; + } +} +$Distance = GetTargetDistance($_Planet['galaxy'], $Target['galaxy'], $_Planet['system'], $Target['system'], $_Planet['planet'], $Target['planet']); + +$Allow_UseQuantumGate = false; +if($Fleet['UseQuantum']) +{ + $QuantumGate_Disallow = array(1, 2, 6, 9); + if($_Planet['quantumgate'] == 1) + { + if(!in_array($Fleet['Mission'], $QuantumGate_Disallow)) + { + if($UsedPlanet) + { + if($TargetData['quantumgate'] == 1) + { + if($YourPlanet) + { + $Allow_UseQuantumGate = true; + $QuantumGate_UseType = 1; + } + else + { + if($OwnerFriend OR $OwnerHasMarcantilePact) + { + $Allow_UseQuantumGate = true; + $QuantumGate_UseType = 1; + } + else + { + $Check_SpaceTimeJump = true; + } + } + } + else + { + $Check_SpaceTimeJump = true; + } + } + else + { + $Check_SpaceTimeJump = true; + } + + if($Check_SpaceTimeJump === true) + { + if($_Planet['galaxy'] == $Target['galaxy']) + { + if(($_Planet['quantumgate_lastuse'] + ($QuantumGateInterval * 60 * 60)) <= $Now) + { + $Allow_UseQuantumGate = true; + $QuantumGate_UseType = 2; + } + else + { + $CannotUseTill = $_Planet['quantumgate_lastuse'] + ($QuantumGateInterval * 60 * 60); + messageRed(sprintf($_Lang['CannotUseQuantumGateTill'], prettyDate('d m Y \o H:i:s', $CannotUseTill, 1)), $ErrorTitle); + } + } + else + { + messageRed($_Lang['fl3_SpaceTimeJumpGalaxy'], $ErrorTitle); + } + } + } + else + { + messageRed($_Lang['fl3_QuantumDisallowAttack'], $ErrorTitle); + } + } + else + { + messageRed($_Lang['fl3_NoQuantumGate'], $ErrorTitle); + } +} + +if($Allow_UseQuantumGate) +{ + if($QuantumGate_UseType == 1) + { + $DurationTarget = $DurationBack = 1; + $Consumption = 0; + } + elseif($QuantumGate_UseType == 2) + { + $DurationTarget = 1; + $DurationBack = GetMissionDuration($GenFleetSpeed, $MaxFleetSpeed, $Distance, $SpeedFactor); + $Consumption = GetFleetConsumption($Fleet['array'], $SpeedFactor, $DurationBack, $Distance, $_User) / 2; + } +} +else +{ + $DurationTarget = $DurationBack = GetMissionDuration($GenFleetSpeed, $MaxFleetSpeed, $Distance, $SpeedFactor); + $Consumption = GetFleetConsumption($Fleet['array'], $SpeedFactor, $DurationTarget, $Distance, $_User); +} + +if($_Planet['deuterium'] < $Consumption) +{ + messageRed($_Lang['fl3_NoEnoughFuel'], $ErrorTitle); +} +if($Consumption > ($Fleet['storage'] + $Fleet['FuelStorage'])) +{ + messageRed($_Lang['fl3_NoEnoughtStorage4Fuel'], $ErrorTitle); +} +if($_Planet['deuterium'] < ($Consumption + $Fleet['resources']['deuterium'])) +{ + messageRed($_Lang['fl3_PlanetNoEnoughdeuterium'], $ErrorTitle); +} +if($Fleet['FuelStorage'] >= $Consumption) +{ + $Fleet['storage'] += $Consumption; +} +else +{ + $Fleet['storage'] += $Fleet['FuelStorage']; +} +$Fleet['storage'] -= $Consumption; +foreach($Fleet['resources'] as $Value) +{ + $Fleet['TotalResStorage'] += $Value; +} +if($Fleet['TotalResStorage'] > $Fleet['storage']) +{ + messageRed($_Lang['fl3_NoEnoughStorage4Res'], $ErrorTitle); +} + +$Fleet['SetCalcTime'] = $Now + $DurationTarget; +$Fleet['SetStayTime'] = ($Fleet['StayTime'] > 0 ? $Fleet['SetCalcTime'] + $Fleet['StayTime'] : '0'); +$Fleet['SetBackTime'] = $Fleet['SetCalcTime'] + $Fleet['StayTime'] + $DurationBack; + +if(isset($UpdateACS)) +{ + $NewEndTime = $Fleet['SetCalcTime']; + $OldFlightTime = $CheckACS['start_time_org'] - $CheckACS['mf_start_time']; + $FlightDifference = ($NewEndTime - $CheckACS['mf_start_time']) - $OldFlightTime; + + if($OldFlightTime == 0) + { + $OldFlightTime = 1; + } + if($FlightDifference == 0) + { + $FlightDifference = 1; + } + if(($FlightDifference/$OldFlightTime) <= 0.3) + { + if($NewEndTime < $CheckACS['start_time']) + { + $Difference = $CheckACS['start_time'] - $NewEndTime; + $Fleet['SetCalcTime'] += $Difference; + $Fleet['SetBackTime'] += $Difference; + } + elseif($NewEndTime > $CheckACS['start_time']) + { + $Difference = $NewEndTime - $CheckACS['start_time']; + $UpdateACSRow[] = "`start_time` = `start_time` + {$Difference}"; + $UpdateACSFleets[] = "`fleet_start_time` = `fleet_start_time` + {$Difference}"; + $UpdateACSFleets[] = "`fleet_end_time` = `fleet_end_time` + {$Difference}"; + } + } + else + { + messageRed($_Lang['fl3_ACSFleet2Slow'], $ErrorTitle); + } +} + +if($Allow_UseQuantumGate AND $QuantumGate_UseType == 2) +{ + $Add2UpdatePlanet[] = "`quantumgate_lastuse` = {$Now}"; + $Add2UpdatePlanetPHP['quantumgate_lastuse'] = $Now; +} + +// MultiAlert System +$SendAlert = false; +$IPIntersectionFound = 'false'; +$IPIntersectionFiltred = 'false'; +$IPIntersectionNow = 'false'; +if($UsedPlanet AND !$YourPlanet AND !$PlanetAbandoned) +{ + include($_EnginePath.'includes/functions/AlertSystemUtilities.php'); + $CheckIntersection = AlertUtils_IPIntersect($_User['id'], $TargetData['owner'], array + ( + 'LastTimeDiff' => (TIME_DAY * 30), + 'ThisTimeDiff' => (TIME_DAY * 30), + 'ThisTimeStamp' => ($Now - SERVER_MAINOPEN_TSTAMP) + )); + if($CheckIntersection !== false) + { + $IPIntersectionFound = 'true'; + if($_User['user_lastip'] == $TargetData['lastip']) + { + $IPIntersectionNow = 'true'; + } + + $FiltersData['place'] = 1; + $FiltersData['alertsender'] = 1; + $FiltersData['users'] = array($_User['id'], $TargetData['owner']); + $FiltersData['ips'] = $CheckIntersection['Intersect']; + $FiltersData['sender'] = $_User['id']; + $FiltersData['target'] = $TargetData['owner']; + foreach($CheckIntersection['Intersect'] as $IP) + { + $FiltersData['logcount'][$IP][$_User['id']] = $CheckIntersection['IPLogData'][$_User['id']][$IP]['Count']; + $FiltersData['logcount'][$IP][$TargetData['owner']] = $CheckIntersection['IPLogData'][$TargetData['owner']][$IP]['Count']; + } + + if($_User['multiIP_DeclarationID'] > 0 AND $_User['multiIP_DeclarationID'] == $TargetData['multiIP_DeclarationID']) + { + $Query_CheckDeclaration = ''; + $Query_CheckDeclaration .= "SELECT `id` FROM {{table}} WHERE "; + $Query_CheckDeclaration .= "`status` = 1 AND `id` = {$_User['multiIP_DeclarationID']} "; + $Query_CheckDeclaration .= "LIMIT 1;"; + $CheckDeclaration = doquery($Query_CheckDeclaration, 'declarations', true); + $DeclarationID = $CheckDeclaration['id']; + } + else + { + $DeclarationID = 0; + } + + $FilterResult = AlertUtils_CheckFilters($FiltersData); + if($FilterResult['FilterUsed']) + { + $IPIntersectionFiltred = 'true'; + } + if(!$FilterResult['SendAlert']) + { + $DontSendAlert = true; + } + if(!$FilterResult['ShowAlert']) + { + $DontShowAlert = true; + } + + if(!isset($DontSendAlert)) + { + $SendAlert = true; + } + if(1 == 0 AND $DontShowAlert !== true) + { + // Currently there is no indicator that user wants to get MultiAlert Messages (do disable this code) + $LockFleetSending = true; + $ShowMultiAlert = true; + $_Alert['MultiAlert']['Data']['Blocked'] = true; + } + } +} + +if(!isset($LockFleetSending)) +{ + $FleetArray = array(); + foreach($Fleet['array'] as $ShipID => $ShipCount) + { + $FleetArray[] = "{$ShipID},{$ShipCount}"; + } + $FleetArrayCopy = $Fleet['array']; + $Fleet['array'] = implode(';', $FleetArray); + + if(empty($TargetData['id'])) + { + $TargetData['id'] = '0'; + } + if(empty($TargetData['owner'])) + { + $TargetData['owner'] = '0'; + } + if(empty($TargetData['galaxy_id'])) + { + $TargetData['galaxy_id'] = '0'; + } + + $Query_Insert = ''; + $Query_Insert .= "INSERT INTO {{table}} SET "; + $Query_Insert .= "`fleet_owner` = {$_User['id']}, "; + $Query_Insert .= "`fleet_mission` = {$Fleet['Mission']}, "; + $Query_Insert .= "`fleet_amount` = {$Fleet['count']}, "; + $Query_Insert .= "`fleet_array` = '{$Fleet['array']}', "; + $Query_Insert .= "`fleet_start_time` = {$Fleet['SetCalcTime']}, "; + $Query_Insert .= "`fleet_start_id` = {$_Planet['id']}, "; + $Query_Insert .= "`fleet_start_galaxy` = {$_Planet['galaxy']}, "; + $Query_Insert .= "`fleet_start_system` = {$_Planet['system']}, "; + $Query_Insert .= "`fleet_start_planet` = {$_Planet['planet']}, "; + $Query_Insert .= "`fleet_start_type` = {$_Planet['planet_type']}, "; + $Query_Insert .= "`fleet_end_time` = {$Fleet['SetBackTime']}, "; + $Query_Insert .= "`fleet_end_id` = {$TargetData['id']}, "; + $Query_Insert .= "`fleet_end_id_galaxy` = {$TargetData['galaxy_id']}, "; + $Query_Insert .= "`fleet_end_stay` = {$Fleet['SetStayTime']}, "; + $Query_Insert .= "`fleet_end_galaxy` = {$Target['galaxy']}, "; + $Query_Insert .= "`fleet_end_system` = {$Target['system']}, "; + $Query_Insert .= "`fleet_end_planet` = {$Target['planet']}, "; + $Query_Insert .= "`fleet_end_type` = {$Target['type']}, "; + $Query_Insert .= "`fleet_resource_metal` = {$Fleet['resources']['metal']}, "; + $Query_Insert .= "`fleet_resource_crystal` = {$Fleet['resources']['crystal']}, "; + $Query_Insert .= "`fleet_resource_deuterium` = {$Fleet['resources']['deuterium']}, "; + $Query_Insert .= "`fleet_target_owner` = '{$TargetData['owner']}', "; + $Query_Insert .= "`fleet_send_time` = {$Now};"; + doquery($Query_Insert, 'fleets'); + + $LastFleetID = doquery("SELECT LAST_INSERT_ID() as `id`;", '', true); + $LastFleetID = $LastFleetID['id']; + + // PushAlert + if($UsedPlanet AND !$YourPlanet AND !$PlanetAbandoned) + { + if($Fleet['Mission'] == 3) + { + if($StatsData['mine'] < $StatsData['his']) + { + if(!empty($Fleet['resources'])) + { + foreach($Fleet['resources'] as $ThisValue) + { + if($ThisValue > 0) + { + $_Alert['PushAlert']['HasResources'] = true; + break; + } + } + } + if($_Alert['PushAlert']['HasResources'] === true) + { + $FiltersData = array(); + $FiltersData['place'] = 1; + $FiltersData['alertsender'] = 1; + $FiltersData['users'] = array($_User['id'], $TargetData['owner']); + $FiltersData['sender'] = $_User['id']; + $FiltersData['target'] = $TargetData['owner']; + $FilterResult = AlertUtils_CheckFilters($FiltersData, array('DontLoad' => true, 'DontLoad_OnlyIfCacheEmpty' => true)); + + if($FilterResult['SendAlert']) + { + $_Alert['PushAlert']['Data']['TargetUserID'] = $TargetData['owner']; + if($_User['ally_id'] > 0 AND $_User['ally_id'] == $TargetData['ally_id']) + { + $_Alert['PushAlert']['Data']['SameAlly'] = $TargetData['ally_id']; + } + else if($OwnerIsAlliedUser === true) + { + $_Alert['PushAlert']['Data']['AllyPact'] = array + ( + 'SenderAlly' => $_User['ally_id'], + 'TargetAlly' => $TargetData['ally_id'], + ); + } + if($OwnerIsBuddyFriend === true) + { + $_Alert['PushAlert']['Data']['BuddyFriends'] = true; + } + $_Alert['PushAlert']['Data']['FleetID'] = $LastFleetID; + $_Alert['PushAlert']['Data']['Stats']['Sender'] = array('Points' => $StatsData['mine'], 'Position' => $_User['total_rank']); + $_Alert['PushAlert']['Data']['Stats']['Target'] = array('Points' => $StatsData['his'], 'Position' => $TargetData['total_rank']); + $_Alert['PushAlert']['Data']['Resources'] = array + ( + 'Metal' => floatval($Fleet['resources']['metal']), + 'Crystal' => floatval($Fleet['resources']['crystal']), + 'Deuterium' => floatval($Fleet['resources']['deuterium']) + ); + + Alerts_Add(1, $Now, 5, 4, 5, $_User['id'], $_Alert['PushAlert']['Data']); + } + } + } + } + } +} + +if($SendAlert) +{ + $_Alert['MultiAlert']['Importance'] = 10; + $_Alert['MultiAlert']['Data']['MissionID'] = $Fleet['Mission']; + if($LastFleetID > 0) + { + $_Alert['MultiAlert']['Data']['FleetID'] = $LastFleetID; + } + $_Alert['MultiAlert']['Data']['TargetUserID'] = $TargetData['owner']; + foreach($CheckIntersection['Intersect'] as $ThisIPID) + { + $_Alert['MultiAlert']['Data']['Intersect'][] = array + ( + 'IPID' => $ThisIPID, + 'SenderData' => $CheckIntersection['IPLogData'][$_User['id']][$ThisIPID], + 'TargetData' => $CheckIntersection['IPLogData'][$TargetData['owner']][$ThisIPID] + ); + } + if($DeclarationID > 0) + { + $_Alert['MultiAlert']['Data']['DeclarationID'] = $DeclarationID; + $_Alert['MultiAlert']['Type'] = 2; + } + else + { + $_Alert['MultiAlert']['Type'] = 1; + } + + $Query_AlertOtherUsers = ''; + $Query_AlertOtherUsers .= "SELECT DISTINCT `User_ID` FROM {{table}} WHERE "; + $Query_AlertOtherUsers .= "`User_ID` NOT IN ({$_User['id']}, {$TargetData['owner']}) AND "; + $Query_AlertOtherUsers .= "`IP_ID` IN (".implode(', ', $CheckIntersection['Intersect']).") AND "; + $Query_AlertOtherUsers .= "`Count` > `FailCount`;"; + $Result_AlertOtherUsers = doquery($Query_AlertOtherUsers, 'user_enterlog'); + if(mysql_num_rows($Result_AlertOtherUsers) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_AlertOtherUsers)) + { + $_Alert['MultiAlert']['Data']['OtherUsers'][] = $FetchData['User_ID']; + } + } + + Alerts_Add(1, $Now, $_Alert['MultiAlert']['Type'], 1, $_Alert['MultiAlert']['Importance'], $_User['id'], $_Alert['MultiAlert']['Data']); +} + +if(isset($ShowMultiAlert)) +{ + messageRed($_Lang['MultiAlert'], $_Lang['fl_error']); +} + +if(isset($UpdateACS)) +{ + if(!empty($CheckACS['fleets_id'])) + { + $NewFleetsID[] = $CheckACS['fleets_id']; + } + $NewFleetsID[] = '|'.$LastFleetID.'|'; + $UpdateACSRow[] = "`fleets_id` = '".implode(',', $NewFleetsID)."'"; + + if(!empty($CheckACS['user_joined'])) + { + if(strstr($CheckACS['user_joined'], '|'.$_User['id'].'|') === FALSE) + { + $NewUsers[] = $CheckACS['user_joined']; + $NewUsers[] = '|'.$_User['id'].'|'; + $UpdateACSRow[] = "`user_joined` = '".implode(',', $NewUsers)."'"; + } + } + else + { + $UpdateACSRow[] = "`user_joined` = '|{$_User['id']}|'"; + } + + $UpdateACSRow[] = "`fleets_count` = `fleets_count` + 1"; + + if(!empty($UpdateACSRow)) + { + doquery("UPDATE {{table}} SET ".implode(', ', $UpdateACSRow)." WHERE `id` = {$Fleet['ACS_ID']};", 'acs'); + } + + if(!empty($UpdateACSFleets)) + { + $Fleets = $CheckACS['main_fleet_id']; + if(!empty($CheckACS['fleets_id'])) + { + $Fleets .= ','.str_replace('|', '', $CheckACS['fleets_id']); + } + doquery("UPDATE {{table}} SET ".implode(', ', $UpdateACSFleets)." WHERE `fleet_id` IN ({$Fleets});", 'fleets'); + } +} + +if($Allow_UseQuantumGate) +{ + $QuantumGate_Used = '1'; +} +else +{ + $QuantumGate_Used = '0'; +} +$QryArchive = ''; +$QryArchive .= "INSERT INTO {{table}} (`Fleet_ID`, `Fleet_Owner`, `Fleet_Mission`, `Fleet_Array`, `Fleet_Time_Send`, `Fleet_Time_Start`, `Fleet_Time_Stay`, `Fleet_Time_End`, `Fleet_Start_ID`, `Fleet_Start_Galaxy`, `Fleet_Start_System`, `Fleet_Start_Planet`, `Fleet_Start_Type`, `Fleet_Start_Res_Metal`, `Fleet_Start_Res_Crystal`, `Fleet_Start_Res_Deuterium`, `Fleet_End_ID`, `Fleet_End_ID_Galaxy`, `Fleet_End_Galaxy`, `Fleet_End_System`, `Fleet_End_Planet`, `Fleet_End_Type`, `Fleet_End_Owner`, `Fleet_ACSID`, `Fleet_Info_HadSameIP_Ever`, `Fleet_Info_HadSameIP_Ever_Filtred`, `Fleet_Info_HadSameIP_OnSend`, `Fleet_Info_UsedTeleport`) VALUES "; +$QryArchive .= " ({$LastFleetID}, {$_User['id']}, {$Fleet['Mission']}, '{$Fleet['array']}', {$Now}, {$Fleet['SetCalcTime']}, {$Fleet['SetStayTime']}, {$Fleet['SetBackTime']}, {$_Planet['id']}, {$_Planet['galaxy']}, {$_Planet['system']}, {$_Planet['planet']}, {$_Planet['planet_type']}, {$Fleet['resources']['metal']}, {$Fleet['resources']['crystal']}, {$Fleet['resources']['deuterium']}, '{$TargetData['id']}', '{$TargetData['galaxy_id']}', {$Target['galaxy']}, {$Target['system']}, {$Target['planet']}, {$Target['type']}, '{$TargetData['owner']}', '{$Fleet['ACS_ID']}', {$IPIntersectionFound}, {$IPIntersectionFiltred}, {$IPIntersectionNow}, {$QuantumGate_Used}) "; + +if(!empty($UpdateACSFleets)) +{ + $UpdateACSFleetsIDs = explode(',', str_replace('|', '', $CheckACS['fleets_id'])); + $UpdateACSFleetsIDs[] = $CheckACS['main_fleet_id']; + if(!empty($UpdateACSFleetsIDs)) + { + $QryArchive .= ', '; + foreach($UpdateACSFleetsIDs as $FleetID) + { + if(!empty($FleetID)) + { + $QryArchiveA[] = "({$FleetID}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)"; + } + } + $QryArchive .= implode(', ',$QryArchiveA); + $QryArchive .= " ON DUPLICATE KEY UPDATE "; + $QryArchive .= "`Fleet_Time_ACSAdd` = `Fleet_Time_ACSAdd` + {$Difference}"; + } +} +doquery($QryArchive, 'fleet_archive'); + +$_Planet['metal'] -= $Fleet['resources']['metal']; +$_Planet['crystal'] -= $Fleet['resources']['crystal']; +$_Planet['deuterium'] -= ($Fleet['resources']['deuterium'] + $Consumption); + +$_Lang['ShipsRows'] = ''; +foreach($FleetArrayCopy as $ShipID => $ShipCount) +{ + $_Planet[$_Vars_GameElements[$ShipID]] -= $ShipCount; + $_Lang['ShipsRows'] .= ''.$_Lang['tech'][$ShipID].''.prettyNumber($ShipCount).''; +} +if(!empty($Add2UpdatePlanetPHP)) +{ + foreach($Add2UpdatePlanetPHP as $Key => $Value) + { + $_Planet[$Key] = $Value; + } +} + +$QryUpdatePlanet = ''; +$QryUpdatePlanet .= "UPDATE {{table}} SET "; +$QryUpdatePlanet .= implode(', ', $FleetRemover).', '; +$QryUpdatePlanet .= "`metal` = '{$_Planet['metal']}', "; +$QryUpdatePlanet .= "`crystal` = '{$_Planet['crystal']}', "; +$QryUpdatePlanet .= "`deuterium` = '{$_Planet['deuterium']}' "; +if(!empty($Add2UpdatePlanet)) +{ + $QryUpdatePlanet .= ", ".implode(', ', $Add2UpdatePlanet); +} +$QryUpdatePlanet .= " WHERE "; +$QryUpdatePlanet .= "`id` = {$_Planet['id']};"; + +doquery('LOCK TABLE {{table}} WRITE', 'planets'); +doquery($QryUpdatePlanet, 'planets'); +doquery('UNLOCK TABLES', ''); + +// User Development Log +if($Fleet['resources']['metal'] > 0) +{ + $Add2UserDev_Log[] = 'M,'.$Fleet['resources']['metal']; +} +if($Fleet['resources']['crystal'] > 0) +{ + $Add2UserDev_Log[] = 'C,'.$Fleet['resources']['crystal']; +} +if($Fleet['resources']['deuterium'] > 0) +{ + $Add2UserDev_Log[] = 'D,'.$Fleet['resources']['deuterium']; +} +if($Consumption > 0) +{ + $Add2UserDev_Log[] = 'F,'.$Consumption; +} +$RTrim = rtrim($Fleet['array'], ';'); +if(!empty($Add2UserDev_Log)) +{ + $Add2UserDev_Log = ';'.implode(';', $Add2UserDev_Log); +} +$UserDev_Log[] = array('PlanetID' => $_Planet['id'], 'Date' => $Now, 'Place' => 10, 'Code' => $Fleet['Mission'], 'ElementID' => $LastFleetID, 'AdditionalData' => $RTrim.$Add2UserDev_Log); +// --- + +$_Lang['FleetMission'] = $_Lang['type_mission'][$Fleet['Mission']]; +$_Lang['FleetDistance'] = prettyNumber($Distance); +$_Lang['FleetSpeed'] = prettyNumber($MaxFleetSpeed); +$_Lang['FleetFuel'] = prettyNumber($Consumption); +$_Lang['StartGalaxy'] = $_Planet['galaxy']; +$_Lang['StartSystem'] = $_Planet['system']; +$_Lang['StartPlanet'] = $_Planet['planet']; +$_Lang['StartType'] = ($_Planet['planet_type'] == 1 ? 'planet' : ($_Planet['planet_type'] == 3 ? 'moon' : 'debris')); +$_Lang['TargetGalaxy'] = $Target['galaxy']; +$_Lang['TargetSystem'] = $Target['system']; +$_Lang['TargetPlanet'] = $Target['planet']; +$_Lang['TargetType'] = ($Target['type'] == 1 ? 'planet' : ($Target['type'] == 3 ? 'moon' : 'debris')); +$_Lang['FleetStartTime'] = prettyDate('d m Y H:i:s', $Fleet['SetCalcTime'], 1); +$_Lang['FleetEndTime'] = prettyDate('d m Y H:i:s', $Fleet['SetBackTime'], 1); +$_Lang['useQuickRes'] = ($_POST['useQuickRes'] == '1' ? 'true' : 'false'); + +display(parsetemplate(gettemplate('fleet3_body'), $_Lang), $_Lang['fl_title']); + +?> diff --git a/fleetretreat.php b/fleetretreat.php index 8062309be..7c3fe6169 100644 --- a/fleetretreat.php +++ b/fleetretreat.php @@ -1,49 +1,49 @@ - 0) - { - include($_EnginePath.'includes/functions/FleetControl_Retreat.php'); - $Result = FleetControl_Retreat("`fleet_id` = {$FleetID} AND `fleet_owner` = {$_User['id']}"); - if($Result['Rows'] != 0) - { - if($Result['Errors'][$FleetID] == 1) - { - $SetMsg = 4; - } - else if($Result['Errors'][$FleetID] == 2) - { - $SetMsg = 1; - } - else - { - if($Result['Types'][$FleetID] == 1) - { - $SetMsg = 2; - $SetColor = 2; - } - else if($Result['Types'][$FleetID] == 2) - { - $SetMsg = 3; - $SetColor = 2; - } - } - } - } - - header("Location: fleet.php?ret=1&m={$SetMsg}&c={$SetColor}"); - safeDie(); - -?> \ No newline at end of file + 0) +{ + include($_EnginePath.'includes/functions/FleetControl_Retreat.php'); + $Result = FleetControl_Retreat("`fleet_id` = {$FleetID} AND `fleet_owner` = {$_User['id']}"); + if($Result['Rows'] != 0) + { + if($Result['Errors'][$FleetID] == 1) + { + $SetMsg = 4; + } + else if($Result['Errors'][$FleetID] == 2) + { + $SetMsg = 1; + } + else + { + if($Result['Types'][$FleetID] == 1) + { + $SetMsg = 2; + $SetColor = 2; + } + else if($Result['Types'][$FleetID] == 2) + { + $SetMsg = 3; + $SetColor = 2; + } + } + } +} + +header("Location: fleet.php?ret=1&m={$SetMsg}&c={$SetColor}"); +safeDie(); + +?> diff --git a/fleetshortcut.php b/fleetshortcut.php index 0c42a9a06..7974c51ff 100644 --- a/fleetshortcut.php +++ b/fleetshortcut.php @@ -1,243 +1,243 @@ - 0, `planets`.`name`, '') AS `name`, "; - $Query_GetShortcuts .= "IF(`planets`.`id` > 0, `planets`.`galaxy`, {{table}}.galaxy) AS `galaxy`, "; - $Query_GetShortcuts .= "IF(`planets`.`id` > 0, `planets`.`system`, {{table}}.system) AS `system`, "; - $Query_GetShortcuts .= "IF(`planets`.`id` > 0, `planets`.`planet`, {{table}}.planet) AS `planet`, "; - $Query_GetShortcuts .= "IF(`planets`.`id` > 0, `planets`.`planet_type`, {{table}}.type) AS `planet_type` "; - $Query_GetShortcuts .= "FROM {{table}} "; - $Query_GetShortcuts .= "LEFT JOIN {{prefix}}planets as `planets` ON `planets`.`id` = {{table}}.`id_planet` "; - $Query_GetShortcuts .= "WHERE {{table}}.`id_owner` = {$_User['id']} ORDER BY {{table}}.id ASC;"; - $Result_GetShortcuts = doquery($Query_GetShortcuts, 'fleet_shortcuts'); - if(mysql_num_rows($Result_GetShortcuts) > 0) - { - while($Data = mysql_fetch_assoc($Result_GetShortcuts)) - { - $_Lang['shortcuts_list'] .= ''; - } - } - else - { - $_Lang['shortcuts_list'] = ''; - } - - $page = parsetemplate(gettemplate('fleetshortcut_overview'), $_Lang); - } - else - { - switch($Mode) - { - case 'add': - { - if(isset($_POST['action']) && $_POST['action'] == 'add') - { - $Name = trim($_POST['name']); - $Galaxy = intval($_POST['galaxy']); - $System = intval($_POST['system']); - $Planet = intval($_POST['planet']); - $Type = intval($_POST['type']); - if(in_array($Type, array(1,2,3)) && $Galaxy > 0 && $System > 0 && $Planet > 0 && $Galaxy <= MAX_GALAXY_IN_WORLD && $System <= MAX_SYSTEM_IN_GALAXY && $Planet <= (MAX_PLANET_IN_SYSTEM + 1)) - { - $TargetID = '0'; - if($Type == 1 || $Type == 3) - { - $Query_GetTarget = ''; - $Query_GetTarget .= "SELECT `id` FROM {{table}} WHERE "; - $Query_GetTarget .= "`galaxy` = {$Galaxy} AND `system` = {$System} AND `planet` = {$Planet} AND `planet_type` = {$Type} "; - $Query_GetTarget .= "LIMIT 1;"; - $SelectTarget = doquery($Query_GetTarget, 'planets'); - if(mysql_num_rows($SelectTarget) == 1) - { - $SelectTarget = mysql_fetch_assoc($SelectTarget); - $TargetID = $SelectTarget['id']; - } - } - - if(!empty($Name)) - { - if(!preg_match('/^[a-zA-Z0-9\_\-\ ]{1,}$/D', $Name)) - { - message($_Lang['Forbidden_signs_in_name'], $_Lang['Adding_shortcut'], 'fleetshortcut.php?mode=add', 2); - } - } - - $Query_CheckShortcut = ''; - $Query_CheckShortcut .= "SELECT `id` FROM {{table}} WHERE "; - $Query_CheckShortcut .= "`galaxy` = {$Galaxy} AND `system` = {$System} AND `planet` = {$Planet} AND `type` = {$Type} "; - $Query_CheckShortcut .= "AND `id_owner` = {$_User['id']} "; - $Query_CheckShortcut .= "LIMIT 1;"; - $Result_CheckShortcut = doquery($Query_CheckShortcut, 'fleet_shortcuts'); - if(mysql_num_rows($Result_CheckShortcut) == 1) - { - message($_Lang['That_target_already_exists'], $_Lang['Adding_shortcut'], 'fleetshortcut.php?mode=add', 2); - } - - doquery("INSERT INTO {{table}} VALUES (NULL, {$_User['id']}, {$TargetID}, {$Galaxy}, {$System}, {$Planet}, {$Type}, '{$Name}');", 'fleet_shortcuts'); - message($_Lang['Shortcut_hasbeen_added'], $_Lang['Adding_shortcut'],'fleetshortcut.php', 2); - } - else - { - message($_Lang['Bad_coordinates'], $_Lang['Adding_shortcut'], 'fleetshortcut.php?mode=add', 2); - } - } - else - { - $_Lang['Action_shortcut'] = $_Lang['Adding_shortcut']; - $_Lang['Action']= $_Lang['Add']; - $_Lang['post_action'] = 'add'; - - $page = parsetemplate(gettemplate('fleetshortcut_add_edit'), $_Lang); - } - break; - } - case 'delete': - { - $ID = (isset($_GET['id']) ? intval($_GET['id']) : 0); - - if($ID <= 0) - { - message($_Lang['Bad_ID_given'], $_Lang['Deleting_shortcut'], 'fleetshortcut.php', 2); - } - - $SelectLink = doquery("SELECT `id_owner` FROM {{table}} WHERE `id` = {$ID} LIMIT 1;", 'fleet_shortcuts', true); - if($SelectLink['id_owner'] > 0) - { - if($SelectLink['id_owner'] == $_User['id']) - { - doquery("DELETE FROM {{table}} WHERE `id` = {$ID};", 'fleet_shortcuts'); - message($_Lang['Link_hasbeen_deleted'], $_Lang['Deleting_shortcut'], 'fleetshortcut.php', 2); - } - else - { - message($_Lang['This_shortcut_is_not_yours'], $_Lang['Deleting_shortcut'], 'fleetshortcut.php', 2); - } - } - else - { - message($_Lang['Bad_ID_given'], $_Lang['Deleting_shortcut'], 'fleetshortcut.php', 2); - } - break; - } - case 'edit': - { - $ID = (isset($_GET['id']) ? intval($_GET['id']) : 0); - - if($ID <= 0) - { - message($_Lang['Bad_ID_given'], $_Lang['Deleting_shortcut'], 'fleetshortcut.php', 2); - } - - $SelectLink = doquery("SELECT * FROM {{table}} WHERE `id` = {$ID} LIMIT 1;", 'fleet_shortcuts', true); - if($SelectLink['id_owner'] > 0) - { - if($SelectLink['id_owner'] == $_User['id']) - { - if(isset($_POST['action']) && $_POST['action'] == 'edit') - { - $Name = trim($_POST['name']); - $Galaxy = intval($_POST['galaxy']); - $System = intval($_POST['system']); - $Planet = intval($_POST['planet']); - $Type = intval($_POST['type']); - if(in_array($Type, array(1,2,3)) && $Galaxy > 0 && $System > 0 && $Planet > 0 && $Galaxy <= MAX_GALAXY_IN_WORLD && $System <= MAX_SYSTEM_IN_GALAXY && $Planet <= (MAX_PLANET_IN_SYSTEM + 1)) - { - $TargetID = '0'; - if($Type == 1 || $Type == 3) - { - $SelectTarget = doquery("SELECT `id` FROM {{table}} WHERE `galaxy` = {$Galaxy} AND `system` = {$System} AND `planet` = {$Planet} AND `planet_type` = {$Type} LIMIT 1;", 'planets', true); - if($SelectTarget['id'] > 0) - { - $TargetID = $SelectTarget['id']; - } - } - - if(!empty($Name)) - { - if(!preg_match('/^[a-zA-Z0-9\_\-\ ]{1,}$/D', $Name)) - { - message($_Lang['Forbidden_signs_in_name'], $_Lang['Editing_shortcut'], 'fleetshortcut.php?mode=edit&id='.$ID, 2); - } - } - - $SelectTarget = doquery("SELECT `id` FROM {{table}} WHERE `galaxy` = {$Galaxy} AND `system` = {$System} AND `planet` = {$Planet} AND `type` = {$Type} AND `id_owner` = {$_User['id']} LIMIT 1;", 'fleet_shortcuts'); - if(mysql_num_rows($SelectTarget) == 1) - { - $SelectTarget = mysql_fetch_assoc($SelectTarget); - if($SelectTarget['id'] > 0 AND $SelectTarget['id'] != $ID) - { - message($_Lang['That_target_already_exists'], $_Lang['Editing_shortcut'], 'fleetshortcut.php?mode=edit&id='.$ID, 2); - } - else if($SelectTarget['id'] == $ID) - { - message($_Lang['NothingChanged'], $_Lang['Editing_shortcut'], 'fleetshortcut.php?mode=edit&id='.$ID, 2); - } - } - - doquery("UPDATE {{table}} SET `id_planet` = {$TargetID}, `galaxy` = {$Galaxy}, `system` = {$System}, `planet` = {$Planet}, `type` = {$Type}, `own_name` = '{$Name}' WHERE `id` = {$ID};", 'fleet_shortcuts'); - message($_Lang['Shortcut_hasbeen_saved'], $_Lang['Editing_shortcut'], 'fleetshortcut.php', 2); - } - else - { - message($_Lang['Bad_coordinates'], $_Lang['Editing_shortcut'], 'fleetshortcut.php?mode=edit&id='.$ID, 2); - } - } - else - { - $_Lang['Action_shortcut'] = $_Lang['Editing_shortcut']; - $_Lang['Action'] = $_Lang['Edit']; - $_Lang['post_action'] = 'edit'; - $_Lang['edit_id'] = $ID; - $_Lang['set_name'] = $SelectLink['own_name']; - $_Lang['set_galaxy'] = $SelectLink['galaxy']; - $_Lang['set_system'] = $SelectLink['system']; - $_Lang['set_planet'] = $SelectLink['planet']; - switch($SelectLink['type']) - { - case 1: - $_Lang['planet_selected'] = 'selected'; - break; - case 2: - $_Lang['debris_selected'] = 'selected'; - break; - case 3: - $_Lang['moon_selected'] = 'selected'; - break; - } - - $page = parsetemplate(gettemplate('fleetshortcut_add_edit'), $_Lang); - } - } - else - { - message($_Lang['This_shortcut_is_not_yours'], $_Lang['Editing_shortcut'],'fleetshortcut.php', 2); - } - } - else - { - message($_Lang['Bad_ID_given'], $_Lang['Editing_shortcut'],'fleetshortcut.php', 2); - } - break; - } - } - } - - display($page, $_Lang['Title']); - -?> \ No newline at end of file + 0, `planets`.`name`, '') AS `name`, "; + $Query_GetShortcuts .= "IF(`planets`.`id` > 0, `planets`.`galaxy`, {{table}}.galaxy) AS `galaxy`, "; + $Query_GetShortcuts .= "IF(`planets`.`id` > 0, `planets`.`system`, {{table}}.system) AS `system`, "; + $Query_GetShortcuts .= "IF(`planets`.`id` > 0, `planets`.`planet`, {{table}}.planet) AS `planet`, "; + $Query_GetShortcuts .= "IF(`planets`.`id` > 0, `planets`.`planet_type`, {{table}}.type) AS `planet_type` "; + $Query_GetShortcuts .= "FROM {{table}} "; + $Query_GetShortcuts .= "LEFT JOIN {{prefix}}planets as `planets` ON `planets`.`id` = {{table}}.`id_planet` "; + $Query_GetShortcuts .= "WHERE {{table}}.`id_owner` = {$_User['id']} ORDER BY {{table}}.id ASC;"; + $Result_GetShortcuts = doquery($Query_GetShortcuts, 'fleet_shortcuts'); + if(mysql_num_rows($Result_GetShortcuts) > 0) + { + while($Data = mysql_fetch_assoc($Result_GetShortcuts)) + { + $_Lang['shortcuts_list'] .= ''; + } + } + else + { + $_Lang['shortcuts_list'] = ''; + } + + $page = parsetemplate(gettemplate('fleetshortcut_overview'), $_Lang); +} +else +{ + switch($Mode) + { + case 'add': + { + if(isset($_POST['action']) && $_POST['action'] == 'add') + { + $Name = trim($_POST['name']); + $Galaxy = intval($_POST['galaxy']); + $System = intval($_POST['system']); + $Planet = intval($_POST['planet']); + $Type = intval($_POST['type']); + if(in_array($Type, array(1,2,3)) && $Galaxy > 0 && $System > 0 && $Planet > 0 && $Galaxy <= MAX_GALAXY_IN_WORLD && $System <= MAX_SYSTEM_IN_GALAXY && $Planet <= (MAX_PLANET_IN_SYSTEM + 1)) + { + $TargetID = '0'; + if($Type == 1 || $Type == 3) + { + $Query_GetTarget = ''; + $Query_GetTarget .= "SELECT `id` FROM {{table}} WHERE "; + $Query_GetTarget .= "`galaxy` = {$Galaxy} AND `system` = {$System} AND `planet` = {$Planet} AND `planet_type` = {$Type} "; + $Query_GetTarget .= "LIMIT 1;"; + $SelectTarget = doquery($Query_GetTarget, 'planets'); + if(mysql_num_rows($SelectTarget) == 1) + { + $SelectTarget = mysql_fetch_assoc($SelectTarget); + $TargetID = $SelectTarget['id']; + } + } + + if(!empty($Name)) + { + if(!preg_match('/^[a-zA-Z0-9\_\-\ ]{1,}$/D', $Name)) + { + message($_Lang['Forbidden_signs_in_name'], $_Lang['Adding_shortcut'], 'fleetshortcut.php?mode=add', 2); + } + } + + $Query_CheckShortcut = ''; + $Query_CheckShortcut .= "SELECT `id` FROM {{table}} WHERE "; + $Query_CheckShortcut .= "`galaxy` = {$Galaxy} AND `system` = {$System} AND `planet` = {$Planet} AND `type` = {$Type} "; + $Query_CheckShortcut .= "AND `id_owner` = {$_User['id']} "; + $Query_CheckShortcut .= "LIMIT 1;"; + $Result_CheckShortcut = doquery($Query_CheckShortcut, 'fleet_shortcuts'); + if(mysql_num_rows($Result_CheckShortcut) == 1) + { + message($_Lang['That_target_already_exists'], $_Lang['Adding_shortcut'], 'fleetshortcut.php?mode=add', 2); + } + + doquery("INSERT INTO {{table}} VALUES (NULL, {$_User['id']}, {$TargetID}, {$Galaxy}, {$System}, {$Planet}, {$Type}, '{$Name}');", 'fleet_shortcuts'); + message($_Lang['Shortcut_hasbeen_added'], $_Lang['Adding_shortcut'],'fleetshortcut.php', 2); + } + else + { + message($_Lang['Bad_coordinates'], $_Lang['Adding_shortcut'], 'fleetshortcut.php?mode=add', 2); + } + } + else + { + $_Lang['Action_shortcut'] = $_Lang['Adding_shortcut']; + $_Lang['Action']= $_Lang['Add']; + $_Lang['post_action'] = 'add'; + + $page = parsetemplate(gettemplate('fleetshortcut_add_edit'), $_Lang); + } + break; + } + case 'delete': + { + $ID = (isset($_GET['id']) ? intval($_GET['id']) : 0); + + if($ID <= 0) + { + message($_Lang['Bad_ID_given'], $_Lang['Deleting_shortcut'], 'fleetshortcut.php', 2); + } + + $SelectLink = doquery("SELECT `id_owner` FROM {{table}} WHERE `id` = {$ID} LIMIT 1;", 'fleet_shortcuts', true); + if($SelectLink['id_owner'] > 0) + { + if($SelectLink['id_owner'] == $_User['id']) + { + doquery("DELETE FROM {{table}} WHERE `id` = {$ID};", 'fleet_shortcuts'); + message($_Lang['Link_hasbeen_deleted'], $_Lang['Deleting_shortcut'], 'fleetshortcut.php', 2); + } + else + { + message($_Lang['This_shortcut_is_not_yours'], $_Lang['Deleting_shortcut'], 'fleetshortcut.php', 2); + } + } + else + { + message($_Lang['Bad_ID_given'], $_Lang['Deleting_shortcut'], 'fleetshortcut.php', 2); + } + break; + } + case 'edit': + { + $ID = (isset($_GET['id']) ? intval($_GET['id']) : 0); + + if($ID <= 0) + { + message($_Lang['Bad_ID_given'], $_Lang['Deleting_shortcut'], 'fleetshortcut.php', 2); + } + + $SelectLink = doquery("SELECT * FROM {{table}} WHERE `id` = {$ID} LIMIT 1;", 'fleet_shortcuts', true); + if($SelectLink['id_owner'] > 0) + { + if($SelectLink['id_owner'] == $_User['id']) + { + if(isset($_POST['action']) && $_POST['action'] == 'edit') + { + $Name = trim($_POST['name']); + $Galaxy = intval($_POST['galaxy']); + $System = intval($_POST['system']); + $Planet = intval($_POST['planet']); + $Type = intval($_POST['type']); + if(in_array($Type, array(1,2,3)) && $Galaxy > 0 && $System > 0 && $Planet > 0 && $Galaxy <= MAX_GALAXY_IN_WORLD && $System <= MAX_SYSTEM_IN_GALAXY && $Planet <= (MAX_PLANET_IN_SYSTEM + 1)) + { + $TargetID = '0'; + if($Type == 1 || $Type == 3) + { + $SelectTarget = doquery("SELECT `id` FROM {{table}} WHERE `galaxy` = {$Galaxy} AND `system` = {$System} AND `planet` = {$Planet} AND `planet_type` = {$Type} LIMIT 1;", 'planets', true); + if($SelectTarget['id'] > 0) + { + $TargetID = $SelectTarget['id']; + } + } + + if(!empty($Name)) + { + if(!preg_match('/^[a-zA-Z0-9\_\-\ ]{1,}$/D', $Name)) + { + message($_Lang['Forbidden_signs_in_name'], $_Lang['Editing_shortcut'], 'fleetshortcut.php?mode=edit&id='.$ID, 2); + } + } + + $SelectTarget = doquery("SELECT `id` FROM {{table}} WHERE `galaxy` = {$Galaxy} AND `system` = {$System} AND `planet` = {$Planet} AND `type` = {$Type} AND `id_owner` = {$_User['id']} LIMIT 1;", 'fleet_shortcuts'); + if(mysql_num_rows($SelectTarget) == 1) + { + $SelectTarget = mysql_fetch_assoc($SelectTarget); + if($SelectTarget['id'] > 0 AND $SelectTarget['id'] != $ID) + { + message($_Lang['That_target_already_exists'], $_Lang['Editing_shortcut'], 'fleetshortcut.php?mode=edit&id='.$ID, 2); + } + else if($SelectTarget['id'] == $ID) + { + message($_Lang['NothingChanged'], $_Lang['Editing_shortcut'], 'fleetshortcut.php?mode=edit&id='.$ID, 2); + } + } + + doquery("UPDATE {{table}} SET `id_planet` = {$TargetID}, `galaxy` = {$Galaxy}, `system` = {$System}, `planet` = {$Planet}, `type` = {$Type}, `own_name` = '{$Name}' WHERE `id` = {$ID};", 'fleet_shortcuts'); + message($_Lang['Shortcut_hasbeen_saved'], $_Lang['Editing_shortcut'], 'fleetshortcut.php', 2); + } + else + { + message($_Lang['Bad_coordinates'], $_Lang['Editing_shortcut'], 'fleetshortcut.php?mode=edit&id='.$ID, 2); + } + } + else + { + $_Lang['Action_shortcut'] = $_Lang['Editing_shortcut']; + $_Lang['Action'] = $_Lang['Edit']; + $_Lang['post_action'] = 'edit'; + $_Lang['edit_id'] = $ID; + $_Lang['set_name'] = $SelectLink['own_name']; + $_Lang['set_galaxy'] = $SelectLink['galaxy']; + $_Lang['set_system'] = $SelectLink['system']; + $_Lang['set_planet'] = $SelectLink['planet']; + switch($SelectLink['type']) + { + case 1: + $_Lang['planet_selected'] = 'selected'; + break; + case 2: + $_Lang['debris_selected'] = 'selected'; + break; + case 3: + $_Lang['moon_selected'] = 'selected'; + break; + } + + $page = parsetemplate(gettemplate('fleetshortcut_add_edit'), $_Lang); + } + } + else + { + message($_Lang['This_shortcut_is_not_yours'], $_Lang['Editing_shortcut'],'fleetshortcut.php', 2); + } + } + else + { + message($_Lang['Bad_ID_given'], $_Lang['Editing_shortcut'],'fleetshortcut.php', 2); + } + break; + } + } +} + +display($page, $_Lang['Title']); + +?> diff --git a/galacticshop.php b/galacticshop.php index 124e9dcfc..97d18e94b 100644 --- a/galacticshop.php +++ b/galacticshop.php @@ -1,612 +1,612 @@ - 0) - { - $GetUsernames = array(); - while($Free = mysql_fetch_assoc($GetFreeItems)) - { - if(!isset($_Lang['FreeItemsList'][$Free['ID']])) - { - $_Lang['FreeItemsList'][$Free['ID']] = ''; - } - $_Lang['FreeItemsList'][$Free['ID']] .= ''.$_Lang['shop_items'][$Free['ItemID']]['name'].''.($_Lang['shop_items'][$Free['ItemID']]['duration'] !== false ? '
'.$_Lang['FreeDuration'].': '.$_Lang['shop_items'][$Free['ItemID']]['duration'] : '').'
'; - $_Lang['FreeItemsList'][$Free['ID']] .= '{USERID_'.$Free['GivenBy'].'}
'.prettyDate('d m Y - H:i:s', $Free['GiveDate'], 1).'
'; - $_Lang['FreeItemsList'][$Free['ID']] .= ''; - if(!in_array($Free['GivenBy'], $GetUsernames)) - { - $GetUsernames[$Free['GivenBy']] = $Free['GivenBy']; - } - $FreeItems[$Free['ID']] = $Free; - } - if(!empty($GetUsernames)) - { - $GetUsernamesQry = doquery("SELECT `id`, `username` FROM {{table}} WHERE `id` IN (".implode(', ', $GetUsernames).");", 'users'); - if(mysql_num_rows($GetUsernamesQry) > 0) - { - while($Username = mysql_fetch_assoc($GetUsernamesQry)) - { - foreach($_Lang['FreeItemsList'] as $Key => $Value) - { - $_Lang['FreeItemsList'][$Key] = str_replace('{USERID_'.$Username['id'].'}', $Username['username'], $Value); - } - unset($GetUsernames[$Username['id']]); - } - } - if(!empty($GetUsernames)) - { - foreach($GetUsernames as $DeleteID) - { - foreach($_Lang['FreeItemsList'] as $Key => $Value) - { - if($DeleteID > 0) - { - $_Lang['FreeItemsList'][$Key] = str_replace('{USERID_'.$Username['id'].'}', ''.$_Lang['User_Deleted'].'', $Value); - } - else - { - $_Lang['FreeItemsList'][$Key] = str_replace('{USERID_0}', ''.$_Lang['Free_GivenBySys'].'', $Value); - } - } - } - } - } - } - - if(!empty($_GET['use_freeid'])) - { - $_POST = false; - $Use_FreeID = intval(str_replace('freeid_', '', $_GET['use_freeid'])); - if($Use_FreeID > 0) - { - if(!empty($FreeItems[$Use_FreeID])) - { - $_POST['mode'] = 'buyitem'; - $_POST['buyitem_'.$FreeItems[$Use_FreeID]['ItemID']] = $_Lang['BuyIT']; - $DontGetDarkEnergy = true; - } - else - { - $_Lang['showError'] = $_Lang['Free_BadItemGiven']; - $_Lang['SetActiveMarker'] = '03'; - } - } - else - { - $_Lang['showError'] = $_Lang['Free_BadIDGiven']; - $_Lang['SetActiveMarker'] = '03'; - } - } - - if(!empty($_POST['mode'])) - { - switch($_POST['mode']) - { - // Buy Dark Energy - case 'buyde': - { - $_Lang['SetActiveMarker'] = '01'; - - // Currently it breaks here just to ensure, that this section won't be executed without proper code - break; - - // ------------------------------------------------------------------------- - // HERE PLACE YOUR SMS SHOP CODE OR WHATEVER YOU WILL USE TO HANDLE PAYMENTS - // ------------------------------------------------------------------------- - // - // Language variables - // $_Lang['ErrorNoCode'] - No code given - // $_Lang['ErrorBadOption'] - Bad option selected - // $_Lang['ErrorUnknown'] - Unknown error when connecting to remote server - // $_Lang['ErrorWrongCode'] - User gave wrong code - // $_Lang['ErrorCodeShouldBe8CharsLong'] - Code should be at least 8 characters long - // - // Variables to set - // $addDarkEnergy - How much Dark Energy use should get - // $check - Given by user Code received by SMS (just to save it to the DataBase) - // - If you don't want to save this code, delete code marked with "SAVECODETODB" comment - // - // - // Also please remember, that you have to implement how this section is presented to the user - // Place your implementation in galacticshop.tpl (template file) in place of this text: - // "THIS OPTION IS NOT IMPLEMENTED YET" - // - // If you want, you can use my implementation for DotPay.pl payment system - // (it's saved under galacticshop_dotpay.tpl template file) - // - - if($_User['referred'] > 0) - { - if(empty($GlobalParsedTasks[$_User['referred']]['tasks_done_parsed'])) - { - $GetUserTasksDone = doquery("SELECT `id`, `tasks_done` FROM {{table}} WHERE `id` = {$_User['referred']} LIMIT 1;", 'users', true); - if($GetUserTasksDone['id'] == $_User['referred']) - { - unset($GetUserTasksDone['id']); - Tasks_CheckUservar($GetUserTasksDone); - $GlobalParsedTasks[$_User['referred']] = $GetUserTasksDone; - $ThisTaskUser = $GlobalParsedTasks[$_User['referred']]; - $ThisTaskUser['id'] = $_User['referred']; - } - } - else - { - $ThisTaskUser = $GlobalParsedTasks[$_User['referred']]; - $ThisTaskUser['id'] = $_User['referred']; - } - - if(!empty($ThisTaskUser)) - { - $ThisUserID = $_User['id']; - - Tasks_TriggerTask($ThisTaskUser, 'INVITEDUSER_BOUGHT_DE', array - ( - 'mainCheck' => function($JobArray) use ($addDarkEnergy) - { - if($addDarkEnergy < $JobArray['count']) - { - return true; - } - } - )); - Tasks_TriggerTask($ThisTaskUser, 'INVITEDUSERS_BOUGHT_DE_LIMIT', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $addDarkEnergy) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $addDarkEnergy); - } - )); - Tasks_TriggerTask($ThisTaskUser, 'INVITEDUSERS_BOUGHT_DE_USERCOUNT', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use (&$ThisTaskUser, $ThisUserID) - { - global $UserTasksUpdate; - - if(!empty($UserTasksUpdate[$ThisTaskUser['id']]['jobdata'][$ThisCat][$TaskID][$JobID])) - { - $ThisTaskUser['tasks_done_parsed']['jobdata'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$ThisTaskUser['id']]['jobdata'][$ThisCat][$TaskID][$JobID]; - } - $ThisJobData = $ThisTaskUser['tasks_done_parsed']['jobdata'][$ThisCat][$TaskID][$JobID]; - if(!empty($ThisJobData['users']) AND in_array($ThisUserID, $ThisJobData['users'])) - { - return true; - } - - $ThisTaskUser['tasks_done_parsed']['jobdata'][$ThisCat][$TaskID][$JobID]['users'][] = $ThisUserID; - $UserTasksUpdate[$ThisTaskUser['id']]['jobdata'][$ThisCat][$TaskID][$JobID] = $ThisTaskUser['tasks_done_parsed']['jobdata'][$ThisCat][$TaskID][$JobID]; - if(!empty($UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID])) - { - $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID]; - } - $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] += 1; - if($ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] < $JobArray[$JobArray['statusField']]) - { - $UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; - return true; - } - } - )); - } - } - - // SAVECODETODB - // Send this Action to PremiumCodes Log - $SecurePassedCode = preg_replace('#[^0-9a-zA-Z]{1,}#si', '', $check); - doquery("INSERT INTO {{table}} VALUES (NULL, {$_User['id']}, UNIX_TIMESTAMP(), ".intval($_POST['option']).", '{$SecurePassedCode}');", 'premiumcodes'); - // END OF SAVECODETODB - - $result = doquery("UPDATE {{table}} SET `darkEnergy` = `darkEnergy` + {$addDarkEnergy} WHERE `id` = {$_User['id']};", 'users'); - if($result == true) - { - $_User['darkEnergy'] += $addDarkEnergy; - if($_User['referred'] > 0) - { - $Provision = floor($addDarkEnergy * REFERING_PROVISION); - doquery("UPDATE {{table}} SET `darkEnergy` = `darkEnergy` + {$Provision} WHERE `id` = {$_User['referred']};", 'users'); - doquery("UPDATE {{table}} SET `provisions_granted` = `provisions_granted` + {$Provision} WHERE `referrer_id` = {$_User['referred']} AND `newuser_id` = {$_User['id']};", 'referring_table'); - } - header('Location: galacticshop.php?darkenergy_bought=true&count='.$addDarkEnergy.'&show=deform'); - safeDie(); - } - else - { - $_Lang['showError'] = $_Lang['ErrorSQL']; - } - break; - } - // Buy item - case 'buyitem': - { - if($DontGetDarkEnergy !== true) - { - $_Lang['SetActiveMarker'] = '02'; - } - else - { - $_Lang['SetActiveMarker'] = '03'; - } - if((array)$_Lang['shop_items'] === $_Lang['shop_items']) - { - $Keys = array_keys($_POST); - $KeysCount = count($Keys); - if($KeysCount == 2) - { - sort($Keys); - $ItemID = intval(substr($Keys[0], 8)); - if($ItemID >= 1) - { - if((array)$_Lang['shop_items'][$ItemID] === $_Lang['shop_items'][$ItemID]) - { - if((!isset($_Lang['shop_items'][$ItemID]['buyable']) || $_Lang['shop_items'][$ItemID]['buyable'] !== false) || $DontGetDarkEnergy === true) - { - if($_User['darkEnergy'] >= $_Lang['shop_items'][$ItemID]['price'] || $DontGetDarkEnergy === true) - { - // ProAccounts - if($ItemID == 1 OR $ItemID == 2 OR $ItemID == 11 OR $ItemID == 13) - { - $Duration = $_Lang['shop_items'][$ItemID]['duration_days'] * TIME_DAY; - if($Duration > 0) - { - $QueryTable = 'users'; - if($_User['pro_time'] > time()) - { - $Query = "UPDATE {{table}} SET `pro_time` = `pro_time` + {$Duration} WHERE `id` = {$_User['id']};"; - $_User['pro_time'] += $Duration; - $Msg = $_Lang['ProAccountExtended']; - } - else - { - $Query = "UPDATE {{table}} SET `pro_time` = UNIX_TIMESTAMP() + {$Duration} WHERE `id` = {$_User['id']};"; - $_User['pro_time'] = time() + $Duration; - $Msg = $_Lang['ProAccountAdded']; - } - } - else - { - $_Lang['showError'] = $_Lang['ErrorConfigError']; - } - //End of ProAccounts - // --------------------- - // Add fields to Planet - } - elseif($ItemID == 3) - { - if($_Planet['id'] > 0) - { - if($_Planet['planet_type'] == 1) - { - $AddFields = $_Lang['shop_items'][$ItemID]['addFields']; - if($AddFields > 0) - { - $QueryTable = 'planets'; - $Query = "UPDATE {{table}} SET `field_max` = `field_max` + {$AddFields} WHERE `id` = {$_Planet['id']};"; - $Msg = $_Lang['PlanetFieldsAdded']; - } - else - { - $_Lang['showError'] = $_Lang['ErrorConfigError']; - } - } - else - { - $_Lang['showError'] = $_Lang['ErrorAddFieldsNoMoon']; - } - } - else - { - $_Lang['showError'] = $_Lang['ErrorNoPlanetID']; - } - //End of Add fields to Planet - // ---------------------------- - // Add Officers or Spy Jammer - } - elseif(($ItemID >= 4 AND $ItemID <= 8) OR $ItemID == 12) - { - $Duration = $_Lang['shop_items'][$ItemID]['duration_days'] * TIME_DAY; - if($Duration > 0) - { - $QueryTable = 'users'; - switch($ItemID) - { - case 4: - $Field = 'spy_jam_time'; - $MsgAdd = $_Lang['SpyJamAdd']; - $MsgExt = $_Lang['SpyJamExt']; - break; - case 5: - $Field = 'geologist_time'; - $MsgAdd = $_Lang['GeologistAdd']; - $MsgExt = $_Lang['GeologistExt']; - break; - case 6: - $Field = 'engineer_time'; - $MsgAdd = $_Lang['EngineerAdd']; - $MsgExt = $_Lang['EngineerExt']; - break; - case 7: - $Field = 'admiral_time'; - $MsgAdd = $_Lang['AdmiralAdd']; - $MsgExt = $_Lang['AdmiralExt']; - break; - case 8: - $Field = 'technocrat_time'; - $MsgAdd = $_Lang['TechnocratAdd']; - $MsgExt = $_Lang['TechnocratExt']; - break; - case 12: - $Field = 'geologist_time'; - $MsgAdd = $_Lang['GeologistAdd']; - $MsgExt = $_Lang['GeologistExt']; - break; - } - if($_User[$Field] > time()) - { - $Query = "UPDATE {{table}} SET `{$Field}` = `{$Field}` + {$Duration} WHERE `id` = {$_User['id']};"; - $_User[$Field] += $Duration; - $Msg = $MsgExt; - } - else - { - $Query = "UPDATE {{table}} SET `{$Field}` = UNIX_TIMESTAMP() + {$Duration} WHERE `id` = {$_User['id']};"; - $_User[$Field] = time() + $Duration; - $Msg = $MsgAdd; - } - } - else - { - $_Lang['showError'] = $_Lang['ErrorConfigError']; - } - //End of Add Officers or Spy Jammer - // ---------------------------- - // Add Additional Planet Slots - } - elseif($ItemID == 9) - { - if($AdditionalPlanets < 3) - { - $QueryTable = 'users'; - $Query = "UPDATE {{table}} SET `additional_planets` = `additional_planets` + 1 WHERE `id` = {$_User['id']};"; - if($AdditionalPlanets < 2) - { - $TempSprintf = $_Lang['PlanetSlots_left'][$AdditionalPlanets]; - $Msg = sprintf($_Lang['PlanetBought'], $TempSprintf); - } - else - { - $Msg = sprintf($_Lang['PlanetBoughtLast']); - } - $AdditionalPlanets++; - $_User['additional_planets']++; - } - else - { - $_Lang['showError'] = $_Lang['ErrorCanBuyOnly3Planets']; - } - //End of Add Additional Planet Slots - // ---------------------------- - // Add Trader Uses (Transactions) - } - elseif(in_array($ItemID, array(14, 15, 16))) - { - $QueryTable = 'users'; - $Query = "UPDATE {{table}} SET `trader_usesCount` = `trader_usesCount` + {$_Lang['shop_items'][$ItemID]['amount']} WHERE `id` = {$_User['id']};"; - $Msg = sprintf($_Lang['TraderUsesBought'], prettyNumber($_Lang['shop_items'][$ItemID]['amount'])); - $_User['trader_usesCount'] += $_Lang['shop_items'][$ItemID]['amount']; - } - //End of Add Trader Uses (Transactions) - - // Send Query here! - if(!empty($Query) AND !empty($QueryTable)) - { - if($DontGetDarkEnergy !== true) - { - $Result = doquery("UPDATE {{table}} SET `darkEnergy` = `darkEnergy` - {$_Lang['shop_items'][$ItemID]['price']} WHERE `id` = {$_User['id']};", 'users'); - } - else - { - $Result = TRUE; - } - if($Result == TRUE) - { - if($DontGetDarkEnergy !== true) - { - $_User['darkEnergy'] -= $_Lang['shop_items'][$ItemID]['price']; - } - else - { - doquery("UPDATE {{table}} SET `Used` = true, `UseDate` = UNIX_TIMESTAMP() WHERE `ID` = {$Use_FreeID};", 'premium_free'); - unset($_Lang['FreeItemsList'][$Use_FreeID]); - } - - // Send PremiumPayments to Log - doquery("INSERT INTO {{table}} VALUES (NULL, {$_User['id']}, UNIX_TIMESTAMP(), {$ItemID}, ".($DontGetDarkEnergy === true ? 'true' : 'false').");", 'premiumpayments'); - // --- - - $Result = doquery($Query, $QueryTable); - if($Result == TRUE) - { - $_Lang['showMsg'] = $Msg; - } - else - { - $_Lang['showError'] = $_Lang['ErrorSQL']; - } - } - else - { - $_Lang['showError'] = $_Lang['ErrorSQL']; - } - } - else - { - if(empty($_Lang['showError'])) - { - $_Lang['showError'] = $_Lang['ErrorNoQuery']; - } - } - } - else - { - $_Lang['showError'] = $_Lang['ErrorNoEnoughDE']; - } - } - else - { - $_Lang['showError'] = $_Lang['ErrorNotBuyable']; - } - } - else - { - $_Lang['showError'] = $_Lang['ErrorBadIDGiven']; - } - } - else - { - $_Lang['showError'] = $_Lang['ErrorBadIDGiven']; - } - } - else - { - if($KeysCount > 2) - { - $_Lang['showError'] = $_Lang['ErrorTooMuchItemIDGiven']; - } - else - { - $_Lang['showError'] = $_Lang['ErrorNoItemIDGiven']; - } - } - } - else - { - $_Lang['showError'] = $_Lang['ErrorCurrentlyNothinkToSell']; - } - break; - } - } - } - - if(empty($_Lang['FreeItemsList'])) - { - $_Lang['FreeItemsList'] = ''.$_Lang['Free_NoFreeItems'].''; - } - else - { - $_Lang['FreeItemsList'] = implode("\n", $_Lang['FreeItemsList']); - } - - $BreakLine = ''; - - if(!empty($_Lang['showError'])) - { - $_Lang['showError'] = ''.$_Lang['showError'].''.$BreakLine; - } - if(!empty($_Lang['showMsg'])) - { - $_Lang['showMsg'] = ''.$_Lang['showMsg'].''.$BreakLine; - } - $_Lang['shop_items'][9]['price'] = $_Lang['shop_items'][9]['price_array'][$AdditionalPlanets]; - - if((array)$_Lang['shop_items'] === $_Lang['shop_items']) - { - foreach($_Lang['shop_items'] as $key => $val) - { - if(!isset($val['buyable']) || $val['buyable'] !== false) - { - $_Lang['Articles'] .= ''.$val['name'].''; - $_Lang['Articles'] .= ''.$val['desc'].''; - if(empty($val['action'])) - { - if($val['price'] > 0 || $val['price'] === 0) - { - $_Lang['Articles'] .= ''.$val['price'].' '.$_Lang['DEprice'].'
'; - } - else - { - $_Lang['Articles'] .= ''.$_Lang['CannotBuyItAnymore'].''; - } - } - else - { - switch($val['action']) - { - case 'redirect': - $_Lang['Articles'] .= ''.$val['price'].' '.$_Lang['DEprice'].'
'; - break; - } - } - } - } - } - if(empty($_Lang['Articles'])) - { - $_Lang['Articles'] = ''.$_Lang['NoItemsOnStock'].''; - } - - if(isset($_GET['darkenergy_bought']) && $_GET['darkenergy_bought'] == 'true') - { - if(!isset($_GET['count'])) - { - $_GET['count'] = 5; - } - $CheckDEFormTabs = array(5 => '01', 15 => '02', 25 => '03', 45 => '04'); - $_Lang['SetActiveFormTab'] = $CheckDEFormTabs[$_GET['count']]; - } - - $_Lang['DarkEnergy_Counter'] = $_User['darkEnergy']; - if($_User['darkEnergy'] >= 15) - { - $_Lang['DarkEnergy_Color'] = 'lime'; - } - elseif($_User['darkEnergy'] > 0) - { - $_Lang['DarkEnergy_Color'] = 'orange'; - } - else - { - $_Lang['DarkEnergy_Color'] = 'red'; - } - - $page = parsetemplate(gettemplate('galacticshop'), $_Lang); - display($page, $_Lang['Title'], false); - -?> \ No newline at end of file + 0) +{ + $GetUsernames = array(); + while($Free = mysql_fetch_assoc($GetFreeItems)) + { + if(!isset($_Lang['FreeItemsList'][$Free['ID']])) + { + $_Lang['FreeItemsList'][$Free['ID']] = ''; + } + $_Lang['FreeItemsList'][$Free['ID']] .= ''.$_Lang['shop_items'][$Free['ItemID']]['name'].''.($_Lang['shop_items'][$Free['ItemID']]['duration'] !== false ? '
'.$_Lang['FreeDuration'].': '.$_Lang['shop_items'][$Free['ItemID']]['duration'] : '').'
'; + $_Lang['FreeItemsList'][$Free['ID']] .= '{USERID_'.$Free['GivenBy'].'}
'.prettyDate('d m Y - H:i:s', $Free['GiveDate'], 1).'
'; + $_Lang['FreeItemsList'][$Free['ID']] .= ''; + if(!in_array($Free['GivenBy'], $GetUsernames)) + { + $GetUsernames[$Free['GivenBy']] = $Free['GivenBy']; + } + $FreeItems[$Free['ID']] = $Free; + } + if(!empty($GetUsernames)) + { + $GetUsernamesQry = doquery("SELECT `id`, `username` FROM {{table}} WHERE `id` IN (".implode(', ', $GetUsernames).");", 'users'); + if(mysql_num_rows($GetUsernamesQry) > 0) + { + while($Username = mysql_fetch_assoc($GetUsernamesQry)) + { + foreach($_Lang['FreeItemsList'] as $Key => $Value) + { + $_Lang['FreeItemsList'][$Key] = str_replace('{USERID_'.$Username['id'].'}', $Username['username'], $Value); + } + unset($GetUsernames[$Username['id']]); + } + } + if(!empty($GetUsernames)) + { + foreach($GetUsernames as $DeleteID) + { + foreach($_Lang['FreeItemsList'] as $Key => $Value) + { + if($DeleteID > 0) + { + $_Lang['FreeItemsList'][$Key] = str_replace('{USERID_'.$Username['id'].'}', ''.$_Lang['User_Deleted'].'', $Value); + } + else + { + $_Lang['FreeItemsList'][$Key] = str_replace('{USERID_0}', ''.$_Lang['Free_GivenBySys'].'', $Value); + } + } + } + } + } +} + +if(!empty($_GET['use_freeid'])) +{ + $_POST = false; + $Use_FreeID = intval(str_replace('freeid_', '', $_GET['use_freeid'])); + if($Use_FreeID > 0) + { + if(!empty($FreeItems[$Use_FreeID])) + { + $_POST['mode'] = 'buyitem'; + $_POST['buyitem_'.$FreeItems[$Use_FreeID]['ItemID']] = $_Lang['BuyIT']; + $DontGetDarkEnergy = true; + } + else + { + $_Lang['showError'] = $_Lang['Free_BadItemGiven']; + $_Lang['SetActiveMarker'] = '03'; + } + } + else + { + $_Lang['showError'] = $_Lang['Free_BadIDGiven']; + $_Lang['SetActiveMarker'] = '03'; + } +} + +if(!empty($_POST['mode'])) +{ + switch($_POST['mode']) + { + // Buy Dark Energy + case 'buyde': + { + $_Lang['SetActiveMarker'] = '01'; + + // Currently it breaks here just to ensure, that this section won't be executed without proper code + break; + + // ------------------------------------------------------------------------- + // HERE PLACE YOUR SMS SHOP CODE OR WHATEVER YOU WILL USE TO HANDLE PAYMENTS + // ------------------------------------------------------------------------- + // + // Language variables + // $_Lang['ErrorNoCode'] - No code given + // $_Lang['ErrorBadOption'] - Bad option selected + // $_Lang['ErrorUnknown'] - Unknown error when connecting to remote server + // $_Lang['ErrorWrongCode'] - User gave wrong code + // $_Lang['ErrorCodeShouldBe8CharsLong'] - Code should be at least 8 characters long + // + // Variables to set + // $addDarkEnergy - How much Dark Energy use should get + // $check - Given by user Code received by SMS (just to save it to the DataBase) + // - If you don't want to save this code, delete code marked with "SAVECODETODB" comment + // + // + // Also please remember, that you have to implement how this section is presented to the user + // Place your implementation in galacticshop.tpl (template file) in place of this text: + // "THIS OPTION IS NOT IMPLEMENTED YET" + // + // If you want, you can use my implementation for DotPay.pl payment system + // (it's saved under galacticshop_dotpay.tpl template file) + // + + if($_User['referred'] > 0) + { + if(empty($GlobalParsedTasks[$_User['referred']]['tasks_done_parsed'])) + { + $GetUserTasksDone = doquery("SELECT `id`, `tasks_done` FROM {{table}} WHERE `id` = {$_User['referred']} LIMIT 1;", 'users', true); + if($GetUserTasksDone['id'] == $_User['referred']) + { + unset($GetUserTasksDone['id']); + Tasks_CheckUservar($GetUserTasksDone); + $GlobalParsedTasks[$_User['referred']] = $GetUserTasksDone; + $ThisTaskUser = $GlobalParsedTasks[$_User['referred']]; + $ThisTaskUser['id'] = $_User['referred']; + } + } + else + { + $ThisTaskUser = $GlobalParsedTasks[$_User['referred']]; + $ThisTaskUser['id'] = $_User['referred']; + } + + if(!empty($ThisTaskUser)) + { + $ThisUserID = $_User['id']; + + Tasks_TriggerTask($ThisTaskUser, 'INVITEDUSER_BOUGHT_DE', array + ( + 'mainCheck' => function($JobArray) use ($addDarkEnergy) + { + if($addDarkEnergy < $JobArray['count']) + { + return true; + } + } + )); + Tasks_TriggerTask($ThisTaskUser, 'INVITEDUSERS_BOUGHT_DE_LIMIT', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $addDarkEnergy) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $addDarkEnergy); + } + )); + Tasks_TriggerTask($ThisTaskUser, 'INVITEDUSERS_BOUGHT_DE_USERCOUNT', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use (&$ThisTaskUser, $ThisUserID) + { + global $UserTasksUpdate; + + if(!empty($UserTasksUpdate[$ThisTaskUser['id']]['jobdata'][$ThisCat][$TaskID][$JobID])) + { + $ThisTaskUser['tasks_done_parsed']['jobdata'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$ThisTaskUser['id']]['jobdata'][$ThisCat][$TaskID][$JobID]; + } + $ThisJobData = $ThisTaskUser['tasks_done_parsed']['jobdata'][$ThisCat][$TaskID][$JobID]; + if(!empty($ThisJobData['users']) AND in_array($ThisUserID, $ThisJobData['users'])) + { + return true; + } + + $ThisTaskUser['tasks_done_parsed']['jobdata'][$ThisCat][$TaskID][$JobID]['users'][] = $ThisUserID; + $UserTasksUpdate[$ThisTaskUser['id']]['jobdata'][$ThisCat][$TaskID][$JobID] = $ThisTaskUser['tasks_done_parsed']['jobdata'][$ThisCat][$TaskID][$JobID]; + if(!empty($UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID])) + { + $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID]; + } + $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] += 1; + if($ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] < $JobArray[$JobArray['statusField']]) + { + $UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; + return true; + } + } + )); + } + } + + // SAVECODETODB + // Send this Action to PremiumCodes Log + $SecurePassedCode = preg_replace('#[^0-9a-zA-Z]{1,}#si', '', $check); + doquery("INSERT INTO {{table}} VALUES (NULL, {$_User['id']}, UNIX_TIMESTAMP(), ".intval($_POST['option']).", '{$SecurePassedCode}');", 'premiumcodes'); + // END OF SAVECODETODB + + $result = doquery("UPDATE {{table}} SET `darkEnergy` = `darkEnergy` + {$addDarkEnergy} WHERE `id` = {$_User['id']};", 'users'); + if($result == true) + { + $_User['darkEnergy'] += $addDarkEnergy; + if($_User['referred'] > 0) + { + $Provision = floor($addDarkEnergy * REFERING_PROVISION); + doquery("UPDATE {{table}} SET `darkEnergy` = `darkEnergy` + {$Provision} WHERE `id` = {$_User['referred']};", 'users'); + doquery("UPDATE {{table}} SET `provisions_granted` = `provisions_granted` + {$Provision} WHERE `referrer_id` = {$_User['referred']} AND `newuser_id` = {$_User['id']};", 'referring_table'); + } + header('Location: galacticshop.php?darkenergy_bought=true&count='.$addDarkEnergy.'&show=deform'); + safeDie(); + } + else + { + $_Lang['showError'] = $_Lang['ErrorSQL']; + } + break; + } + // Buy item + case 'buyitem': + { + if($DontGetDarkEnergy !== true) + { + $_Lang['SetActiveMarker'] = '02'; + } + else + { + $_Lang['SetActiveMarker'] = '03'; + } + if((array)$_Lang['shop_items'] === $_Lang['shop_items']) + { + $Keys = array_keys($_POST); + $KeysCount = count($Keys); + if($KeysCount == 2) + { + sort($Keys); + $ItemID = intval(substr($Keys[0], 8)); + if($ItemID >= 1) + { + if((array)$_Lang['shop_items'][$ItemID] === $_Lang['shop_items'][$ItemID]) + { + if((!isset($_Lang['shop_items'][$ItemID]['buyable']) || $_Lang['shop_items'][$ItemID]['buyable'] !== false) || $DontGetDarkEnergy === true) + { + if($_User['darkEnergy'] >= $_Lang['shop_items'][$ItemID]['price'] || $DontGetDarkEnergy === true) + { + // ProAccounts + if($ItemID == 1 OR $ItemID == 2 OR $ItemID == 11 OR $ItemID == 13) + { + $Duration = $_Lang['shop_items'][$ItemID]['duration_days'] * TIME_DAY; + if($Duration > 0) + { + $QueryTable = 'users'; + if($_User['pro_time'] > time()) + { + $Query = "UPDATE {{table}} SET `pro_time` = `pro_time` + {$Duration} WHERE `id` = {$_User['id']};"; + $_User['pro_time'] += $Duration; + $Msg = $_Lang['ProAccountExtended']; + } + else + { + $Query = "UPDATE {{table}} SET `pro_time` = UNIX_TIMESTAMP() + {$Duration} WHERE `id` = {$_User['id']};"; + $_User['pro_time'] = time() + $Duration; + $Msg = $_Lang['ProAccountAdded']; + } + } + else + { + $_Lang['showError'] = $_Lang['ErrorConfigError']; + } + //End of ProAccounts + // --------------------- + // Add fields to Planet + } + elseif($ItemID == 3) + { + if($_Planet['id'] > 0) + { + if($_Planet['planet_type'] == 1) + { + $AddFields = $_Lang['shop_items'][$ItemID]['addFields']; + if($AddFields > 0) + { + $QueryTable = 'planets'; + $Query = "UPDATE {{table}} SET `field_max` = `field_max` + {$AddFields} WHERE `id` = {$_Planet['id']};"; + $Msg = $_Lang['PlanetFieldsAdded']; + } + else + { + $_Lang['showError'] = $_Lang['ErrorConfigError']; + } + } + else + { + $_Lang['showError'] = $_Lang['ErrorAddFieldsNoMoon']; + } + } + else + { + $_Lang['showError'] = $_Lang['ErrorNoPlanetID']; + } + //End of Add fields to Planet + // ---------------------------- + // Add Officers or Spy Jammer + } + elseif(($ItemID >= 4 AND $ItemID <= 8) OR $ItemID == 12) + { + $Duration = $_Lang['shop_items'][$ItemID]['duration_days'] * TIME_DAY; + if($Duration > 0) + { + $QueryTable = 'users'; + switch($ItemID) + { + case 4: + $Field = 'spy_jam_time'; + $MsgAdd = $_Lang['SpyJamAdd']; + $MsgExt = $_Lang['SpyJamExt']; + break; + case 5: + $Field = 'geologist_time'; + $MsgAdd = $_Lang['GeologistAdd']; + $MsgExt = $_Lang['GeologistExt']; + break; + case 6: + $Field = 'engineer_time'; + $MsgAdd = $_Lang['EngineerAdd']; + $MsgExt = $_Lang['EngineerExt']; + break; + case 7: + $Field = 'admiral_time'; + $MsgAdd = $_Lang['AdmiralAdd']; + $MsgExt = $_Lang['AdmiralExt']; + break; + case 8: + $Field = 'technocrat_time'; + $MsgAdd = $_Lang['TechnocratAdd']; + $MsgExt = $_Lang['TechnocratExt']; + break; + case 12: + $Field = 'geologist_time'; + $MsgAdd = $_Lang['GeologistAdd']; + $MsgExt = $_Lang['GeologistExt']; + break; + } + if($_User[$Field] > time()) + { + $Query = "UPDATE {{table}} SET `{$Field}` = `{$Field}` + {$Duration} WHERE `id` = {$_User['id']};"; + $_User[$Field] += $Duration; + $Msg = $MsgExt; + } + else + { + $Query = "UPDATE {{table}} SET `{$Field}` = UNIX_TIMESTAMP() + {$Duration} WHERE `id` = {$_User['id']};"; + $_User[$Field] = time() + $Duration; + $Msg = $MsgAdd; + } + } + else + { + $_Lang['showError'] = $_Lang['ErrorConfigError']; + } + //End of Add Officers or Spy Jammer + // ---------------------------- + // Add Additional Planet Slots + } + elseif($ItemID == 9) + { + if($AdditionalPlanets < 3) + { + $QueryTable = 'users'; + $Query = "UPDATE {{table}} SET `additional_planets` = `additional_planets` + 1 WHERE `id` = {$_User['id']};"; + if($AdditionalPlanets < 2) + { + $TempSprintf = $_Lang['PlanetSlots_left'][$AdditionalPlanets]; + $Msg = sprintf($_Lang['PlanetBought'], $TempSprintf); + } + else + { + $Msg = sprintf($_Lang['PlanetBoughtLast']); + } + $AdditionalPlanets++; + $_User['additional_planets']++; + } + else + { + $_Lang['showError'] = $_Lang['ErrorCanBuyOnly3Planets']; + } + //End of Add Additional Planet Slots + // ---------------------------- + // Add Trader Uses (Transactions) + } + elseif(in_array($ItemID, array(14, 15, 16))) + { + $QueryTable = 'users'; + $Query = "UPDATE {{table}} SET `trader_usesCount` = `trader_usesCount` + {$_Lang['shop_items'][$ItemID]['amount']} WHERE `id` = {$_User['id']};"; + $Msg = sprintf($_Lang['TraderUsesBought'], prettyNumber($_Lang['shop_items'][$ItemID]['amount'])); + $_User['trader_usesCount'] += $_Lang['shop_items'][$ItemID]['amount']; + } + //End of Add Trader Uses (Transactions) + + // Send Query here! + if(!empty($Query) AND !empty($QueryTable)) + { + if($DontGetDarkEnergy !== true) + { + $Result = doquery("UPDATE {{table}} SET `darkEnergy` = `darkEnergy` - {$_Lang['shop_items'][$ItemID]['price']} WHERE `id` = {$_User['id']};", 'users'); + } + else + { + $Result = TRUE; + } + if($Result == TRUE) + { + if($DontGetDarkEnergy !== true) + { + $_User['darkEnergy'] -= $_Lang['shop_items'][$ItemID]['price']; + } + else + { + doquery("UPDATE {{table}} SET `Used` = true, `UseDate` = UNIX_TIMESTAMP() WHERE `ID` = {$Use_FreeID};", 'premium_free'); + unset($_Lang['FreeItemsList'][$Use_FreeID]); + } + + // Send PremiumPayments to Log + doquery("INSERT INTO {{table}} VALUES (NULL, {$_User['id']}, UNIX_TIMESTAMP(), {$ItemID}, ".($DontGetDarkEnergy === true ? 'true' : 'false').");", 'premiumpayments'); + // --- + + $Result = doquery($Query, $QueryTable); + if($Result == TRUE) + { + $_Lang['showMsg'] = $Msg; + } + else + { + $_Lang['showError'] = $_Lang['ErrorSQL']; + } + } + else + { + $_Lang['showError'] = $_Lang['ErrorSQL']; + } + } + else + { + if(empty($_Lang['showError'])) + { + $_Lang['showError'] = $_Lang['ErrorNoQuery']; + } + } + } + else + { + $_Lang['showError'] = $_Lang['ErrorNoEnoughDE']; + } + } + else + { + $_Lang['showError'] = $_Lang['ErrorNotBuyable']; + } + } + else + { + $_Lang['showError'] = $_Lang['ErrorBadIDGiven']; + } + } + else + { + $_Lang['showError'] = $_Lang['ErrorBadIDGiven']; + } + } + else + { + if($KeysCount > 2) + { + $_Lang['showError'] = $_Lang['ErrorTooMuchItemIDGiven']; + } + else + { + $_Lang['showError'] = $_Lang['ErrorNoItemIDGiven']; + } + } + } + else + { + $_Lang['showError'] = $_Lang['ErrorCurrentlyNothinkToSell']; + } + break; + } + } +} + +if(empty($_Lang['FreeItemsList'])) +{ + $_Lang['FreeItemsList'] = ''.$_Lang['Free_NoFreeItems'].''; +} +else +{ + $_Lang['FreeItemsList'] = implode("\n", $_Lang['FreeItemsList']); +} + +$BreakLine = ''; + +if(!empty($_Lang['showError'])) +{ + $_Lang['showError'] = ''.$_Lang['showError'].''.$BreakLine; +} +if(!empty($_Lang['showMsg'])) +{ + $_Lang['showMsg'] = ''.$_Lang['showMsg'].''.$BreakLine; +} +$_Lang['shop_items'][9]['price'] = $_Lang['shop_items'][9]['price_array'][$AdditionalPlanets]; + +if((array)$_Lang['shop_items'] === $_Lang['shop_items']) +{ + foreach($_Lang['shop_items'] as $key => $val) + { + if(!isset($val['buyable']) || $val['buyable'] !== false) + { + $_Lang['Articles'] .= ''.$val['name'].''; + $_Lang['Articles'] .= ''.$val['desc'].''; + if(empty($val['action'])) + { + if($val['price'] > 0 || $val['price'] === 0) + { + $_Lang['Articles'] .= ''.$val['price'].' '.$_Lang['DEprice'].'
'; + } + else + { + $_Lang['Articles'] .= ''.$_Lang['CannotBuyItAnymore'].''; + } + } + else + { + switch($val['action']) + { + case 'redirect': + $_Lang['Articles'] .= ''.$val['price'].' '.$_Lang['DEprice'].'
'; + break; + } + } + } + } +} +if(empty($_Lang['Articles'])) +{ + $_Lang['Articles'] = ''.$_Lang['NoItemsOnStock'].''; +} + +if(isset($_GET['darkenergy_bought']) && $_GET['darkenergy_bought'] == 'true') +{ + if(!isset($_GET['count'])) + { + $_GET['count'] = 5; + } + $CheckDEFormTabs = array(5 => '01', 15 => '02', 25 => '03', 45 => '04'); + $_Lang['SetActiveFormTab'] = $CheckDEFormTabs[$_GET['count']]; +} + +$_Lang['DarkEnergy_Counter'] = $_User['darkEnergy']; +if($_User['darkEnergy'] >= 15) +{ + $_Lang['DarkEnergy_Color'] = 'lime'; +} +elseif($_User['darkEnergy'] > 0) +{ + $_Lang['DarkEnergy_Color'] = 'orange'; +} +else +{ + $_Lang['DarkEnergy_Color'] = 'red'; +} + +$page = parsetemplate(gettemplate('galacticshop'), $_Lang); +display($page, $_Lang['Title'], false); + +?> diff --git a/galaxy.php b/galaxy.php index 41436d684..6fc0197a8 100644 --- a/galaxy.php +++ b/galaxy.php @@ -1,222 +1,222 @@ - 0) ? 2 : 0); - $CurrentMIP = $CurrentPlanet['interplanetary_missile']; - $CurrentRC = $CurrentPlanet['recycler']; - $CurrentSP = $CurrentPlanet['espionage_probe']; - $CurrentCS = $CurrentPlanet['colony_ship']; - $SensonPhalanxLevel = $CurrentPlanet['sensor_phalanx']; - $CurrentSystem = $CurrentPlanet['system']; - $CurrentGalaxy = $CurrentPlanet['galaxy']; - $CanDestroy = ($CurrentPlanet[$_Vars_GameElements[214]] > 0 ? true : false); - - $GetFlyingFleetsCount = doquery("SELECT COUNT(*) AS `Count` FROM {{table}} WHERE `fleet_owner` = {$_User['id']};", 'fleets', true); - $maxfleet_count = $GetFlyingFleetsCount['Count']; - - // Get GalaxyShow Mode - $mode = intval($_GET['mode']); - if(!in_array($mode, array(0, 1, 2, 3))) - { - $mode = 0; - } - - if($mode === 0) - { - // Show CurrentPlanet Solar System - $galaxy = $CurrentPlanet['galaxy']; - $system = $CurrentPlanet['system']; - $planet = $CurrentPlanet['planet']; - } - else if($mode === 1) - { - // User sent $_POST Data - if(isset($_POST['galaxyLeft']) && $_POST['galaxyLeft'] === 'dr') - { - if($_POST['galaxy'] <= 1 OR $_POST['galaxy'] > MAX_GALAXY_IN_WORLD) - { - $_POST['galaxy']= MAX_GALAXY_IN_WORLD; - $galaxy = MAX_GALAXY_IN_WORLD; - } - else - { - $galaxy = $_POST['galaxy'] - 1; - } - } - else if(isset($_POST['galaxyRight']) && $_POST['galaxyRight'] === 'dr') - { - if($_POST['galaxy'] >= MAX_GALAXY_IN_WORLD OR $_POST['galaxy'] < 1) - { - $_POST['galaxy']= 1; - $galaxy = 1; - } - else - { - $galaxy = $_POST['galaxy'] + 1; - } - } - else - { - $_POST['galaxy'] = intval($_POST['galaxy']); - if($_POST['galaxy'] > 0 AND $_POST['galaxy'] <= MAX_GALAXY_IN_WORLD) - { - $galaxy = $_POST['galaxy']; - } - else - { - $galaxy = 1; - } - } - - if(isset($_POST['systemLeft']) && $_POST['systemLeft'] === 'dr') - { - if($_POST['system'] <= 1 OR $_POST['system'] > MAX_SYSTEM_IN_GALAXY) - { - $_POST['system']= MAX_SYSTEM_IN_GALAXY; - $system = MAX_SYSTEM_IN_GALAXY; - } - else - { - $system = $_POST['system'] - 1; - } - } - else if(isset($_POST['systemRight']) && $_POST['systemRight'] === 'dr') - { - if($_POST['system'] >= MAX_SYSTEM_IN_GALAXY OR $_POST['system'] < 1) - { - $_POST['system']= 1; - $system = 1; - } - else - { - $system = $_POST['system'] + 1; - } - } - else - { - $_POST['system'] = intval($_POST['system']); - if($_POST['system'] > 0 AND $_POST['system'] <= MAX_SYSTEM_IN_GALAXY) - { - $system = $_POST['system']; - } - else - { - $system = 1; - } - } - $planet = 0; - } - else if($mode === 2 OR $mode === 3) - { - // User sent $_GET Data - $_GET['galaxy'] = isset($_GET['galaxy']) ? intval($_GET['galaxy']) : 0; - $_GET['system'] = isset($_GET['system']) ? intval($_GET['system']) : 0; - $_GET['planet'] = isset($_GET['planet']) ? intval($_GET['planet']) : 0; - - if($_GET['galaxy'] > 0 AND $_GET['galaxy'] <= MAX_GALAXY_IN_WORLD) - { - $galaxy = $_GET['galaxy']; - } - else - { - $galaxy = 1; - } - if($_GET['system'] > 0 AND $_GET['system'] <= MAX_SYSTEM_IN_GALAXY) - { - $system = $_GET['system']; - } - else - { - $system = 1; - } - if($_GET['planet'] > 0 AND $_GET['planet'] <= MAX_PLANET_IN_SYSTEM) - { - $planet = $_GET['planet']; - } - else - { - $planet = 0; - } - } - - $planetcount = 0; - $MoonCount = 0; - - $GalaxyTPL = gettemplate('galaxy_body'); - - // Include Script - $ScriptTPL = gettemplate('galaxy_scripts'); - $ScriptLang = includeLang('galaxy_ajax', true); - $ScriptLang['SkinPath'] = $_SkinPath; - $ScriptLang['Insert_ReponseCodes'] = ''; - foreach($ScriptLang as $Key => $Value) - { - if(strstr($Key, 'ajax_send_') !== false) - { - $Code = str_replace('ajax_send_', '', $Key); - $ScriptLang['Insert_ReponseCodes'] .= "RespCodes['{$Code}'] = '{$Value}';\n"; - } - } - $ScriptLang['maxGal'] = MAX_GALAXY_IN_WORLD; - $ScriptLang['maxSys'] = MAX_SYSTEM_IN_GALAXY; - if($_User['settings_UseAJAXGalaxy'] == 1) - { - $ScriptLang['UseAjax'] = 'true'; - $HideMissileForm = true; - } - else - { - $ScriptLang['UseAjax'] = 'false'; - } - if($_User['settings_useprettyinputbox'] == 1) - { - $ScriptLang['P_AllowPrettyInputBox'] = 'true'; - } - else - { - $ScriptLang['P_AllowPrettyInputBox'] = 'false'; - } - $Parse['Input_GalaxyScripts'] = parsetemplate($ScriptTPL, $ScriptLang); - - $Parse['Input_GalaxySelector'] = ShowGalaxySelector($galaxy, $system); - if($mode === 2 OR $_User['settings_UseAJAXGalaxy'] == 1) - { - $Parse['Input_GalaxyMissileSelector'] = ShowGalaxyMISelector($galaxy, $system, $planet, $CurrentMIP, $HideMissileForm); - } - $Parse['Input_GalaxyHeaders'] = ShowGalaxyTitles(); - $Parse['Input_GalaxyRows'] = ShowGalaxyRows($galaxy, $system, $planet); - $Parse['Input_GalaxyFooter'] = ShowGalaxyFooter($galaxy, $system, $CurrentMIP, $CurrentRC, $CurrentSP, $CurrentCS); - - $Page = parsetemplate($GalaxyTPL, $Parse); - - display($Page, $_Lang['PageTitle'], false); - -?> \ No newline at end of file + 0) ? 2 : 0); +$CurrentMIP = $CurrentPlanet['interplanetary_missile']; +$CurrentRC = $CurrentPlanet['recycler']; +$CurrentSP = $CurrentPlanet['espionage_probe']; +$CurrentCS = $CurrentPlanet['colony_ship']; +$SensonPhalanxLevel = $CurrentPlanet['sensor_phalanx']; +$CurrentSystem = $CurrentPlanet['system']; +$CurrentGalaxy = $CurrentPlanet['galaxy']; +$CanDestroy = ($CurrentPlanet[$_Vars_GameElements[214]] > 0 ? true : false); + +$GetFlyingFleetsCount = doquery("SELECT COUNT(*) AS `Count` FROM {{table}} WHERE `fleet_owner` = {$_User['id']};", 'fleets', true); +$maxfleet_count = $GetFlyingFleetsCount['Count']; + +// Get GalaxyShow Mode +$mode = intval($_GET['mode']); +if(!in_array($mode, array(0, 1, 2, 3))) +{ + $mode = 0; +} + +if($mode === 0) +{ + // Show CurrentPlanet Solar System + $galaxy = $CurrentPlanet['galaxy']; + $system = $CurrentPlanet['system']; + $planet = $CurrentPlanet['planet']; +} +else if($mode === 1) +{ + // User sent $_POST Data + if(isset($_POST['galaxyLeft']) && $_POST['galaxyLeft'] === 'dr') + { + if($_POST['galaxy'] <= 1 OR $_POST['galaxy'] > MAX_GALAXY_IN_WORLD) + { + $_POST['galaxy']= MAX_GALAXY_IN_WORLD; + $galaxy = MAX_GALAXY_IN_WORLD; + } + else + { + $galaxy = $_POST['galaxy'] - 1; + } + } + else if(isset($_POST['galaxyRight']) && $_POST['galaxyRight'] === 'dr') + { + if($_POST['galaxy'] >= MAX_GALAXY_IN_WORLD OR $_POST['galaxy'] < 1) + { + $_POST['galaxy']= 1; + $galaxy = 1; + } + else + { + $galaxy = $_POST['galaxy'] + 1; + } + } + else + { + $_POST['galaxy'] = intval($_POST['galaxy']); + if($_POST['galaxy'] > 0 AND $_POST['galaxy'] <= MAX_GALAXY_IN_WORLD) + { + $galaxy = $_POST['galaxy']; + } + else + { + $galaxy = 1; + } + } + + if(isset($_POST['systemLeft']) && $_POST['systemLeft'] === 'dr') + { + if($_POST['system'] <= 1 OR $_POST['system'] > MAX_SYSTEM_IN_GALAXY) + { + $_POST['system']= MAX_SYSTEM_IN_GALAXY; + $system = MAX_SYSTEM_IN_GALAXY; + } + else + { + $system = $_POST['system'] - 1; + } + } + else if(isset($_POST['systemRight']) && $_POST['systemRight'] === 'dr') + { + if($_POST['system'] >= MAX_SYSTEM_IN_GALAXY OR $_POST['system'] < 1) + { + $_POST['system']= 1; + $system = 1; + } + else + { + $system = $_POST['system'] + 1; + } + } + else + { + $_POST['system'] = intval($_POST['system']); + if($_POST['system'] > 0 AND $_POST['system'] <= MAX_SYSTEM_IN_GALAXY) + { + $system = $_POST['system']; + } + else + { + $system = 1; + } + } + $planet = 0; +} +else if($mode === 2 OR $mode === 3) +{ + // User sent $_GET Data + $_GET['galaxy'] = isset($_GET['galaxy']) ? intval($_GET['galaxy']) : 0; + $_GET['system'] = isset($_GET['system']) ? intval($_GET['system']) : 0; + $_GET['planet'] = isset($_GET['planet']) ? intval($_GET['planet']) : 0; + + if($_GET['galaxy'] > 0 AND $_GET['galaxy'] <= MAX_GALAXY_IN_WORLD) + { + $galaxy = $_GET['galaxy']; + } + else + { + $galaxy = 1; + } + if($_GET['system'] > 0 AND $_GET['system'] <= MAX_SYSTEM_IN_GALAXY) + { + $system = $_GET['system']; + } + else + { + $system = 1; + } + if($_GET['planet'] > 0 AND $_GET['planet'] <= MAX_PLANET_IN_SYSTEM) + { + $planet = $_GET['planet']; + } + else + { + $planet = 0; + } +} + +$planetcount = 0; +$MoonCount = 0; + +$GalaxyTPL = gettemplate('galaxy_body'); + +// Include Script +$ScriptTPL = gettemplate('galaxy_scripts'); +$ScriptLang = includeLang('galaxy_ajax', true); +$ScriptLang['SkinPath'] = $_SkinPath; +$ScriptLang['Insert_ReponseCodes'] = ''; +foreach($ScriptLang as $Key => $Value) +{ + if(strstr($Key, 'ajax_send_') !== false) + { + $Code = str_replace('ajax_send_', '', $Key); + $ScriptLang['Insert_ReponseCodes'] .= "RespCodes['{$Code}'] = '{$Value}';\n"; + } +} +$ScriptLang['maxGal'] = MAX_GALAXY_IN_WORLD; +$ScriptLang['maxSys'] = MAX_SYSTEM_IN_GALAXY; +if($_User['settings_UseAJAXGalaxy'] == 1) +{ + $ScriptLang['UseAjax'] = 'true'; + $HideMissileForm = true; +} +else +{ + $ScriptLang['UseAjax'] = 'false'; +} +if($_User['settings_useprettyinputbox'] == 1) +{ + $ScriptLang['P_AllowPrettyInputBox'] = 'true'; +} +else +{ + $ScriptLang['P_AllowPrettyInputBox'] = 'false'; +} +$Parse['Input_GalaxyScripts'] = parsetemplate($ScriptTPL, $ScriptLang); + +$Parse['Input_GalaxySelector'] = ShowGalaxySelector($galaxy, $system); +if($mode === 2 OR $_User['settings_UseAJAXGalaxy'] == 1) +{ + $Parse['Input_GalaxyMissileSelector'] = ShowGalaxyMISelector($galaxy, $system, $planet, $CurrentMIP, $HideMissileForm); +} +$Parse['Input_GalaxyHeaders'] = ShowGalaxyTitles(); +$Parse['Input_GalaxyRows'] = ShowGalaxyRows($galaxy, $system, $planet); +$Parse['Input_GalaxyFooter'] = ShowGalaxyFooter($galaxy, $system, $CurrentMIP, $CurrentRC, $CurrentSP, $CurrentCS); + +$Page = parsetemplate($GalaxyTPL, $Parse); + +display($Page, $_Lang['PageTitle'], false); + +?> diff --git a/generate_sig.php b/generate_sig.php index 9a9d1bbc5..44a512aa6 100644 --- a/generate_sig.php +++ b/generate_sig.php @@ -1,199 +1,199 @@ -= filemtime($ImagePath))) - { - // Use Browser Cache - header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($ImagePath)).' GMT', true, 304); - } - else - { - // Resend new version - header('Content-Type: image/png'); - header('Content-Length: '.filesize($ImagePath)); - header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($ImagePath)).' GMT', true, 200); - $Image = fopen($ImagePath, 'r'); - fpassthru($Image); - } - die(); -} - -$CachePath = './cache/img/signatures/'; -$_EnginePath = './'; - -$UID = (isset($_GET['uid']) ? round($_GET['uid']) : 0); -$SigLang = (isset($_GET['lang']) ? $_GET['lang'] : null); -$DefaultLang = 'pl'; - -if(!in_array($SigLang, array('pl'))) -{ - $SigLang = $DefaultLang; -} - -if($UID > 0) -{ - $UserFile = "{$CachePath}{$SigLang}/user_".str_pad($UID, 6, 0, STR_PAD_LEFT).'.png'; - - if(file_exists($UserFile)) - { - if(file_exists('./cache/data/last_stats_update.php')) - { - include('./cache/data/last_stats_update.php'); - if(!isset($LastStatsUpdate)) - { - $LastStatsUpdate = 0; - } - } - else - { - $LastStatsUpdate = 0; - } - if(filemtime($UserFile) >= $LastStatsUpdate) - { - // Return existing image - ReturnImage($UserFile); - } - } - - // --- Generate new image --- - // Load DB Driver & Lang - if(substr(sprintf('%o', fileperms($CachePath.'pl')), -4) != '0777') - { - if(!chmod($CachePath.'pl', 0777)) - { - ReturnImage("{$CachePath}static/signature_{$SigLang}_error4.png"); - } - } - define('INSIDE', true); - - if($_SERVER['SERVER_ADDR'] == '127.0.0.1' OR $_SERVER['SERVER_ADDR'] == '::1') - { - // We are on Localhost - define('LOCALHOST', TRUE); - define('TESTSERVER', FALSE); - } - else - { - // We are not on Localhost - define('LOCALHOST', FALSE); - if($_SERVER['HTTP_HOST'] === GAMEURL_REMOTE_TESTSERVERHOST) - { - define('TESTSERVER', TRUE); - } - else - { - define('TESTSERVER', FALSE); - } - } - - include("{$_EnginePath}includes/db.php"); - include("{$_EnginePath}language/{$SigLang}/generate_sig.lang"); - - $Constants = array - ( - 'UserYTop' => 10, - 'AllyYTop' => 34, - 'UniPosYTop' => 3, - 'Width' => 468, - 'Padding' => 6, - ); - - // Get Data - $UserData = doquery("SELECT `username`, `ally_id` FROM {{table}} WHERE `id` = {$UID} LIMIT 1;", 'users', true, true); - if(empty($UserData['username'])) - { - // Throw Error: User don't exist - copy("{$CachePath}static/signature_{$SigLang}_error2.png", $UserFile); - ReturnImage($UserFile); - } - $UserStat = doquery("SELECT `total_rank`, `total_points` FROM {{table}} WHERE `id_owner` = {$UID} AND `stat_type` = 1 LIMIT 1;", 'statpoints', true); - if($UserStat['total_rank'] <= 0) - { - // Throw Error: Stats not calculated - copy("{$CachePath}static/signature_{$SigLang}_error3.png", $UserFile); - ReturnImage($UserFile); - } - - // Generate Texts - if(strlen($UserData['username']) > 20) - { - $UserData['username'] = substr($UserData['username'], 0, 20).'...'; - } - $Texts['User'] = $UserData['username']; - $Texts['Points'] = number_format($UserStat['total_points'], 0, '', '.').' '.$_Lang['Points']; - $Texts['Position'] = $_Lang['Position'].': '.number_format($UserStat['total_rank'], 0, '', '.'); - $Texts['Uni'] = $_Lang['Universum']; - $Texts['Ally'] = null; - if($UserData['ally_id'] > 0) - { - $UserAlly = doquery("SELECT `ally_name`, `ally_tag` FROM {{table}} WHERE `id` = {$UserData['ally_id']} LIMIT 1;", 'alliance', true); - if(!empty($UserAlly['ally_tag'])) - { - $Texts['Ally'] = "{$_Lang['Ally']}: {$UserAlly['ally_tag']}"; - } - } - - foreach($Texts as $ThisKey => &$ThisValue) - { - if($ThisKey == 'Uni') - { - continue; - } - $ThisValue = strtoupper($ThisValue); - } - - // Load image and create White Color - $ImageCopy = imagecreatefrompng("{$CachePath}static/signature_userbg.png"); - $FontLink = "{$CachePath}static/font_roboto_bold.ttf"; - $Colors['white'] = imagecolorallocate($ImageCopy, 255, 255, 255); - - // Calculate UserString Size - $Size = imagettfbbox(10, 0, $FontLink, $Texts['User']); - $Width = $Size[4] - $Size[0]; - $Height = ($Size[5] - $Size[1]) * -1; - $CalcYPos['User'] = $Constants['UserYTop'] + $Height + 1; - // Calculate AllyString Size - $Size = imagettfbbox(10, 0, $FontLink, $Texts['Ally']); - $Width = $Size[4] - $Size[0]; - $Height = ($Size[5] - $Size[1]) * -1; - $CalcYPos['Ally'] = $Constants['AllyYTop'] + $Height; - // Calculate PointsString Size - $Size = imagettfbbox(10, 0, $FontLink, $Texts['Points']); - $Width = $Size[4] - $Size[0]; - $Height = ($Size[5] - $Size[1]) * -1; - $CalcYPos['Points'] = $Constants['UserYTop'] + $Height + 1; - $CalcXPos['Points'] = $Constants['Width'] - $Width - $Constants['Padding']; - // Calculate PositionString Size - $Size = imagettfbbox(10, 0, $FontLink, $Texts['Position']); - $Width = $Size[4] - $Size[0]; - $Height = ($Size[5] - $Size[1]) * -1; - $CalcYPos['Position'] = $Constants['AllyYTop'] + $Height; - $CalcXPos['Position'] = $Constants['Width'] - $Width - $Constants['Padding']; - // Calculate UniString Size - $Size = imagettfbbox(10, 0, $FontLink, $Texts['Uni']); - $Width = $Size[4] - $Size[0]; - $Height = ($Size[5] - $Size[1]) * -1; - $CalcYPos['Uni'] = $Constants['UniPosYTop'] + $Height; - $CalcXPos['Uni'] = ($Constants['Width'] - $Width) / 2; - - // Insert Texts - imagettftext($ImageCopy, 10, 0, $Constants['Padding'], $CalcYPos['User'], $Colors['white'], $FontLink, $Texts['User']); - imagettftext($ImageCopy, 10, 0, $Constants['Padding'], $CalcYPos['Ally'], $Colors['white'], $FontLink, $Texts['Ally']); - imagettftext($ImageCopy, 10, 0, $CalcXPos['Points'], $CalcYPos['Points'], $Colors['white'], $FontLink, $Texts['Points']); - imagettftext($ImageCopy, 10, 0, $CalcXPos['Position'], $CalcYPos['Position'], $Colors['white'], $FontLink, $Texts['Position']); - imagettftext($ImageCopy, 10, 0, $CalcXPos['Uni'], $CalcYPos['Uni'], $Colors['white'], $FontLink, $Texts['Uni']); - - // Save File - imagepng($ImageCopy, $UserFile); - // Return File & die - ReturnImage($UserFile); -} -else -{ - // Throw Error: BadData Given - $FilePath = "{$CachePath}static/signature_{$SigLang}_error1.png"; - ReturnImage($FilePath); -} - -?> \ No newline at end of file += filemtime($ImagePath))) + { + // Use Browser Cache + header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($ImagePath)).' GMT', true, 304); + } + else + { + // Resend new version + header('Content-Type: image/png'); + header('Content-Length: '.filesize($ImagePath)); + header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($ImagePath)).' GMT', true, 200); + $Image = fopen($ImagePath, 'r'); + fpassthru($Image); + } + die(); +} + +$CachePath = './cache/img/signatures/'; +$_EnginePath = './'; + +$UID = (isset($_GET['uid']) ? round($_GET['uid']) : 0); +$SigLang = (isset($_GET['lang']) ? $_GET['lang'] : null); +$DefaultLang = 'pl'; + +if(!in_array($SigLang, array('pl'))) +{ + $SigLang = $DefaultLang; +} + +if($UID > 0) +{ + $UserFile = "{$CachePath}{$SigLang}/user_".str_pad($UID, 6, 0, STR_PAD_LEFT).'.png'; + + if(file_exists($UserFile)) + { + if(file_exists('./cache/data/last_stats_update.php')) + { + include('./cache/data/last_stats_update.php'); + if(!isset($LastStatsUpdate)) + { + $LastStatsUpdate = 0; + } + } + else + { + $LastStatsUpdate = 0; + } + if(filemtime($UserFile) >= $LastStatsUpdate) + { + // Return existing image + ReturnImage($UserFile); + } + } + + // --- Generate new image --- + // Load DB Driver & Lang + if(substr(sprintf('%o', fileperms($CachePath.'pl')), -4) != '0777') + { + if(!chmod($CachePath.'pl', 0777)) + { + ReturnImage("{$CachePath}static/signature_{$SigLang}_error4.png"); + } + } + define('INSIDE', true); + + if($_SERVER['SERVER_ADDR'] == '127.0.0.1' OR $_SERVER['SERVER_ADDR'] == '::1') + { + // We are on Localhost + define('LOCALHOST', TRUE); + define('TESTSERVER', FALSE); + } + else + { + // We are not on Localhost + define('LOCALHOST', FALSE); + if($_SERVER['HTTP_HOST'] === GAMEURL_REMOTE_TESTSERVERHOST) + { + define('TESTSERVER', TRUE); + } + else + { + define('TESTSERVER', FALSE); + } + } + + include("{$_EnginePath}includes/db.php"); + include("{$_EnginePath}language/{$SigLang}/generate_sig.lang"); + + $Constants = array + ( + 'UserYTop' => 10, + 'AllyYTop' => 34, + 'UniPosYTop' => 3, + 'Width' => 468, + 'Padding' => 6, + ); + + // Get Data + $UserData = doquery("SELECT `username`, `ally_id` FROM {{table}} WHERE `id` = {$UID} LIMIT 1;", 'users', true, true); + if(empty($UserData['username'])) + { + // Throw Error: User don't exist + copy("{$CachePath}static/signature_{$SigLang}_error2.png", $UserFile); + ReturnImage($UserFile); + } + $UserStat = doquery("SELECT `total_rank`, `total_points` FROM {{table}} WHERE `id_owner` = {$UID} AND `stat_type` = 1 LIMIT 1;", 'statpoints', true); + if($UserStat['total_rank'] <= 0) + { + // Throw Error: Stats not calculated + copy("{$CachePath}static/signature_{$SigLang}_error3.png", $UserFile); + ReturnImage($UserFile); + } + + // Generate Texts + if(strlen($UserData['username']) > 20) + { + $UserData['username'] = substr($UserData['username'], 0, 20).'...'; + } + $Texts['User'] = $UserData['username']; + $Texts['Points'] = number_format($UserStat['total_points'], 0, '', '.').' '.$_Lang['Points']; + $Texts['Position'] = $_Lang['Position'].': '.number_format($UserStat['total_rank'], 0, '', '.'); + $Texts['Uni'] = $_Lang['Universum']; + $Texts['Ally'] = null; + if($UserData['ally_id'] > 0) + { + $UserAlly = doquery("SELECT `ally_name`, `ally_tag` FROM {{table}} WHERE `id` = {$UserData['ally_id']} LIMIT 1;", 'alliance', true); + if(!empty($UserAlly['ally_tag'])) + { + $Texts['Ally'] = "{$_Lang['Ally']}: {$UserAlly['ally_tag']}"; + } + } + + foreach($Texts as $ThisKey => &$ThisValue) + { + if($ThisKey == 'Uni') + { + continue; + } + $ThisValue = strtoupper($ThisValue); + } + + // Load image and create White Color + $ImageCopy = imagecreatefrompng("{$CachePath}static/signature_userbg.png"); + $FontLink = "{$CachePath}static/font_roboto_bold.ttf"; + $Colors['white'] = imagecolorallocate($ImageCopy, 255, 255, 255); + + // Calculate UserString Size + $Size = imagettfbbox(10, 0, $FontLink, $Texts['User']); + $Width = $Size[4] - $Size[0]; + $Height = ($Size[5] - $Size[1]) * -1; + $CalcYPos['User'] = $Constants['UserYTop'] + $Height + 1; + // Calculate AllyString Size + $Size = imagettfbbox(10, 0, $FontLink, $Texts['Ally']); + $Width = $Size[4] - $Size[0]; + $Height = ($Size[5] - $Size[1]) * -1; + $CalcYPos['Ally'] = $Constants['AllyYTop'] + $Height; + // Calculate PointsString Size + $Size = imagettfbbox(10, 0, $FontLink, $Texts['Points']); + $Width = $Size[4] - $Size[0]; + $Height = ($Size[5] - $Size[1]) * -1; + $CalcYPos['Points'] = $Constants['UserYTop'] + $Height + 1; + $CalcXPos['Points'] = $Constants['Width'] - $Width - $Constants['Padding']; + // Calculate PositionString Size + $Size = imagettfbbox(10, 0, $FontLink, $Texts['Position']); + $Width = $Size[4] - $Size[0]; + $Height = ($Size[5] - $Size[1]) * -1; + $CalcYPos['Position'] = $Constants['AllyYTop'] + $Height; + $CalcXPos['Position'] = $Constants['Width'] - $Width - $Constants['Padding']; + // Calculate UniString Size + $Size = imagettfbbox(10, 0, $FontLink, $Texts['Uni']); + $Width = $Size[4] - $Size[0]; + $Height = ($Size[5] - $Size[1]) * -1; + $CalcYPos['Uni'] = $Constants['UniPosYTop'] + $Height; + $CalcXPos['Uni'] = ($Constants['Width'] - $Width) / 2; + + // Insert Texts + imagettftext($ImageCopy, 10, 0, $Constants['Padding'], $CalcYPos['User'], $Colors['white'], $FontLink, $Texts['User']); + imagettftext($ImageCopy, 10, 0, $Constants['Padding'], $CalcYPos['Ally'], $Colors['white'], $FontLink, $Texts['Ally']); + imagettftext($ImageCopy, 10, 0, $CalcXPos['Points'], $CalcYPos['Points'], $Colors['white'], $FontLink, $Texts['Points']); + imagettftext($ImageCopy, 10, 0, $CalcXPos['Position'], $CalcYPos['Position'], $Colors['white'], $FontLink, $Texts['Position']); + imagettftext($ImageCopy, 10, 0, $CalcXPos['Uni'], $CalcYPos['Uni'], $Colors['white'], $FontLink, $Texts['Uni']); + + // Save File + imagepng($ImageCopy, $UserFile); + // Return File & die + ReturnImage($UserFile); +} +else +{ + // Throw Error: BadData Given + $FilePath = "{$CachePath}static/signature_{$SigLang}_error1.png"; + ReturnImage($FilePath); +} + +?> diff --git a/images/index.php b/images/index.php index ee150fd01..bc99142d1 100644 --- a/images/index.php +++ b/images/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/images/jquery.farbtastic/index.php b/images/jquery.farbtastic/index.php index ee150fd01..bc99142d1 100644 --- a/images/jquery.farbtastic/index.php +++ b/images/jquery.farbtastic/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/includes/CombatEngineAres.php b/includes/CombatEngineAres.php index e0bbbbd1f..419ffb00c 100644 --- a/includes/CombatEngineAres.php +++ b/includes/CombatEngineAres.php @@ -1,1335 +1,1335 @@ - &$Techs) - { - $Techs[109] = 1 + (0.1 * $Techs[109]); - $Techs[110] = 1 + (0.1 * $Techs[110]); - $Techs[111] = 1 + (0.1 * $Techs[111]); - - if(empty($Techs['TotalForceFactor'])) - { - $Techs['TotalForceFactor'] = 1; - } - if(empty($Techs['TotalShieldFactor'])) - { - $Techs['TotalShieldFactor'] = 1; - } - } - foreach($Defender as $User => $Ships) - { - $UserKey = "|{$User}"; - foreach($Ships as $ID => $Count) - { - $UserShipKey = "{$ID}{$UserKey}"; - $ForceUpgrade = 0; - - if($UseRapidFire) - { - foreach($_Vars_CombatData[$ID]['sd'] as $TID => $SDVal) - { - if($SDVal > 1) - { - if(!empty($DefenderTech[$User]['SDAdd'])) - { - $SDVal += $DefenderTech[$User]['SDAdd']; - } - else if(!empty($DefenderTech[$User]['SDFactor'])) - { - $SDVal = round($SDVal * $DefenderTech[$User]['SDFactor']); - } - if($SDVal > 1) - { - $ShipsSD['d'][$User][$ID][$TID] = $SDVal - 1; - } - } - } - if(!empty($ShipsSD['d'][$User][$ID])) - { - arsort($ShipsSD['d'][$User][$ID]); - } - } - $DefenderShips[$User][$ID] = $Count; - if(!isset($DefShipsTypes[$ID])) - { - $DefShipsTypes[$ID] = 0; - } - $DefShipsTypes[$ID] += 1; - $DefShipsTypesOwners[$ID][$User] = 1; - $DefShipsTypesCount[$ID][$User] = $Count; - - // Calculate Ships Force, Shield and Hull values - if(!empty($_Vars_CombatUpgrades[$ID])) - { - foreach($_Vars_CombatUpgrades[$ID] as $UpTech => $ReqLevel) - { - $TechAvailable = $DefenderTech[$User][$UpTech]; - if($TechAvailable > $ReqLevel) - { - $ForceUpgrade += ($TechAvailable - $ReqLevel) * 0.05; - } - } - } - $DefShipsForce[$UserShipKey] = floor($_Vars_CombatData[$ID]['attack'] * ($DefenderTech[$User][109] + $ForceUpgrade) * $DefenderTech[$User]['TotalForceFactor']); - $DefShipsShield[$UserShipKey] = floor($_Vars_CombatData[$ID]['shield'] * $DefenderTech[$User][110] * $DefenderTech[$User]['TotalShieldFactor']); - if(empty($ShipsHullValues[$ID])) - { - $ShipsHullValues[$ID] = ($_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal']) / 10; - } - $DefShipsHull[$UserShipKey] = floor($ShipsHullValues[$ID]* $DefenderTech[$User][111]); - } - } - asort($DefShipsForce); - } - else - { - $DefenderShips = false; - } - - if(!empty($Attacker)) - { - foreach($AttackerTech as $User => &$Techs) - { - $Techs[109] = 1 + (0.1 * $Techs[109]); - $Techs[110] = 1 + (0.1 * $Techs[110]); - $Techs[111] = 1 + (0.1 * $Techs[111]); - - if(empty($Techs['TotalForceFactor'])) - { - $Techs['TotalForceFactor'] = 1; - } - if(empty($Techs['TotalShieldFactor'])) - { - $Techs['TotalShieldFactor'] = 1; - } - } - foreach($Attacker as $User => $Ships) - { - $UserKey = "|{$User}"; - foreach($Ships as $ID => $Count) - { - $UserShipKey = "{$ID}{$UserKey}"; - $ForceUpgrade = 0; - - if($UseRapidFire) - { - foreach($_Vars_CombatData[$ID]['sd'] as $TID => $SDVal) - { - if($SDVal > 1) - { - if(!empty($AttackerTech[$User]['SDAdd'])) - { - $SDVal += $AttackerTech[$User]['SDAdd']; - } - else if(!empty($AttackerTech[$User]['SDFactor'])) - { - $SDVal = round($SDVal * $AttackerTech[$User]['SDFactor']); - } - if($SDVal > 1) - { - $ShipsSD['a'][$User][$ID][$TID] = $SDVal - 1; - } - } - } - if(!empty($ShipsSD['d'][$User][$ID])) - { - arsort($ShipsSD['d'][$User][$ID]); - } - } - $AttackerShips[$User][$ID] = $Count; - if(!isset($AtkShipsTypes[$ID])) - { - $AtkShipsTypes[$ID] = 0; - } - $AtkShipsTypes[$ID] += 1; - $AtkShipsTypesOwners[$ID][$User] = 1; - $AtkShipsTypesCount[$ID][$User] = $Count; - - // Calculate Ships Force, Shield and Hull values - if(!empty($_Vars_CombatUpgrades[$ID])) - { - foreach($_Vars_CombatUpgrades[$ID] as $UpTech => $ReqLevel) - { - $TechAvailable = $AttackerTech[$User][$UpTech]; - if($TechAvailable > $ReqLevel) - { - $ForceUpgrade += ($TechAvailable - $ReqLevel) * 0.05; - } - } - } - $AtkShipsForce[$UserShipKey] = floor($_Vars_CombatData[$ID]['attack'] * ($AttackerTech[$User][109] + $ForceUpgrade) * $AttackerTech[$User]['TotalForceFactor']); - $AtkShipsShield[$UserShipKey] = floor($_Vars_CombatData[$ID]['shield'] * $AttackerTech[$User][110] * $AttackerTech[$User]['TotalShieldFactor']); - if(empty($ShipsHullValues[$ID])) - { - $ShipsHullValues[$ID] = ($_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal']) / 10; - } - $AtkShipsHull[$UserShipKey] = floor($ShipsHullValues[$ID]* $AttackerTech[$User][111]); - } - } - $AtkShipsForce_Copy = $AtkShipsForce; - asort($AtkShipsForce); - asort($AtkShipsForce_Copy); - } - else - { - return array('result' => false, 'error' => 'NO_ATTACKER'); - } - - $RoundsLimit = BATTLE_MAX_ROUNDS + 1; - for($i = 1; $i <= $RoundsLimit; $i += 1) - { - // Clear Lost Ships in last round - $AtkLost = array(); - $DefLost = array(); - // Clear Targets Shield Supply - $DefShields = false; - $AtkShields = false; - // Clear Already destroyed targets - $AlreadyDestroyedDef = false; - $AlreadyDestroyedAtk = false; - // Clear RapidFire Exclusions - $AtkDontShootRF = false; - $DefDontShootRF = false; - // Clear TotalACS Force - $TotalDefTypesForce = false; - $TotalAtkTypesForce = false; - // END of Clearing - - $Rounds[$i]['atk']['ships'] = (isset($AttackerShips) ? $AttackerShips : null); - $Rounds[$i]['def']['ships'] = (isset($DefenderShips) ? $DefenderShips : null); - $Rounds[$i]['atk']['force'] = 0; - $Rounds[$i]['atk']['count'] = 0; - $Rounds[$i]['atk']['shield'] = 0; - $Rounds[$i]['def']['force'] = 0; - $Rounds[$i]['def']['count'] = 0; - $Rounds[$i]['def']['shield'] = 0; - - if($i > BATTLE_MAX_ROUNDS) - { - break; - } - - if(empty($AttackerShips) OR empty($DefenderShips)) - { - break; - } - - // Prepare target list - // ------------------- - // Defender Targets - $DefShipsForce_Copy = $DefShipsForce; - foreach($DefShipsForce_Copy as $TempKey => &$TempForce) - { - $TempForce += $DefShipsShield[$TempKey]; - $TempKey = explode('|', $TempKey); - $TempForce *= $DefShipsTypesCount[$TempKey[0]][$TempKey[1]]; - if(!isset($TotalDefTypesForce[$TempKey[0]])) - { - $TotalDefTypesForce[$TempKey[0]] = 0; - } - $TotalDefTypesForce[$TempKey[0]] += $TempForce; - } - foreach($DefShipsForce_Copy as $TempKey => &$TempForce) - { - $TempKey = explode('|', $TempKey); - if($TempForce < $TotalDefTypesForce[$TempKey[0]]) - { - $TempForce = $TotalDefTypesForce[$TempKey[0]]; - } - } - asort($DefShipsForce_Copy); - // Attacker Targets - $AtkShipsForce_Copy = $AtkShipsForce; - foreach($AtkShipsForce_Copy as $TempKey => &$TempForce) - { - $TempForce += $AtkShipsShield[$TempKey]; - $TempKey = explode('|', $TempKey); - $TempForce *= $AtkShipsTypesCount[$TempKey[0]][$TempKey[1]]; - if(!isset($TotalAtkTypesForce[$TempKey[0]])) - { - $TotalAtkTypesForce[$TempKey[0]] = 0; - } - $TotalAtkTypesForce[$TempKey[0]] += $TempForce; - } - foreach($AtkShipsForce_Copy as $TempKey => &$TempForce) - { - $TempKey = explode('|', $TempKey); - if($TempForce < $TotalAtkTypesForce[$TempKey[0]]) - { - $TempForce = $TotalAtkTypesForce[$TempKey[0]]; - } - } - asort($AtkShipsForce_Copy); - - // ------------------------------------------------------------------------------------------------------------------------------------ - // Calculate Attacker(s) Part - // 1. Let's calculate all regular fires! - - foreach($AtkShipsForce as $AKey => $AForce) - { - if($AForce == 0) - { - continue; // Jump out if this Ship is useless (like Solar Satelite or Spy Probe) - } - $Temp = explode('|', $AKey); - $AUser = $Temp[1]; - $AShip = $Temp[0]; - $ACount_Copy = $AtkShipsTypesCount[$AShip][$AUser]; - $AssignmentCalc = false; - $AShipsAssign = false; - - // ----------------------- - // Calculate Regular Fire! - foreach($DefShipsForce_Copy as $TKey => $TForce) - { - $Temp = explode('|', $TKey); - $TShip = $Temp[0]; - $TUser = $Temp[1]; - - // Here calculating, if it's ACS and more than one user have this ShipType - if($DefShipsTypes[$TShip] > 1 && !isset($AssignmentCalc[$TShip])) - { - $TShipTotalCount = 0; - $TShipKeys = false; - foreach($DefShipsTypesOwners[$TShip] as $Owner => $NotImportant) - { - $ThisKey = "{$TShip}|{$Owner}"; - $CalcCount = ($DefShipsTypesCount[$TShip][$Owner] - (isset($AlreadyDestroyedDef[$ThisKey]) ? $AlreadyDestroyedDef[$ThisKey] : 0)); - $TShipKeys[$ThisKey] = $CalcCount; - $TShipTotalCount += $CalcCount; - } - $ACount_Temp = $ACount_Copy; - foreach($TShipKeys as $Key => $Count) - { - $Count = floor(($Count/$TShipTotalCount) * $ACount_Copy); - $ACount_Temp -= $Count; - $AShipsAssign[$Key] = $Count; - } - if($ACount_Temp > 0) - { - arsort($AShipsAssign); - foreach($AShipsAssign as $Key => &$Data) - { - $Data += $ACount_Temp; - break; - } - } - $AssignmentCalc[$TShip] = true; - } - - if($DefShipsTypes[$TShip] > 1) - { - $ACount = $AShipsAssign[$TKey]; - } - else - { - $ACount = $ACount_Copy; - } - if($ACount == 0) - { - continue; - } - - // Here calculating firing - if($AForce >= ($DefShipsShield[$TKey] * 0.01)) - { - $AvailableForce = $AForce * $ACount; - $Force2TDShield = 0; - if(($AForce * 0.01) < $DefShipsShield[$TKey]) - { - if(isset($DefShields[$TKey]['left']) && $DefShields[$TKey]['left'] === true) - { - $Force2TDShield = $DefShields[$TKey]['shield']; - } - else - { - $Force2TDShield = $DefShipsShield[$TKey] * $DefShipsTypesCount[$TShip][$TUser]; - } - } - if($AvailableForce > $Force2TDShield) - { - if(($AForce * 0.01) < $DefShipsShield[$TKey]) - { - $DefShields[$TKey] = array('left' => true, 'shield' => 0); - } - $LeftForce = $AvailableForce - $Force2TDShield; - if($ACount < ($DefShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedDef[$TKey]) ? $AlreadyDestroyedDef[$TKey] : 0))) - { - $Able2Destroy = $ACount; - } - else - { - $Able2Destroy = ($DefShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedDef[$TKey]) ? $AlreadyDestroyedDef[$TKey] : 0)); - } - $NeedForce = ($DefShipsHull[$TKey] * $Able2Destroy); - if(isset($DefHullDmg[$TKey])) - { - $NeedForce -= ($DefHullDmg[$TKey] * $DefShipsHull[$TKey]); - } - if($NeedForce > $LeftForce) - { - $UsedForce = $LeftForce + $Force2TDShield; - $Shoots = $UsedForce / $AForce; - $DestroyedOrg = ($LeftForce / $DefShipsHull[$TKey]); - if(isset($DefHullDmg[$TKey])) - { - $DestroyedOrg += $DefHullDmg[$TKey]; - } - $Destroyed = floor($LeftForce / $DefShipsHull[$TKey]); - $Difference = $DestroyedOrg - $Destroyed; - $DefHullDmg[$TKey] = $Difference; - if($DefHullDmg[$TKey] >= 1) - { - $Destroyed += 1; - $DefHullDmg[$TKey] -= 1; - } - } - else - { - $UsedForce = $NeedForce + $Force2TDShield; - $Shoots = ceil($UsedForce / $AForce); - if($Shoots < $Able2Destroy) - { - $Shoots = $Able2Destroy; - } - $Destroyed = $Able2Destroy; - } - $Rounds[$i]['atk']['force'] += $UsedForce; - $Rounds[$i]['atk']['count'] += $Shoots; - $Rounds[$i]['def']['shield'] += $Force2TDShield; - - if(!isset($DefLost[$TShip][$TUser])) - { - $DefLost[$TShip][$TUser] = 0; - } - if(!isset($ForceContribution['atk'][$AUser])) - { - $ForceContribution['atk'][$AUser] = 0; - } - if(!isset($ShotDown['atk']['d'][$AUser][$TShip])) - { - $ShotDown['atk']['d'][$AUser][$TShip] = 0; - } - if(!isset($ShotDown['def']['l'][$TUser][$TShip])) - { - $ShotDown['def']['l'][$TUser][$TShip] = 0; - } - - $DefLost[$TShip][$TUser] += $Destroyed; - $ForceContribution['atk'][$AUser] += $UsedForce; - $ShotDown['atk']['d'][$AUser][$TShip] += $Destroyed; - $ShotDown['def']['l'][$TUser][$TShip] += $Destroyed; - if($Destroyed == ($DefShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedDef[$TKey]) ? $AlreadyDestroyedDef[$TKey] : 0))) - { - unset($DefShipsForce_Copy[$TKey]); - if(isset($DefHullDmg[$TKey])) - { - unset($DefHullDmg[$TKey]); - } - unset($DefShipsTypesOwners[$TShip][$TUser]); - $DefShipsTypes[$TShip] -= 1; - } - else - { - if($Destroyed > 0) - { - if(!isset($AlreadyDestroyedDef[$TKey])) - { - $AlreadyDestroyedDef[$TKey] = 0; - } - $AlreadyDestroyedDef[$TKey] += $Destroyed; - } - } - $ACount_Copy -= $Shoots; - } - else - { - $Rounds[$i]['atk']['force'] += $AvailableForce; - $Rounds[$i]['atk']['count'] += $ACount; - $Rounds[$i]['def']['shield'] += $AvailableForce; - $DefShields[$TKey] = array('left' => true, 'shield' => $Force2TDShield - $AvailableForce); - $ACount_Copy -= $ACount; - } - } - else - { - $UsedForce = $AForce * $ACount; - $Rounds[$i]['atk']['force'] += $UsedForce; - $Rounds[$i]['atk']['count'] += $ACount; - $Rounds[$i]['def']['shield'] += $UsedForce; - $ACount_Copy -= $ACount; - } - } - - // --------------------- - // Calculate Rapid Fire! - if($UseRapidFire) - { - $NoMoreRapidFire = false; - - if(!empty($ShipsSD['a'][$AUser][$AShip])) - { - foreach($ShipsSD['a'][$AUser][$AShip] as $TShip => $TSDVal) - { - if($NoMoreRapidFire) - { - break; - } - if(isset($DefShipsTypes[$TShip]) && $DefShipsTypes[$TShip] > 0) - { - $TotalForceNeed = 0; - $TotalShootsNeed = 0; - $GainedForce = 0; - $GainedShoots = 0; - $AShipsAssign = false; - $RapidForce4Shield = false; - $RapidForce4Hull = false; - $RapidForceMinShoots = false; - - foreach($DefShipsTypesOwners[$TShip] as $Owner => $NotImportant) - { - $ThisKey = "{$TShip}|{$Owner}"; - $CalcCount = ($DefShipsTypesCount[$TShip][$Owner] - (isset($AlreadyDestroyedDef[$ThisKey]) ? $AlreadyDestroyedDef[$ThisKey] : 0)); - if($DefShipsTypes[$TShip] > 1) - { - $TShipKeys[$ThisKey] = $CalcCount; - $TShipTotalCount += $CalcCount; - } - if(isset($DefShields[$ThisKey]['left']) && $DefShields[$ThisKey]['left'] === true) - { - $Force2TDShield = $DefShields[$ThisKey]['shield']; - } - else - { - $Force2TDShield = $DefShipsShield[$ThisKey] * $CalcCount; - } - $RapidForce4Shield[$Owner] = $Force2TDShield; - $RapidForce4Hull[$Owner] = $CalcCount * $DefShipsHull[$ThisKey]; - if(isset($DefHullDmg[$ThisKey])) - { - $RapidForce4Hull[$Owner] -= $DefHullDmg[$ThisKey] * $DefShipsHull[$ThisKey]; - } - $RapidForceMinShoots[$Owner] = $CalcCount; - - $TotalForceNeed += ($RapidForce4Shield[$Owner] + $RapidForce4Hull[$Owner]); - $TotalShootsNeed += $RapidForceMinShoots[$Owner]; - } - - $TotalAvailableShoots = floor(($AtkShipsTypesCount[$AShip][$AUser] * $ShipsSD['a'][$AUser][$AShip][$TShip]) * (1 - (isset($AtkDontShootRF[$AKey]) ? $AtkDontShootRF[$AKey] : 0))); - $TotalAvailableForce = $TotalAvailableShoots * $AForce; - - if($TotalAvailableShoots > $TotalShootsNeed) - { - if($TotalAvailableForce > $TotalForceNeed) - { - $GainedShoots = ceil($TotalForceNeed / $AForce); - if($GainedShoots < $TotalShootsNeed) - { - $GainedShoots = $TotalShootsNeed; - } - if($GainedShoots == $TotalAvailableShoots) - { - $NoMoreRapidFire = true; - } - else - { - $TotalEverAvailableShoots = $AtkShipsTypesCount[$AShip][$AUser] * $ShipsSD['a'][$AUser][$AShip][$TShip]; - if(!isset($AtkDontShootRF[$AKey])) - { - $AtkDontShootRF[$AKey] = 0; - } - $AtkDontShootRF[$AKey] += $GainedShoots / $TotalEverAvailableShoots; - } - } - else - { - $GainedShoots = $TotalAvailableShoots; - $NoMoreRapidFire = true; - } - } - else - { - $GainedShoots = $TotalAvailableShoots; - $NoMoreRapidFire = true; - } - - if($GainedShoots > 0) - { - if($DefShipsTypes[$TShip] > 1) - { - $ACount_Temp = $GainedShoots; - foreach($TShipKeys as $Key => $Count) - { - $Count = floor(($Count/$TShipTotalCount) * $GainedShoots); - $ACount_Temp -= $Count; - $AShipsAssign[$Key] = $Count; - } - if($ACount_Temp > 0) - { - arsort($AShipsAssign); - foreach($AShipsAssign as $Key => &$Data) - { - $Data += $ACount_Temp; - break; - } - } - } - - foreach($DefShipsTypesOwners[$TShip] as $Owner => $NotImportant) - { - $TKey = "{$TShip}|{$Owner}"; - $TUser = $Owner; - - if($DefShipsTypes[$TShip] > 1) - { - $ACount = $AShipsAssign[$TKey]; - } - else - { - $ACount = $GainedShoots; - } - if($ACount == 0) - { - continue; - } - - // Here calculating firing - if($AForce >= ($DefShipsShield[$TKey] * 0.01)) - { - $AvailableForce = $AForce * $ACount; - $Force2TDShield = 0; - if(($AForce * 0.01) < $DefShipsShield[$TKey]) - { - if(isset($DefShields[$TKey]['left']) && $DefShields[$TKey]['left'] === true) - { - $Force2TDShield = $DefShields[$TKey]['shield']; - } - else - { - $Force2TDShield = $DefShipsShield[$TKey] * $DefShipsTypesCount[$TShip][$TUser]; - } - } - if($AvailableForce > $Force2TDShield) - { - if(($AForce * 0.01) < $DefShipsShield[$TKey]) - { - $DefShields[$TKey] = array('left' => true, 'shield' => 0); - } - $LeftForce = $AvailableForce - $Force2TDShield; - if($ACount < ($DefShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedDef[$TKey]) ? $AlreadyDestroyedDef[$TKey] : 0))) - { - $Able2Destroy = $ACount; - } - else - { - $Able2Destroy = ($DefShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedDef[$TKey]) ? $AlreadyDestroyedDef[$TKey] : 0)); - } - $NeedForce = ($DefShipsHull[$TKey] * $Able2Destroy); - if(isset($DefHullDmg[$TKey])) - { - $NeedForce -= ($DefHullDmg[$TKey] * $DefShipsHull[$TKey]); - } - if($NeedForce > $LeftForce) - { - $UsedForce = $LeftForce + $Force2TDShield; - $Shoots = $UsedForce / $AForce; - $DestroyedOrg = ($LeftForce / $DefShipsHull[$TKey]); - if(isset($DefHullDmg[$TKey])) - { - $DestroyedOrg += $DefHullDmg[$TKey]; - } - $Destroyed = floor($LeftForce / $DefShipsHull[$TKey]); - $Difference = $DestroyedOrg - $Destroyed; - $DefHullDmg[$TKey] = $Difference; - if($DefHullDmg[$TKey] >= 1) - { - $Destroyed += 1; - $DefHullDmg[$TKey] -= 1; - } - } - else - { - $UsedForce = $NeedForce + $Force2TDShield; - $Shoots = ceil($UsedForce / $AForce); - if($Shoots < $Able2Destroy) - { - $Shoots = $Able2Destroy; - } - $Destroyed = $Able2Destroy; - } - $Rounds[$i]['atk']['force'] += $UsedForce; - $Rounds[$i]['atk']['count'] += $Shoots; - $Rounds[$i]['def']['shield'] += $Force2TDShield; - - if(!isset($DefLost[$TShip][$TUser])) - { - $DefLost[$TShip][$TUser] = 0; - } - if(!isset($ForceContribution['atk'][$AUser])) - { - $ForceContribution['atk'][$AUser] = 0; - } - if(!isset($ShotDown['atk']['d'][$AUser][$TShip])) - { - $ShotDown['atk']['d'][$AUser][$TShip] = 0; - } - if(!isset($ShotDown['def']['l'][$TUser][$TShip])) - { - $ShotDown['def']['l'][$TUser][$TShip] = 0; - } - - $DefLost[$TShip][$TUser] += $Destroyed; - $ForceContribution['atk'][$AUser] += $UsedForce; - $ShotDown['atk']['d'][$AUser][$TShip] += $Destroyed; - $ShotDown['def']['l'][$TUser][$TShip] += $Destroyed; - if($Destroyed == ($DefShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedDef[$TKey]) ? $AlreadyDestroyedDef[$TKey] : 0))) - { - unset($DefShipsForce_Copy[$TKey]); - if(isset($DefHullDmg[$TKey])) - { - unset($DefHullDmg[$TKey]); - } - unset($DefShipsTypesOwners[$TShip][$TUser]); - $DefShipsTypes[$TShip] -= 1; - } - else - { - if($Destroyed > 0) - { - if(!isset($AlreadyDestroyedDef[$TKey])) - { - $AlreadyDestroyedDef[$TKey] = 0; - } - $AlreadyDestroyedDef[$TKey] += $Destroyed; - } - } - } - else - { - $Rounds[$i]['atk']['force'] += $AvailableForce; - $Rounds[$i]['atk']['count'] += $ACount; - $Rounds[$i]['def']['shield'] += $AvailableForce; - $DefShields[$TKey] = array('left' => true, 'shield' => $Force2TDShield - $AvailableForce); - } - } - else - { - $UsedForce = $AForce * $ACount; - $Rounds[$i]['atk']['force'] += $UsedForce; - $Rounds[$i]['atk']['count'] += $ACount; - $Rounds[$i]['def']['shield'] += $UsedForce; - } - } - } - } - } - } - } - } - - // ------------------------------------------------------------------------------------------------------------------------------------ - - // Calculate Defender(s) Part - // 1. Let's calculate all regular fires! - - foreach($DefShipsForce as $AKey => $AForce) - { - if($AForce == 0) - { - continue; // Jump out if this Ship is useless (like Solar Satelite or Spy Probe) - } - $Temp = explode('|', $AKey); - $AUser = $Temp[1]; - $AShip = $Temp[0]; - $ACount_Copy = $DefShipsTypesCount[$AShip][$AUser]; - $AssignmentCalc = false; - $AShipsAssign = false; - - // ----------------------- - // Calculate Regular Fire! - foreach($AtkShipsForce_Copy as $TKey => $TForce) - { - $Temp = explode('|', $TKey); - $TShip = $Temp[0]; - $TUser = $Temp[1]; - - // Here calculating, if it's ACS and more than one user have this ShipType - if($AtkShipsTypes[$TShip] > 1 && !isset($AssignmentCalc[$TShip])) - { - $TShipTotalCount = 0; - $TShipKeys = false; - foreach($AtkShipsTypesOwners[$TShip] as $Owner => $NotImportant) - { - $ThisKey = "{$TShip}|{$Owner}"; - $CalcCount = ($AtkShipsTypesCount[$TShip][$Owner] - (isset($AlreadyDestroyedAtk[$ThisKey]) ? $AlreadyDestroyedAtk[$ThisKey] : 0)); - $TShipKeys[$ThisKey] = $CalcCount; - $TShipTotalCount += $CalcCount; - } - $ACount_Temp = $ACount_Copy; - foreach($TShipKeys as $Key => $Count) - { - $Count = floor(($Count/$TShipTotalCount) * $ACount_Copy); - $ACount_Temp -= $Count; - $AShipsAssign[$Key] = $Count; - } - if($ACount_Temp > 0) - { - arsort($AShipsAssign); - foreach($AShipsAssign as $Key => &$Data) - { - $Data += $ACount_Temp; - break; - } - } - $AssignmentCalc[$TShip] = true; - } - - if($AtkShipsTypes[$TShip] > 1) - { - $ACount = $AShipsAssign[$TKey]; - } - else - { - $ACount = $ACount_Copy; - } - if($ACount == 0) - { - continue; - } - - // Here calculating firing - if($AForce >= ($AtkShipsShield[$TKey] * 0.01)) - { - $AvailableForce = $AForce * $ACount; - $Force2TDShield = 0; - if(($AForce * 0.01) < $AtkShipsShield[$TKey]) - { - if(isset($AtkShields[$TKey]['left']) && $AtkShields[$TKey]['left'] === true) - { - $Force2TDShield = $AtkShields[$TKey]['shield']; - } - else - { - $Force2TDShield = $AtkShipsShield[$TKey] * $AtkShipsTypesCount[$TShip][$TUser]; - } - } - if($AvailableForce > $Force2TDShield) - { - if(($AForce * 0.01) < $AtkShipsShield[$TKey]) - { - $AtkShields[$TKey] = array('left' => true, 'shield' => 0); - } - $LeftForce = $AvailableForce - $Force2TDShield; - if($ACount < ($AtkShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedAtk[$TKey]) ? $AlreadyDestroyedAtk[$TKey] : 0))) - { - $Able2Destroy = $ACount; - } - else - { - $Able2Destroy = ($AtkShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedAtk[$TKey]) ? $AlreadyDestroyedAtk[$TKey] : 0)); - } - $NeedForce = ($AtkShipsHull[$TKey] * $Able2Destroy); - if(isset($AtkHullDmg[$TKey])) - { - $NeedForce -= ($AtkHullDmg[$TKey] * $AtkShipsHull[$TKey]); - } - if($NeedForce > $LeftForce) - { - $UsedForce = $LeftForce + $Force2TDShield; - $Shoots = $UsedForce / $AForce; - $DestroyedOrg = ($LeftForce / $AtkShipsHull[$TKey]); - if(isset($AtkHullDmg[$TKey])) - { - $DestroyedOrg += $AtkHullDmg[$TKey]; - } - $Destroyed = floor($LeftForce / $AtkShipsHull[$TKey]); - $Difference = $DestroyedOrg - $Destroyed; - $AtkHullDmg[$TKey] = $Difference; - if($AtkHullDmg[$TKey] >= 1) - { - $Destroyed += 1; - $AtkHullDmg[$TKey] -= 1; - } - } - else - { - $UsedForce = $NeedForce + $Force2TDShield; - $Shoots = ceil($UsedForce / $AForce); - if($Shoots < $Able2Destroy) - { - $Shoots = $Able2Destroy; - } - $Destroyed = $Able2Destroy; - } - $Rounds[$i]['def']['force'] += $UsedForce; - $Rounds[$i]['def']['count'] += $Shoots; - $Rounds[$i]['atk']['shield'] += $Force2TDShield; - - if(!isset($AtkLost[$TShip][$TUser])) - { - $AtkLost[$TShip][$TUser] = 0; - } - if(!isset($ForceContribution['def'][$AUser])) - { - $ForceContribution['def'][$AUser] = 0; - } - if(!isset($ShotDown['def']['d'][$AUser][$TShip])) - { - $ShotDown['def']['d'][$AUser][$TShip] = 0; - } - if(!isset($ShotDown['atk']['l'][$TUser][$TShip])) - { - $ShotDown['atk']['l'][$TUser][$TShip] = 0; - } - - $AtkLost[$TShip][$TUser] += $Destroyed; - $ForceContribution['def'][$AUser] += $UsedForce; - $ShotDown['def']['d'][$AUser][$TShip] += $Destroyed; - $ShotDown['atk']['l'][$TUser][$TShip] += $Destroyed; - if($Destroyed == ($AtkShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedAtk[$TKey]) ? $AlreadyDestroyedAtk[$TKey] : 0))) - { - unset($AtkShipsForce_Copy[$TKey]); - if(isset($AtkHullDmg[$TKey])) - { - unset($AtkHullDmg[$TKey]); - } - unset($AtkShipsTypesOwners[$TShip][$TUser]); - $AtkShipsTypes[$TShip] -= 1; - } - else - { - if($Destroyed > 0) - { - if(!isset($AlreadyDestroyedAtk[$TKey])) - { - $AlreadyDestroyedAtk[$TKey] = 0; - } - $AlreadyDestroyedAtk[$TKey] += $Destroyed; - } - } - $ACount_Copy -= $Shoots; - } - else - { - $Rounds[$i]['def']['force'] += $AvailableForce; - $Rounds[$i]['def']['count'] += $ACount; - $Rounds[$i]['atk']['shield'] += $AvailableForce; - $AtkShields[$TKey] = array('left' => true, 'shield' => $Force2TDShield - $AvailableForce); - $ACount_Copy -= $ACount; - } - } - else - { - $UsedForce = $AForce * $ACount; - $Rounds[$i]['def']['force'] += $UsedForce; - $Rounds[$i]['def']['count'] += $ACount; - $Rounds[$i]['atk']['shield'] += $UsedForce; - $ACount_Copy -= $ACount; - } - } - - // --------------------- - // Calculate Rapid Fire! - if($UseRapidFire) - { - $NoMoreRapidFire = false; - - if(!empty($ShipsSD['d'][$AUser][$AShip])) - { - foreach($ShipsSD['d'][$AUser][$AShip] as $TShip => $TSDVal) - { - if($NoMoreRapidFire) - { - break; - } - if(isset($AtkShipsTypes[$TShip]) && $AtkShipsTypes[$TShip] > 0) - { - $TotalForceNeed = 0; - $TotalShootsNeed = 0; - $GainedForce = 0; - $GainedShoots = 0; - $AShipsAssign = false; - $RapidForce4Shield = false; - $RapidForce4Hull = false; - $RapidForceMinShoots = false; - - foreach($AtkShipsTypesOwners[$TShip] as $Owner => $NotImportant) - { - $ThisKey = "{$TShip}|{$Owner}"; - $CalcCount = ($AtkShipsTypesCount[$TShip][$Owner] - (isset($AlreadyDestroyedAtk[$ThisKey]) ? $AlreadyDestroyedAtk[$ThisKey] : 0)); - if($AtkShipsTypes[$TShip] > 1) - { - $TShipKeys[$ThisKey] = $CalcCount; - $TShipTotalCount += $CalcCount; - } - if(isset($AtkShields[$ThisKey]['left']) && $AtkShields[$ThisKey]['left'] === true) - { - $Force2TDShield = $AtkShields[$ThisKey]['shield']; - } - else - { - $Force2TDShield = $AtkShipsShield[$ThisKey] * $CalcCount; - } - $RapidForce4Shield[$Owner] = $Force2TDShield; - $RapidForce4Hull[$Owner] = $CalcCount * $AtkShipsHull[$ThisKey]; - if(isset($AtkHullDmg[$ThisKey])) - { - $RapidForce4Hull[$Owner] -= $AtkHullDmg[$ThisKey] * $AtkShipsHull[$ThisKey]; - } - $RapidForceMinShoots[$Owner] = $CalcCount; - - $TotalForceNeed += ($RapidForce4Shield[$Owner] + $RapidForce4Hull[$Owner]); - $TotalShootsNeed += $RapidForceMinShoots[$Owner]; - } - - $TotalAvailableShoots = floor(($DefShipsTypesCount[$AShip][$AUser] * $ShipsSD['d'][$AUser][$AShip][$TShip]) * (1 - (isset($DefDontShootRF[$AKey]) ? $DefDontShootRF[$AKey] : 0))); - $TotalAvailableForce = $TotalAvailableShoots * $AForce; - - if($TotalAvailableShoots > $TotalShootsNeed) - { - if($TotalAvailableForce > $TotalForceNeed) - { - $GainedShoots = ceil($TotalForceNeed / $AForce); - if($GainedShoots < $TotalShootsNeed) - { - $GainedShoots = $TotalShootsNeed; - } - if($GainedShoots == $TotalAvailableShoots) - { - $NoMoreRapidFire = true; - } - else - { - $TotalEverAvailableShoots = $DefShipsTypesCount[$AShip][$AUser] * $ShipsSD['d'][$AUser][$AShip][$TShip]; - if(!isset($DefDontShootRF[$AKey])) - { - $DefDontShootRF[$AKey] = 0; - } - $DefDontShootRF[$AKey] += $GainedShoots / $TotalEverAvailableShoots; - } - } - else - { - $GainedShoots = $TotalAvailableShoots; - $NoMoreRapidFire = true; - } - } - else - { - $GainedShoots = $TotalAvailableShoots; - $NoMoreRapidFire = true; - } - - if($GainedShoots > 0) - { - if($AtkShipsTypes[$TShip] > 1) - { - $ACount_Temp = $GainedShoots; - foreach($TShipKeys as $Key => $Count) - { - $Count = floor(($Count/$TShipTotalCount) * $GainedShoots); - $ACount_Temp -= $Count; - $AShipsAssign[$Key] = $Count; - } - if($ACount_Temp > 0) - { - arsort($AShipsAssign); - foreach($AShipsAssign as $Key => &$Data) - { - $Data += $ACount_Temp; - break; - } - } - } - - foreach($AtkShipsTypesOwners[$TShip] as $Owner => $NotImportant) - { - $TKey = "{$TShip}|{$Owner}"; - $TUser = $Owner; - - if($AtkShipsTypes[$TShip] > 1) - { - $ACount = $AShipsAssign[$TKey]; - } - else - { - $ACount = $GainedShoots; - } - if($ACount == 0) - { - continue; - } - - // Here calculating firing - if($AForce >= ($AtkShipsShield[$TKey] * 0.01)) - { - $AvailableForce = $AForce * $ACount; - $Force2TDShield = 0; - if(($AForce * 0.01) < $AtkShipsShield[$TKey]) - { - if(isset($AtkShields[$TKey]['left']) && $AtkShields[$TKey]['left'] === true) - { - $Force2TDShield = $AtkShields[$TKey]['shield']; - } - else - { - $Force2TDShield = $AtkShipsShield[$TKey] * $AtkShipsTypesCount[$TShip][$TUser]; - } - } - if($AvailableForce > $Force2TDShield) - { - if(($AForce * 0.01) < $AtkShipsShield[$TKey]) - { - $AtkShields[$TKey] = array('left' => true, 'shield' => 0); - } - $LeftForce = $AvailableForce - $Force2TDShield; - if($ACount < ($AtkShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedAtk[$TKey]) ? $AlreadyDestroyedAtk[$TKey] : 0))) - { - $Able2Destroy = $ACount; - } - else - { - $Able2Destroy = ($AtkShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedAtk[$TKey]) ? $AlreadyDestroyedAtk[$TKey] : 0)); - } - $NeedForce = ($AtkShipsHull[$TKey] * $Able2Destroy); - if(isset($AtkHullDmg[$TKey])) - { - $NeedForce -= ($AtkHullDmg[$TKey] * $AtkShipsHull[$TKey]); - } - if($NeedForce > $LeftForce) - { - $UsedForce = $LeftForce + $Force2TDShield; - $Shoots = $UsedForce / $AForce; - $DestroyedOrg = ($LeftForce / $AtkShipsHull[$TKey]); - if(isset($AtkHullDmg[$TKey])) - { - $DestroyedOrg += $AtkHullDmg[$TKey]; - } - $Destroyed = floor($LeftForce / $AtkShipsHull[$TKey]); - $Difference = $DestroyedOrg - $Destroyed; - $AtkHullDmg[$TKey] = $Difference; - if($AtkHullDmg[$TKey] >= 1) - { - $Destroyed += 1; - $AtkHullDmg[$TKey] -= 1; - } - } - else - { - $UsedForce = $NeedForce + $Force2TDShield; - $Shoots = ceil($UsedForce / $AForce); - if($Shoots < $Able2Destroy) - { - $Shoots = $Able2Destroy; - } - $Destroyed = $Able2Destroy; - } - $Rounds[$i]['def']['force'] += $UsedForce; - $Rounds[$i]['def']['count'] += $Shoots; - $Rounds[$i]['atk']['shield'] += $Force2TDShield; - - if(!isset($AtkLost[$TShip][$TUser])) - { - $AtkLost[$TShip][$TUser] = 0; - } - if(!isset($ForceContribution['def'][$AUser])) - { - $ForceContribution['def'][$AUser] = 0; - } - if(!isset($ShotDown['def']['d'][$AUser][$TShip])) - { - $ShotDown['def']['d'][$AUser][$TShip] = 0; - } - if(!isset($ShotDown['atk']['l'][$TUser][$TShip])) - { - $ShotDown['atk']['l'][$TUser][$TShip] = 0; - } - - $AtkLost[$TShip][$TUser] += $Destroyed; - $ForceContribution['def'][$AUser] += $UsedForce; - $ShotDown['def']['d'][$AUser][$TShip] += $Destroyed; - $ShotDown['atk']['l'][$TUser][$TShip] += $Destroyed; - if($Destroyed == ($AtkShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedAtk[$TKey]) ? $AlreadyDestroyedAtk[$ThisKey] : 0))) - { - unset($AtkShipsForce_Copy[$TKey]); - if(isset($AtkHullDmg[$TKey])) - { - unset($AtkHullDmg[$TKey]); - } - unset($AtkShipsTypesOwners[$TShip][$TUser]); - $AtkShipsTypes[$TShip] -= 1; - } - else - { - if($Destroyed > 0) - { - if(!isset($AlreadyDestroyedAtk[$TKey])) - { - $AlreadyDestroyedAtk[$TKey] = 0; - } - $AlreadyDestroyedAtk[$TKey] += $Destroyed; - } - } - } - else - { - $Rounds[$i]['def']['force'] += $AvailableForce; - $Rounds[$i]['def']['count'] += $ACount; - $Rounds[$i]['atk']['shield'] += $AvailableForce; - $AtkShields[$TKey] = array('left' => true, 'shield' => $Force2TDShield - $AvailableForce); - } - } - else - { - $UsedForce = $AForce * $ACount; - $Rounds[$i]['def']['force'] += $UsedForce; - $Rounds[$i]['def']['count'] += $ACount; - $Rounds[$i]['atk']['shield'] += $UsedForce; - } - } - } - } - } - } - } - } - - // ------------------------------------------------------------------------------------------------------------------------------------ - - // Now Calculate all loses and update all Arrays - // --------------------------------------------- - - // Defenders - foreach($DefLost as $ShipID => $ShipUsers) - { - $ShipKey = "{$ShipID}|"; - foreach($ShipUsers as $User => $Count) - { - $UserKey = "{$ShipKey}{$User}"; - if($Count == $DefenderShips[$User][$ShipID]) - { - unset($DefenderShips[$User][$ShipID]); - unset($DefShipsForce[$UserKey]); - } - else - { - $DefenderShips[$User][$ShipID] -= $Count; - $DefShipsTypesCount[$ShipID][$User] -= $Count; - } - if(!isset($DefLoseCount[$ShipID])) - { - $DefLoseCount[$ShipID] = 0; - } - $DefLoseCount[$ShipID] += $Count; - if($User == 0) - { - if($ShipID > 400 AND $ShipID < 500) - { - if(!isset($PlanetDefSysLost[$ShipID])) - { - $PlanetDefSysLost[$ShipID] = 0; - } - $PlanetDefSysLost[$ShipID] += $Count; - } - } - } - } - foreach($DefenderShips as $User => $Data) - { - if(empty($Data)) - { - unset($DefenderShips[$User]); - } - } - if(empty($DefenderShips)) - { - unset($DefenderShips); - } - - // Attackers - foreach($AtkLost as $ShipID => $ShipUsers) - { - $ShipKey = "{$ShipID}|"; - foreach($ShipUsers as $User => $Count) - { - $UserKey = "{$ShipKey}{$User}"; - if($Count == $AttackerShips[$User][$ShipID]) - { - unset($AttackerShips[$User][$ShipID]); - unset($AtkShipsForce[$UserKey]); - } - else - { - $AttackerShips[$User][$ShipID] -= $Count; - $AtkShipsTypesCount[$ShipID][$User] -= $Count; - } - if(!isset($AtkLoseCount[$ShipID])) - { - $AtkLoseCount[$ShipID] = 0; - } - $AtkLoseCount[$ShipID] += $Count; - } - } - foreach($AttackerShips as $User => $Data) - { - if(empty($Data)) - { - unset($AttackerShips[$User]); - } - } - if(empty($AttackerShips)) - { - unset($AttackerShips); - } - } - - if((!empty($AttackerShips) AND !empty($DefenderShips)) OR (empty($AttackerShips) AND empty($DefenderShips))) - { - $BattleResult = COMBAT_DRAW; // It's a Draw - } - else if(empty($AttackerShips)) - { - $BattleResult = COMBAT_DEF;// Defenders Won! - } - else if(empty($DefenderShips)) - { - $BattleResult = COMBAT_ATK;// Attackers Won! - } - else - { - return array('result' => false, 'error' => 'BAD_COMBAT_RESULT'); - } - - return array - ( - 'return' => true, - 'AttackerShips' => (isset($AttackerShips) ? $AttackerShips : null), - 'DefenderShips' => (isset($DefenderShips) ? $DefenderShips : null), - 'rounds' => $Rounds, 'result' => $BattleResult, - 'AtkLose' => $AtkLoseCount, 'DefLose' => $DefLoseCount, 'DefSysLost' => $PlanetDefSysLost, - 'ShotDown' => (isset($ShotDown) ? $ShotDown : null), 'ForceContribution' => (isset($ForceContribution) ? $ForceContribution : null) - ); -} - -?> \ No newline at end of file + &$Techs) + { + $Techs[109] = 1 + (0.1 * $Techs[109]); + $Techs[110] = 1 + (0.1 * $Techs[110]); + $Techs[111] = 1 + (0.1 * $Techs[111]); + + if(empty($Techs['TotalForceFactor'])) + { + $Techs['TotalForceFactor'] = 1; + } + if(empty($Techs['TotalShieldFactor'])) + { + $Techs['TotalShieldFactor'] = 1; + } + } + foreach($Defender as $User => $Ships) + { + $UserKey = "|{$User}"; + foreach($Ships as $ID => $Count) + { + $UserShipKey = "{$ID}{$UserKey}"; + $ForceUpgrade = 0; + + if($UseRapidFire) + { + foreach($_Vars_CombatData[$ID]['sd'] as $TID => $SDVal) + { + if($SDVal > 1) + { + if(!empty($DefenderTech[$User]['SDAdd'])) + { + $SDVal += $DefenderTech[$User]['SDAdd']; + } + else if(!empty($DefenderTech[$User]['SDFactor'])) + { + $SDVal = round($SDVal * $DefenderTech[$User]['SDFactor']); + } + if($SDVal > 1) + { + $ShipsSD['d'][$User][$ID][$TID] = $SDVal - 1; + } + } + } + if(!empty($ShipsSD['d'][$User][$ID])) + { + arsort($ShipsSD['d'][$User][$ID]); + } + } + $DefenderShips[$User][$ID] = $Count; + if(!isset($DefShipsTypes[$ID])) + { + $DefShipsTypes[$ID] = 0; + } + $DefShipsTypes[$ID] += 1; + $DefShipsTypesOwners[$ID][$User] = 1; + $DefShipsTypesCount[$ID][$User] = $Count; + + // Calculate Ships Force, Shield and Hull values + if(!empty($_Vars_CombatUpgrades[$ID])) + { + foreach($_Vars_CombatUpgrades[$ID] as $UpTech => $ReqLevel) + { + $TechAvailable = $DefenderTech[$User][$UpTech]; + if($TechAvailable > $ReqLevel) + { + $ForceUpgrade += ($TechAvailable - $ReqLevel) * 0.05; + } + } + } + $DefShipsForce[$UserShipKey] = floor($_Vars_CombatData[$ID]['attack'] * ($DefenderTech[$User][109] + $ForceUpgrade) * $DefenderTech[$User]['TotalForceFactor']); + $DefShipsShield[$UserShipKey] = floor($_Vars_CombatData[$ID]['shield'] * $DefenderTech[$User][110] * $DefenderTech[$User]['TotalShieldFactor']); + if(empty($ShipsHullValues[$ID])) + { + $ShipsHullValues[$ID] = ($_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal']) / 10; + } + $DefShipsHull[$UserShipKey] = floor($ShipsHullValues[$ID]* $DefenderTech[$User][111]); + } + } + asort($DefShipsForce); + } + else + { + $DefenderShips = false; + } + + if(!empty($Attacker)) + { + foreach($AttackerTech as $User => &$Techs) + { + $Techs[109] = 1 + (0.1 * $Techs[109]); + $Techs[110] = 1 + (0.1 * $Techs[110]); + $Techs[111] = 1 + (0.1 * $Techs[111]); + + if(empty($Techs['TotalForceFactor'])) + { + $Techs['TotalForceFactor'] = 1; + } + if(empty($Techs['TotalShieldFactor'])) + { + $Techs['TotalShieldFactor'] = 1; + } + } + foreach($Attacker as $User => $Ships) + { + $UserKey = "|{$User}"; + foreach($Ships as $ID => $Count) + { + $UserShipKey = "{$ID}{$UserKey}"; + $ForceUpgrade = 0; + + if($UseRapidFire) + { + foreach($_Vars_CombatData[$ID]['sd'] as $TID => $SDVal) + { + if($SDVal > 1) + { + if(!empty($AttackerTech[$User]['SDAdd'])) + { + $SDVal += $AttackerTech[$User]['SDAdd']; + } + else if(!empty($AttackerTech[$User]['SDFactor'])) + { + $SDVal = round($SDVal * $AttackerTech[$User]['SDFactor']); + } + if($SDVal > 1) + { + $ShipsSD['a'][$User][$ID][$TID] = $SDVal - 1; + } + } + } + if(!empty($ShipsSD['d'][$User][$ID])) + { + arsort($ShipsSD['d'][$User][$ID]); + } + } + $AttackerShips[$User][$ID] = $Count; + if(!isset($AtkShipsTypes[$ID])) + { + $AtkShipsTypes[$ID] = 0; + } + $AtkShipsTypes[$ID] += 1; + $AtkShipsTypesOwners[$ID][$User] = 1; + $AtkShipsTypesCount[$ID][$User] = $Count; + + // Calculate Ships Force, Shield and Hull values + if(!empty($_Vars_CombatUpgrades[$ID])) + { + foreach($_Vars_CombatUpgrades[$ID] as $UpTech => $ReqLevel) + { + $TechAvailable = $AttackerTech[$User][$UpTech]; + if($TechAvailable > $ReqLevel) + { + $ForceUpgrade += ($TechAvailable - $ReqLevel) * 0.05; + } + } + } + $AtkShipsForce[$UserShipKey] = floor($_Vars_CombatData[$ID]['attack'] * ($AttackerTech[$User][109] + $ForceUpgrade) * $AttackerTech[$User]['TotalForceFactor']); + $AtkShipsShield[$UserShipKey] = floor($_Vars_CombatData[$ID]['shield'] * $AttackerTech[$User][110] * $AttackerTech[$User]['TotalShieldFactor']); + if(empty($ShipsHullValues[$ID])) + { + $ShipsHullValues[$ID] = ($_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal']) / 10; + } + $AtkShipsHull[$UserShipKey] = floor($ShipsHullValues[$ID]* $AttackerTech[$User][111]); + } + } + $AtkShipsForce_Copy = $AtkShipsForce; + asort($AtkShipsForce); + asort($AtkShipsForce_Copy); + } + else + { + return array('result' => false, 'error' => 'NO_ATTACKER'); + } + + $RoundsLimit = BATTLE_MAX_ROUNDS + 1; + for($i = 1; $i <= $RoundsLimit; $i += 1) + { + // Clear Lost Ships in last round + $AtkLost = array(); + $DefLost = array(); + // Clear Targets Shield Supply + $DefShields = false; + $AtkShields = false; + // Clear Already destroyed targets + $AlreadyDestroyedDef = false; + $AlreadyDestroyedAtk = false; + // Clear RapidFire Exclusions + $AtkDontShootRF = false; + $DefDontShootRF = false; + // Clear TotalACS Force + $TotalDefTypesForce = false; + $TotalAtkTypesForce = false; + // END of Clearing + + $Rounds[$i]['atk']['ships'] = (isset($AttackerShips) ? $AttackerShips : null); + $Rounds[$i]['def']['ships'] = (isset($DefenderShips) ? $DefenderShips : null); + $Rounds[$i]['atk']['force'] = 0; + $Rounds[$i]['atk']['count'] = 0; + $Rounds[$i]['atk']['shield'] = 0; + $Rounds[$i]['def']['force'] = 0; + $Rounds[$i]['def']['count'] = 0; + $Rounds[$i]['def']['shield'] = 0; + + if($i > BATTLE_MAX_ROUNDS) + { + break; + } + + if(empty($AttackerShips) OR empty($DefenderShips)) + { + break; + } + + // Prepare target list + // ------------------- + // Defender Targets + $DefShipsForce_Copy = $DefShipsForce; + foreach($DefShipsForce_Copy as $TempKey => &$TempForce) + { + $TempForce += $DefShipsShield[$TempKey]; + $TempKey = explode('|', $TempKey); + $TempForce *= $DefShipsTypesCount[$TempKey[0]][$TempKey[1]]; + if(!isset($TotalDefTypesForce[$TempKey[0]])) + { + $TotalDefTypesForce[$TempKey[0]] = 0; + } + $TotalDefTypesForce[$TempKey[0]] += $TempForce; + } + foreach($DefShipsForce_Copy as $TempKey => &$TempForce) + { + $TempKey = explode('|', $TempKey); + if($TempForce < $TotalDefTypesForce[$TempKey[0]]) + { + $TempForce = $TotalDefTypesForce[$TempKey[0]]; + } + } + asort($DefShipsForce_Copy); + // Attacker Targets + $AtkShipsForce_Copy = $AtkShipsForce; + foreach($AtkShipsForce_Copy as $TempKey => &$TempForce) + { + $TempForce += $AtkShipsShield[$TempKey]; + $TempKey = explode('|', $TempKey); + $TempForce *= $AtkShipsTypesCount[$TempKey[0]][$TempKey[1]]; + if(!isset($TotalAtkTypesForce[$TempKey[0]])) + { + $TotalAtkTypesForce[$TempKey[0]] = 0; + } + $TotalAtkTypesForce[$TempKey[0]] += $TempForce; + } + foreach($AtkShipsForce_Copy as $TempKey => &$TempForce) + { + $TempKey = explode('|', $TempKey); + if($TempForce < $TotalAtkTypesForce[$TempKey[0]]) + { + $TempForce = $TotalAtkTypesForce[$TempKey[0]]; + } + } + asort($AtkShipsForce_Copy); + + // ------------------------------------------------------------------------------------------------------------------------------------ + // Calculate Attacker(s) Part + // 1. Let's calculate all regular fires! + + foreach($AtkShipsForce as $AKey => $AForce) + { + if($AForce == 0) + { + continue; // Jump out if this Ship is useless (like Solar Satelite or Spy Probe) + } + $Temp = explode('|', $AKey); + $AUser = $Temp[1]; + $AShip = $Temp[0]; + $ACount_Copy = $AtkShipsTypesCount[$AShip][$AUser]; + $AssignmentCalc = false; + $AShipsAssign = false; + + // ----------------------- + // Calculate Regular Fire! + foreach($DefShipsForce_Copy as $TKey => $TForce) + { + $Temp = explode('|', $TKey); + $TShip = $Temp[0]; + $TUser = $Temp[1]; + + // Here calculating, if it's ACS and more than one user have this ShipType + if($DefShipsTypes[$TShip] > 1 && !isset($AssignmentCalc[$TShip])) + { + $TShipTotalCount = 0; + $TShipKeys = false; + foreach($DefShipsTypesOwners[$TShip] as $Owner => $NotImportant) + { + $ThisKey = "{$TShip}|{$Owner}"; + $CalcCount = ($DefShipsTypesCount[$TShip][$Owner] - (isset($AlreadyDestroyedDef[$ThisKey]) ? $AlreadyDestroyedDef[$ThisKey] : 0)); + $TShipKeys[$ThisKey] = $CalcCount; + $TShipTotalCount += $CalcCount; + } + $ACount_Temp = $ACount_Copy; + foreach($TShipKeys as $Key => $Count) + { + $Count = floor(($Count/$TShipTotalCount) * $ACount_Copy); + $ACount_Temp -= $Count; + $AShipsAssign[$Key] = $Count; + } + if($ACount_Temp > 0) + { + arsort($AShipsAssign); + foreach($AShipsAssign as $Key => &$Data) + { + $Data += $ACount_Temp; + break; + } + } + $AssignmentCalc[$TShip] = true; + } + + if($DefShipsTypes[$TShip] > 1) + { + $ACount = $AShipsAssign[$TKey]; + } + else + { + $ACount = $ACount_Copy; + } + if($ACount == 0) + { + continue; + } + + // Here calculating firing + if($AForce >= ($DefShipsShield[$TKey] * 0.01)) + { + $AvailableForce = $AForce * $ACount; + $Force2TDShield = 0; + if(($AForce * 0.01) < $DefShipsShield[$TKey]) + { + if(isset($DefShields[$TKey]['left']) && $DefShields[$TKey]['left'] === true) + { + $Force2TDShield = $DefShields[$TKey]['shield']; + } + else + { + $Force2TDShield = $DefShipsShield[$TKey] * $DefShipsTypesCount[$TShip][$TUser]; + } + } + if($AvailableForce > $Force2TDShield) + { + if(($AForce * 0.01) < $DefShipsShield[$TKey]) + { + $DefShields[$TKey] = array('left' => true, 'shield' => 0); + } + $LeftForce = $AvailableForce - $Force2TDShield; + if($ACount < ($DefShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedDef[$TKey]) ? $AlreadyDestroyedDef[$TKey] : 0))) + { + $Able2Destroy = $ACount; + } + else + { + $Able2Destroy = ($DefShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedDef[$TKey]) ? $AlreadyDestroyedDef[$TKey] : 0)); + } + $NeedForce = ($DefShipsHull[$TKey] * $Able2Destroy); + if(isset($DefHullDmg[$TKey])) + { + $NeedForce -= ($DefHullDmg[$TKey] * $DefShipsHull[$TKey]); + } + if($NeedForce > $LeftForce) + { + $UsedForce = $LeftForce + $Force2TDShield; + $Shoots = $UsedForce / $AForce; + $DestroyedOrg = ($LeftForce / $DefShipsHull[$TKey]); + if(isset($DefHullDmg[$TKey])) + { + $DestroyedOrg += $DefHullDmg[$TKey]; + } + $Destroyed = floor($LeftForce / $DefShipsHull[$TKey]); + $Difference = $DestroyedOrg - $Destroyed; + $DefHullDmg[$TKey] = $Difference; + if($DefHullDmg[$TKey] >= 1) + { + $Destroyed += 1; + $DefHullDmg[$TKey] -= 1; + } + } + else + { + $UsedForce = $NeedForce + $Force2TDShield; + $Shoots = ceil($UsedForce / $AForce); + if($Shoots < $Able2Destroy) + { + $Shoots = $Able2Destroy; + } + $Destroyed = $Able2Destroy; + } + $Rounds[$i]['atk']['force'] += $UsedForce; + $Rounds[$i]['atk']['count'] += $Shoots; + $Rounds[$i]['def']['shield'] += $Force2TDShield; + + if(!isset($DefLost[$TShip][$TUser])) + { + $DefLost[$TShip][$TUser] = 0; + } + if(!isset($ForceContribution['atk'][$AUser])) + { + $ForceContribution['atk'][$AUser] = 0; + } + if(!isset($ShotDown['atk']['d'][$AUser][$TShip])) + { + $ShotDown['atk']['d'][$AUser][$TShip] = 0; + } + if(!isset($ShotDown['def']['l'][$TUser][$TShip])) + { + $ShotDown['def']['l'][$TUser][$TShip] = 0; + } + + $DefLost[$TShip][$TUser] += $Destroyed; + $ForceContribution['atk'][$AUser] += $UsedForce; + $ShotDown['atk']['d'][$AUser][$TShip] += $Destroyed; + $ShotDown['def']['l'][$TUser][$TShip] += $Destroyed; + if($Destroyed == ($DefShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedDef[$TKey]) ? $AlreadyDestroyedDef[$TKey] : 0))) + { + unset($DefShipsForce_Copy[$TKey]); + if(isset($DefHullDmg[$TKey])) + { + unset($DefHullDmg[$TKey]); + } + unset($DefShipsTypesOwners[$TShip][$TUser]); + $DefShipsTypes[$TShip] -= 1; + } + else + { + if($Destroyed > 0) + { + if(!isset($AlreadyDestroyedDef[$TKey])) + { + $AlreadyDestroyedDef[$TKey] = 0; + } + $AlreadyDestroyedDef[$TKey] += $Destroyed; + } + } + $ACount_Copy -= $Shoots; + } + else + { + $Rounds[$i]['atk']['force'] += $AvailableForce; + $Rounds[$i]['atk']['count'] += $ACount; + $Rounds[$i]['def']['shield'] += $AvailableForce; + $DefShields[$TKey] = array('left' => true, 'shield' => $Force2TDShield - $AvailableForce); + $ACount_Copy -= $ACount; + } + } + else + { + $UsedForce = $AForce * $ACount; + $Rounds[$i]['atk']['force'] += $UsedForce; + $Rounds[$i]['atk']['count'] += $ACount; + $Rounds[$i]['def']['shield'] += $UsedForce; + $ACount_Copy -= $ACount; + } + } + + // --------------------- + // Calculate Rapid Fire! + if($UseRapidFire) + { + $NoMoreRapidFire = false; + + if(!empty($ShipsSD['a'][$AUser][$AShip])) + { + foreach($ShipsSD['a'][$AUser][$AShip] as $TShip => $TSDVal) + { + if($NoMoreRapidFire) + { + break; + } + if(isset($DefShipsTypes[$TShip]) && $DefShipsTypes[$TShip] > 0) + { + $TotalForceNeed = 0; + $TotalShootsNeed = 0; + $GainedForce = 0; + $GainedShoots = 0; + $AShipsAssign = false; + $RapidForce4Shield = false; + $RapidForce4Hull = false; + $RapidForceMinShoots = false; + + foreach($DefShipsTypesOwners[$TShip] as $Owner => $NotImportant) + { + $ThisKey = "{$TShip}|{$Owner}"; + $CalcCount = ($DefShipsTypesCount[$TShip][$Owner] - (isset($AlreadyDestroyedDef[$ThisKey]) ? $AlreadyDestroyedDef[$ThisKey] : 0)); + if($DefShipsTypes[$TShip] > 1) + { + $TShipKeys[$ThisKey] = $CalcCount; + $TShipTotalCount += $CalcCount; + } + if(isset($DefShields[$ThisKey]['left']) && $DefShields[$ThisKey]['left'] === true) + { + $Force2TDShield = $DefShields[$ThisKey]['shield']; + } + else + { + $Force2TDShield = $DefShipsShield[$ThisKey] * $CalcCount; + } + $RapidForce4Shield[$Owner] = $Force2TDShield; + $RapidForce4Hull[$Owner] = $CalcCount * $DefShipsHull[$ThisKey]; + if(isset($DefHullDmg[$ThisKey])) + { + $RapidForce4Hull[$Owner] -= $DefHullDmg[$ThisKey] * $DefShipsHull[$ThisKey]; + } + $RapidForceMinShoots[$Owner] = $CalcCount; + + $TotalForceNeed += ($RapidForce4Shield[$Owner] + $RapidForce4Hull[$Owner]); + $TotalShootsNeed += $RapidForceMinShoots[$Owner]; + } + + $TotalAvailableShoots = floor(($AtkShipsTypesCount[$AShip][$AUser] * $ShipsSD['a'][$AUser][$AShip][$TShip]) * (1 - (isset($AtkDontShootRF[$AKey]) ? $AtkDontShootRF[$AKey] : 0))); + $TotalAvailableForce = $TotalAvailableShoots * $AForce; + + if($TotalAvailableShoots > $TotalShootsNeed) + { + if($TotalAvailableForce > $TotalForceNeed) + { + $GainedShoots = ceil($TotalForceNeed / $AForce); + if($GainedShoots < $TotalShootsNeed) + { + $GainedShoots = $TotalShootsNeed; + } + if($GainedShoots == $TotalAvailableShoots) + { + $NoMoreRapidFire = true; + } + else + { + $TotalEverAvailableShoots = $AtkShipsTypesCount[$AShip][$AUser] * $ShipsSD['a'][$AUser][$AShip][$TShip]; + if(!isset($AtkDontShootRF[$AKey])) + { + $AtkDontShootRF[$AKey] = 0; + } + $AtkDontShootRF[$AKey] += $GainedShoots / $TotalEverAvailableShoots; + } + } + else + { + $GainedShoots = $TotalAvailableShoots; + $NoMoreRapidFire = true; + } + } + else + { + $GainedShoots = $TotalAvailableShoots; + $NoMoreRapidFire = true; + } + + if($GainedShoots > 0) + { + if($DefShipsTypes[$TShip] > 1) + { + $ACount_Temp = $GainedShoots; + foreach($TShipKeys as $Key => $Count) + { + $Count = floor(($Count/$TShipTotalCount) * $GainedShoots); + $ACount_Temp -= $Count; + $AShipsAssign[$Key] = $Count; + } + if($ACount_Temp > 0) + { + arsort($AShipsAssign); + foreach($AShipsAssign as $Key => &$Data) + { + $Data += $ACount_Temp; + break; + } + } + } + + foreach($DefShipsTypesOwners[$TShip] as $Owner => $NotImportant) + { + $TKey = "{$TShip}|{$Owner}"; + $TUser = $Owner; + + if($DefShipsTypes[$TShip] > 1) + { + $ACount = $AShipsAssign[$TKey]; + } + else + { + $ACount = $GainedShoots; + } + if($ACount == 0) + { + continue; + } + + // Here calculating firing + if($AForce >= ($DefShipsShield[$TKey] * 0.01)) + { + $AvailableForce = $AForce * $ACount; + $Force2TDShield = 0; + if(($AForce * 0.01) < $DefShipsShield[$TKey]) + { + if(isset($DefShields[$TKey]['left']) && $DefShields[$TKey]['left'] === true) + { + $Force2TDShield = $DefShields[$TKey]['shield']; + } + else + { + $Force2TDShield = $DefShipsShield[$TKey] * $DefShipsTypesCount[$TShip][$TUser]; + } + } + if($AvailableForce > $Force2TDShield) + { + if(($AForce * 0.01) < $DefShipsShield[$TKey]) + { + $DefShields[$TKey] = array('left' => true, 'shield' => 0); + } + $LeftForce = $AvailableForce - $Force2TDShield; + if($ACount < ($DefShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedDef[$TKey]) ? $AlreadyDestroyedDef[$TKey] : 0))) + { + $Able2Destroy = $ACount; + } + else + { + $Able2Destroy = ($DefShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedDef[$TKey]) ? $AlreadyDestroyedDef[$TKey] : 0)); + } + $NeedForce = ($DefShipsHull[$TKey] * $Able2Destroy); + if(isset($DefHullDmg[$TKey])) + { + $NeedForce -= ($DefHullDmg[$TKey] * $DefShipsHull[$TKey]); + } + if($NeedForce > $LeftForce) + { + $UsedForce = $LeftForce + $Force2TDShield; + $Shoots = $UsedForce / $AForce; + $DestroyedOrg = ($LeftForce / $DefShipsHull[$TKey]); + if(isset($DefHullDmg[$TKey])) + { + $DestroyedOrg += $DefHullDmg[$TKey]; + } + $Destroyed = floor($LeftForce / $DefShipsHull[$TKey]); + $Difference = $DestroyedOrg - $Destroyed; + $DefHullDmg[$TKey] = $Difference; + if($DefHullDmg[$TKey] >= 1) + { + $Destroyed += 1; + $DefHullDmg[$TKey] -= 1; + } + } + else + { + $UsedForce = $NeedForce + $Force2TDShield; + $Shoots = ceil($UsedForce / $AForce); + if($Shoots < $Able2Destroy) + { + $Shoots = $Able2Destroy; + } + $Destroyed = $Able2Destroy; + } + $Rounds[$i]['atk']['force'] += $UsedForce; + $Rounds[$i]['atk']['count'] += $Shoots; + $Rounds[$i]['def']['shield'] += $Force2TDShield; + + if(!isset($DefLost[$TShip][$TUser])) + { + $DefLost[$TShip][$TUser] = 0; + } + if(!isset($ForceContribution['atk'][$AUser])) + { + $ForceContribution['atk'][$AUser] = 0; + } + if(!isset($ShotDown['atk']['d'][$AUser][$TShip])) + { + $ShotDown['atk']['d'][$AUser][$TShip] = 0; + } + if(!isset($ShotDown['def']['l'][$TUser][$TShip])) + { + $ShotDown['def']['l'][$TUser][$TShip] = 0; + } + + $DefLost[$TShip][$TUser] += $Destroyed; + $ForceContribution['atk'][$AUser] += $UsedForce; + $ShotDown['atk']['d'][$AUser][$TShip] += $Destroyed; + $ShotDown['def']['l'][$TUser][$TShip] += $Destroyed; + if($Destroyed == ($DefShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedDef[$TKey]) ? $AlreadyDestroyedDef[$TKey] : 0))) + { + unset($DefShipsForce_Copy[$TKey]); + if(isset($DefHullDmg[$TKey])) + { + unset($DefHullDmg[$TKey]); + } + unset($DefShipsTypesOwners[$TShip][$TUser]); + $DefShipsTypes[$TShip] -= 1; + } + else + { + if($Destroyed > 0) + { + if(!isset($AlreadyDestroyedDef[$TKey])) + { + $AlreadyDestroyedDef[$TKey] = 0; + } + $AlreadyDestroyedDef[$TKey] += $Destroyed; + } + } + } + else + { + $Rounds[$i]['atk']['force'] += $AvailableForce; + $Rounds[$i]['atk']['count'] += $ACount; + $Rounds[$i]['def']['shield'] += $AvailableForce; + $DefShields[$TKey] = array('left' => true, 'shield' => $Force2TDShield - $AvailableForce); + } + } + else + { + $UsedForce = $AForce * $ACount; + $Rounds[$i]['atk']['force'] += $UsedForce; + $Rounds[$i]['atk']['count'] += $ACount; + $Rounds[$i]['def']['shield'] += $UsedForce; + } + } + } + } + } + } + } + } + + // ------------------------------------------------------------------------------------------------------------------------------------ + + // Calculate Defender(s) Part + // 1. Let's calculate all regular fires! + + foreach($DefShipsForce as $AKey => $AForce) + { + if($AForce == 0) + { + continue; // Jump out if this Ship is useless (like Solar Satelite or Spy Probe) + } + $Temp = explode('|', $AKey); + $AUser = $Temp[1]; + $AShip = $Temp[0]; + $ACount_Copy = $DefShipsTypesCount[$AShip][$AUser]; + $AssignmentCalc = false; + $AShipsAssign = false; + + // ----------------------- + // Calculate Regular Fire! + foreach($AtkShipsForce_Copy as $TKey => $TForce) + { + $Temp = explode('|', $TKey); + $TShip = $Temp[0]; + $TUser = $Temp[1]; + + // Here calculating, if it's ACS and more than one user have this ShipType + if($AtkShipsTypes[$TShip] > 1 && !isset($AssignmentCalc[$TShip])) + { + $TShipTotalCount = 0; + $TShipKeys = false; + foreach($AtkShipsTypesOwners[$TShip] as $Owner => $NotImportant) + { + $ThisKey = "{$TShip}|{$Owner}"; + $CalcCount = ($AtkShipsTypesCount[$TShip][$Owner] - (isset($AlreadyDestroyedAtk[$ThisKey]) ? $AlreadyDestroyedAtk[$ThisKey] : 0)); + $TShipKeys[$ThisKey] = $CalcCount; + $TShipTotalCount += $CalcCount; + } + $ACount_Temp = $ACount_Copy; + foreach($TShipKeys as $Key => $Count) + { + $Count = floor(($Count/$TShipTotalCount) * $ACount_Copy); + $ACount_Temp -= $Count; + $AShipsAssign[$Key] = $Count; + } + if($ACount_Temp > 0) + { + arsort($AShipsAssign); + foreach($AShipsAssign as $Key => &$Data) + { + $Data += $ACount_Temp; + break; + } + } + $AssignmentCalc[$TShip] = true; + } + + if($AtkShipsTypes[$TShip] > 1) + { + $ACount = $AShipsAssign[$TKey]; + } + else + { + $ACount = $ACount_Copy; + } + if($ACount == 0) + { + continue; + } + + // Here calculating firing + if($AForce >= ($AtkShipsShield[$TKey] * 0.01)) + { + $AvailableForce = $AForce * $ACount; + $Force2TDShield = 0; + if(($AForce * 0.01) < $AtkShipsShield[$TKey]) + { + if(isset($AtkShields[$TKey]['left']) && $AtkShields[$TKey]['left'] === true) + { + $Force2TDShield = $AtkShields[$TKey]['shield']; + } + else + { + $Force2TDShield = $AtkShipsShield[$TKey] * $AtkShipsTypesCount[$TShip][$TUser]; + } + } + if($AvailableForce > $Force2TDShield) + { + if(($AForce * 0.01) < $AtkShipsShield[$TKey]) + { + $AtkShields[$TKey] = array('left' => true, 'shield' => 0); + } + $LeftForce = $AvailableForce - $Force2TDShield; + if($ACount < ($AtkShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedAtk[$TKey]) ? $AlreadyDestroyedAtk[$TKey] : 0))) + { + $Able2Destroy = $ACount; + } + else + { + $Able2Destroy = ($AtkShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedAtk[$TKey]) ? $AlreadyDestroyedAtk[$TKey] : 0)); + } + $NeedForce = ($AtkShipsHull[$TKey] * $Able2Destroy); + if(isset($AtkHullDmg[$TKey])) + { + $NeedForce -= ($AtkHullDmg[$TKey] * $AtkShipsHull[$TKey]); + } + if($NeedForce > $LeftForce) + { + $UsedForce = $LeftForce + $Force2TDShield; + $Shoots = $UsedForce / $AForce; + $DestroyedOrg = ($LeftForce / $AtkShipsHull[$TKey]); + if(isset($AtkHullDmg[$TKey])) + { + $DestroyedOrg += $AtkHullDmg[$TKey]; + } + $Destroyed = floor($LeftForce / $AtkShipsHull[$TKey]); + $Difference = $DestroyedOrg - $Destroyed; + $AtkHullDmg[$TKey] = $Difference; + if($AtkHullDmg[$TKey] >= 1) + { + $Destroyed += 1; + $AtkHullDmg[$TKey] -= 1; + } + } + else + { + $UsedForce = $NeedForce + $Force2TDShield; + $Shoots = ceil($UsedForce / $AForce); + if($Shoots < $Able2Destroy) + { + $Shoots = $Able2Destroy; + } + $Destroyed = $Able2Destroy; + } + $Rounds[$i]['def']['force'] += $UsedForce; + $Rounds[$i]['def']['count'] += $Shoots; + $Rounds[$i]['atk']['shield'] += $Force2TDShield; + + if(!isset($AtkLost[$TShip][$TUser])) + { + $AtkLost[$TShip][$TUser] = 0; + } + if(!isset($ForceContribution['def'][$AUser])) + { + $ForceContribution['def'][$AUser] = 0; + } + if(!isset($ShotDown['def']['d'][$AUser][$TShip])) + { + $ShotDown['def']['d'][$AUser][$TShip] = 0; + } + if(!isset($ShotDown['atk']['l'][$TUser][$TShip])) + { + $ShotDown['atk']['l'][$TUser][$TShip] = 0; + } + + $AtkLost[$TShip][$TUser] += $Destroyed; + $ForceContribution['def'][$AUser] += $UsedForce; + $ShotDown['def']['d'][$AUser][$TShip] += $Destroyed; + $ShotDown['atk']['l'][$TUser][$TShip] += $Destroyed; + if($Destroyed == ($AtkShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedAtk[$TKey]) ? $AlreadyDestroyedAtk[$TKey] : 0))) + { + unset($AtkShipsForce_Copy[$TKey]); + if(isset($AtkHullDmg[$TKey])) + { + unset($AtkHullDmg[$TKey]); + } + unset($AtkShipsTypesOwners[$TShip][$TUser]); + $AtkShipsTypes[$TShip] -= 1; + } + else + { + if($Destroyed > 0) + { + if(!isset($AlreadyDestroyedAtk[$TKey])) + { + $AlreadyDestroyedAtk[$TKey] = 0; + } + $AlreadyDestroyedAtk[$TKey] += $Destroyed; + } + } + $ACount_Copy -= $Shoots; + } + else + { + $Rounds[$i]['def']['force'] += $AvailableForce; + $Rounds[$i]['def']['count'] += $ACount; + $Rounds[$i]['atk']['shield'] += $AvailableForce; + $AtkShields[$TKey] = array('left' => true, 'shield' => $Force2TDShield - $AvailableForce); + $ACount_Copy -= $ACount; + } + } + else + { + $UsedForce = $AForce * $ACount; + $Rounds[$i]['def']['force'] += $UsedForce; + $Rounds[$i]['def']['count'] += $ACount; + $Rounds[$i]['atk']['shield'] += $UsedForce; + $ACount_Copy -= $ACount; + } + } + + // --------------------- + // Calculate Rapid Fire! + if($UseRapidFire) + { + $NoMoreRapidFire = false; + + if(!empty($ShipsSD['d'][$AUser][$AShip])) + { + foreach($ShipsSD['d'][$AUser][$AShip] as $TShip => $TSDVal) + { + if($NoMoreRapidFire) + { + break; + } + if(isset($AtkShipsTypes[$TShip]) && $AtkShipsTypes[$TShip] > 0) + { + $TotalForceNeed = 0; + $TotalShootsNeed = 0; + $GainedForce = 0; + $GainedShoots = 0; + $AShipsAssign = false; + $RapidForce4Shield = false; + $RapidForce4Hull = false; + $RapidForceMinShoots = false; + + foreach($AtkShipsTypesOwners[$TShip] as $Owner => $NotImportant) + { + $ThisKey = "{$TShip}|{$Owner}"; + $CalcCount = ($AtkShipsTypesCount[$TShip][$Owner] - (isset($AlreadyDestroyedAtk[$ThisKey]) ? $AlreadyDestroyedAtk[$ThisKey] : 0)); + if($AtkShipsTypes[$TShip] > 1) + { + $TShipKeys[$ThisKey] = $CalcCount; + $TShipTotalCount += $CalcCount; + } + if(isset($AtkShields[$ThisKey]['left']) && $AtkShields[$ThisKey]['left'] === true) + { + $Force2TDShield = $AtkShields[$ThisKey]['shield']; + } + else + { + $Force2TDShield = $AtkShipsShield[$ThisKey] * $CalcCount; + } + $RapidForce4Shield[$Owner] = $Force2TDShield; + $RapidForce4Hull[$Owner] = $CalcCount * $AtkShipsHull[$ThisKey]; + if(isset($AtkHullDmg[$ThisKey])) + { + $RapidForce4Hull[$Owner] -= $AtkHullDmg[$ThisKey] * $AtkShipsHull[$ThisKey]; + } + $RapidForceMinShoots[$Owner] = $CalcCount; + + $TotalForceNeed += ($RapidForce4Shield[$Owner] + $RapidForce4Hull[$Owner]); + $TotalShootsNeed += $RapidForceMinShoots[$Owner]; + } + + $TotalAvailableShoots = floor(($DefShipsTypesCount[$AShip][$AUser] * $ShipsSD['d'][$AUser][$AShip][$TShip]) * (1 - (isset($DefDontShootRF[$AKey]) ? $DefDontShootRF[$AKey] : 0))); + $TotalAvailableForce = $TotalAvailableShoots * $AForce; + + if($TotalAvailableShoots > $TotalShootsNeed) + { + if($TotalAvailableForce > $TotalForceNeed) + { + $GainedShoots = ceil($TotalForceNeed / $AForce); + if($GainedShoots < $TotalShootsNeed) + { + $GainedShoots = $TotalShootsNeed; + } + if($GainedShoots == $TotalAvailableShoots) + { + $NoMoreRapidFire = true; + } + else + { + $TotalEverAvailableShoots = $DefShipsTypesCount[$AShip][$AUser] * $ShipsSD['d'][$AUser][$AShip][$TShip]; + if(!isset($DefDontShootRF[$AKey])) + { + $DefDontShootRF[$AKey] = 0; + } + $DefDontShootRF[$AKey] += $GainedShoots / $TotalEverAvailableShoots; + } + } + else + { + $GainedShoots = $TotalAvailableShoots; + $NoMoreRapidFire = true; + } + } + else + { + $GainedShoots = $TotalAvailableShoots; + $NoMoreRapidFire = true; + } + + if($GainedShoots > 0) + { + if($AtkShipsTypes[$TShip] > 1) + { + $ACount_Temp = $GainedShoots; + foreach($TShipKeys as $Key => $Count) + { + $Count = floor(($Count/$TShipTotalCount) * $GainedShoots); + $ACount_Temp -= $Count; + $AShipsAssign[$Key] = $Count; + } + if($ACount_Temp > 0) + { + arsort($AShipsAssign); + foreach($AShipsAssign as $Key => &$Data) + { + $Data += $ACount_Temp; + break; + } + } + } + + foreach($AtkShipsTypesOwners[$TShip] as $Owner => $NotImportant) + { + $TKey = "{$TShip}|{$Owner}"; + $TUser = $Owner; + + if($AtkShipsTypes[$TShip] > 1) + { + $ACount = $AShipsAssign[$TKey]; + } + else + { + $ACount = $GainedShoots; + } + if($ACount == 0) + { + continue; + } + + // Here calculating firing + if($AForce >= ($AtkShipsShield[$TKey] * 0.01)) + { + $AvailableForce = $AForce * $ACount; + $Force2TDShield = 0; + if(($AForce * 0.01) < $AtkShipsShield[$TKey]) + { + if(isset($AtkShields[$TKey]['left']) && $AtkShields[$TKey]['left'] === true) + { + $Force2TDShield = $AtkShields[$TKey]['shield']; + } + else + { + $Force2TDShield = $AtkShipsShield[$TKey] * $AtkShipsTypesCount[$TShip][$TUser]; + } + } + if($AvailableForce > $Force2TDShield) + { + if(($AForce * 0.01) < $AtkShipsShield[$TKey]) + { + $AtkShields[$TKey] = array('left' => true, 'shield' => 0); + } + $LeftForce = $AvailableForce - $Force2TDShield; + if($ACount < ($AtkShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedAtk[$TKey]) ? $AlreadyDestroyedAtk[$TKey] : 0))) + { + $Able2Destroy = $ACount; + } + else + { + $Able2Destroy = ($AtkShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedAtk[$TKey]) ? $AlreadyDestroyedAtk[$TKey] : 0)); + } + $NeedForce = ($AtkShipsHull[$TKey] * $Able2Destroy); + if(isset($AtkHullDmg[$TKey])) + { + $NeedForce -= ($AtkHullDmg[$TKey] * $AtkShipsHull[$TKey]); + } + if($NeedForce > $LeftForce) + { + $UsedForce = $LeftForce + $Force2TDShield; + $Shoots = $UsedForce / $AForce; + $DestroyedOrg = ($LeftForce / $AtkShipsHull[$TKey]); + if(isset($AtkHullDmg[$TKey])) + { + $DestroyedOrg += $AtkHullDmg[$TKey]; + } + $Destroyed = floor($LeftForce / $AtkShipsHull[$TKey]); + $Difference = $DestroyedOrg - $Destroyed; + $AtkHullDmg[$TKey] = $Difference; + if($AtkHullDmg[$TKey] >= 1) + { + $Destroyed += 1; + $AtkHullDmg[$TKey] -= 1; + } + } + else + { + $UsedForce = $NeedForce + $Force2TDShield; + $Shoots = ceil($UsedForce / $AForce); + if($Shoots < $Able2Destroy) + { + $Shoots = $Able2Destroy; + } + $Destroyed = $Able2Destroy; + } + $Rounds[$i]['def']['force'] += $UsedForce; + $Rounds[$i]['def']['count'] += $Shoots; + $Rounds[$i]['atk']['shield'] += $Force2TDShield; + + if(!isset($AtkLost[$TShip][$TUser])) + { + $AtkLost[$TShip][$TUser] = 0; + } + if(!isset($ForceContribution['def'][$AUser])) + { + $ForceContribution['def'][$AUser] = 0; + } + if(!isset($ShotDown['def']['d'][$AUser][$TShip])) + { + $ShotDown['def']['d'][$AUser][$TShip] = 0; + } + if(!isset($ShotDown['atk']['l'][$TUser][$TShip])) + { + $ShotDown['atk']['l'][$TUser][$TShip] = 0; + } + + $AtkLost[$TShip][$TUser] += $Destroyed; + $ForceContribution['def'][$AUser] += $UsedForce; + $ShotDown['def']['d'][$AUser][$TShip] += $Destroyed; + $ShotDown['atk']['l'][$TUser][$TShip] += $Destroyed; + if($Destroyed == ($AtkShipsTypesCount[$TShip][$TUser] - (isset($AlreadyDestroyedAtk[$TKey]) ? $AlreadyDestroyedAtk[$ThisKey] : 0))) + { + unset($AtkShipsForce_Copy[$TKey]); + if(isset($AtkHullDmg[$TKey])) + { + unset($AtkHullDmg[$TKey]); + } + unset($AtkShipsTypesOwners[$TShip][$TUser]); + $AtkShipsTypes[$TShip] -= 1; + } + else + { + if($Destroyed > 0) + { + if(!isset($AlreadyDestroyedAtk[$TKey])) + { + $AlreadyDestroyedAtk[$TKey] = 0; + } + $AlreadyDestroyedAtk[$TKey] += $Destroyed; + } + } + } + else + { + $Rounds[$i]['def']['force'] += $AvailableForce; + $Rounds[$i]['def']['count'] += $ACount; + $Rounds[$i]['atk']['shield'] += $AvailableForce; + $AtkShields[$TKey] = array('left' => true, 'shield' => $Force2TDShield - $AvailableForce); + } + } + else + { + $UsedForce = $AForce * $ACount; + $Rounds[$i]['def']['force'] += $UsedForce; + $Rounds[$i]['def']['count'] += $ACount; + $Rounds[$i]['atk']['shield'] += $UsedForce; + } + } + } + } + } + } + } + } + + // ------------------------------------------------------------------------------------------------------------------------------------ + + // Now Calculate all loses and update all Arrays + // --------------------------------------------- + + // Defenders + foreach($DefLost as $ShipID => $ShipUsers) + { + $ShipKey = "{$ShipID}|"; + foreach($ShipUsers as $User => $Count) + { + $UserKey = "{$ShipKey}{$User}"; + if($Count == $DefenderShips[$User][$ShipID]) + { + unset($DefenderShips[$User][$ShipID]); + unset($DefShipsForce[$UserKey]); + } + else + { + $DefenderShips[$User][$ShipID] -= $Count; + $DefShipsTypesCount[$ShipID][$User] -= $Count; + } + if(!isset($DefLoseCount[$ShipID])) + { + $DefLoseCount[$ShipID] = 0; + } + $DefLoseCount[$ShipID] += $Count; + if($User == 0) + { + if($ShipID > 400 AND $ShipID < 500) + { + if(!isset($PlanetDefSysLost[$ShipID])) + { + $PlanetDefSysLost[$ShipID] = 0; + } + $PlanetDefSysLost[$ShipID] += $Count; + } + } + } + } + foreach($DefenderShips as $User => $Data) + { + if(empty($Data)) + { + unset($DefenderShips[$User]); + } + } + if(empty($DefenderShips)) + { + unset($DefenderShips); + } + + // Attackers + foreach($AtkLost as $ShipID => $ShipUsers) + { + $ShipKey = "{$ShipID}|"; + foreach($ShipUsers as $User => $Count) + { + $UserKey = "{$ShipKey}{$User}"; + if($Count == $AttackerShips[$User][$ShipID]) + { + unset($AttackerShips[$User][$ShipID]); + unset($AtkShipsForce[$UserKey]); + } + else + { + $AttackerShips[$User][$ShipID] -= $Count; + $AtkShipsTypesCount[$ShipID][$User] -= $Count; + } + if(!isset($AtkLoseCount[$ShipID])) + { + $AtkLoseCount[$ShipID] = 0; + } + $AtkLoseCount[$ShipID] += $Count; + } + } + foreach($AttackerShips as $User => $Data) + { + if(empty($Data)) + { + unset($AttackerShips[$User]); + } + } + if(empty($AttackerShips)) + { + unset($AttackerShips); + } + } + + if((!empty($AttackerShips) AND !empty($DefenderShips)) OR (empty($AttackerShips) AND empty($DefenderShips))) + { + $BattleResult = COMBAT_DRAW; // It's a Draw + } + else if(empty($AttackerShips)) + { + $BattleResult = COMBAT_DEF;// Defenders Won! + } + else if(empty($DefenderShips)) + { + $BattleResult = COMBAT_ATK;// Attackers Won! + } + else + { + return array('result' => false, 'error' => 'BAD_COMBAT_RESULT'); + } + + return array + ( + 'return' => true, + 'AttackerShips' => (isset($AttackerShips) ? $AttackerShips : null), + 'DefenderShips' => (isset($DefenderShips) ? $DefenderShips : null), + 'rounds' => $Rounds, 'result' => $BattleResult, + 'AtkLose' => $AtkLoseCount, 'DefLose' => $DefLoseCount, 'DefSysLost' => $PlanetDefSysLost, + 'ShotDown' => (isset($ShotDown) ? $ShotDown : null), 'ForceContribution' => (isset($ForceContribution) ? $ForceContribution : null) + ); +} + +?> diff --git a/includes/CombatEngineV2.php b/includes/CombatEngineV2.php index 1a3fcde01..c5312e4ce 100644 --- a/includes/CombatEngineV2.php +++ b/includes/CombatEngineV2.php @@ -1,612 +1,612 @@ - $Ships){ - foreach($Ships as $ID => $Count){ - $DefenderShips[$User][$ID] += $Count; - $DefenderShipList[$User][] = $ID; - $DefenderUsers[$User] = true; - if(empty($ShipsHullValues[$ID])){ - $ShipsHullValues[$ID] = ($_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal']) / 10; - } - } - } - foreach($DefenderTech as $User => &$Techs){ - $Techs['tech_armour'] = 1 + (0.1 * $Techs['tech_armour']); - $Techs['tech_shielding'] = 1 + (0.1 * $Techs['tech_shielding']); - $Techs['tech_weapons'] = 1 + (0.1 * $Techs['tech_weapons']); - } - } else { - $DefendersCount = 1; - $DefenderShips = false; - } - - if(!empty($Attacker)){ - $AttackersCount = count($Attacker); - //$AttackerShips = array(); - foreach($Attacker as $User => $Ships){ - foreach($Ships as $ID => $Count){ - $AttackerShips[$User][$ID] += $Count; - $AttackerShipList[$User][] = $ID; - $AttackerUsers[$User] = true; - if(empty($ShipsHullValues[$ID])){ - $ShipsHullValues[$ID] = ($_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal']) / 10; - } - } - } - foreach($AttackerTech as $User => &$Techs){ - $Techs['tech_armour'] = 1 + (0.1 * $Techs['tech_armour']); - $Techs['tech_shielding'] = 1 + (0.1 * $Techs['tech_shielding']); - $Techs['tech_weapons'] = 1 + (0.1 * $Techs['tech_weapons']); - } - } else { - return array('result' => false, 'error' => 'NO_ATTACKER'); - } - - $RoundsLimit = BATTLE_MAX_ROUNDS + 1; - for($i = 1; $i <= $RoundsLimit; $i += 1){ - $AttackerForce = 0; - $AttackerShield = -1; - $AttackerCount = 0; - $AttackerForReport = array(); - $AttackerDestroyedTarget = false; - $AttackerLost = array(); - $DefenderForce = 0; - $DefenderShield = -1; - $DefenderCount = 0; - $DefenderForReport = array(); - $DefenderDestroyedTarget = false; - $DefenderLost = array(); - $CalcAtkRapidFire = true; - $CalcDefRapidFire = true; - $Break = false; - $DoNotCalcExplosion = array(); - $AtkShipDestroyedInExplosion= false; - $DefShipDestroyedInExplosion= false; - - $Rounds[$i]['atk']['ships'] = $AttackerShips; - $Rounds[$i]['def']['ships'] = $DefenderShips; - - if($i > BATTLE_MAX_ROUNDS){ - break; - } - - if(empty($AttackerShips) OR empty($DefenderShips)){ - break; - } - - // Calculate Attacker(s) Force - // -------------------------------------------- - // 1. Get Target - $AttackerTargetUser = array_rand($DefenderUsers); - $AttackerTarget = array_rand($DefenderShipList[$AttackerTargetUser]); - $AttackerTargetIndex = $AttackerTarget; - $AttackerTarget = $DefenderShipList[$AttackerTargetUser][$AttackerTarget]; - - // 2. Calculate Force - foreach($AttackerShips as $User => $Ships){ - foreach($Ships as $ID => $Count){ - $AttackerForce += $Count * $_Vars_CombatData[$ID]['attack'] * $AttackerTech[$User]['tech_weapons']; - $AttackerCount += $Count; - } - } - // -------------------------------------------- - // End of Calculations for Attacker(s) - - - // Calculate Defender(s) Force - // -------------------------------------------- - // 1. Get Target - $DefenderTargetUser = array_rand($AttackerUsers); - $DefenderTarget = array_rand($AttackerShipList[$DefenderTargetUser]); - $DefenderTargetIndex = $DefenderTarget; - $DefenderTarget = $AttackerShipList[$DefenderTargetUser][$DefenderTarget]; - - // 2. Calculate Force - foreach($DefenderShips as $User => $Ships){ - foreach($Ships as $ID => $Count){ - $DefenderForce += $Count * $_Vars_CombatData[$ID]['attack'] * $DefenderTech[$User]['tech_weapons']; - $DefenderCount += $Count; - } - } - // -------------------------------------------- - // End of Calculations for Defender(s) - - // -------------------------------------------- - // Calculate Destruction - Now firing Attacker - $Rounds[$i]['atk']['force'] = $AttackerForce; - $Rounds[$i]['atk']['count'] = $AttackerCount; - while($AttackerForce > 0){ - $ClearForce = false; - $Destroyed = 0; - $AttackerDestroyedTarget = false; - - if($DefenderShield < 0){ - $DefenderShield = $DefenderShips[$AttackerTargetUser][$AttackerTarget] * $_Vars_CombatData[$AttackerTarget]['shield'] * $DefenderTech[$AttackerTargetUser]['tech_shielding']; - if($DefenderShield > $AttackerForce){ - $Rounds[$i]['def']['shield'] = $AttackerForce; - } else { - $Rounds[$i]['def']['shield'] = $DefenderShield; - } - $AttackerForce -= $DefenderShield; - $DefenderShield -= $Rounds[$i]['def']['shield']; - } - if($AttackerForce <= 0){ - break; - } - $HowManyCouldDestroy = $AttackerForce / ($ShipsHullValues[$AttackerTarget] * $DefenderTech[$AttackerTargetUser]['tech_armour']); - - if($HowManyCouldDestroy >= $DefenderShips[$AttackerTargetUser][$AttackerTarget]){ - $Destroyed = $DefenderShips[$AttackerTargetUser][$AttackerTarget]; - $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] = 0; - $AttackerDestroyedTarget = true; - } else { - $HowManyCouldDestroyReal = floor($HowManyCouldDestroy); - $ChanceToBlow = $HowManyCouldDestroy - $HowManyCouldDestroyReal; - - if($ChanceToBlow < 1){ - $ClearForce = true; - } - - if($HowManyCouldDestroy < 1 AND $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] > 0){ - $ChanceToBlow += $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget]; - } - if($ChanceToBlow > 0.3){ - if($ChanceToBlow >= 1 OR mt_rand(1,100) <= ($ChanceToBlow * 100)){ - $HowManyCouldDestroyReal += 1; - $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] = 0; - $DefShipDestroyedInExplosion = true; - } else { - $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] = $ChanceToBlow; - } - $DoNotCalcExplosion['def'][$AttackerTargetUser][$AttackerTarget] = 1; - } else { - $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] = $ChanceToBlow; - } - if($HowManyCouldDestroyReal >= $DefenderShips[$AttackerTargetUser][$AttackerTarget]){ - $Destroyed = $DefenderShips[$AttackerTargetUser][$AttackerTarget]; - $AttackerDestroyedTarget = true; - } else { - $Destroyed = $HowManyCouldDestroyReal; - } - } - $DefenderLost[$AttackerTargetUser][$AttackerTarget] += $Destroyed; - $DefLoseCount[$AttackerTarget] += $Destroyed; - if($AttackerTargetUser == 0 AND $AttackerTarget > 400 AND $AttackerTarget < 500){ - $PlanetDefSysLost[$AttackerTarget] += $Destroyed; - } - if($ClearForce){ - if($HowManyCouldDestroyReal <= $Destroyed){ - $AttackerForce = 0; - } - } else { - $AttackerForce -= ($ShipsHullValues[$AttackerTarget] * $DefenderTech[$AttackerTargetUser]['tech_armour']) * $Destroyed; - } - if($AttackerDestroyedTarget){ - unset($DefenderShipList[$AttackerTargetUser][$AttackerTargetIndex]); - if(empty($DefenderShipList[$AttackerTargetUser])){ - unset($DefenderShipList[$AttackerTargetUser]); - unset($DefenderUsers[$AttackerTargetUser]); - } - if(empty($DefenderShipList)){ - $CalcAtkRapidFire = false; - break; - } - if($AttackerForce > 0 OR ($UseRapidFire == TRUE AND $CalcAtkRapidFire == TRUE)){ - $AttackerTargetUser = array_rand($DefenderUsers); - $AttackerTarget = array_rand($DefenderShipList[$AttackerTargetUser]); - $AttackerTargetIndex = $AttackerTarget; - $AttackerTarget = $DefenderShipList[$AttackerTargetUser][$AttackerTarget]; - $DefenderShield = -1; - } - } - } - - - // Calculate Rapid Fire - if($UseRapidFire){ - if($CalcAtkRapidFire){ - $RapidFireMaxShips = 0; - foreach($AttackerShips as $User => $Ships){ - foreach($Ships as $ID => $Count){ - if($_Vars_CombatData[$ID]['sd'][$AttackerTarget] > 1){ - $Chance = floor((($_Vars_CombatData[$ID]['sd'][$AttackerTarget] - 1) / $_Vars_CombatData[$ID]['sd'][$AttackerTarget]) * 100); - for($SDCounter = 0; $SDCounter < $Count; $SDCounter += 1){ - while(mt_rand(1,100) <= $Chance){ - $CalcForce = $_Vars_CombatData[$ID]['attack'] * $AttackerTech[$AttackerTargetUser]['tech_weapons']; - $AttackerForce += $CalcForce; - $Rounds[$i]['atk']['count'] += 1; - $Rounds[$i]['atk']['force'] += $CalcForce; - $RapidFireMaxShips += 1; - } - } - } - } - } - - if($AttackerForce > 0){ - $Destroyed = 0; - $AttackerDestroyedTarget = false; - - $DefenderShipsLeft = $DefenderShips[$AttackerTargetUser][$AttackerTarget] - $DefenderLost[$AttackerTargetUser][$AttackerTarget]; - - if($DefenderShield < 0){ - $DefenderShield = $DefenderShipsLeft * $_Vars_CombatData[$AttackerTarget]['shield'] * $DefenderTech[$AttackerTargetUser]['tech_shielding']; - if($DefenderShield > $AttackerForce){ - $Rounds[$i]['def']['shield'] += $AttackerForce; - } else { - $Rounds[$i]['def']['shield'] += $DefenderShield; - } - $AttackerForce -= $DefenderShield; - } elseif($DefenderShield > 0){ - if($DefenderShield > $AttackerForce){ - $Rounds[$i]['def']['shield'] += $AttackerForce; - } else { - $Rounds[$i]['def']['shield'] += $DefenderShield; - } - $AttackerForce -= $DefenderShield; - } - - $HowManyCouldDestroy = $AttackerForce / ($ShipsHullValues[$AttackerTarget] * $DefenderTech[$AttackerTargetUser]['tech_armour']); - if($HowManyCouldDestroy > $RapidFireMaxShips){ - $HowManyCouldDestroy = $RapidFireMaxShips; - } - - if($HowManyCouldDestroy >= $DefenderShipsLeft){ - $Destroyed = $DefenderShipsLeft; - $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] = 0; - $AttackerDestroyedTarget = true; - } else { - $HowManyCouldDestroyReal = floor($HowManyCouldDestroy); - $ChanceToBlow = $HowManyCouldDestroy - $HowManyCouldDestroyReal; - if($HowManyCouldDestroy < 1 AND $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] > 0){ - $ChanceToBlow += $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget]; - } - if($ChanceToBlow > 0.3){ - if($ChanceToBlow >= 1 OR mt_rand(1,100) <= ($ChanceToBlow * 100)){ - $HowManyCouldDestroyReal += 1; - $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] = 0; - } else { - $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] = $ChanceToBlow; - } - $DoNotCalcExplosion['def'][$AttackerTargetUser][$AttackerTarget] = 1; - } else { - $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] = $ChanceToBlow; - } - if($HowManyCouldDestroyReal >= $DefenderShipsLeft){ - $Destroyed = $DefenderShipsLeft; - $AttackerDestroyedTarget = true; - } else { - $Destroyed = $HowManyCouldDestroyReal; - } - $ClearForce = true; - } - $DefenderLost[$AttackerTargetUser][$AttackerTarget] += $Destroyed; - $DefLoseCount[$AttackerTarget] += $Destroyed; - if($AttackerTargetUser == 0 AND $AttackerTarget > 400 AND $AttackerTarget < 500){ - $PlanetDefSysLost[$AttackerTarget] += $Destroyed; - } - if($AttackerDestroyedTarget){ - unset($DefenderShipList[$AttackerTargetUser][$AttackerTargetIndex]); - if(empty($DefenderShipList[$AttackerTargetUser])){ - unset($DefenderShipList[$AttackerTargetUser]); - unset($DefenderUsers[$AttackerTargetUser]); - } - } - } - } - } - - - // Calculate ships Explosion (Def Ships) - if(!empty($SaveHullDmg['def'])){ - foreach($SaveHullDmg['def'] as $User => $Ships){ - foreach($Ships as $Ship => $ExplosionChance){ - if($DoNotCalcExplosion['def'][$User][$Ship] != 1){ - if($ExplosionChance > 0.3){ - if($ExplosionChance >= 1 OR mt_rand(1,100) <= ($ExplosionChance * 100)){ - $SaveHullDmg['def'][$User][$Ship] = 0; - $DefenderLost[$User][$Ship] += 1; - $DefLoseCount[$Ship] += 1; - if($User == 0 AND $Ship > 400 AND $Ship < 500){ - $PlanetDefSysLost[$Ship] += 1; - } - - if($DefenderLost[$User][$Ship] >= $DefenderShips[$User][$Ship]){ - unset($DefenderShipList[$User][$Ship]); - if(empty($DefenderShipList[$User])){ - unset($DefenderShipList[$User]); - unset($DefenderUsers[$User]); - } - } - } - } - } - } - } - } - - - // End of Calculations - // -------------------------------------------- - - // -------------------------------------------- - // Calculate Destruction - Now firing Defender - - $Rounds[$i]['def']['force'] = $DefenderForce; - $Rounds[$i]['def']['count'] = $DefenderCount; - while($DefenderForce > 0){ - $ClearForce = false; - $Destroyed = 0; - $DefenderDestroyedTarget = false; - - if($AttackerShield < 0){ - $AttackerShield = $AttackerShips[$DefenderTargetUser][$DefenderTarget] * $_Vars_CombatData[$DefenderTarget]['shield'] * $DefenderTech[$DefenderTargetUser]['tech_shielding']; - if($AttackerShield > $DefenderForce){ - $Rounds[$i]['atk']['shield'] = $DefenderForce; - } else { - $Rounds[$i]['atk']['shield'] = $AttackerShield; - } - $DefenderForce -= $AttackerShield; - $AttackerShield -= $Rounds[$i]['atk']['shield']; - } - if($DefenderForce <= 0){ - break; - } - $HowManyCouldDestroy = $DefenderForce / ($ShipsHullValues[$DefenderTarget] * $AttackerTech[$DefenderTargetUser]['tech_armour']); - - if($HowManyCouldDestroy >= $AttackerShips[$DefenderTargetUser][$DefenderTarget]){ - $Destroyed = $AttackerShips[$DefenderTargetUser][$DefenderTarget]; - $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] = 0; - $DefenderDestroyedTarget = true; - } else { - $HowManyCouldDestroyReal = floor($HowManyCouldDestroy); - $ChanceToBlow = $HowManyCouldDestroy - $HowManyCouldDestroyReal; - - if($ChanceToBlow < 1){ - $ClearForce = true; - } - - if($HowManyCouldDestroy < 1 AND $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] > 0){ - $ChanceToBlow += $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget]; - } - if($ChanceToBlow > 0.3){ - if($ChanceToBlow >= 1 OR mt_rand(1,100) <= ($ChanceToBlow * 100)){ - $HowManyCouldDestroyReal += 1; - $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] = 0; - $AtkShipDestroyedInExplosion = true; - } else { - $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] = $ChanceToBlow; - } - $DoNotCalcExplosion['atk'][$DefenderTargetUser][$DefenderTarget] = 1; - } else { - $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] = $ChanceToBlow; - } - if($HowManyCouldDestroyReal >= $AttackerShips[$DefenderTargetUser][$DefenderTarget]){ - $Destroyed = $AttackerShips[$DefenderTargetUser][$DefenderTarget]; - $DefenderDestroyedTarget = true; - } else { - $Destroyed = $HowManyCouldDestroyReal; - } - } - $AttackerLost[$DefenderTargetUser][$DefenderTarget] += $Destroyed; - $AtkLoseCount[$DefenderTarget] += $Destroyed; - if($ClearForce){ - if($HowManyCouldDestroyReal <= $Destroyed){ - $DefenderForce = 0; - } - } else { - $DefenderForce -= ($ShipsHullValues[$DefenderTarget] * $AttackerTech[$DefenderTargetUser]['tech_armour']) * $Destroyed; - } - if($DefenderDestroyedTarget){ - unset($AttackerShipList[$DefenderTargetUser][$DefenderTargetIndex]); - if(empty($AttackerShipList[$DefenderTargetUser])){ - unset($AttackerShipList[$DefenderTargetUser]); - unset($AttackerUsers[$DefenderTargetUser]); - } - if(empty($AttackerShipList)){ - $CalcDefRapidFire = false; - break; - } - if($DefenderForce > 0 OR ($UseRapidFire == TRUE AND $CalcDefRapidFire == TRUE)){ - $DefenderTargetUser = array_rand($AttackerUsers); - $DefenderTarget = array_rand($AttackerShipList[$DefenderTargetUser]); - $DefenderTargetIndex = $DefenderTarget; - $DefenderTarget = $AttackerShipList[$DefenderTargetUser][$DefenderTarget]; - $AttackerShield = -1; - } - } - } - - - // Calculate Rapid Fire - if($UseRapidFire){ - if($CalcDefRapidFire){ - $RapidFireMaxShips = 0; - foreach($DefenderShips as $User => $Ships){ - foreach($Ships as $ID => $Count){ - if($_Vars_CombatData[$ID]['sd'][$DefenderTarget] > 1){ - $Chance = floor((($_Vars_CombatData[$ID]['sd'][$DefenderTarget] - 1) / $_Vars_CombatData[$ID]['sd'][$DefenderTarget]) * 100); - for($SDCounter = 0; $SDCounter < $Count; $SDCounter += 1){ - while(mt_rand(1,100) <= $Chance){ - $CalcForce = $_Vars_CombatData[$ID]['attack'] * $DefenderTech[$DefenderTargetUser]['tech_weapons']; - $DefenderForce += $CalcForce; - $Rounds[$i]['def']['count'] += 1; - $Rounds[$i]['def']['force'] += $CalcForce; - $RapidFireMaxShips += 1; - } - } - } - } - } - - if($DefenderForce > 0){ - $Destroyed = 0; - $DefenderDestroyedTarget = false; - - $AttackerShipsLeft = $AttackerShips[$DefenderTargetUser][$DefenderTarget] - $AttackerLost[$DefenderTargetUser][$DefenderTarget]; - - if($AttackerShield < 0){ - $AttackerShield = $AttackerShipsLeft * $_Vars_CombatData[$DefenderTarget]['shield'] * $AttackerTech[$DefenderTargetUser]['tech_shielding']; - if($AttackerShield > $DefenderForce){ - $Rounds[$i]['atk']['shield'] += $DefenderForce; - } else { - $Rounds[$i]['atk']['shield'] += $AttackerShield; - } - $DefenderForce -= $AttackerShield; - } elseif($AttackerShield > 0){ - if($AttackerShield > $DefenderForce){ - $Rounds[$i]['atk']['shield'] += $DefenderForce; - } else { - $Rounds[$i]['atk']['shield'] += $AttackerShield; - } - $DefenderForce -= $AttackerShield; - } - - $HowManyCouldDestroy = $DefenderForce / ($ShipsHullValues[$DefenderTarget] * $AttackerTech[$DefenderTargetUser]['tech_armour']); - if($HowManyCouldDestroy > $RapidFireMaxShips){ - $HowManyCouldDestroy = $RapidFireMaxShips; - } - - if($HowManyCouldDestroy >= $AttackerShipsLeft){ - $Destroyed = $AttackerShipsLeft; - $SaveHullDmg['def'][$DefenderTargetUser][$DefenderTarget] = 0; - $DefenderDestroyedTarget = true; - } else { - $HowManyCouldDestroyReal = floor($HowManyCouldDestroy); - $ChanceToBlow = $HowManyCouldDestroy - $HowManyCouldDestroyReal; - if($HowManyCouldDestroy < 1 AND $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] > 0){ - $ChanceToBlow += $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget]; - } - if($ChanceToBlow > 0.3){ - if($ChanceToBlow >= 1 OR mt_rand(1,100) <= ($ChanceToBlow * 100)){ - $HowManyCouldDestroyReal += 1; - $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] = 0; - } else { - $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] = $ChanceToBlow; - } - $DoNotCalcExplosion['atk'][$DefenderTargetUser][$DefenderTarget] = 1; - } else { - $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] = $ChanceToBlow; - } - if($HowManyCouldDestroyReal >= $AttackerShipsLeft){ - $Destroyed = $AttackerShipsLeft; - $DefenderDestroyedTarget = true; - } else { - $Destroyed = $HowManyCouldDestroyReal; - } - $ClearForce = true; - } - $AttackerLost[$DefenderTargetUser][$DefenderTarget] += $Destroyed; - $AtkLoseCount[$DefenderTarget] += $Destroyed; - if($DefenderDestroyedTarget){ - unset($AttackerShipList[$DefenderTargetUser][$DefenderTargetIndex]); - if(empty($AttackerShipList[$DefenderTargetUser])){ - unset($AttackerShipList[$DefenderTargetUser]); - unset($AttackerUsers[$DefenderTargetUser]); - } - } - } - } - } - - // Calculate ships Explosion (Atk Ships) - if(!empty($SaveHullDmg['atk'])){ - foreach($SaveHullDmg['atk'] as $User => $Ships){ - foreach($Ships as $Ship => $ExplosionChance){ - if($DoNotCalcExplosion['atk'][$User][$Ship] != 1){ - if($ExplosionChance > 0.3){ - if($ExplosionChance >= 1 OR mt_rand(1,100) <= ($ExplosionChance * 100)){ - $SaveHullDmg['atk'][$User][$Ship] = 0; - $AttackerLost[$User][$Ship] += 1; - $AtkLoseCount[$Ship] += 1; - - if($AttackerLost[$User][$Ship] >= $AttackerShips[$User][$Ship]){ - unset($AttackerShipList[$User][$Ship]); - if(empty($AttackerShipList[$User])){ - unset($AttackerShipList[$User]); - unset($AttackerUsers[$User]); - } - } - } - } - } - } - } - } - - // End of Calculations - // -------------------------------------------- - - if(!empty($AttackerLost)){ - foreach($AttackerLost as $User => $Ships){ - foreach($Ships as $ID => $Count){ - if($Count > 0){ - if($AttackerShips[$User][$ID] <= $Count){ - unset($AttackerShips[$User][$ID]); - } else { - $AttackerShips[$User][$ID] -= $Count; - } - } - } - } - } - - if(!empty($DefenderLost)){ - foreach($DefenderLost as $User => $Ships){ - foreach($Ships as $ID => $Count){ - if($Count > 0){ - if($DefenderShips[$User][$ID] <= $Count){ - unset($DefenderShips[$User][$ID]); - } else { - $DefenderShips[$User][$ID] -= $Count; - } - } - } - } - } - - if(empty($DefenderShipList)){ - unset($DefenderShips); - } - if(empty($AttackerShipList)){ - unset($AttackerShips); - } - - } - - if((!empty($AttackerShips) AND !empty($DefenderShips)) OR (empty($AttackerShips) AND empty($DefenderShips))){ - $BattleResult = COMBAT_DRAW; // It's a Draw - } elseif(empty($AttackerShips)){ - $BattleResult = COMBAT_DEF; // Defenders Won! - } elseif(empty($DefenderShips)){ - $BattleResult = COMBAT_ATK; // Attackers Won! - } else { - return array('result' => false, 'error' => 'BAD_COMBAT_RESULT'); - } - - return array('return' => true, 'AttackerShips' => $AttackerShips, 'DefenderShips' => $DefenderShips, 'rounds' => $Rounds, 'result' => $BattleResult, 'AtkLose' => $AtkLoseCount, 'DefLose' => $DefLoseCount, 'DefSysLost' => $PlanetDefSysLost); -} - -?> \ No newline at end of file + $Ships){ + foreach($Ships as $ID => $Count){ + $DefenderShips[$User][$ID] += $Count; + $DefenderShipList[$User][] = $ID; + $DefenderUsers[$User] = true; + if(empty($ShipsHullValues[$ID])){ + $ShipsHullValues[$ID] = ($_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal']) / 10; + } + } + } + foreach($DefenderTech as $User => &$Techs){ + $Techs['tech_armour'] = 1 + (0.1 * $Techs['tech_armour']); + $Techs['tech_shielding'] = 1 + (0.1 * $Techs['tech_shielding']); + $Techs['tech_weapons'] = 1 + (0.1 * $Techs['tech_weapons']); + } + } else { + $DefendersCount = 1; + $DefenderShips = false; + } + + if(!empty($Attacker)){ + $AttackersCount = count($Attacker); + //$AttackerShips = array(); + foreach($Attacker as $User => $Ships){ + foreach($Ships as $ID => $Count){ + $AttackerShips[$User][$ID] += $Count; + $AttackerShipList[$User][] = $ID; + $AttackerUsers[$User] = true; + if(empty($ShipsHullValues[$ID])){ + $ShipsHullValues[$ID] = ($_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal']) / 10; + } + } + } + foreach($AttackerTech as $User => &$Techs){ + $Techs['tech_armour'] = 1 + (0.1 * $Techs['tech_armour']); + $Techs['tech_shielding'] = 1 + (0.1 * $Techs['tech_shielding']); + $Techs['tech_weapons'] = 1 + (0.1 * $Techs['tech_weapons']); + } + } else { + return array('result' => false, 'error' => 'NO_ATTACKER'); + } + + $RoundsLimit = BATTLE_MAX_ROUNDS + 1; + for($i = 1; $i <= $RoundsLimit; $i += 1){ + $AttackerForce = 0; + $AttackerShield = -1; + $AttackerCount = 0; + $AttackerForReport = array(); + $AttackerDestroyedTarget = false; + $AttackerLost = array(); + $DefenderForce = 0; + $DefenderShield = -1; + $DefenderCount = 0; + $DefenderForReport = array(); + $DefenderDestroyedTarget = false; + $DefenderLost = array(); + $CalcAtkRapidFire = true; + $CalcDefRapidFire = true; + $Break = false; + $DoNotCalcExplosion = array(); + $AtkShipDestroyedInExplosion= false; + $DefShipDestroyedInExplosion= false; + + $Rounds[$i]['atk']['ships'] = $AttackerShips; + $Rounds[$i]['def']['ships'] = $DefenderShips; + + if($i > BATTLE_MAX_ROUNDS){ + break; + } + + if(empty($AttackerShips) OR empty($DefenderShips)){ + break; + } + + // Calculate Attacker(s) Force + // -------------------------------------------- + // 1. Get Target + $AttackerTargetUser = array_rand($DefenderUsers); + $AttackerTarget = array_rand($DefenderShipList[$AttackerTargetUser]); + $AttackerTargetIndex = $AttackerTarget; + $AttackerTarget = $DefenderShipList[$AttackerTargetUser][$AttackerTarget]; + + // 2. Calculate Force + foreach($AttackerShips as $User => $Ships){ + foreach($Ships as $ID => $Count){ + $AttackerForce += $Count * $_Vars_CombatData[$ID]['attack'] * $AttackerTech[$User]['tech_weapons']; + $AttackerCount += $Count; + } + } + // -------------------------------------------- + // End of Calculations for Attacker(s) + + + // Calculate Defender(s) Force + // -------------------------------------------- + // 1. Get Target + $DefenderTargetUser = array_rand($AttackerUsers); + $DefenderTarget = array_rand($AttackerShipList[$DefenderTargetUser]); + $DefenderTargetIndex = $DefenderTarget; + $DefenderTarget = $AttackerShipList[$DefenderTargetUser][$DefenderTarget]; + + // 2. Calculate Force + foreach($DefenderShips as $User => $Ships){ + foreach($Ships as $ID => $Count){ + $DefenderForce += $Count * $_Vars_CombatData[$ID]['attack'] * $DefenderTech[$User]['tech_weapons']; + $DefenderCount += $Count; + } + } + // -------------------------------------------- + // End of Calculations for Defender(s) + + // -------------------------------------------- + // Calculate Destruction - Now firing Attacker + $Rounds[$i]['atk']['force'] = $AttackerForce; + $Rounds[$i]['atk']['count'] = $AttackerCount; + while($AttackerForce > 0){ + $ClearForce = false; + $Destroyed = 0; + $AttackerDestroyedTarget = false; + + if($DefenderShield < 0){ + $DefenderShield = $DefenderShips[$AttackerTargetUser][$AttackerTarget] * $_Vars_CombatData[$AttackerTarget]['shield'] * $DefenderTech[$AttackerTargetUser]['tech_shielding']; + if($DefenderShield > $AttackerForce){ + $Rounds[$i]['def']['shield'] = $AttackerForce; + } else { + $Rounds[$i]['def']['shield'] = $DefenderShield; + } + $AttackerForce -= $DefenderShield; + $DefenderShield -= $Rounds[$i]['def']['shield']; + } + if($AttackerForce <= 0){ + break; + } + $HowManyCouldDestroy = $AttackerForce / ($ShipsHullValues[$AttackerTarget] * $DefenderTech[$AttackerTargetUser]['tech_armour']); + + if($HowManyCouldDestroy >= $DefenderShips[$AttackerTargetUser][$AttackerTarget]){ + $Destroyed = $DefenderShips[$AttackerTargetUser][$AttackerTarget]; + $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] = 0; + $AttackerDestroyedTarget = true; + } else { + $HowManyCouldDestroyReal = floor($HowManyCouldDestroy); + $ChanceToBlow = $HowManyCouldDestroy - $HowManyCouldDestroyReal; + + if($ChanceToBlow < 1){ + $ClearForce = true; + } + + if($HowManyCouldDestroy < 1 AND $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] > 0){ + $ChanceToBlow += $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget]; + } + if($ChanceToBlow > 0.3){ + if($ChanceToBlow >= 1 OR mt_rand(1,100) <= ($ChanceToBlow * 100)){ + $HowManyCouldDestroyReal += 1; + $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] = 0; + $DefShipDestroyedInExplosion = true; + } else { + $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] = $ChanceToBlow; + } + $DoNotCalcExplosion['def'][$AttackerTargetUser][$AttackerTarget] = 1; + } else { + $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] = $ChanceToBlow; + } + if($HowManyCouldDestroyReal >= $DefenderShips[$AttackerTargetUser][$AttackerTarget]){ + $Destroyed = $DefenderShips[$AttackerTargetUser][$AttackerTarget]; + $AttackerDestroyedTarget = true; + } else { + $Destroyed = $HowManyCouldDestroyReal; + } + } + $DefenderLost[$AttackerTargetUser][$AttackerTarget] += $Destroyed; + $DefLoseCount[$AttackerTarget] += $Destroyed; + if($AttackerTargetUser == 0 AND $AttackerTarget > 400 AND $AttackerTarget < 500){ + $PlanetDefSysLost[$AttackerTarget] += $Destroyed; + } + if($ClearForce){ + if($HowManyCouldDestroyReal <= $Destroyed){ + $AttackerForce = 0; + } + } else { + $AttackerForce -= ($ShipsHullValues[$AttackerTarget] * $DefenderTech[$AttackerTargetUser]['tech_armour']) * $Destroyed; + } + if($AttackerDestroyedTarget){ + unset($DefenderShipList[$AttackerTargetUser][$AttackerTargetIndex]); + if(empty($DefenderShipList[$AttackerTargetUser])){ + unset($DefenderShipList[$AttackerTargetUser]); + unset($DefenderUsers[$AttackerTargetUser]); + } + if(empty($DefenderShipList)){ + $CalcAtkRapidFire = false; + break; + } + if($AttackerForce > 0 OR ($UseRapidFire == TRUE AND $CalcAtkRapidFire == TRUE)){ + $AttackerTargetUser = array_rand($DefenderUsers); + $AttackerTarget = array_rand($DefenderShipList[$AttackerTargetUser]); + $AttackerTargetIndex = $AttackerTarget; + $AttackerTarget = $DefenderShipList[$AttackerTargetUser][$AttackerTarget]; + $DefenderShield = -1; + } + } + } + + + // Calculate Rapid Fire + if($UseRapidFire){ + if($CalcAtkRapidFire){ + $RapidFireMaxShips = 0; + foreach($AttackerShips as $User => $Ships){ + foreach($Ships as $ID => $Count){ + if($_Vars_CombatData[$ID]['sd'][$AttackerTarget] > 1){ + $Chance = floor((($_Vars_CombatData[$ID]['sd'][$AttackerTarget] - 1) / $_Vars_CombatData[$ID]['sd'][$AttackerTarget]) * 100); + for($SDCounter = 0; $SDCounter < $Count; $SDCounter += 1){ + while(mt_rand(1,100) <= $Chance){ + $CalcForce = $_Vars_CombatData[$ID]['attack'] * $AttackerTech[$AttackerTargetUser]['tech_weapons']; + $AttackerForce += $CalcForce; + $Rounds[$i]['atk']['count'] += 1; + $Rounds[$i]['atk']['force'] += $CalcForce; + $RapidFireMaxShips += 1; + } + } + } + } + } + + if($AttackerForce > 0){ + $Destroyed = 0; + $AttackerDestroyedTarget = false; + + $DefenderShipsLeft = $DefenderShips[$AttackerTargetUser][$AttackerTarget] - $DefenderLost[$AttackerTargetUser][$AttackerTarget]; + + if($DefenderShield < 0){ + $DefenderShield = $DefenderShipsLeft * $_Vars_CombatData[$AttackerTarget]['shield'] * $DefenderTech[$AttackerTargetUser]['tech_shielding']; + if($DefenderShield > $AttackerForce){ + $Rounds[$i]['def']['shield'] += $AttackerForce; + } else { + $Rounds[$i]['def']['shield'] += $DefenderShield; + } + $AttackerForce -= $DefenderShield; + } elseif($DefenderShield > 0){ + if($DefenderShield > $AttackerForce){ + $Rounds[$i]['def']['shield'] += $AttackerForce; + } else { + $Rounds[$i]['def']['shield'] += $DefenderShield; + } + $AttackerForce -= $DefenderShield; + } + + $HowManyCouldDestroy = $AttackerForce / ($ShipsHullValues[$AttackerTarget] * $DefenderTech[$AttackerTargetUser]['tech_armour']); + if($HowManyCouldDestroy > $RapidFireMaxShips){ + $HowManyCouldDestroy = $RapidFireMaxShips; + } + + if($HowManyCouldDestroy >= $DefenderShipsLeft){ + $Destroyed = $DefenderShipsLeft; + $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] = 0; + $AttackerDestroyedTarget = true; + } else { + $HowManyCouldDestroyReal = floor($HowManyCouldDestroy); + $ChanceToBlow = $HowManyCouldDestroy - $HowManyCouldDestroyReal; + if($HowManyCouldDestroy < 1 AND $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] > 0){ + $ChanceToBlow += $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget]; + } + if($ChanceToBlow > 0.3){ + if($ChanceToBlow >= 1 OR mt_rand(1,100) <= ($ChanceToBlow * 100)){ + $HowManyCouldDestroyReal += 1; + $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] = 0; + } else { + $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] = $ChanceToBlow; + } + $DoNotCalcExplosion['def'][$AttackerTargetUser][$AttackerTarget] = 1; + } else { + $SaveHullDmg['def'][$AttackerTargetUser][$AttackerTarget] = $ChanceToBlow; + } + if($HowManyCouldDestroyReal >= $DefenderShipsLeft){ + $Destroyed = $DefenderShipsLeft; + $AttackerDestroyedTarget = true; + } else { + $Destroyed = $HowManyCouldDestroyReal; + } + $ClearForce = true; + } + $DefenderLost[$AttackerTargetUser][$AttackerTarget] += $Destroyed; + $DefLoseCount[$AttackerTarget] += $Destroyed; + if($AttackerTargetUser == 0 AND $AttackerTarget > 400 AND $AttackerTarget < 500){ + $PlanetDefSysLost[$AttackerTarget] += $Destroyed; + } + if($AttackerDestroyedTarget){ + unset($DefenderShipList[$AttackerTargetUser][$AttackerTargetIndex]); + if(empty($DefenderShipList[$AttackerTargetUser])){ + unset($DefenderShipList[$AttackerTargetUser]); + unset($DefenderUsers[$AttackerTargetUser]); + } + } + } + } + } + + + // Calculate ships Explosion (Def Ships) + if(!empty($SaveHullDmg['def'])){ + foreach($SaveHullDmg['def'] as $User => $Ships){ + foreach($Ships as $Ship => $ExplosionChance){ + if($DoNotCalcExplosion['def'][$User][$Ship] != 1){ + if($ExplosionChance > 0.3){ + if($ExplosionChance >= 1 OR mt_rand(1,100) <= ($ExplosionChance * 100)){ + $SaveHullDmg['def'][$User][$Ship] = 0; + $DefenderLost[$User][$Ship] += 1; + $DefLoseCount[$Ship] += 1; + if($User == 0 AND $Ship > 400 AND $Ship < 500){ + $PlanetDefSysLost[$Ship] += 1; + } + + if($DefenderLost[$User][$Ship] >= $DefenderShips[$User][$Ship]){ + unset($DefenderShipList[$User][$Ship]); + if(empty($DefenderShipList[$User])){ + unset($DefenderShipList[$User]); + unset($DefenderUsers[$User]); + } + } + } + } + } + } + } + } + + + // End of Calculations + // -------------------------------------------- + + // -------------------------------------------- + // Calculate Destruction - Now firing Defender + + $Rounds[$i]['def']['force'] = $DefenderForce; + $Rounds[$i]['def']['count'] = $DefenderCount; + while($DefenderForce > 0){ + $ClearForce = false; + $Destroyed = 0; + $DefenderDestroyedTarget = false; + + if($AttackerShield < 0){ + $AttackerShield = $AttackerShips[$DefenderTargetUser][$DefenderTarget] * $_Vars_CombatData[$DefenderTarget]['shield'] * $DefenderTech[$DefenderTargetUser]['tech_shielding']; + if($AttackerShield > $DefenderForce){ + $Rounds[$i]['atk']['shield'] = $DefenderForce; + } else { + $Rounds[$i]['atk']['shield'] = $AttackerShield; + } + $DefenderForce -= $AttackerShield; + $AttackerShield -= $Rounds[$i]['atk']['shield']; + } + if($DefenderForce <= 0){ + break; + } + $HowManyCouldDestroy = $DefenderForce / ($ShipsHullValues[$DefenderTarget] * $AttackerTech[$DefenderTargetUser]['tech_armour']); + + if($HowManyCouldDestroy >= $AttackerShips[$DefenderTargetUser][$DefenderTarget]){ + $Destroyed = $AttackerShips[$DefenderTargetUser][$DefenderTarget]; + $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] = 0; + $DefenderDestroyedTarget = true; + } else { + $HowManyCouldDestroyReal = floor($HowManyCouldDestroy); + $ChanceToBlow = $HowManyCouldDestroy - $HowManyCouldDestroyReal; + + if($ChanceToBlow < 1){ + $ClearForce = true; + } + + if($HowManyCouldDestroy < 1 AND $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] > 0){ + $ChanceToBlow += $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget]; + } + if($ChanceToBlow > 0.3){ + if($ChanceToBlow >= 1 OR mt_rand(1,100) <= ($ChanceToBlow * 100)){ + $HowManyCouldDestroyReal += 1; + $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] = 0; + $AtkShipDestroyedInExplosion = true; + } else { + $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] = $ChanceToBlow; + } + $DoNotCalcExplosion['atk'][$DefenderTargetUser][$DefenderTarget] = 1; + } else { + $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] = $ChanceToBlow; + } + if($HowManyCouldDestroyReal >= $AttackerShips[$DefenderTargetUser][$DefenderTarget]){ + $Destroyed = $AttackerShips[$DefenderTargetUser][$DefenderTarget]; + $DefenderDestroyedTarget = true; + } else { + $Destroyed = $HowManyCouldDestroyReal; + } + } + $AttackerLost[$DefenderTargetUser][$DefenderTarget] += $Destroyed; + $AtkLoseCount[$DefenderTarget] += $Destroyed; + if($ClearForce){ + if($HowManyCouldDestroyReal <= $Destroyed){ + $DefenderForce = 0; + } + } else { + $DefenderForce -= ($ShipsHullValues[$DefenderTarget] * $AttackerTech[$DefenderTargetUser]['tech_armour']) * $Destroyed; + } + if($DefenderDestroyedTarget){ + unset($AttackerShipList[$DefenderTargetUser][$DefenderTargetIndex]); + if(empty($AttackerShipList[$DefenderTargetUser])){ + unset($AttackerShipList[$DefenderTargetUser]); + unset($AttackerUsers[$DefenderTargetUser]); + } + if(empty($AttackerShipList)){ + $CalcDefRapidFire = false; + break; + } + if($DefenderForce > 0 OR ($UseRapidFire == TRUE AND $CalcDefRapidFire == TRUE)){ + $DefenderTargetUser = array_rand($AttackerUsers); + $DefenderTarget = array_rand($AttackerShipList[$DefenderTargetUser]); + $DefenderTargetIndex = $DefenderTarget; + $DefenderTarget = $AttackerShipList[$DefenderTargetUser][$DefenderTarget]; + $AttackerShield = -1; + } + } + } + + + // Calculate Rapid Fire + if($UseRapidFire){ + if($CalcDefRapidFire){ + $RapidFireMaxShips = 0; + foreach($DefenderShips as $User => $Ships){ + foreach($Ships as $ID => $Count){ + if($_Vars_CombatData[$ID]['sd'][$DefenderTarget] > 1){ + $Chance = floor((($_Vars_CombatData[$ID]['sd'][$DefenderTarget] - 1) / $_Vars_CombatData[$ID]['sd'][$DefenderTarget]) * 100); + for($SDCounter = 0; $SDCounter < $Count; $SDCounter += 1){ + while(mt_rand(1,100) <= $Chance){ + $CalcForce = $_Vars_CombatData[$ID]['attack'] * $DefenderTech[$DefenderTargetUser]['tech_weapons']; + $DefenderForce += $CalcForce; + $Rounds[$i]['def']['count'] += 1; + $Rounds[$i]['def']['force'] += $CalcForce; + $RapidFireMaxShips += 1; + } + } + } + } + } + + if($DefenderForce > 0){ + $Destroyed = 0; + $DefenderDestroyedTarget = false; + + $AttackerShipsLeft = $AttackerShips[$DefenderTargetUser][$DefenderTarget] - $AttackerLost[$DefenderTargetUser][$DefenderTarget]; + + if($AttackerShield < 0){ + $AttackerShield = $AttackerShipsLeft * $_Vars_CombatData[$DefenderTarget]['shield'] * $AttackerTech[$DefenderTargetUser]['tech_shielding']; + if($AttackerShield > $DefenderForce){ + $Rounds[$i]['atk']['shield'] += $DefenderForce; + } else { + $Rounds[$i]['atk']['shield'] += $AttackerShield; + } + $DefenderForce -= $AttackerShield; + } elseif($AttackerShield > 0){ + if($AttackerShield > $DefenderForce){ + $Rounds[$i]['atk']['shield'] += $DefenderForce; + } else { + $Rounds[$i]['atk']['shield'] += $AttackerShield; + } + $DefenderForce -= $AttackerShield; + } + + $HowManyCouldDestroy = $DefenderForce / ($ShipsHullValues[$DefenderTarget] * $AttackerTech[$DefenderTargetUser]['tech_armour']); + if($HowManyCouldDestroy > $RapidFireMaxShips){ + $HowManyCouldDestroy = $RapidFireMaxShips; + } + + if($HowManyCouldDestroy >= $AttackerShipsLeft){ + $Destroyed = $AttackerShipsLeft; + $SaveHullDmg['def'][$DefenderTargetUser][$DefenderTarget] = 0; + $DefenderDestroyedTarget = true; + } else { + $HowManyCouldDestroyReal = floor($HowManyCouldDestroy); + $ChanceToBlow = $HowManyCouldDestroy - $HowManyCouldDestroyReal; + if($HowManyCouldDestroy < 1 AND $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] > 0){ + $ChanceToBlow += $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget]; + } + if($ChanceToBlow > 0.3){ + if($ChanceToBlow >= 1 OR mt_rand(1,100) <= ($ChanceToBlow * 100)){ + $HowManyCouldDestroyReal += 1; + $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] = 0; + } else { + $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] = $ChanceToBlow; + } + $DoNotCalcExplosion['atk'][$DefenderTargetUser][$DefenderTarget] = 1; + } else { + $SaveHullDmg['atk'][$DefenderTargetUser][$DefenderTarget] = $ChanceToBlow; + } + if($HowManyCouldDestroyReal >= $AttackerShipsLeft){ + $Destroyed = $AttackerShipsLeft; + $DefenderDestroyedTarget = true; + } else { + $Destroyed = $HowManyCouldDestroyReal; + } + $ClearForce = true; + } + $AttackerLost[$DefenderTargetUser][$DefenderTarget] += $Destroyed; + $AtkLoseCount[$DefenderTarget] += $Destroyed; + if($DefenderDestroyedTarget){ + unset($AttackerShipList[$DefenderTargetUser][$DefenderTargetIndex]); + if(empty($AttackerShipList[$DefenderTargetUser])){ + unset($AttackerShipList[$DefenderTargetUser]); + unset($AttackerUsers[$DefenderTargetUser]); + } + } + } + } + } + + // Calculate ships Explosion (Atk Ships) + if(!empty($SaveHullDmg['atk'])){ + foreach($SaveHullDmg['atk'] as $User => $Ships){ + foreach($Ships as $Ship => $ExplosionChance){ + if($DoNotCalcExplosion['atk'][$User][$Ship] != 1){ + if($ExplosionChance > 0.3){ + if($ExplosionChance >= 1 OR mt_rand(1,100) <= ($ExplosionChance * 100)){ + $SaveHullDmg['atk'][$User][$Ship] = 0; + $AttackerLost[$User][$Ship] += 1; + $AtkLoseCount[$Ship] += 1; + + if($AttackerLost[$User][$Ship] >= $AttackerShips[$User][$Ship]){ + unset($AttackerShipList[$User][$Ship]); + if(empty($AttackerShipList[$User])){ + unset($AttackerShipList[$User]); + unset($AttackerUsers[$User]); + } + } + } + } + } + } + } + } + + // End of Calculations + // -------------------------------------------- + + if(!empty($AttackerLost)){ + foreach($AttackerLost as $User => $Ships){ + foreach($Ships as $ID => $Count){ + if($Count > 0){ + if($AttackerShips[$User][$ID] <= $Count){ + unset($AttackerShips[$User][$ID]); + } else { + $AttackerShips[$User][$ID] -= $Count; + } + } + } + } + } + + if(!empty($DefenderLost)){ + foreach($DefenderLost as $User => $Ships){ + foreach($Ships as $ID => $Count){ + if($Count > 0){ + if($DefenderShips[$User][$ID] <= $Count){ + unset($DefenderShips[$User][$ID]); + } else { + $DefenderShips[$User][$ID] -= $Count; + } + } + } + } + } + + if(empty($DefenderShipList)){ + unset($DefenderShips); + } + if(empty($AttackerShipList)){ + unset($AttackerShips); + } + + } + + if((!empty($AttackerShips) AND !empty($DefenderShips)) OR (empty($AttackerShips) AND empty($DefenderShips))){ + $BattleResult = COMBAT_DRAW; // It's a Draw + } elseif(empty($AttackerShips)){ + $BattleResult = COMBAT_DEF; // Defenders Won! + } elseif(empty($DefenderShips)){ + $BattleResult = COMBAT_ATK; // Attackers Won! + } else { + return array('result' => false, 'error' => 'BAD_COMBAT_RESULT'); + } + + return array('return' => true, 'AttackerShips' => $AttackerShips, 'DefenderShips' => $DefenderShips, 'rounds' => $Rounds, 'result' => $BattleResult, 'AtkLose' => $AtkLoseCount, 'DefLose' => $DefLoseCount, 'DefSysLost' => $PlanetDefSysLost); +} + +?> diff --git a/includes/CombatEngineV3.php b/includes/CombatEngineV3.php index 5bdf5d3d1..021e74e08 100644 --- a/includes/CombatEngineV3.php +++ b/includes/CombatEngineV3.php @@ -1,554 +1,554 @@ - &$Techs){ - $Techs['tech_armour'] = 1 + (0.1 * $Techs['tech_armour']); - $Techs['tech_shielding'] = 1 + (0.1 * $Techs['tech_shielding']); - $Techs['tech_weapons'] = 1 + (0.1 * $Techs['tech_weapons']); - } - foreach($Defender as $User => $Ships){ - $DefendersCount += 1; - foreach($Ships as $ID => $Count){ - $DefendersShipTypes[$User] += 1; - $DefenderShips[$User][$ID] += $Count; - $DefenderShipList[$User][] = $ID; - $DefenderUsers[$User] = true; - if(empty($ShipsHullValues[$ID])){ - $ShipsHullValues[$ID] = ($_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal']) / 10; - } - $DefenderShipsForces[$User][$ID] = $_Vars_CombatData[$ID]['attack'] * $DefenderTech[$User]['tech_weapons']; - $DefenderShipsShield[$User][$ID] = $_Vars_CombatData[$ID]['shield'] * $DefenderTech[$User]['tech_shielding']; - } - } - } else { - $DefendersCount = 1; - $DefenderShips = false; - } - - if(!empty($Attacker)){ - //$AttackersCount = count($Attacker); - //$AttackerShips = array(); - foreach($AttackerTech as $User => &$Techs){ - $Techs['tech_armour'] = 1 + (0.1 * $Techs['tech_armour']); - $Techs['tech_shielding'] = 1 + (0.1 * $Techs['tech_shielding']); - $Techs['tech_weapons'] = 1 + (0.1 * $Techs['tech_weapons']); - } - foreach($Attacker as $User => $Ships){ - $AttackersCount += 1; - foreach($Ships as $ID => $Count){ - $AttackersShipTypes[$User] += 1; - $AttackerShips[$User][$ID] += $Count; - $AttackerShipList[$User][] = $ID; - $AttackerUsers[$User] = true; - if(empty($ShipsHullValues[$ID])){ - $ShipsHullValues[$ID] = ($_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal']) / 10; - } - $AttackerShipsForces[$User][$ID] = $_Vars_CombatData[$ID]['attack'] * $AttackerTech[$User]['tech_weapons']; - $AttackerShipsShield[$User][$ID] = $_Vars_CombatData[$ID]['shield'] * $AttackerTech[$User]['tech_shielding']; - } - } - } else { - return array('result' => false, 'error' => 'NO_ATTACKER'); - } - - $RoundsLimit = BATTLE_MAX_ROUNDS + 1; - for($i = 1; $i <= $RoundsLimit; $i += 1){ - $AttackerForce = 0; - $AttackerShield = -1; - $AttackerCount = 0; - $AttackerForReport = array(); - $AttackerDestroyedTarget = false; - $AttackerLost = array(); - $DefenderForce = 0; - $DefenderShield = -1; - $DefenderCount = 0; - $DefenderForReport = array(); - $DefenderDestroyedTarget = false; - $DefenderLost = array(); - $CalcAtkRapidFire = true; - $CalcDefRapidFire = true; - $Break = false; - $DoNotCalcExplosion = array(); - $AtkShipDestroyedInExplosion= false; - $DefShipDestroyedInExplosion= false; - // Clear Targets - $AttackerTargets = array(); - - $Rounds[$i]['atk']['ships'] = $AttackerShips; - $Rounds[$i]['def']['ships'] = $DefenderShips; - - if($i > BATTLE_MAX_ROUNDS){ - break; - } - - if(empty($AttackerShips) OR empty($DefenderShips)){ - break; - } - - // ------------------------------------------------------------------------------------------------------------------------------------ - // Calculate Attacker(s) Part - // 1. Create attacking list - foreach($AttackerShipList as $User => $Ships){ - foreach($Ships as $ID){ - if($DefendersCount == 1){ - foreach($DefenderUsers as $UserID => $True){ - $PickAttackerTargetUserID = $UserID; - } - } else { - $PickAttackerTargetUserID = array_rand($DefenderUsers); - } - if($DefendersShipTypes[$PickAttackerTargetUserID] == 1){ - foreach($DefenderShipList[$PickAttackerTargetUserID] as $ShipID){ - $PickAttackerTargetShipID = $ShipID; - } - } else { - $PickAttackerTargetShipID = $DefenderShipList[$PickAttackerTargetUserID][array_rand($DefenderShipList[$PickAttackerTargetUserID])]; - } - $AttackerTargets[$PickAttackerTargetUserID][$PickAttackerTargetShipID][$User][] = $ID; - } - } - // 2. Calculate Battle - foreach($AttackerTargets as $DefUser => $DefShips){ - foreach($DefShips as $DefShipID => $AtkFiring){ - $InterLoop += 1; - // 2.1 Here start calculation for each selected Target - // - A. Initialization - $AtkForce = 0; - $AtkCount = 0; - $Destroyed = 0; - $UseShieldInRF = false; - // - B. Calculate Attacker Force - foreach($AtkFiring as $AtkUser => $ThisUShips){ - foreach($ThisUShips as $ID){ - $AtkForce += $AttackerShips[$AtkUser][$ID] * $AttackerShipsForces[$AtkUser][$ID]; - $AtkCount += $AttackerShips[$AtkUser][$ID]; - } - } - $Rounds[$i]['atk']['force'] += $AtkForce; - $Rounds[$i]['atk']['count'] += $AtkCount; - // - B. END - // - C. Calculate Defender Shield - if($AtkForce <= 0){ - continue; - } - - $DefShield = $DefenderShips[$DefUser][$DefShipID] * $DefenderShipsShield[$DefUser][$DefShipID]; - if($DefShield > 0 AND ($DefShield / $AtkForce) > 0.01){ - if($DefShield > $AtkForce){ - $Rounds[$i]['def']['shield'] += $AtkForce; - } else { - $Rounds[$i]['def']['shield'] += $DefShield; - } - $AtkForce -= $DefShield; - $DefShield -= $Rounds[$i]['def']['shield']; - if($DefShield > 0){ - $UseShieldInRF = true; - } - } - - if($AtkForce <= 0){ - continue; - } - // - C. END - // - D. Calculate Firing (Regular) - $HowManyCouldDestroy = $AtkForce / ($ShipsHullValues[$DefShipID] * $DefenderTech[$DefUser]['tech_armour']); - - if($HowManyCouldDestroy >= $DefenderShips[$DefUser][$DefShipID]){ - $Destroyed = $DefenderShips[$DefUser][$DefShipID]; - $SaveHullDmg['def'][$DefUser][$DefShipID] = 0; - $AttackerDestroyedTarget = true; - } else { - $HowManyCouldDestroyReal = floor($HowManyCouldDestroy); - $ChanceToBlow = $HowManyCouldDestroy - $HowManyCouldDestroyReal; - - if($SaveHullDmg['def'][$DefUser][$DefShipID] > 0){ - $ChanceToBlow += $SaveHullDmg['def'][$DefUser][$DefShipID]; - } - if($ChanceToBlow >= 1){ - $HowManyCouldDestroyReal += 1; - $SaveHullDmg['def'][$DefUser][$DefShipID] = $ChanceToBlow - 1; - } else { - $SaveHullDmg['def'][$DefUser][$DefShipID] = $ChanceToBlow; - } - - if($HowManyCouldDestroyReal >= $DefenderShips[$DefUser][$DefShipID]){ - $Destroyed = $DefenderShips[$DefUser][$DefShipID]; - $AttackerDestroyedTarget = true; - } else { - $Destroyed = $HowManyCouldDestroyReal; - } - } - $DefenderLost[$DefUser][$DefShipID] += $Destroyed; - $DefLoseCount[$DefShipID] += $Destroyed; - if($AttackerTargetUser == 0 AND $AttackerTarget > 400 AND $AttackerTarget < 500){ - $PlanetDefSysLost[$DefShipID] += $Destroyed; - } - if($AttackerDestroyedTarget){ - $SaveHullDmg['def'][$DefUser][$DefShipID] = 0; - } - // - D. END - // - E. Calculate Firing (Rapid Fire) - if($UseRapidFire){ - if(!$AttackerDestroyedTarget){ - $RapidFireMaxShips = 0; - $AtkForce = 0; - $AttackerDestroyedTarget = false; - foreach($AtkFiring as $AtkUser => $ThisUShips){ - foreach($ThisUShips as $ID){ - if($_Vars_CombatData[$ID]['sd'][$DefShipID] > 1){ - if(!$SDChance[$ID][$DefShipID]){ - $SDChance[$ID][$DefShipID] = floor((($_Vars_CombatData[$ID]['sd'][$DefShipID] - 1) / $_Vars_CombatData[$ID]['sd'][$DefShipID]) * 100); - } - for($SDCounter = $AttackerShips[$AtkUser][$ID]; $SDCounter > 0; $SDCounter -= 1){ - while(mt_rand(1,100) <= $SDChance[$ID][$DefShipID]){ - $AtkForce += $AttackerShipsForces[$AtkUser][$ID]; - $Rounds[$i]['atk']['count'] += 1; - $Rounds[$i]['atk']['force'] += $AttackerShipsForces[$AtkUser][$ID]; - $RapidFireMaxShips += 1; - } - } - } - } - } - - if($AtkForce > 0){ - $HowManyCouldDestroy = $AtkForce / ($ShipsHullValues[$DefShipID] * $DefenderTech[$DefUser]['tech_armour']); - - if($HowManyCouldDestroy >= ($DefenderShips[$DefUser][$DefShipID] - $Destroyed)){ - $Destroyed = ($DefenderShips[$DefUser][$DefShipID] - $Destroyed); - $SaveHullDmg['def'][$DefUser][$DefShipID] = 0; - $AttackerDestroyedTarget = true; - } else { - $HowManyCouldDestroyReal = floor($HowManyCouldDestroy); - $ChanceToBlow = $HowManyCouldDestroy - $HowManyCouldDestroyReal; - - if($SaveHullDmg['def'][$DefUser][$DefShipID] > 0){ - $ChanceToBlow += $SaveHullDmg['def'][$DefUser][$DefShipID]; - } - if($ChanceToBlow >= 1){ - $HowManyCouldDestroyReal += 1; - $SaveHullDmg['def'][$DefUser][$DefShipID] = $ChanceToBlow - 1; - } else { - $SaveHullDmg['def'][$DefUser][$DefShipID] = $ChanceToBlow; - } - - if($HowManyCouldDestroyReal >= ($DefenderShips[$DefUser][$DefShipID] - $Destroyed)){ - $Destroyed = ($DefenderShips[$DefUser][$DefShipID] - $Destroyed); - $AttackerDestroyedTarget = true; - } else { - $Destroyed = $HowManyCouldDestroyReal; - } - } - $DefenderLost[$DefUser][$DefShipID] += $Destroyed; - $DefLoseCount[$DefShipID] += $Destroyed; - if($AttackerTargetUser == 0 AND $AttackerTarget > 400 AND $AttackerTarget < 500){ - $PlanetDefSysLost[$DefShipID] += $Destroyed; - } - if($AttackerDestroyedTarget){ - $SaveHullDmg['def'][$DefUser][$DefShipID] = 0; - } - } - } - } - // - E. END - } - } - // --------------------------------- - // ------------------------------------------------------------------------------------------------------------------------------------ - // Calculate Defender(s) Part - // 1. Create attacking list - foreach($DefenderShipList as $User => $Ships){ - foreach($Ships as $ID){ - if($AttackersCount == 1){ - foreach($AttackerUsers as $UserID => $True){ - $PickDefenderTargetUserID = $UserID; - } - } else { - $PickDefenderTargetUserID = array_rand($AttackerUsers); - } - if($AttackersShipTypes[$PickDefenderTargetUserID] == 1){ - foreach($AttackerShipList[$PickDefenderTargetUserID] as $ShipID){ - $PickDefenderTargetShipID = $ShipID; - } - } else { - $PickDefenderTargetShipID = $AttackerShipList[$PickDefenderTargetUserID][array_rand($AttackerShipList[$PickDefenderTargetUserID])]; - } - $DefenderTargets[$PickDefenderTargetUserID][$PickDefenderTargetShipID][$User][] = $ID; - } - } - // 2. Calculate Battle - foreach($DefenderTargets as $AtkUser => $AtkShips){ - foreach($AtkShips as $AtkShipID => $DefFiring){ - // 2.1 Here start calculation for each selected Target - // - A. Initialization - $DefForce = 0; - $DefCount = 0; - $Destroyed = 0; - $UseShieldInRF = false; - // - B. Calculate Attacker Force - foreach($DefFiring as $DefUser => $ThisUShips){ - foreach($ThisUShips as $ID){ - $DefForce += $DefenderShips[$DefUser][$ID] * $DefenderShipsForces[$DefUser][$ID]; - $DefCount += $DefenderShips[$DefUser][$ID]; - } - } - $Rounds[$i]['def']['force'] += $DefForce; - $Rounds[$i]['def']['count'] += $DefCount; - // - B. END - // - C. Calculate Defender Shield - if($DefForce <= 0){ - continue; - } - - $AtkShield = $AttackerShips[$AtkUser][$AtkShipID] * $AttackerShipsShield[$AtkUser][$AtkShipID]; - if($AtkShield > 0 AND ($AtkShield / $DefForce) > 0.01){ - if($AtkShield > $DefForce){ - $Rounds[$i]['atk']['shield'] += $DefForce; - } else { - $Rounds[$i]['atk']['shield'] += $AtkShield; - } - $DefForce -= $AtkShield; - $AtkShield -= $Rounds[$i]['atk']['shield']; - if($AtkShield > 0){ - $UseShieldInRF = true; - } - } - - if($DefForce <= 0){ - continue; - } - // - C. END - // - D. Calculate Firing (Regular) - $HowManyCouldDestroy = $DefForce / ($ShipsHullValues[$AtkShipID] * $AttackerTech[$AtkUser]['tech_armour']); - - if($HowManyCouldDestroy >= $AttackerShips[$AtkUser][$AtkShipID]){ - $Destroyed = $AttackerShips[$AtkUser][$AtkShipID]; - $SaveHullDmg['atk'][$AtkUser][$AtkShipID] = 0; - $DefenderDestroyedTarget = true; - } else { - $HowManyCouldDestroyReal = floor($HowManyCouldDestroy); - $ChanceToBlow = $HowManyCouldDestroy - $HowManyCouldDestroyReal; - - if($SaveHullDmg['atk'][$AtkUser][$AtkShipID] > 0){ - $ChanceToBlow += $SaveHullDmg['atk'][$AtkUser][$AtkShipID]; - } - if($ChanceToBlow >= 1){ - $HowManyCouldDestroyReal += 1; - $SaveHullDmg['atk'][$AtkUser][$AtkShipID] = $ChanceToBlow - 1; - } else { - $SaveHullDmg['atk'][$AtkUser][$AtkShipID] = $ChanceToBlow; - } - - if($HowManyCouldDestroyReal >= $AttackerShips[$AtkUser][$AtkShipID]){ - $Destroyed = $AttackerShips[$AtkUser][$AtkShipID]; - $DefenderDestroyedTarget = true; - } else { - $Destroyed = $HowManyCouldDestroyReal; - } - } - $AttackerLost[$AtkUser][$AtkShipID] += $Destroyed; - $AtkLoseCount[$AtkShipID] += $Destroyed; - if($DefenderDestroyedTarget){ - $SaveHullDmg['atk'][$AtkUser][$AtkShipID] = 0; - } - // - D. END - // - E. Calculate Firing (Rapid Fire) - if($UseRapidFire){ - if(!$DefenderDestroyedTarget){ - $RapidFireMaxShips = 0; - $DefForce = 0; - $DefenderDestroyedTarget = false; - foreach($DefFiring as $DefUser => $ThisUShips){ - foreach($ThisUShips as $ID){ - if($_Vars_CombatData[$ID]['sd'][$AtkShipID] > 1){ - if(!$SDChance[$ID][$AtkShipID]){ - $SDChance[$ID][$AtkShipID] = floor((($_Vars_CombatData[$ID]['sd'][$AtkShipID] - 1) / $_Vars_CombatData[$ID]['sd'][$AtkShipID]) * 100); - } - for($SDCounter = $DefenderShips[$DefUser][$ID]; $SDCounter > 0; $SDCounter -= 1){ - while(mt_rand(1,100) <= $SDChance[$ID][$AtkShipID]){ - $DefForce += $DefenderShipsForces[$DefUser][$ID]; - $Rounds[$i]['def']['count'] += 1; - $Rounds[$i]['def']['force'] += $DefenderShipsForces[$DefUser][$ID]; - $RapidFireMaxShips += 1; - } - } - } - } - } - - if($DefForce > 0){ - $HowManyCouldDestroy = $DefForce / ($ShipsHullValues[$AtkShipID] * $AttackerTech[$AtkUser]['tech_armour']); - - if($HowManyCouldDestroy >= ($AttackerShips[$AtkUser][$AtkShipID] - $Destroyed)){ - $Destroyed = ($AttackerShips[$AtkUser][$AtkShipID] - $Destroyed); - $SaveHullDmg['atk'][$AtkUser][$AtkShipID] = 0; - $DefenderDestroyedTarget = true; - } else { - $HowManyCouldDestroyReal = floor($HowManyCouldDestroy); - $ChanceToBlow = $HowManyCouldDestroy - $HowManyCouldDestroyReal; - - if($SaveHullDmg['atk'][$AtkUser][$AtkShipID] > 0){ - $ChanceToBlow += $SaveHullDmg['atk'][$AtkUser][$AtkShipID]; - } - if($ChanceToBlow >= 1){ - $HowManyCouldDestroyReal += 1; - $SaveHullDmg['atk'][$AtkUser][$AtkShipID] = $ChanceToBlow - 1; - } else { - $SaveHullDmg['atk'][$AtkUser][$AtkShipID] = $ChanceToBlow; - } - - if($HowManyCouldDestroyReal >= ($AttackerShips[$AtkUser][$AtkShipID] - $Destroyed)){ - $Destroyed = ($AttackerShips[$AtkUser][$AtkShipID] - $Destroyed); - $DefenderDestroyedTarget = true; - } else { - $Destroyed = $HowManyCouldDestroyReal; - } - } - $AttackerLost[$AtkUser][$AtkShipID] += $Destroyed; - $AtkLoseCount[$AtkShipID] += $Destroyed; - if($DefenderDestroyedTarget){ - $SaveHullDmg['atk'][$AtkUser][$AtkShipID] = 0; - } - } - } - } - // - E. END - } - } - - // ------------------------------------------------------------------------------------------------------------------------------------ - // Common Parts - - // Calculate ships Explosion - if(!empty($SaveHullDmg)){ - foreach($SaveHullDmg as $WhichPart => $Data){ - foreach($Data as $User => $Ships){ - foreach($Ships as $Ship => $ExplosionChance){ - if($ExplosionChance > 0.3){ - if($ExplosionChance >= 1 OR mt_rand(1,100) <= ($ExplosionChance * 100)){ - $SaveHullDmg[$WhichPart][$User][$Ship] = 0; - if($WhichPart == 'def'){ - $DefenderLost[$User][$Ship] += 1; - $DefLoseCount[$Ship] += 1; - if($User == 0 AND $Ship > 400 AND $Ship < 500){ - $PlanetDefSysLost[$Ship] += 1; - } - - if($DefenderLost[$User][$Ship] >= $DefenderShips[$User][$Ship]){ - unset($DefenderShipList[$User][$Ship]); - if(empty($DefenderShipList[$User])){ - unset($DefenderShipList[$User]); - unset($DefenderUsers[$User]); - } - } - } else { - $AttackerLost[$User][$Ship] += 1; - $AtkLoseCount[$Ship] += 1; - - if($AttackerLost[$User][$Ship] >= $AttackerShips[$User][$Ship]){ - unset($AttackerShipList[$User][$Ship]); - if(empty($AttackerShipList[$User])){ - unset($AttackerShipList[$User]); - unset($AttackerUsers[$User]); - } - } - } - } - } - } - } - } - } - - // End of Calculations - // -------------------------------------------- - - if(!empty($AttackerLost)){ - foreach($AttackerLost as $User => $Ships){ - foreach($Ships as $ID => $Count){ - if($Count > 0){ - if($AttackerShips[$User][$ID] <= $Count){ - unset($AttackerShips[$User][$ID]); - unset($AttackerShipList[$User][array_search($ID, $AttackerShipList[$User])]); - if(empty($AttackerShipList[$User])){ - unset($AttackerShipList[$User]); - unset($AttackerUsers[$User]); - $AttackersCount -= 1; - } - $AttackersShipTypes[$User] -= 1; - } else { - $AttackerShips[$User][$ID] -= $Count; - } - } - } - } - } - - if(!empty($DefenderLost)){ - - foreach($DefenderLost as $User => $Ships){ - foreach($Ships as $ID => $Count){ - if($Count > 0){ - if($DefenderShips[$User][$ID] <= $Count){ - unset($DefenderShips[$User][$ID]); - unset($DefenderShipList[$User][array_search($ID, $DefenderShipList[$User])]); - if(empty($DefenderShipList[$User])){ - unset($DefenderShipList[$User]); - unset($DefenderUsers[$User]); - $DefendersCount -= 1; - } - $DefendersShipTypes[$User] -= 1; - } else { - $DefenderShips[$User][$ID] -= $Count; - } - } - } - } - } - - if(empty($DefenderShipList)){ - unset($DefenderShips); - } - if(empty($AttackerShipList)){ - unset($AttackerShips); - } - - } - - if((!empty($AttackerShips) AND !empty($DefenderShips)) OR (empty($AttackerShips) AND empty($DefenderShips))){ - var_dump($AttackerShips); - var_dump($DefenderShips); - $BattleResult = COMBAT_DRAW; // It's a Draw - } elseif(empty($AttackerShips)){ - $BattleResult = COMBAT_DEF; // Defenders Won! - } elseif(empty($DefenderShips)){ - $BattleResult = COMBAT_ATK; // Attackers Won! - } else { - return array('result' => false, 'error' => 'BAD_COMBAT_RESULT'); - } - - return array('return' => true, 'AttackerShips' => $AttackerShips, 'DefenderShips' => $DefenderShips, 'rounds' => $Rounds, 'result' => $BattleResult, 'AtkLose' => $AtkLoseCount, 'DefLose' => $DefLoseCount, 'DefSysLost' => $PlanetDefSysLost); -} - -?> \ No newline at end of file + &$Techs){ + $Techs['tech_armour'] = 1 + (0.1 * $Techs['tech_armour']); + $Techs['tech_shielding'] = 1 + (0.1 * $Techs['tech_shielding']); + $Techs['tech_weapons'] = 1 + (0.1 * $Techs['tech_weapons']); + } + foreach($Defender as $User => $Ships){ + $DefendersCount += 1; + foreach($Ships as $ID => $Count){ + $DefendersShipTypes[$User] += 1; + $DefenderShips[$User][$ID] += $Count; + $DefenderShipList[$User][] = $ID; + $DefenderUsers[$User] = true; + if(empty($ShipsHullValues[$ID])){ + $ShipsHullValues[$ID] = ($_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal']) / 10; + } + $DefenderShipsForces[$User][$ID] = $_Vars_CombatData[$ID]['attack'] * $DefenderTech[$User]['tech_weapons']; + $DefenderShipsShield[$User][$ID] = $_Vars_CombatData[$ID]['shield'] * $DefenderTech[$User]['tech_shielding']; + } + } + } else { + $DefendersCount = 1; + $DefenderShips = false; + } + + if(!empty($Attacker)){ + //$AttackersCount = count($Attacker); + //$AttackerShips = array(); + foreach($AttackerTech as $User => &$Techs){ + $Techs['tech_armour'] = 1 + (0.1 * $Techs['tech_armour']); + $Techs['tech_shielding'] = 1 + (0.1 * $Techs['tech_shielding']); + $Techs['tech_weapons'] = 1 + (0.1 * $Techs['tech_weapons']); + } + foreach($Attacker as $User => $Ships){ + $AttackersCount += 1; + foreach($Ships as $ID => $Count){ + $AttackersShipTypes[$User] += 1; + $AttackerShips[$User][$ID] += $Count; + $AttackerShipList[$User][] = $ID; + $AttackerUsers[$User] = true; + if(empty($ShipsHullValues[$ID])){ + $ShipsHullValues[$ID] = ($_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal']) / 10; + } + $AttackerShipsForces[$User][$ID] = $_Vars_CombatData[$ID]['attack'] * $AttackerTech[$User]['tech_weapons']; + $AttackerShipsShield[$User][$ID] = $_Vars_CombatData[$ID]['shield'] * $AttackerTech[$User]['tech_shielding']; + } + } + } else { + return array('result' => false, 'error' => 'NO_ATTACKER'); + } + + $RoundsLimit = BATTLE_MAX_ROUNDS + 1; + for($i = 1; $i <= $RoundsLimit; $i += 1){ + $AttackerForce = 0; + $AttackerShield = -1; + $AttackerCount = 0; + $AttackerForReport = array(); + $AttackerDestroyedTarget = false; + $AttackerLost = array(); + $DefenderForce = 0; + $DefenderShield = -1; + $DefenderCount = 0; + $DefenderForReport = array(); + $DefenderDestroyedTarget = false; + $DefenderLost = array(); + $CalcAtkRapidFire = true; + $CalcDefRapidFire = true; + $Break = false; + $DoNotCalcExplosion = array(); + $AtkShipDestroyedInExplosion= false; + $DefShipDestroyedInExplosion= false; + // Clear Targets + $AttackerTargets = array(); + + $Rounds[$i]['atk']['ships'] = $AttackerShips; + $Rounds[$i]['def']['ships'] = $DefenderShips; + + if($i > BATTLE_MAX_ROUNDS){ + break; + } + + if(empty($AttackerShips) OR empty($DefenderShips)){ + break; + } + + // ------------------------------------------------------------------------------------------------------------------------------------ + // Calculate Attacker(s) Part + // 1. Create attacking list + foreach($AttackerShipList as $User => $Ships){ + foreach($Ships as $ID){ + if($DefendersCount == 1){ + foreach($DefenderUsers as $UserID => $True){ + $PickAttackerTargetUserID = $UserID; + } + } else { + $PickAttackerTargetUserID = array_rand($DefenderUsers); + } + if($DefendersShipTypes[$PickAttackerTargetUserID] == 1){ + foreach($DefenderShipList[$PickAttackerTargetUserID] as $ShipID){ + $PickAttackerTargetShipID = $ShipID; + } + } else { + $PickAttackerTargetShipID = $DefenderShipList[$PickAttackerTargetUserID][array_rand($DefenderShipList[$PickAttackerTargetUserID])]; + } + $AttackerTargets[$PickAttackerTargetUserID][$PickAttackerTargetShipID][$User][] = $ID; + } + } + // 2. Calculate Battle + foreach($AttackerTargets as $DefUser => $DefShips){ + foreach($DefShips as $DefShipID => $AtkFiring){ + $InterLoop += 1; + // 2.1 Here start calculation for each selected Target + // - A. Initialization + $AtkForce = 0; + $AtkCount = 0; + $Destroyed = 0; + $UseShieldInRF = false; + // - B. Calculate Attacker Force + foreach($AtkFiring as $AtkUser => $ThisUShips){ + foreach($ThisUShips as $ID){ + $AtkForce += $AttackerShips[$AtkUser][$ID] * $AttackerShipsForces[$AtkUser][$ID]; + $AtkCount += $AttackerShips[$AtkUser][$ID]; + } + } + $Rounds[$i]['atk']['force'] += $AtkForce; + $Rounds[$i]['atk']['count'] += $AtkCount; + // - B. END + // - C. Calculate Defender Shield + if($AtkForce <= 0){ + continue; + } + + $DefShield = $DefenderShips[$DefUser][$DefShipID] * $DefenderShipsShield[$DefUser][$DefShipID]; + if($DefShield > 0 AND ($DefShield / $AtkForce) > 0.01){ + if($DefShield > $AtkForce){ + $Rounds[$i]['def']['shield'] += $AtkForce; + } else { + $Rounds[$i]['def']['shield'] += $DefShield; + } + $AtkForce -= $DefShield; + $DefShield -= $Rounds[$i]['def']['shield']; + if($DefShield > 0){ + $UseShieldInRF = true; + } + } + + if($AtkForce <= 0){ + continue; + } + // - C. END + // - D. Calculate Firing (Regular) + $HowManyCouldDestroy = $AtkForce / ($ShipsHullValues[$DefShipID] * $DefenderTech[$DefUser]['tech_armour']); + + if($HowManyCouldDestroy >= $DefenderShips[$DefUser][$DefShipID]){ + $Destroyed = $DefenderShips[$DefUser][$DefShipID]; + $SaveHullDmg['def'][$DefUser][$DefShipID] = 0; + $AttackerDestroyedTarget = true; + } else { + $HowManyCouldDestroyReal = floor($HowManyCouldDestroy); + $ChanceToBlow = $HowManyCouldDestroy - $HowManyCouldDestroyReal; + + if($SaveHullDmg['def'][$DefUser][$DefShipID] > 0){ + $ChanceToBlow += $SaveHullDmg['def'][$DefUser][$DefShipID]; + } + if($ChanceToBlow >= 1){ + $HowManyCouldDestroyReal += 1; + $SaveHullDmg['def'][$DefUser][$DefShipID] = $ChanceToBlow - 1; + } else { + $SaveHullDmg['def'][$DefUser][$DefShipID] = $ChanceToBlow; + } + + if($HowManyCouldDestroyReal >= $DefenderShips[$DefUser][$DefShipID]){ + $Destroyed = $DefenderShips[$DefUser][$DefShipID]; + $AttackerDestroyedTarget = true; + } else { + $Destroyed = $HowManyCouldDestroyReal; + } + } + $DefenderLost[$DefUser][$DefShipID] += $Destroyed; + $DefLoseCount[$DefShipID] += $Destroyed; + if($AttackerTargetUser == 0 AND $AttackerTarget > 400 AND $AttackerTarget < 500){ + $PlanetDefSysLost[$DefShipID] += $Destroyed; + } + if($AttackerDestroyedTarget){ + $SaveHullDmg['def'][$DefUser][$DefShipID] = 0; + } + // - D. END + // - E. Calculate Firing (Rapid Fire) + if($UseRapidFire){ + if(!$AttackerDestroyedTarget){ + $RapidFireMaxShips = 0; + $AtkForce = 0; + $AttackerDestroyedTarget = false; + foreach($AtkFiring as $AtkUser => $ThisUShips){ + foreach($ThisUShips as $ID){ + if($_Vars_CombatData[$ID]['sd'][$DefShipID] > 1){ + if(!$SDChance[$ID][$DefShipID]){ + $SDChance[$ID][$DefShipID] = floor((($_Vars_CombatData[$ID]['sd'][$DefShipID] - 1) / $_Vars_CombatData[$ID]['sd'][$DefShipID]) * 100); + } + for($SDCounter = $AttackerShips[$AtkUser][$ID]; $SDCounter > 0; $SDCounter -= 1){ + while(mt_rand(1,100) <= $SDChance[$ID][$DefShipID]){ + $AtkForce += $AttackerShipsForces[$AtkUser][$ID]; + $Rounds[$i]['atk']['count'] += 1; + $Rounds[$i]['atk']['force'] += $AttackerShipsForces[$AtkUser][$ID]; + $RapidFireMaxShips += 1; + } + } + } + } + } + + if($AtkForce > 0){ + $HowManyCouldDestroy = $AtkForce / ($ShipsHullValues[$DefShipID] * $DefenderTech[$DefUser]['tech_armour']); + + if($HowManyCouldDestroy >= ($DefenderShips[$DefUser][$DefShipID] - $Destroyed)){ + $Destroyed = ($DefenderShips[$DefUser][$DefShipID] - $Destroyed); + $SaveHullDmg['def'][$DefUser][$DefShipID] = 0; + $AttackerDestroyedTarget = true; + } else { + $HowManyCouldDestroyReal = floor($HowManyCouldDestroy); + $ChanceToBlow = $HowManyCouldDestroy - $HowManyCouldDestroyReal; + + if($SaveHullDmg['def'][$DefUser][$DefShipID] > 0){ + $ChanceToBlow += $SaveHullDmg['def'][$DefUser][$DefShipID]; + } + if($ChanceToBlow >= 1){ + $HowManyCouldDestroyReal += 1; + $SaveHullDmg['def'][$DefUser][$DefShipID] = $ChanceToBlow - 1; + } else { + $SaveHullDmg['def'][$DefUser][$DefShipID] = $ChanceToBlow; + } + + if($HowManyCouldDestroyReal >= ($DefenderShips[$DefUser][$DefShipID] - $Destroyed)){ + $Destroyed = ($DefenderShips[$DefUser][$DefShipID] - $Destroyed); + $AttackerDestroyedTarget = true; + } else { + $Destroyed = $HowManyCouldDestroyReal; + } + } + $DefenderLost[$DefUser][$DefShipID] += $Destroyed; + $DefLoseCount[$DefShipID] += $Destroyed; + if($AttackerTargetUser == 0 AND $AttackerTarget > 400 AND $AttackerTarget < 500){ + $PlanetDefSysLost[$DefShipID] += $Destroyed; + } + if($AttackerDestroyedTarget){ + $SaveHullDmg['def'][$DefUser][$DefShipID] = 0; + } + } + } + } + // - E. END + } + } + // --------------------------------- + // ------------------------------------------------------------------------------------------------------------------------------------ + // Calculate Defender(s) Part + // 1. Create attacking list + foreach($DefenderShipList as $User => $Ships){ + foreach($Ships as $ID){ + if($AttackersCount == 1){ + foreach($AttackerUsers as $UserID => $True){ + $PickDefenderTargetUserID = $UserID; + } + } else { + $PickDefenderTargetUserID = array_rand($AttackerUsers); + } + if($AttackersShipTypes[$PickDefenderTargetUserID] == 1){ + foreach($AttackerShipList[$PickDefenderTargetUserID] as $ShipID){ + $PickDefenderTargetShipID = $ShipID; + } + } else { + $PickDefenderTargetShipID = $AttackerShipList[$PickDefenderTargetUserID][array_rand($AttackerShipList[$PickDefenderTargetUserID])]; + } + $DefenderTargets[$PickDefenderTargetUserID][$PickDefenderTargetShipID][$User][] = $ID; + } + } + // 2. Calculate Battle + foreach($DefenderTargets as $AtkUser => $AtkShips){ + foreach($AtkShips as $AtkShipID => $DefFiring){ + // 2.1 Here start calculation for each selected Target + // - A. Initialization + $DefForce = 0; + $DefCount = 0; + $Destroyed = 0; + $UseShieldInRF = false; + // - B. Calculate Attacker Force + foreach($DefFiring as $DefUser => $ThisUShips){ + foreach($ThisUShips as $ID){ + $DefForce += $DefenderShips[$DefUser][$ID] * $DefenderShipsForces[$DefUser][$ID]; + $DefCount += $DefenderShips[$DefUser][$ID]; + } + } + $Rounds[$i]['def']['force'] += $DefForce; + $Rounds[$i]['def']['count'] += $DefCount; + // - B. END + // - C. Calculate Defender Shield + if($DefForce <= 0){ + continue; + } + + $AtkShield = $AttackerShips[$AtkUser][$AtkShipID] * $AttackerShipsShield[$AtkUser][$AtkShipID]; + if($AtkShield > 0 AND ($AtkShield / $DefForce) > 0.01){ + if($AtkShield > $DefForce){ + $Rounds[$i]['atk']['shield'] += $DefForce; + } else { + $Rounds[$i]['atk']['shield'] += $AtkShield; + } + $DefForce -= $AtkShield; + $AtkShield -= $Rounds[$i]['atk']['shield']; + if($AtkShield > 0){ + $UseShieldInRF = true; + } + } + + if($DefForce <= 0){ + continue; + } + // - C. END + // - D. Calculate Firing (Regular) + $HowManyCouldDestroy = $DefForce / ($ShipsHullValues[$AtkShipID] * $AttackerTech[$AtkUser]['tech_armour']); + + if($HowManyCouldDestroy >= $AttackerShips[$AtkUser][$AtkShipID]){ + $Destroyed = $AttackerShips[$AtkUser][$AtkShipID]; + $SaveHullDmg['atk'][$AtkUser][$AtkShipID] = 0; + $DefenderDestroyedTarget = true; + } else { + $HowManyCouldDestroyReal = floor($HowManyCouldDestroy); + $ChanceToBlow = $HowManyCouldDestroy - $HowManyCouldDestroyReal; + + if($SaveHullDmg['atk'][$AtkUser][$AtkShipID] > 0){ + $ChanceToBlow += $SaveHullDmg['atk'][$AtkUser][$AtkShipID]; + } + if($ChanceToBlow >= 1){ + $HowManyCouldDestroyReal += 1; + $SaveHullDmg['atk'][$AtkUser][$AtkShipID] = $ChanceToBlow - 1; + } else { + $SaveHullDmg['atk'][$AtkUser][$AtkShipID] = $ChanceToBlow; + } + + if($HowManyCouldDestroyReal >= $AttackerShips[$AtkUser][$AtkShipID]){ + $Destroyed = $AttackerShips[$AtkUser][$AtkShipID]; + $DefenderDestroyedTarget = true; + } else { + $Destroyed = $HowManyCouldDestroyReal; + } + } + $AttackerLost[$AtkUser][$AtkShipID] += $Destroyed; + $AtkLoseCount[$AtkShipID] += $Destroyed; + if($DefenderDestroyedTarget){ + $SaveHullDmg['atk'][$AtkUser][$AtkShipID] = 0; + } + // - D. END + // - E. Calculate Firing (Rapid Fire) + if($UseRapidFire){ + if(!$DefenderDestroyedTarget){ + $RapidFireMaxShips = 0; + $DefForce = 0; + $DefenderDestroyedTarget = false; + foreach($DefFiring as $DefUser => $ThisUShips){ + foreach($ThisUShips as $ID){ + if($_Vars_CombatData[$ID]['sd'][$AtkShipID] > 1){ + if(!$SDChance[$ID][$AtkShipID]){ + $SDChance[$ID][$AtkShipID] = floor((($_Vars_CombatData[$ID]['sd'][$AtkShipID] - 1) / $_Vars_CombatData[$ID]['sd'][$AtkShipID]) * 100); + } + for($SDCounter = $DefenderShips[$DefUser][$ID]; $SDCounter > 0; $SDCounter -= 1){ + while(mt_rand(1,100) <= $SDChance[$ID][$AtkShipID]){ + $DefForce += $DefenderShipsForces[$DefUser][$ID]; + $Rounds[$i]['def']['count'] += 1; + $Rounds[$i]['def']['force'] += $DefenderShipsForces[$DefUser][$ID]; + $RapidFireMaxShips += 1; + } + } + } + } + } + + if($DefForce > 0){ + $HowManyCouldDestroy = $DefForce / ($ShipsHullValues[$AtkShipID] * $AttackerTech[$AtkUser]['tech_armour']); + + if($HowManyCouldDestroy >= ($AttackerShips[$AtkUser][$AtkShipID] - $Destroyed)){ + $Destroyed = ($AttackerShips[$AtkUser][$AtkShipID] - $Destroyed); + $SaveHullDmg['atk'][$AtkUser][$AtkShipID] = 0; + $DefenderDestroyedTarget = true; + } else { + $HowManyCouldDestroyReal = floor($HowManyCouldDestroy); + $ChanceToBlow = $HowManyCouldDestroy - $HowManyCouldDestroyReal; + + if($SaveHullDmg['atk'][$AtkUser][$AtkShipID] > 0){ + $ChanceToBlow += $SaveHullDmg['atk'][$AtkUser][$AtkShipID]; + } + if($ChanceToBlow >= 1){ + $HowManyCouldDestroyReal += 1; + $SaveHullDmg['atk'][$AtkUser][$AtkShipID] = $ChanceToBlow - 1; + } else { + $SaveHullDmg['atk'][$AtkUser][$AtkShipID] = $ChanceToBlow; + } + + if($HowManyCouldDestroyReal >= ($AttackerShips[$AtkUser][$AtkShipID] - $Destroyed)){ + $Destroyed = ($AttackerShips[$AtkUser][$AtkShipID] - $Destroyed); + $DefenderDestroyedTarget = true; + } else { + $Destroyed = $HowManyCouldDestroyReal; + } + } + $AttackerLost[$AtkUser][$AtkShipID] += $Destroyed; + $AtkLoseCount[$AtkShipID] += $Destroyed; + if($DefenderDestroyedTarget){ + $SaveHullDmg['atk'][$AtkUser][$AtkShipID] = 0; + } + } + } + } + // - E. END + } + } + + // ------------------------------------------------------------------------------------------------------------------------------------ + // Common Parts + + // Calculate ships Explosion + if(!empty($SaveHullDmg)){ + foreach($SaveHullDmg as $WhichPart => $Data){ + foreach($Data as $User => $Ships){ + foreach($Ships as $Ship => $ExplosionChance){ + if($ExplosionChance > 0.3){ + if($ExplosionChance >= 1 OR mt_rand(1,100) <= ($ExplosionChance * 100)){ + $SaveHullDmg[$WhichPart][$User][$Ship] = 0; + if($WhichPart == 'def'){ + $DefenderLost[$User][$Ship] += 1; + $DefLoseCount[$Ship] += 1; + if($User == 0 AND $Ship > 400 AND $Ship < 500){ + $PlanetDefSysLost[$Ship] += 1; + } + + if($DefenderLost[$User][$Ship] >= $DefenderShips[$User][$Ship]){ + unset($DefenderShipList[$User][$Ship]); + if(empty($DefenderShipList[$User])){ + unset($DefenderShipList[$User]); + unset($DefenderUsers[$User]); + } + } + } else { + $AttackerLost[$User][$Ship] += 1; + $AtkLoseCount[$Ship] += 1; + + if($AttackerLost[$User][$Ship] >= $AttackerShips[$User][$Ship]){ + unset($AttackerShipList[$User][$Ship]); + if(empty($AttackerShipList[$User])){ + unset($AttackerShipList[$User]); + unset($AttackerUsers[$User]); + } + } + } + } + } + } + } + } + } + + // End of Calculations + // -------------------------------------------- + + if(!empty($AttackerLost)){ + foreach($AttackerLost as $User => $Ships){ + foreach($Ships as $ID => $Count){ + if($Count > 0){ + if($AttackerShips[$User][$ID] <= $Count){ + unset($AttackerShips[$User][$ID]); + unset($AttackerShipList[$User][array_search($ID, $AttackerShipList[$User])]); + if(empty($AttackerShipList[$User])){ + unset($AttackerShipList[$User]); + unset($AttackerUsers[$User]); + $AttackersCount -= 1; + } + $AttackersShipTypes[$User] -= 1; + } else { + $AttackerShips[$User][$ID] -= $Count; + } + } + } + } + } + + if(!empty($DefenderLost)){ + + foreach($DefenderLost as $User => $Ships){ + foreach($Ships as $ID => $Count){ + if($Count > 0){ + if($DefenderShips[$User][$ID] <= $Count){ + unset($DefenderShips[$User][$ID]); + unset($DefenderShipList[$User][array_search($ID, $DefenderShipList[$User])]); + if(empty($DefenderShipList[$User])){ + unset($DefenderShipList[$User]); + unset($DefenderUsers[$User]); + $DefendersCount -= 1; + } + $DefendersShipTypes[$User] -= 1; + } else { + $DefenderShips[$User][$ID] -= $Count; + } + } + } + } + } + + if(empty($DefenderShipList)){ + unset($DefenderShips); + } + if(empty($AttackerShipList)){ + unset($AttackerShips); + } + + } + + if((!empty($AttackerShips) AND !empty($DefenderShips)) OR (empty($AttackerShips) AND empty($DefenderShips))){ + var_dump($AttackerShips); + var_dump($DefenderShips); + $BattleResult = COMBAT_DRAW; // It's a Draw + } elseif(empty($AttackerShips)){ + $BattleResult = COMBAT_DEF; // Defenders Won! + } elseif(empty($DefenderShips)){ + $BattleResult = COMBAT_ATK; // Attackers Won! + } else { + return array('result' => false, 'error' => 'BAD_COMBAT_RESULT'); + } + + return array('return' => true, 'AttackerShips' => $AttackerShips, 'DefenderShips' => $DefenderShips, 'rounds' => $Rounds, 'result' => $BattleResult, 'AtkLose' => $AtkLoseCount, 'DefLose' => $DefLoseCount, 'DefSysLost' => $PlanetDefSysLost); +} + +?> diff --git a/includes/constants.php b/includes/constants.php index b77b95f06..783b275bf 100644 --- a/includes/constants.php +++ b/includes/constants.php @@ -1,5 +1,234 @@ - \ No newline at end of file + diff --git a/includes/db.php b/includes/db.php index 051cb2bda..86d35e576 100644 --- a/includes/db.php +++ b/includes/db.php @@ -1,79 +1,79 @@ -error(mysql_error().'
'.$query); - mysql_select_db($__ServerConnectionSettings['name']) or $debug->error(mysql_error().'
'.$query); - } - mysql_query("SET NAMES 'UTF8';"); - } - $Replace_Search = array('{{table}}', '{{prefix}}', 'DROP'); - $Replace_Replace = array($__ServerConnectionSettings['prefix'].$table, $__ServerConnectionSettings['prefix'], ''); - $sql = str_replace($Replace_Search, $Replace_Replace, $query); - if(isset($_User['id']) && $_User['id'] > 1) - { - $sql = str_replace('TRUNCATE', '', $sql); - } - - if($SilentMode) - { - $sqlquery = @mysql_query($sql); - } - else - { - $sqlquery = mysql_query($sql) or $debug->error(mysql_error().'
'.$sql.'
File: '.$_SERVER['REQUEST_URI'].'
User: '.$_User['username'].'['.$_User['id'].']
'); - } - - if($fetch) - { - if($SilentMode) - { - $sqlrow = mysql_fetch_array($sqlquery, MYSQL_ASSOC); - } - else - { - $sqlrow = @mysql_fetch_array($sqlquery, MYSQL_ASSOC); - } - return $sqlrow; - } - else - { - return $sqlquery; - } -} - -?> \ No newline at end of file +error(mysql_error().'
'.$query); + mysql_select_db($__ServerConnectionSettings['name']) or $debug->error(mysql_error().'
'.$query); + } + mysql_query("SET NAMES 'UTF8';"); + } + $Replace_Search = array('{{table}}', '{{prefix}}', 'DROP'); + $Replace_Replace = array($__ServerConnectionSettings['prefix'].$table, $__ServerConnectionSettings['prefix'], ''); + $sql = str_replace($Replace_Search, $Replace_Replace, $query); + if(isset($_User['id']) && $_User['id'] > 1) + { + $sql = str_replace('TRUNCATE', '', $sql); + } + + if($SilentMode) + { + $sqlquery = @mysql_query($sql); + } + else + { + $sqlquery = mysql_query($sql) or $debug->error(mysql_error().'
'.$sql.'
File: '.$_SERVER['REQUEST_URI'].'
User: '.$_User['username'].'['.$_User['id'].']
'); + } + + if($fetch) + { + if($SilentMode) + { + $sqlrow = mysql_fetch_array($sqlquery, MYSQL_ASSOC); + } + else + { + $sqlrow = @mysql_fetch_array($sqlquery, MYSQL_ASSOC); + } + return $sqlrow; + } + else + { + return $sqlquery; + } +} + +?> diff --git a/includes/debug.class.php b/includes/debug.class.php index aec3c3080..9d8b0f8e0 100644 --- a/includes/debug.class.php +++ b/includes/debug.class.php @@ -1,71 +1,71 @@ -NestingPrevention += 1; - if($this->NestingPrevention > 1) - { - trigger_error('ErrorNesting Prevention!
'.$this->PreviousMessage, E_USER_ERROR); - } - define('IN_ERROR', true); - - if(LOCALHOST) - { - require($_EnginePath.'config.localhost.php'); - } - else if(TESTSERVER) - { - require($_EnginePath.'config.testserver.php'); - } - else - { - require($_EnginePath.'config.php'); - } - - if(!$_DBLink) - { - trigger_error('DBDriver Connection Error #01
', E_USER_ERROR); - } - if(empty($_User['id'])) - { - $_User['id'] = '0'; - } - $Replace_Search = array('{{table}}', '{{prefix}}'); - $Replace_Replace = array($__ServerConnectionSettings['prefix'].'errors', $__ServerConnectionSettings['prefix']); - - $query = "INSERT INTO {{table}} SET `error_sender` = {$_User['id']}, `error_time` = UNIX_TIMESTAMP(), `error_text` = '".mysql_real_escape_string($message)."';"; - $query = str_replace($Replace_Search, $Replace_Replace, $query); - mysql_query($query) or trigger_error('DBDriver Fatal Error #01
'.mysql_error(), E_USER_ERROR); - - $query = "SELECT LAST_INSERT_ID() as `id` FROM {{table}} LIMIT 1;"; - $query = str_replace($Replace_Search, $Replace_Replace, $query); - $q = mysql_fetch_assoc(mysql_query($query)) or trigger_error('DBDriver Fatal Error #02
'.mysql_error(), E_USER_ERROR); - - $ErrorMsg = 'An Error occured!
Error ID: '.$q['id'].''; - $this->PreviousMessage = $ErrorMsg; - - if(!function_exists('message')) - { - echo $ErrorMsg; - } - else - { - message($ErrorMsg, 'System Error!'); - } - - $this->NestingPrevention -= 1; - - mysql_close($_DBLink); - die(); - } -} - -?> \ No newline at end of file +NestingPrevention += 1; + if($this->NestingPrevention > 1) + { + trigger_error('ErrorNesting Prevention!
'.$this->PreviousMessage, E_USER_ERROR); + } + define('IN_ERROR', true); + + if(LOCALHOST) + { + require($_EnginePath.'config.localhost.php'); + } + else if(TESTSERVER) + { + require($_EnginePath.'config.testserver.php'); + } + else + { + require($_EnginePath.'config.php'); + } + + if(!$_DBLink) + { + trigger_error('DBDriver Connection Error #01
', E_USER_ERROR); + } + if(empty($_User['id'])) + { + $_User['id'] = '0'; + } + $Replace_Search = array('{{table}}', '{{prefix}}'); + $Replace_Replace = array($__ServerConnectionSettings['prefix'].'errors', $__ServerConnectionSettings['prefix']); + + $query = "INSERT INTO {{table}} SET `error_sender` = {$_User['id']}, `error_time` = UNIX_TIMESTAMP(), `error_text` = '".mysql_real_escape_string($message)."';"; + $query = str_replace($Replace_Search, $Replace_Replace, $query); + mysql_query($query) or trigger_error('DBDriver Fatal Error #01
'.mysql_error(), E_USER_ERROR); + + $query = "SELECT LAST_INSERT_ID() as `id` FROM {{table}} LIMIT 1;"; + $query = str_replace($Replace_Search, $Replace_Replace, $query); + $q = mysql_fetch_assoc(mysql_query($query)) or trigger_error('DBDriver Fatal Error #02
'.mysql_error(), E_USER_ERROR); + + $ErrorMsg = 'An Error occured!
Error ID: '.$q['id'].''; + $this->PreviousMessage = $ErrorMsg; + + if(!function_exists('message')) + { + echo $ErrorMsg; + } + else + { + message($ErrorMsg, 'System Error!'); + } + + $this->NestingPrevention -= 1; + + mysql_close($_DBLink); + die(); + } +} + +?> diff --git a/includes/functions.php b/includes/functions.php index 2b6818bc7..5b2931d5b 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -1,1317 +1,1317 @@ - &$Val) - { - if((array)$Val === $Val) - { - $Val = SecureInput($Val); - } - else - { - $Val = addslashes($Val); - } - } - } - else - { - $Input = addslashes($Input); - } - } - - return $Input; -} - -function isPro($_User = false) -{ - if($_User === false) - { - global $_User; - } - if($_User['pro_time'] > time() OR BETA === TRUE) - { - return TRUE; - } - else - { - return FALSE; - } -} - -function isLogged() -{ - global $_User; - - if(isset($_User['id']) && $_User['id'] > 0) - { - return TRUE; - } - else - { - return FALSE; - } -} - -function loggedCheck($noAlert = false) -{ - global $_Lang, $_DontShowMenus; - - if(!isLogged()) - { - $_DontShowMenus = true; - if($noAlert === true) - { - die(); - } - else - { - message($_Lang['YouAreNotLogged'], $_Lang['NotLoggedTitle'], 'login.php', 3); - } - } -} - -function isOnVacation($_User = false) -{ - if($_User === false) - { - global $_User; - } - if($_User['is_onvacation'] == 1) - { - return true; - } - return false; -} - -function canTakeVacationOff($time = false) -{ - global $_User; - if($_User['vacation_type'] != 0) - { - return true; - } - if($time === false) - { - $time = time(); - } - $MinimalVacationTime = ($_User['pro_time'] > $_User['vacation_starttime'] ? MINURLOP_PRO : MINURLOP_FREE) + $_User['vacation_starttime']; - if($MinimalVacationTime <= $time) - { - return true; - } - return false; -} - -// AuthLevel Checks -function CheckAuth($Type, $CheckMode = AUTHCHECK_NORMAL, $TheUser = false) -{ - $TypesArray = array - ( - 'gameowner' => AUTHLEVEL_GAMEOWNER, - 'owner' => AUTHLEVEL_GAMEOWNER, - 'programmer' => AUTHLEVEL_PROGRAMMER, - 'mainadmin' => AUTHLEVEL_MAINADMIN, - 'supportadmin' => AUTHLEVEL_SUPPORTADMIN, - 'supergameoperator' => AUTHLEVEL_SUPERGAMEOPERATOR, - 'sgo' => AUTHLEVEL_SUPERGAMEOPERATOR, - 'gameoperator' => AUTHLEVEL_GAMEOPERATOR, - 'go' => AUTHLEVEL_GAMEOPERATOR, - 'forumteam' => AUTHLEVEL_FORUMTEAM, - 'user' => AUTHLEVEL_USER - ); - - if(!in_array($Type, array_keys($TypesArray)) OR !in_array($CheckMode, array(1, 2))) - { - return null; - } - - if($TheUser === false) - { - global $_User; - $TheUser = &$_User; - } - - if($CheckMode == AUTHCHECK_NORMAL) - { - if(isset($TheUser['authlevel']) && $TheUser['authlevel'] >= $TypesArray[$Type]) - { - return true; - } - } - else if($CheckMode == AUTHCHECK_HIGHER) - { - if(isset($TheUser['authlevel']) && $TheUser['authlevel'] > $TypesArray[$Type]) - { - return true; - } - } - else if($CheckMode == AUTHCHECK_EXACT) - { - if(isset($TheUser['authlevel']) && $TheUser['authlevel'] == $TypesArray[$Type]) - { - return true; - } - } - return false; -} - -function GetAuthLabel($TheUser) -{ - if($TheUser['authlevel'] >= AUTHLEVEL_GAMEOWNER) - { - return AUTHLEVEL_GAMEOWNER; - } - if($TheUser['authlevel'] >= AUTHLEVEL_PROGRAMMER) - { - return AUTHLEVEL_PROGRAMMER; - } - if($TheUser['authlevel'] >= AUTHLEVEL_MAINADMIN) - { - return AUTHLEVEL_MAINADMIN; - } - if($TheUser['authlevel'] >= AUTHLEVEL_SUPPORTADMIN) - { - return AUTHLEVEL_SUPPORTADMIN; - } - if($TheUser['authlevel'] >= AUTHLEVEL_SUPERGAMEOPERATOR) - { - return AUTHLEVEL_SUPERGAMEOPERATOR; - } - if($TheUser['authlevel'] >= AUTHLEVEL_GAMEOPERATOR) - { - return AUTHLEVEL_GAMEOPERATOR; - } - if($TheUser['authlevel'] >= AUTHLEVEL_FORUMTEAM) - { - return AUTHLEVEL_FORUMTEAM; - } - return AUTHLEVEL_USER; -} - -function is_email($email) -{ - return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email)); -} - -function CalculateMaxPlanetFields($planet) -{ - global $_Vars_GameElements; - return $planet['field_max'] + ($planet[$_Vars_GameElements[33]] * FIELDS_ADDED_BY_TERRAFORMER); -} - -// MoraleSystem Functions -function Morale_ReCalculate(&$TheUser, $TheTime = false) -{ - if($TheUser['morale_level'] != 0) - { - if($TheTime === false) - { - $TheTime = time(); - } - - if($TheUser['morale_droptime'] < $TheTime) - { - if($TheUser['morale_lastupdate'] > $TheUser['morale_droptime']) - { - $TimeDiff = $TheTime - $TheUser['morale_lastupdate']; - $TimeStart = $TheUser['morale_lastupdate']; - } - else - { - $TimeDiff = $TheTime - $TheUser['morale_droptime']; - $TimeStart = $TheUser['morale_droptime']; - } - - $MoraleDropInterval = ($TheUser['morale_level'] > 0 ? MORALE_DROPINTERVAL_POSITIVE : MORALE_DROPINTERVAL_NEGATIVE); - $MoraleDrop = floor($TimeDiff / $MoraleDropInterval); - - if($MoraleDrop != 0) - { - if($TheUser['morale_level'] > 0) - { - $TheUser['morale_level'] -= $MoraleDrop; - if($TheUser['morale_level'] < 0) - { - $TheUser['morale_level'] = 0; - } - } - else - { - $TheUser['morale_level'] += $MoraleDrop; - if($TheUser['morale_level'] > 0) - { - $TheUser['morale_level'] = 0; - } - } - - if($TheUser['morale_level'] == 0) - { - $TheUser['morale_droptime'] = 0; - $TheUser['morale_lastupdate'] = 0; - } - else - { - $TheUser['morale_lastupdate'] = $TimeStart + ($MoraleDrop * $MoraleDropInterval); - } - - return true; - } - } - } - - return false; -} - -function Morale_AddMorale(&$TheUser, $Type, $Factor, $LevelFactor = 1, $TimeFactor = 1, $TheTime = false) -{ - $AddLevel = floor((($Factor > MORALE_MAXIMALFACTOR ? MORALE_MAXIMALFACTOR : $Factor) / 2) * $LevelFactor) * $Type; - if($AddLevel == 0) - { - return false; - } - - if($TheTime === false) - { - $TheTime = time(); - } - - $AddTime = floor($Factor * 3600 * $TimeFactor); - - $NewMoralePositive = ($AddLevel > 0 ? true : false); - $OldMoralePositive = ($TheUser['morale_level'] > 0 ? true : false); - - if($NewMoralePositive === $OldMoralePositive) - { - $TheUser['morale_level'] += $AddLevel; - if($TheUser['morale_droptime'] <= $TheTime) - { - $TheUser['morale_droptime'] = $TheTime + $AddTime; - } - else - { - $TheUser['morale_droptime'] += $AddTime; - } - } - else - { - $DropTimeDiff = $TheUser['morale_droptime'] - $TheTime; - if($AddTime > $DropTimeDiff) - { - if($DropTimeDiff < 0) - { - $DropTimeDiff = 0; - } - $TheUser['morale_droptime'] = $TheTime; - $TheUser['morale_level'] += $AddLevel; - if(($NewMoralePositive AND $TheUser['morale_level'] > 0) OR (!$NewMoralePositive AND $TheUser['morale_level'] < 0)) - { - $TheUser['morale_droptime'] += floor(($TheUser['morale_level'] / $AddLevel) * ($AddTime - $DropTimeDiff)); - } - } - else - { - $TheUser['morale_droptime'] -= $AddTime; - } - } - - if($TheUser['morale_level'] > 100) - { - $TheUser['morale_level'] = 100; - } - else if($TheUser['morale_level'] < -100) - { - $TheUser['morale_level'] = -100; - } - - $DropTimeDiff = $TheUser['morale_droptime'] - $TheTime; - $ThisMoralePositive = ($TheUser['morale_level'] > 0 ? true : false); - if($ThisMoralePositive AND $DropTimeDiff > MORALE_MAXDROPTIME_POSITIVE) - { - $TheUser['morale_droptime'] -= ($DropTimeDiff - MORALE_MAXDROPTIME_POSITIVE); - } - else if(!$ThisMoralePositive AND $DropTimeDiff > MORALE_MAXDROPTIME_NEGATIVE) - { - $TheUser['morale_droptime'] -= ($DropTimeDiff - MORALE_MAXDROPTIME_NEGATIVE); - } - - return true; -} - -// Display Functions -function AdminMessage($mes, $title = 'Error', $dest = '', $time = 3) -{ - message($mes, $title, $dest, $time, true); -} - -function message($Message, $Title = 'Error', $RedirectLocation = '', $RedirectTime = '3', $IsAdminMsg = false) -{ - global $page; - - $parse['title'] = $Title; - $parse['mes'] = $Message; - - DisplayHelper_DoRedirect($RedirectLocation, $RedirectTime); - $page .= parsetemplate(gettemplate('sysmessage_body'), $parse); - display($page, $Title, false, $IsAdminMsg); -} - -function display($PageCode, $PageTitle = '', $ShowTopResourceBar = true, $IsAdminPage = false) -{ - global $_DBLink, $_GameConfig, $_User, $_SkinPath, $_Planet, $_DisplaySettings, - $_DontShowMenus, $NewMSGCount, $_BenchTool, $_Vars_AllyRankLabels; - - if(!empty($_BenchTool)){ $_BenchTool->simpleCountStart(false, 'telemetry__d'); } - - $DisplayPage = ''; - if(empty($_SkinPath)) - { - $_SkinPath = DEFAULT_SKINPATH; - } - - $ProbablyOnAdminPage = false; - preg_match('#(admin\/)?([^\/]{1,})\.php#si', $_SERVER['SCRIPT_NAME'], $match); - $pageurl = $match[2]; - if(empty($pageurl)) - { - $pageurl = 'unknown'; - } - else - { - if($match[1] == 'admin/') - { - $pageurl = 'admin/'.$pageurl; - $ProbablyOnAdminPage = true; - } - $pageurl .= '.php'; - } - $pageurl = preg_replace('#[^a-zA-Z0-9\.\_\-\/]{1,}#si', '', $pageurl); - - Handler_MailCache(); - - if($ShowTopResourceBar) - { - $DisplayPage .= ShowTopNavigationBar($_User, $_Planet); - } - else - { - if(isLogged() AND $_DontShowMenus !== true) - { - if(!defined('IN_ERROR')) - { - $NewMSGCount = doquery("SELECT COUNT(`id`) as `count` FROM {{table}} WHERE `id_owner` = {$_User['id']} AND `deleted` = false AND `read` = false;", 'messages', true); - $NewMSGCount = $NewMSGCount['count']; - } - else - { - $NewMSGCount = 0; - } - } - } - - Handler_UserDevLogs(); - Handler_UserTasksUpdate(); - Handler_SystemAlerts(); - - $Parse['TaskInfoBar'] = GlobalTemplate_GetTaskBox(); - $Parse['SkinPath'] = $_SkinPath; - $Parse['PHP_InjectAfterBody'] = GlobalTemplate_GetAfterBody()."\n"; - $Parse['PHP_InjectIntoBottomMenu'] = GlobalTemplate_GetBottomMenuInjection(); - $Parse['PHP_Meta'] = DisplayHelper_GetRedirect(); - - if(!empty($_BenchTool) AND (isset($_GET['showbenchresult']) && $_GET['showbenchresult'] == 'true')) - { - $PageCode .= '{PLACE_BENCHRESULT_HERE}'; - } - - $DisplayPage .= $PageCode; - - $TopMenuAdmin = false; - if($_DontShowMenus === true) - { - $TPL = gettemplate('game_main_body_simple'); - if($IsAdminPage OR (CheckAuth('user', AUTHCHECK_HIGHER) AND $ProbablyOnAdminPage)) - { - $TopMenuAdmin = true; - $Parse['AdminBack'] = '../'; - } - if(empty($PageTitle)) - { - $Parse['title'] = $_GameConfig['game_name']; - } - else - { - $Parse['title'] = $PageTitle.' - '.$_GameConfig['game_name']; - } - $Parse['game_content_replace'] = $DisplayPage; - $Page = parsetemplate($TPL, $Parse); - } - else - { - $TPL = gettemplate('game_main_body'); - if($IsAdminPage OR (CheckAuth('user', AUTHCHECK_HIGHER) AND $ProbablyOnAdminPage)) - { - $TopMenuAdmin = true; - $Parse['AdminBack'] = '../'; - } - - if($_User['id'] > 0) - { - $Parse['InsertChatMsgCount'] = '0'; - $Parse['Insert_AllyChat_MsgCount'] = '0'; - - if(!defined('IN_ERROR')) - { - if($_DisplaySettings['dontShow_MainChat_MsgCount'] !== true) - { - $Query_Counters[0] = ''; - $Query_Counters[0] .= "(SELECT '1' AS `Type`, COUNT(`msg`.`ID`) AS `Count` "; - $Query_Counters[0] .= "FROM `{{prefix}}chat_messages` AS `msg` "; - $Query_Counters[0] .= "LEFT JOIN `{{prefix}}chat_online` AS `visit` ON `visit`.`RID` = 0 AND `visit`.`UID` = {$_User['id']} "; - $Query_Counters[0] .= "WHERE `msg`.`RID` = 0 AND `msg`.`TimeStamp_Add` > IF(`visit`.`LastOnline` > 0, `visit`.`LastOnline`, 0))"; - } - if($_User['ally_ChatRoom_ID'] > 0 AND $_DisplaySettings['dontShow_AllyChat_MsgCount'] !== true) - { - $Query_Counters[1] = ''; - $Query_Counters[1] .= "(SELECT '2' AS `Type`, COUNT(`msg`.`ID`) AS `Count` "; - $Query_Counters[1] .= "FROM `{{prefix}}chat_messages` AS `msg` "; - $Query_Counters[1] .= "LEFT JOIN `{{prefix}}chat_online` AS `visit` ON `visit`.`RID` = {$_User['ally_ChatRoom_ID']} AND `visit`.`UID` = {$_User['id']} "; - $Query_Counters[1] .= "WHERE `msg`.`RID` = {$_User['ally_ChatRoom_ID']} AND `msg`.`TimeStamp_Add` > IF(`visit`.`LastOnline` > 0, `visit`.`LastOnline`, 0))"; - } - $Query_Counters[2] = "(SELECT '3' AS `Type`, COUNT(*) AS `Count` FROM `{{prefix}}buddy` WHERE `owner` = {$_User['id']} AND `active` = 0)"; - - $Query_Counters = implode(' UNION ', $Query_Counters); - $GetCounters = doquery($Query_Counters, ''); - while($CountersData = mysql_fetch_assoc($GetCounters)) - { - if($CountersData['Type'] == 1) - { - $Parse['InsertChatMsgCount'] = prettyNumber($CountersData['Count']); - if($CountersData['Count'] > 0) - { - $Parse['InsertChatMsgCount'] = ''.$Parse['InsertChatMsgCount'].''; - } - } - elseif($CountersData['Type'] == 2) - { - $Parse['Insert_AllyChat_MsgCount'] = prettyNumber($CountersData['Count']); - if($CountersData['Count'] > 0) - { - $Parse['Insert_AllyChat_MsgCount'] = ''.$Parse['Insert_AllyChat_MsgCount'].''; - } - } - elseif($CountersData['Type'] == 3) - { - if($CountersData['Count'] > 0) - { - $Parse['InsertBuddyCount'] = ' ('.prettyNumber($CountersData['Count']).')'; - } - } - } - } - - if($_User['ally_ChatRoom_ID'] > 0 && (!isset($_DisplaySettings['dontShow_AllyChat_Link']) || $_DisplaySettings['dontShow_AllyChat_Link'] !== true)) - { - $InsertAllyChatLink = false; - if($_User['ally_owner'] == $_User['id']) - { - $InsertAllyChatLink = true; - } - else - { - $Temp1 = json_decode($_User['ally_ranks'], true); - foreach($Temp1 as $RankID => $RankData) - { - if($RankID != $_User['ally_rank_id']) - { - continue; - } - foreach($RankData as $DataID => $DataVal) - { - $Temp2[$_Vars_AllyRankLabels[$DataID]] = $DataVal; - } - } - if($Temp2['canusechat'] === true) - { - $InsertAllyChatLink = true; - } - } - if($InsertAllyChatLink === true) - { - global $_LeftMenuSettings; - $_LeftMenuSettings['LM_Insert_AllyChatLink'] = array('rid' => $_User['ally_ChatRoom_ID'], 'count' => $Parse['Insert_AllyChat_MsgCount']); - } - } - } - - $TopMenuLang = includeLang('topmenu', true); - $Parse = array_merge($Parse, $TopMenuLang); - - $Parse['UserID'] = $_User['id']; - $Parse['Username'] = $_User['username']; - - if(isPro()) - { - $Parse['AccType_Color'] = 'red'; - $Parse['AccType_Title'] = $Parse['ProTitle']; - $Parse['AccType_Name']= $Parse['Pro']; - } - else - { - $Parse['AccType_Color'] = 'orange'; - $Parse['AccType_Title'] = $Parse['FreeTitle']; - $Parse['AccType_Name']= $Parse['Free']; - } - if(CheckAuth('go')) - { - $GetAuthLabel = GetAuthLabel($_User); - if($GetAuthLabel == 50) - { - $Parse['AdminLinkTitle']= $Parse['GOLinkTitle']; - $Parse['admin'] = $Parse['go_cp']; - } - elseif($GetAuthLabel == 70) - { - $Parse['AdminLinkTitle']= $Parse['SGOLinkTitle']; - $Parse['admin'] = $Parse['sgo_cp']; - } - else - { - $Parse['admin'] = $Parse['admin_cp']; - } - - if($TopMenuAdmin === true) - { - $Parse['AdminLink'] = ''.$Parse['admin'].''; - } - else - { - $Parse['AdminLink'] = ''.$Parse['admin'].''; - } - } - - if($_User['total_rank'] > 0) - { - $Parse['userpoints'] = $_User['total_rank']; - } - else - { - $Parse['userpoints'] = '0'; - } - $Parse['now'] = date('d.m.Y H:i:s'); - $Parse['ServerTimestamp'] = time(); - - if($IsAdminPage OR (CheckAuth('user', AUTHCHECK_HIGHER) AND $ProbablyOnAdminPage === true)) - { - $GetAuthLabel = GetAuthLabel($_User); - if($GetAuthLabel == 50) - { - $AdminTPL = 'left_menu_go'; - } - elseif($GetAuthLabel == 70) - { - $AdminTPL = 'left_menu_sgo'; - } - elseif($GetAuthLabel >= 90) - { - $AdminTPL = 'left_menu'; - } - else - { - $AdminTPL = 'left_menu_safe'; - } - $Parse['left_menu_replace'] = ShowLeftMenu('admin/'.$AdminTPL); - } - else - { - $Parse['left_menu_replace'] = ShowLeftMenu(); - } - $Parse['game_content_replace'] = $DisplayPage; - $Parse['title'] = (!empty($PageTitle) ? $PageTitle.' - ' : '').$_GameConfig['game_name']; - $Page = parsetemplate($TPL, $Parse); - } - - if(!empty($_BenchTool)){ $_BenchTool->simpleCountStop(); } - - if(!empty($_BenchTool)) - { - $BenchResult = $_BenchTool->ReturnResult(); - if(isset($_GET['showbenchresult']) && $_GET['showbenchresult'] == 'true') - { - $Page = str_replace('{PLACE_BENCHRESULT_HERE}', $BenchResult, $Page); - } - } - Handler_Telemetry($pageurl); - - if(is_resource($_DBLink)) - { - mysql_close($_DBLink); - } - echo $Page; - die(); -} - -function safeDie($DieMsg = '') -{ - global $_DBLink, $_BenchTool; - - preg_match('#(admin\/)?([^\/]{1,})\.php#si', $_SERVER['SCRIPT_NAME'], $match); - $pageurl = $match[2]; - if(empty($pageurl)) - { - $pageurl = 'unknown'; - } - else - { - if($match[1] == 'admin/') - { - $pageurl = 'admin/'.$pageurl; - } - $pageurl .= '.php'; - } - $pageurl = preg_replace('#[^a-zA-Z0-9\.\_\-\/]{1,}#si', '', $pageurl); - - Handler_MailCache(); - Handler_UserDevLogs(); - Handler_UserTasksUpdate(); - Handler_SystemAlerts(); - - if(!empty($_BenchTool)) - { - $BenchResult = $_BenchTool->ReturnResult(); - } - Handler_Telemetry($pageurl); - - if(isset($_DBLink)) - { - mysql_close($_DBLink); - } - die($DieMsg); -} - -function ShowLeftMenu($Template = 'left_menu') -{ - global $_Lang, $_SkinPath, $_GameConfig, $NewMSGCount, $_LeftMenuSettings; - - includeLang('leftmenu'); - if(strstr($Template, 'admin/')) - { - includeLang('admin'); - } - - $Since = 2010; - $MenuTPL = gettemplate($Template); - $parse = $_Lang; - $parse['GameVersion'] = VERSION; - $parse['GameBuild'] = REVISION; - $parse['skinpath'] = $_SkinPath; - - if($NewMSGCount > 0) - { - $parse['Messages_Color'] = 'orange'; - $parse['Messages_AddCounter'] = '('.$NewMSGCount.')'; - } - if(!empty($_LeftMenuSettings['LM_Insert_AllyChatLink'])) - { - $parse['LM_Insert_AllyChatLink'] = "({$_LeftMenuSettings['LM_Insert_AllyChatLink']['count']})"; - } - - $parse['servername'] = $_GameConfig['game_name']; - $parse['CopyTime'] = ($Since == date('Y')) ? $Since : $Since.' - '.date('Y'); - $Menu = parsetemplate( $MenuTPL, $parse); - - return $Menu; -} - -function DisplayHelper_DoRedirect($Location, $Delay) -{ - global $UEV_DisplayHelper_DoRedirect; - - $UEV_DisplayHelper_DoRedirect = array('location' => $Location, 'delay' => $Delay); -} -function DisplayHelper_GetRedirect() -{ - global $UEV_DisplayHelper_DoRedirect; - - if(!empty($UEV_DisplayHelper_DoRedirect['location'])) - { - return ''; - } - else - { - return ''; - } -} -function GlobalTemplate_AppendToAfterBody($code) -{ - global $_Templates_InsertJustAfterBody; - - $_Templates_InsertJustAfterBody .= $code; -} -function GlobalTemplate_AppendToBottomMenuInjection($code) -{ - global $_Templates_BottomMenuInjection; - - $_Templates_BottomMenuInjection .= $code; -} -function GlobalTemplate_AppendToTaskBox($code) -{ - global $_Templates_TaskBox; - - $_Templates_TaskBox .= $code; -} -function GlobalTemplate_GetAfterBody() -{ - global $_Templates_InsertJustAfterBody; - - return $_Templates_InsertJustAfterBody; -} -function GlobalTemplate_GetBottomMenuInjection() -{ - global $_Templates_BottomMenuInjection; - - return $_Templates_BottomMenuInjection; -} -function GlobalTemplate_GetTaskBox() -{ - global $_Templates_TaskBox; - - return $_Templates_TaskBox; -} - -//////////////////////////////////////////////// -//////////////////////////////////////////////// -//////////////////////////////////////////////// - -function multidim2onedim($array, $first_time = true) -{ - static $temp; - - foreach($array as $val) - { - if(is_array($val)) - { - multidim2onedim($val, false); - } - else - { - $temp[] = $val; - } - } - - $return = $temp; - if($first_time === true) - { - $temp = false; - } - return $return; -} - -function innerReplace($array, $replaceArray) -{ - foreach($array as $key => $val) - { - if(isset($array[$key])) - { - $val = preg_replace('#\{([a-z0-9\-_]*?)\}\[([a-z0-9\-_]*?)\]#Ssie', '( ( isset($replaceArray[\'\1\'][\'\2\']) ) ? $replaceArray[\'\1\'][\'\2\'] : \'\' );', $val); - $val = preg_replace('#\{([a-z0-9\-_]*?)\}#Ssie', '( ( isset($replaceArray[\'\1\']) ) ? $replaceArray[\'\1\'] : \'\' );', $val); - - $ocurence = substr_count($val, '%s'); - - if($ocurence > 0) - { - for($i = 0; $i < $ocurence; $i += 1) - { - $ArgArr[] = $array[($key + $i + 1)]; - unset($array[($key + $i + 1)]); - } - $val = vsprintf($val, $ArgArr); - $ArgArr = false; - } - - $temp[] = $val; - } - } - - return $temp; -} - -function ServerStamp($TimeStamp = false) -{ - if($TimeStamp !== false AND $TimeStamp > SERVER_MAINOPEN_TSTAMP) - { - $Stamp = $TimeStamp; - } - else - { - $Stamp = time(); - } - return $Stamp - SERVER_MAINOPEN_TSTAMP; -} - -function CreateAccessLog($RootPath = '', $Prepend2Filename = '') -{ - global $_User, $_SERVER, $_POST; - - // --- Look for or Create LogDir --- - if(isset($_User['id']) && $_User['id'] > 0) - { - $Log_UserID = str_pad($_User['id'], 6, '0', STR_PAD_LEFT); - } - else - { - $Log_UserID = '000000'; - } - $Log_DirName = "{$RootPath}action_logs/{$Log_UserID}"; - - if(!(file_exists($Log_DirName) AND is_dir($Log_DirName))) - { - mkdir($Log_DirName); - file_put_contents($Log_DirName.'/index.php', ''); - } - - // --- Get Current Date and Time --- - $Date = explode('_', date('Y_m_d_H_i_s')); - $CDay = "{$Date[0]}_{$Date[1]}_{$Date[2]}"; - $CTim = ($Date[3] * 3600) + ($Date[4] * 60) + $Date[5]; - - // --- Create Post Hash --- - if(!empty($_POST)) - { - $PackPOST = json_encode($_POST); - $PostHash = md5($PackPOST); - } - else - { - $PackPOST = 'N'; - $PostHash = '8d9c307cb7f3c4a32822a51922d1ceaa'; - } - // --- Create other data --- - $CurrentBrowser = addslashes(trim($_SERVER['HTTP_USER_AGENT'])); - $CurrentScreen = (isset($_User['new_screen_settings']) ? $_User['new_screen_settings'] : ''); - - // --- Get CurrentFile Name --- - $ScriptRequestData = explode('/', $_SERVER['SCRIPT_NAME']); - $FileName = $Prepend2Filename.end($ScriptRequestData).str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['REQUEST_URI']); - $PageHash = md5($FileName); - - // --- Set CurrentLog Name & Path --- - $Log_FileName = "Log_U_{$Log_UserID}_D_{$CDay}.php"; - $Log_FilePath = "{$Log_DirName}/{$Log_FileName}"; - $LastDataFilepath = $Log_DirName.'/GetLastData.php'; - $WriteLogDataFile = false; - if(!file_exists($Log_FilePath)) - { - // This Log is not created yet - $AddDie = true; - $WriteLogDataFile = true; - } - else - { - // This Log was already created - $AddDie = false; - if(file_exists($LastDataFilepath)) - { - // Data about last log are not empty - include($LastDataFilepath); - } - else - { - // Data about last log are empty - $WriteLogDataFile = true; - } - } - - if(!isset($LastLoggedIP)) - { - $LastLoggedIP = ''; - } - if(!isset($LastBrowser)) - { - $LastBrowser = ''; - } - if(!isset($LastScreenSettings)) - { - $LastScreenSettings = ''; - } - if(!isset($LastPageHash)) - { - $LastPageHash = ''; - } - if(!isset($LastPostHash)) - { - $LastPostHash = ''; - } - - $LogFile = fopen($Log_FilePath, 'a'); - $FileSize = filesize($Log_FilePath); - $LogDataNow = ''; - if($AddDie === false) - { - ftruncate($LogFile, $FileSize - 4); - } - else - { - $LogDataNow = '"); - } - if($LastPageHash === $PageHash) - { - $FileName = 'R'; - if($LastPostHash === $PostHash) - { - $PackPOST = ''; - } - } - if(!empty($PackPOST)) - { - $PackPOST = '|'.$PackPOST; - } - $LogDataNow .= "{$CTim}|{$FileName}{$PackPOST}"; - fwrite($LogFile, "{$LogDataNow}\n*/?>"); - fclose($LogFile); -} - -function Handler_MailCache() -{ - global $_Cache; - - if(!empty($_Cache['Messages'])) - { - SendSimpleMultipleMessages($_Cache['Messages']); - } -} - -function Handler_Telemetry($pageurl) -{ - global $_User, $_BenchTool, $_GameConfig, $DisableTelemetry, $_GET, $_POST, $_MemCache; - - if($_GameConfig['TelemetryEnabled'] == 1 AND !empty($_BenchTool) AND $DisableTelemetry !== true) - { - $TimeArray = $_BenchTool->ReturnTimeArray(); - $SimpleArray = $_BenchTool->ReturnSimpleCountArray(); - - $TelemetryData['_t'] = end($TimeArray); - foreach($SimpleArray as $Data) - { - if(strstr($Data['name'], 'telemetry_')) - { - if(isset($Data['result']) && $Data['result'] > 0) - { - $TelemetryData[str_replace('telemetry_', '', $Data['name'])] = $Data['result']; - } - } - } - - $TelemetryPage['page'] = $TelemetryPage['hash'] = $pageurl; - $TelemetryPage['hash'] .= '|'; - foreach($_GET as $Key => $Value) - { - if(in_array($Key, array('mode', 'cmd', 'type'))) - { - if(is_string($Value) OR is_numeric($Value)) - { - $TelemetryPage['get'][$Key] = $Key.'='.preg_replace('#[^a-zA-Z0-9\.\_\-\/]{1,}#si', '*', $Value); - } - else - { - $TelemetryPage['get'][$Key] = $Key.'=(utype)'; - } - $TelemetryPage['hash'] .= $TelemetryPage['get'][$Key].'|'; - } - } - if(!empty($_POST)) - { - $TelemetryPage['post'] = '1'; - } - else - { - $TelemetryPage['post'] = '0'; - } - $TelemetryPage['hash'] .= 'post'.$TelemetryPage['post']; - $TelemetryPage['hash'] = md5($TelemetryPage['hash']); - $TelemetryPage['cacheKey'] = 'Telemetry_pid_'.$TelemetryPage['hash']; - $TelemetryPage['id'] = false; - - if(UNIENGINE_HASAPC) - { - $TelemetryPage['id'] = $_MemCache->$TelemetryPage['cacheKey']; - $FromCache = true; - } - if($TelemetryPage['id'] === false) - { - $FromCache = false; - $SelectPageID = doquery("SELECT `ID` FROM {{table}} WHERE `Hash` = '{$TelemetryPage['hash']}' LIMIT 1;", 'telemetry_pages', true); - if(!($SelectPageID['ID'] > 0)) - { - if(!empty($TelemetryPage['get'])) - { - $TelemetryPage['implodeget'] = implode('&', $TelemetryPage['get']); - } - else - { - $TelemetryPage['implodeget'] = ''; - } - doquery("INSERT INTO {{table}} VALUES (NULL, '{$TelemetryPage['page']}', '{$TelemetryPage['implodeget']}', '{$TelemetryPage['hash']}', {$TelemetryPage['post']});", 'telemetry_pages'); - $SelectPageID = doquery("SELECT LAST_INSERT_ID() as `ID`;", '', true); - $TelemetryPage['id'] = $SelectPageID['ID']; - } - else - { - $TelemetryPage['id'] = $SelectPageID['ID']; - } - } - if($TelemetryPage['id'] > 0) - { - $ThisUserID = (isset($_User['id']) && $_User['id'] > 0) ? $_User['id'] : 0; - - if($FromCache !== true AND UNIENGINE_HASAPC) - { - $_MemCache->$TelemetryPage['cacheKey'] = $TelemetryPage['id']; - } - foreach($TelemetryData as $Key => $Data) - { - $TelemetryData[$Key] = sprintf('%0.6f', $Data); - } - $TelemetryQuery = "INSERT INTO {{table}} VALUES (NULL, {$TelemetryPage['id']}, {$ThisUserID}, UNIX_TIMESTAMP(), '".json_encode($TelemetryData)."');"; - doquery($TelemetryQuery, 'telemetry_data'); - } - } -} - -function Handler_UserDevLogs() -{ - global $UserDev_Log, $_User; - - if(!empty($UserDev_Log)) - { - $UserDev_Log_Query = "INSERT INTO {{table}} (`ID`, `UserID`, `Date`, `Place`, `PlanetID`, `Code`, `ElementID`, `AdditionalData`) VALUES "; - foreach($UserDev_Log as $ThisData) - { - if(empty($ThisData['AdditionalData'])) - { - $ThisData['AdditionalData'] = 'NULL'; - } - else - { - $ThisData['AdditionalData'] = "'{$ThisData['AdditionalData']}'"; - } - if(isset($ThisData['UserID']) && $ThisData['UserID'] > 0) - { - $SetUser = $ThisData['UserID']; - } - else - { - $SetUser = $_User['id']; - } - $ThisData['Date'] = $ThisData['Date'] - SERVER_MAINOPEN_TSTAMP; - $UserDev_Log_Query_Array[] = "(NULL, {$SetUser}, {$ThisData['Date']}, {$ThisData['Place']}, {$ThisData['PlanetID']}, {$ThisData['Code']}, {$ThisData['ElementID']}, {$ThisData['AdditionalData']})"; - } - $UserDev_Log_Query .= implode(', ', $UserDev_Log_Query_Array); - doquery($UserDev_Log_Query, 'user_developmentlog'); - } -} - -function Handler_UserTasksUpdate() -{ - global $_User, $UserTasksUpdate, $GlobalParsedTasks, $_Vars_TasksData; - - if(!empty($UserTasksUpdate)) - { - foreach($UserTasksUpdate as $UserID => $UserData) - { - if($UserID == $_User['id']) - { - $UserParsedTasks = $UserParsedTasksOrg = $_User['tasks_done_parsed']; - } - else - { - $UserParsedTasks = $UserParsedTasksOrg = $GlobalParsedTasks[$UserID]['tasks_done_parsed']; - } - - if(!empty($UserData['done'])) - { - foreach($UserData['done'] as $CatID => $CatData) - { - foreach($CatData as $TaskID => $TaskJobs) - { - $TotalCount = count($TaskJobs); - if(isset($UserParsedTasks['jobs'][$CatID][$TaskID])) - { - $TotalCount += count($UserParsedTasks['jobs'][$CatID][$TaskID]); - } - if($TotalCount == count($_Vars_TasksData[$CatID]['tasks'][$TaskID]['jobs'])) - { - $UserParsedTasks['locked'][$CatID][] = $TaskID; - unset($UserParsedTasks['jobs'][$CatID][$TaskID]); - unset($UserParsedTasks['status'][$CatID][$TaskID]); - unset($UserParsedTasks['jobdata'][$CatID][$TaskID]); - } - else - { - foreach($TaskJobs as $TaskJobDone) - { - $UserParsedTasks['jobs'][$CatID][$TaskID][] = $TaskJobDone; - unset($UserParsedTasks['status'][$CatID][$TaskID][$TaskJobDone]); - unset($UserParsedTasks['jobdata'][$CatID][$TaskID][$TaskJobDone]); - } - } - } - - if(isset($UserParsedTasks['status'][$CatID]) AND empty($UserParsedTasks['status'][$CatID])) - { - unset($UserParsedTasks['status'][$CatID]); - unset($UserParsedTasks['jobdata'][$CatID]); - } - } - } - if(!empty($UserData['status'])) - { - foreach($UserData['status'] as $CatID => $CatData) - { - foreach($CatData as $TaskID => $TaskJobs) - { - foreach($TaskJobs as $JobID => $JobStatus) - { - $UserParsedTasks['status'][$CatID][$TaskID][$JobID] = $JobStatus; - } - } - } - } - if(!empty($UserData['jobdata'])) - { - foreach($UserData['jobdata'] as $CatID => $CatData) - { - foreach($CatData as $TaskID => $TaskJobs) - { - foreach($TaskJobs as $JobID => $JobStatus) - { - $UserParsedTasks['jobdata'][$CatID][$TaskID][$JobID] = $JobStatus; - } - } - } - } - if(empty($UserParsedTasks['status'])) - { - unset($UserParsedTasks['status']); - } - if(empty($UserParsedTasks['jobdata'])) - { - unset($UserParsedTasks['jobdata']); - } - - // Protection against multiplied Tasks and Buggy-Unlock - if(!empty($UserParsedTasks['locked'])) - { - foreach($UserParsedTasks['locked'] as $CatID => $_Vars_TasksData) - { - if(strstr($CatID, 's')) - { - $CatID = str_replace('s', '', $CatID); - } - foreach($_Vars_TasksData as $TaskID) - { - if(!empty($UserParsedTasks[$CatID])) - { - $KeySearch = array_keys($UserParsedTasks[$CatID], $TaskID); - if(!empty($KeySearch[0])) - { - unset($UserParsedTasks[$CatID][$KeySearch[0]]); - } - } - } - if(empty($UserParsedTasks[$CatID])) - { - unset($UserParsedTasks[$CatID]); - } - } - } - - $UserParsedTasks = json_encode($UserParsedTasks); - $UserParsedTasksOrg = json_encode($UserParsedTasksOrg); - - if($UserParsedTasks != $UserParsedTasksOrg) - { - $UserTasks_UpdateArray[] = "({$UserID}, '{$UserParsedTasks}')"; - } - } - if(!empty($UserTasks_UpdateArray)) - { - $UserTasks_UpdateQuery = ''; - $UserTasks_UpdateQuery .= "INSERT INTO {{table}} (`id`, `tasks_done`) VALUES "; - $UserTasks_UpdateQuery .= implode(', ', $UserTasks_UpdateArray); - $UserTasks_UpdateQuery .= " ON DUPLICATE KEY UPDATE `tasks_done` = VALUES(`tasks_done`);"; - doquery($UserTasks_UpdateQuery, 'users'); - } - } -} - -function Alerts_Add($Sender, $Date, $Type, $Code, $Importance, $UserID, $OtherData = '') -{ - global $_SystemAlerts; - - $_SystemAlerts[] = array - ( - 'Sender' => $Sender, - 'Date' => $Date, - 'Type' => $Type, - 'Code' => $Code, - 'Importance' => $Importance, - 'User_ID' => $UserID, - 'Other_Data' => $OtherData - ); -} - -function Handler_SystemAlerts() -{ - global $_SystemAlerts; - - if(!empty($_SystemAlerts)) - { - foreach($_SystemAlerts as $Data) - { - if(!empty($Data['Other_Data'])) - { - $Data['Other_Data'] = mysql_real_escape_string(json_encode($Data['Other_Data'])); - } - $Query_Insert_Values[] = "(NULL, {$Data['Sender']}, {$Data['Date']}, {$Data['Type']}, {$Data['Code']}, {$Data['Importance']}, 0, {$Data['User_ID']}, '{$Data['Other_Data']}')"; - } - - if(!empty($Query_Insert_Values)) - { - $Query_Insert = ''; - $Query_Insert .= "INSERT INTO {{table}} (`ID`, `Sender`, `Date`, `Type`, `Code`, `Importance`, `Status`, `User_ID`, `Other_Data`) VALUES "; - $Query_Insert .= implode(', ', $Query_Insert_Values); - doquery($Query_Insert, 'system_alerts'); - } - } -} - -?> \ No newline at end of file + &$Val) + { + if((array)$Val === $Val) + { + $Val = SecureInput($Val); + } + else + { + $Val = addslashes($Val); + } + } + } + else + { + $Input = addslashes($Input); + } + } + + return $Input; +} + +function isPro($_User = false) +{ + if($_User === false) + { + global $_User; + } + if($_User['pro_time'] > time() OR BETA === TRUE) + { + return TRUE; + } + else + { + return FALSE; + } +} + +function isLogged() +{ + global $_User; + + if(isset($_User['id']) && $_User['id'] > 0) + { + return TRUE; + } + else + { + return FALSE; + } +} + +function loggedCheck($noAlert = false) +{ + global $_Lang, $_DontShowMenus; + + if(!isLogged()) + { + $_DontShowMenus = true; + if($noAlert === true) + { + die(); + } + else + { + message($_Lang['YouAreNotLogged'], $_Lang['NotLoggedTitle'], 'login.php', 3); + } + } +} + +function isOnVacation($_User = false) +{ + if($_User === false) + { + global $_User; + } + if($_User['is_onvacation'] == 1) + { + return true; + } + return false; +} + +function canTakeVacationOff($time = false) +{ + global $_User; + if($_User['vacation_type'] != 0) + { + return true; + } + if($time === false) + { + $time = time(); + } + $MinimalVacationTime = ($_User['pro_time'] > $_User['vacation_starttime'] ? MINURLOP_PRO : MINURLOP_FREE) + $_User['vacation_starttime']; + if($MinimalVacationTime <= $time) + { + return true; + } + return false; +} + +// AuthLevel Checks +function CheckAuth($Type, $CheckMode = AUTHCHECK_NORMAL, $TheUser = false) +{ + $TypesArray = array + ( + 'gameowner' => AUTHLEVEL_GAMEOWNER, + 'owner' => AUTHLEVEL_GAMEOWNER, + 'programmer' => AUTHLEVEL_PROGRAMMER, + 'mainadmin' => AUTHLEVEL_MAINADMIN, + 'supportadmin' => AUTHLEVEL_SUPPORTADMIN, + 'supergameoperator' => AUTHLEVEL_SUPERGAMEOPERATOR, + 'sgo' => AUTHLEVEL_SUPERGAMEOPERATOR, + 'gameoperator' => AUTHLEVEL_GAMEOPERATOR, + 'go' => AUTHLEVEL_GAMEOPERATOR, + 'forumteam' => AUTHLEVEL_FORUMTEAM, + 'user' => AUTHLEVEL_USER + ); + + if(!in_array($Type, array_keys($TypesArray)) OR !in_array($CheckMode, array(1, 2))) + { + return null; + } + + if($TheUser === false) + { + global $_User; + $TheUser = &$_User; + } + + if($CheckMode == AUTHCHECK_NORMAL) + { + if(isset($TheUser['authlevel']) && $TheUser['authlevel'] >= $TypesArray[$Type]) + { + return true; + } + } + else if($CheckMode == AUTHCHECK_HIGHER) + { + if(isset($TheUser['authlevel']) && $TheUser['authlevel'] > $TypesArray[$Type]) + { + return true; + } + } + else if($CheckMode == AUTHCHECK_EXACT) + { + if(isset($TheUser['authlevel']) && $TheUser['authlevel'] == $TypesArray[$Type]) + { + return true; + } + } + return false; +} + +function GetAuthLabel($TheUser) +{ + if($TheUser['authlevel'] >= AUTHLEVEL_GAMEOWNER) + { + return AUTHLEVEL_GAMEOWNER; + } + if($TheUser['authlevel'] >= AUTHLEVEL_PROGRAMMER) + { + return AUTHLEVEL_PROGRAMMER; + } + if($TheUser['authlevel'] >= AUTHLEVEL_MAINADMIN) + { + return AUTHLEVEL_MAINADMIN; + } + if($TheUser['authlevel'] >= AUTHLEVEL_SUPPORTADMIN) + { + return AUTHLEVEL_SUPPORTADMIN; + } + if($TheUser['authlevel'] >= AUTHLEVEL_SUPERGAMEOPERATOR) + { + return AUTHLEVEL_SUPERGAMEOPERATOR; + } + if($TheUser['authlevel'] >= AUTHLEVEL_GAMEOPERATOR) + { + return AUTHLEVEL_GAMEOPERATOR; + } + if($TheUser['authlevel'] >= AUTHLEVEL_FORUMTEAM) + { + return AUTHLEVEL_FORUMTEAM; + } + return AUTHLEVEL_USER; +} + +function is_email($email) +{ + return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email)); +} + +function CalculateMaxPlanetFields($planet) +{ + global $_Vars_GameElements; + return $planet['field_max'] + ($planet[$_Vars_GameElements[33]] * FIELDS_ADDED_BY_TERRAFORMER); +} + +// MoraleSystem Functions +function Morale_ReCalculate(&$TheUser, $TheTime = false) +{ + if($TheUser['morale_level'] != 0) + { + if($TheTime === false) + { + $TheTime = time(); + } + + if($TheUser['morale_droptime'] < $TheTime) + { + if($TheUser['morale_lastupdate'] > $TheUser['morale_droptime']) + { + $TimeDiff = $TheTime - $TheUser['morale_lastupdate']; + $TimeStart = $TheUser['morale_lastupdate']; + } + else + { + $TimeDiff = $TheTime - $TheUser['morale_droptime']; + $TimeStart = $TheUser['morale_droptime']; + } + + $MoraleDropInterval = ($TheUser['morale_level'] > 0 ? MORALE_DROPINTERVAL_POSITIVE : MORALE_DROPINTERVAL_NEGATIVE); + $MoraleDrop = floor($TimeDiff / $MoraleDropInterval); + + if($MoraleDrop != 0) + { + if($TheUser['morale_level'] > 0) + { + $TheUser['morale_level'] -= $MoraleDrop; + if($TheUser['morale_level'] < 0) + { + $TheUser['morale_level'] = 0; + } + } + else + { + $TheUser['morale_level'] += $MoraleDrop; + if($TheUser['morale_level'] > 0) + { + $TheUser['morale_level'] = 0; + } + } + + if($TheUser['morale_level'] == 0) + { + $TheUser['morale_droptime'] = 0; + $TheUser['morale_lastupdate'] = 0; + } + else + { + $TheUser['morale_lastupdate'] = $TimeStart + ($MoraleDrop * $MoraleDropInterval); + } + + return true; + } + } + } + + return false; +} + +function Morale_AddMorale(&$TheUser, $Type, $Factor, $LevelFactor = 1, $TimeFactor = 1, $TheTime = false) +{ + $AddLevel = floor((($Factor > MORALE_MAXIMALFACTOR ? MORALE_MAXIMALFACTOR : $Factor) / 2) * $LevelFactor) * $Type; + if($AddLevel == 0) + { + return false; + } + + if($TheTime === false) + { + $TheTime = time(); + } + + $AddTime = floor($Factor * 3600 * $TimeFactor); + + $NewMoralePositive = ($AddLevel > 0 ? true : false); + $OldMoralePositive = ($TheUser['morale_level'] > 0 ? true : false); + + if($NewMoralePositive === $OldMoralePositive) + { + $TheUser['morale_level'] += $AddLevel; + if($TheUser['morale_droptime'] <= $TheTime) + { + $TheUser['morale_droptime'] = $TheTime + $AddTime; + } + else + { + $TheUser['morale_droptime'] += $AddTime; + } + } + else + { + $DropTimeDiff = $TheUser['morale_droptime'] - $TheTime; + if($AddTime > $DropTimeDiff) + { + if($DropTimeDiff < 0) + { + $DropTimeDiff = 0; + } + $TheUser['morale_droptime'] = $TheTime; + $TheUser['morale_level'] += $AddLevel; + if(($NewMoralePositive AND $TheUser['morale_level'] > 0) OR (!$NewMoralePositive AND $TheUser['morale_level'] < 0)) + { + $TheUser['morale_droptime'] += floor(($TheUser['morale_level'] / $AddLevel) * ($AddTime - $DropTimeDiff)); + } + } + else + { + $TheUser['morale_droptime'] -= $AddTime; + } + } + + if($TheUser['morale_level'] > 100) + { + $TheUser['morale_level'] = 100; + } + else if($TheUser['morale_level'] < -100) + { + $TheUser['morale_level'] = -100; + } + + $DropTimeDiff = $TheUser['morale_droptime'] - $TheTime; + $ThisMoralePositive = ($TheUser['morale_level'] > 0 ? true : false); + if($ThisMoralePositive AND $DropTimeDiff > MORALE_MAXDROPTIME_POSITIVE) + { + $TheUser['morale_droptime'] -= ($DropTimeDiff - MORALE_MAXDROPTIME_POSITIVE); + } + else if(!$ThisMoralePositive AND $DropTimeDiff > MORALE_MAXDROPTIME_NEGATIVE) + { + $TheUser['morale_droptime'] -= ($DropTimeDiff - MORALE_MAXDROPTIME_NEGATIVE); + } + + return true; +} + +// Display Functions +function AdminMessage($mes, $title = 'Error', $dest = '', $time = 3) +{ + message($mes, $title, $dest, $time, true); +} + +function message($Message, $Title = 'Error', $RedirectLocation = '', $RedirectTime = '3', $IsAdminMsg = false) +{ + global $page; + + $parse['title'] = $Title; + $parse['mes'] = $Message; + + DisplayHelper_DoRedirect($RedirectLocation, $RedirectTime); + $page .= parsetemplate(gettemplate('sysmessage_body'), $parse); + display($page, $Title, false, $IsAdminMsg); +} + +function display($PageCode, $PageTitle = '', $ShowTopResourceBar = true, $IsAdminPage = false) +{ + global $_DBLink, $_GameConfig, $_User, $_SkinPath, $_Planet, $_DisplaySettings, + $_DontShowMenus, $NewMSGCount, $_BenchTool, $_Vars_AllyRankLabels; + + if(!empty($_BenchTool)){ $_BenchTool->simpleCountStart(false, 'telemetry__d'); } + + $DisplayPage = ''; + if(empty($_SkinPath)) + { + $_SkinPath = DEFAULT_SKINPATH; + } + + $ProbablyOnAdminPage = false; + preg_match('#(admin\/)?([^\/]{1,})\.php#si', $_SERVER['SCRIPT_NAME'], $match); + $pageurl = $match[2]; + if(empty($pageurl)) + { + $pageurl = 'unknown'; + } + else + { + if($match[1] == 'admin/') + { + $pageurl = 'admin/'.$pageurl; + $ProbablyOnAdminPage = true; + } + $pageurl .= '.php'; + } + $pageurl = preg_replace('#[^a-zA-Z0-9\.\_\-\/]{1,}#si', '', $pageurl); + + Handler_MailCache(); + + if($ShowTopResourceBar) + { + $DisplayPage .= ShowTopNavigationBar($_User, $_Planet); + } + else + { + if(isLogged() AND $_DontShowMenus !== true) + { + if(!defined('IN_ERROR')) + { + $NewMSGCount = doquery("SELECT COUNT(`id`) as `count` FROM {{table}} WHERE `id_owner` = {$_User['id']} AND `deleted` = false AND `read` = false;", 'messages', true); + $NewMSGCount = $NewMSGCount['count']; + } + else + { + $NewMSGCount = 0; + } + } + } + + Handler_UserDevLogs(); + Handler_UserTasksUpdate(); + Handler_SystemAlerts(); + + $Parse['TaskInfoBar'] = GlobalTemplate_GetTaskBox(); + $Parse['SkinPath'] = $_SkinPath; + $Parse['PHP_InjectAfterBody'] = GlobalTemplate_GetAfterBody()."\n"; + $Parse['PHP_InjectIntoBottomMenu'] = GlobalTemplate_GetBottomMenuInjection(); + $Parse['PHP_Meta'] = DisplayHelper_GetRedirect(); + + if(!empty($_BenchTool) AND (isset($_GET['showbenchresult']) && $_GET['showbenchresult'] == 'true')) + { + $PageCode .= '{PLACE_BENCHRESULT_HERE}'; + } + + $DisplayPage .= $PageCode; + + $TopMenuAdmin = false; + if($_DontShowMenus === true) + { + $TPL = gettemplate('game_main_body_simple'); + if($IsAdminPage OR (CheckAuth('user', AUTHCHECK_HIGHER) AND $ProbablyOnAdminPage)) + { + $TopMenuAdmin = true; + $Parse['AdminBack'] = '../'; + } + if(empty($PageTitle)) + { + $Parse['title'] = $_GameConfig['game_name']; + } + else + { + $Parse['title'] = $PageTitle.' - '.$_GameConfig['game_name']; + } + $Parse['game_content_replace'] = $DisplayPage; + $Page = parsetemplate($TPL, $Parse); + } + else + { + $TPL = gettemplate('game_main_body'); + if($IsAdminPage OR (CheckAuth('user', AUTHCHECK_HIGHER) AND $ProbablyOnAdminPage)) + { + $TopMenuAdmin = true; + $Parse['AdminBack'] = '../'; + } + + if($_User['id'] > 0) + { + $Parse['InsertChatMsgCount'] = '0'; + $Parse['Insert_AllyChat_MsgCount'] = '0'; + + if(!defined('IN_ERROR')) + { + if($_DisplaySettings['dontShow_MainChat_MsgCount'] !== true) + { + $Query_Counters[0] = ''; + $Query_Counters[0] .= "(SELECT '1' AS `Type`, COUNT(`msg`.`ID`) AS `Count` "; + $Query_Counters[0] .= "FROM `{{prefix}}chat_messages` AS `msg` "; + $Query_Counters[0] .= "LEFT JOIN `{{prefix}}chat_online` AS `visit` ON `visit`.`RID` = 0 AND `visit`.`UID` = {$_User['id']} "; + $Query_Counters[0] .= "WHERE `msg`.`RID` = 0 AND `msg`.`TimeStamp_Add` > IF(`visit`.`LastOnline` > 0, `visit`.`LastOnline`, 0))"; + } + if($_User['ally_ChatRoom_ID'] > 0 AND $_DisplaySettings['dontShow_AllyChat_MsgCount'] !== true) + { + $Query_Counters[1] = ''; + $Query_Counters[1] .= "(SELECT '2' AS `Type`, COUNT(`msg`.`ID`) AS `Count` "; + $Query_Counters[1] .= "FROM `{{prefix}}chat_messages` AS `msg` "; + $Query_Counters[1] .= "LEFT JOIN `{{prefix}}chat_online` AS `visit` ON `visit`.`RID` = {$_User['ally_ChatRoom_ID']} AND `visit`.`UID` = {$_User['id']} "; + $Query_Counters[1] .= "WHERE `msg`.`RID` = {$_User['ally_ChatRoom_ID']} AND `msg`.`TimeStamp_Add` > IF(`visit`.`LastOnline` > 0, `visit`.`LastOnline`, 0))"; + } + $Query_Counters[2] = "(SELECT '3' AS `Type`, COUNT(*) AS `Count` FROM `{{prefix}}buddy` WHERE `owner` = {$_User['id']} AND `active` = 0)"; + + $Query_Counters = implode(' UNION ', $Query_Counters); + $GetCounters = doquery($Query_Counters, ''); + while($CountersData = mysql_fetch_assoc($GetCounters)) + { + if($CountersData['Type'] == 1) + { + $Parse['InsertChatMsgCount'] = prettyNumber($CountersData['Count']); + if($CountersData['Count'] > 0) + { + $Parse['InsertChatMsgCount'] = ''.$Parse['InsertChatMsgCount'].''; + } + } + elseif($CountersData['Type'] == 2) + { + $Parse['Insert_AllyChat_MsgCount'] = prettyNumber($CountersData['Count']); + if($CountersData['Count'] > 0) + { + $Parse['Insert_AllyChat_MsgCount'] = ''.$Parse['Insert_AllyChat_MsgCount'].''; + } + } + elseif($CountersData['Type'] == 3) + { + if($CountersData['Count'] > 0) + { + $Parse['InsertBuddyCount'] = ' ('.prettyNumber($CountersData['Count']).')'; + } + } + } + } + + if($_User['ally_ChatRoom_ID'] > 0 && (!isset($_DisplaySettings['dontShow_AllyChat_Link']) || $_DisplaySettings['dontShow_AllyChat_Link'] !== true)) + { + $InsertAllyChatLink = false; + if($_User['ally_owner'] == $_User['id']) + { + $InsertAllyChatLink = true; + } + else + { + $Temp1 = json_decode($_User['ally_ranks'], true); + foreach($Temp1 as $RankID => $RankData) + { + if($RankID != $_User['ally_rank_id']) + { + continue; + } + foreach($RankData as $DataID => $DataVal) + { + $Temp2[$_Vars_AllyRankLabels[$DataID]] = $DataVal; + } + } + if($Temp2['canusechat'] === true) + { + $InsertAllyChatLink = true; + } + } + if($InsertAllyChatLink === true) + { + global $_LeftMenuSettings; + $_LeftMenuSettings['LM_Insert_AllyChatLink'] = array('rid' => $_User['ally_ChatRoom_ID'], 'count' => $Parse['Insert_AllyChat_MsgCount']); + } + } + } + + $TopMenuLang = includeLang('topmenu', true); + $Parse = array_merge($Parse, $TopMenuLang); + + $Parse['UserID'] = $_User['id']; + $Parse['Username'] = $_User['username']; + + if(isPro()) + { + $Parse['AccType_Color'] = 'red'; + $Parse['AccType_Title'] = $Parse['ProTitle']; + $Parse['AccType_Name']= $Parse['Pro']; + } + else + { + $Parse['AccType_Color'] = 'orange'; + $Parse['AccType_Title'] = $Parse['FreeTitle']; + $Parse['AccType_Name']= $Parse['Free']; + } + if(CheckAuth('go')) + { + $GetAuthLabel = GetAuthLabel($_User); + if($GetAuthLabel == 50) + { + $Parse['AdminLinkTitle']= $Parse['GOLinkTitle']; + $Parse['admin'] = $Parse['go_cp']; + } + elseif($GetAuthLabel == 70) + { + $Parse['AdminLinkTitle']= $Parse['SGOLinkTitle']; + $Parse['admin'] = $Parse['sgo_cp']; + } + else + { + $Parse['admin'] = $Parse['admin_cp']; + } + + if($TopMenuAdmin === true) + { + $Parse['AdminLink'] = ''.$Parse['admin'].''; + } + else + { + $Parse['AdminLink'] = ''.$Parse['admin'].''; + } + } + + if($_User['total_rank'] > 0) + { + $Parse['userpoints'] = $_User['total_rank']; + } + else + { + $Parse['userpoints'] = '0'; + } + $Parse['now'] = date('d.m.Y H:i:s'); + $Parse['ServerTimestamp'] = time(); + + if($IsAdminPage OR (CheckAuth('user', AUTHCHECK_HIGHER) AND $ProbablyOnAdminPage === true)) + { + $GetAuthLabel = GetAuthLabel($_User); + if($GetAuthLabel == 50) + { + $AdminTPL = 'left_menu_go'; + } + elseif($GetAuthLabel == 70) + { + $AdminTPL = 'left_menu_sgo'; + } + elseif($GetAuthLabel >= 90) + { + $AdminTPL = 'left_menu'; + } + else + { + $AdminTPL = 'left_menu_safe'; + } + $Parse['left_menu_replace'] = ShowLeftMenu('admin/'.$AdminTPL); + } + else + { + $Parse['left_menu_replace'] = ShowLeftMenu(); + } + $Parse['game_content_replace'] = $DisplayPage; + $Parse['title'] = (!empty($PageTitle) ? $PageTitle.' - ' : '').$_GameConfig['game_name']; + $Page = parsetemplate($TPL, $Parse); + } + + if(!empty($_BenchTool)){ $_BenchTool->simpleCountStop(); } + + if(!empty($_BenchTool)) + { + $BenchResult = $_BenchTool->ReturnResult(); + if(isset($_GET['showbenchresult']) && $_GET['showbenchresult'] == 'true') + { + $Page = str_replace('{PLACE_BENCHRESULT_HERE}', $BenchResult, $Page); + } + } + Handler_Telemetry($pageurl); + + if(is_resource($_DBLink)) + { + mysql_close($_DBLink); + } + echo $Page; + die(); +} + +function safeDie($DieMsg = '') +{ + global $_DBLink, $_BenchTool; + + preg_match('#(admin\/)?([^\/]{1,})\.php#si', $_SERVER['SCRIPT_NAME'], $match); + $pageurl = $match[2]; + if(empty($pageurl)) + { + $pageurl = 'unknown'; + } + else + { + if($match[1] == 'admin/') + { + $pageurl = 'admin/'.$pageurl; + } + $pageurl .= '.php'; + } + $pageurl = preg_replace('#[^a-zA-Z0-9\.\_\-\/]{1,}#si', '', $pageurl); + + Handler_MailCache(); + Handler_UserDevLogs(); + Handler_UserTasksUpdate(); + Handler_SystemAlerts(); + + if(!empty($_BenchTool)) + { + $BenchResult = $_BenchTool->ReturnResult(); + } + Handler_Telemetry($pageurl); + + if(isset($_DBLink)) + { + mysql_close($_DBLink); + } + die($DieMsg); +} + +function ShowLeftMenu($Template = 'left_menu') +{ + global $_Lang, $_SkinPath, $_GameConfig, $NewMSGCount, $_LeftMenuSettings; + + includeLang('leftmenu'); + if(strstr($Template, 'admin/')) + { + includeLang('admin'); + } + + $Since = 2010; + $MenuTPL = gettemplate($Template); + $parse = $_Lang; + $parse['GameVersion'] = VERSION; + $parse['GameBuild'] = REVISION; + $parse['skinpath'] = $_SkinPath; + + if($NewMSGCount > 0) + { + $parse['Messages_Color'] = 'orange'; + $parse['Messages_AddCounter'] = '('.$NewMSGCount.')'; + } + if(!empty($_LeftMenuSettings['LM_Insert_AllyChatLink'])) + { + $parse['LM_Insert_AllyChatLink'] = "({$_LeftMenuSettings['LM_Insert_AllyChatLink']['count']})"; + } + + $parse['servername'] = $_GameConfig['game_name']; + $parse['CopyTime'] = ($Since == date('Y')) ? $Since : $Since.' - '.date('Y'); + $Menu = parsetemplate( $MenuTPL, $parse); + + return $Menu; +} + +function DisplayHelper_DoRedirect($Location, $Delay) +{ + global $UEV_DisplayHelper_DoRedirect; + + $UEV_DisplayHelper_DoRedirect = array('location' => $Location, 'delay' => $Delay); +} +function DisplayHelper_GetRedirect() +{ + global $UEV_DisplayHelper_DoRedirect; + + if(!empty($UEV_DisplayHelper_DoRedirect['location'])) + { + return ''; + } + else + { + return ''; + } +} +function GlobalTemplate_AppendToAfterBody($code) +{ + global $_Templates_InsertJustAfterBody; + + $_Templates_InsertJustAfterBody .= $code; +} +function GlobalTemplate_AppendToBottomMenuInjection($code) +{ + global $_Templates_BottomMenuInjection; + + $_Templates_BottomMenuInjection .= $code; +} +function GlobalTemplate_AppendToTaskBox($code) +{ + global $_Templates_TaskBox; + + $_Templates_TaskBox .= $code; +} +function GlobalTemplate_GetAfterBody() +{ + global $_Templates_InsertJustAfterBody; + + return $_Templates_InsertJustAfterBody; +} +function GlobalTemplate_GetBottomMenuInjection() +{ + global $_Templates_BottomMenuInjection; + + return $_Templates_BottomMenuInjection; +} +function GlobalTemplate_GetTaskBox() +{ + global $_Templates_TaskBox; + + return $_Templates_TaskBox; +} + +//////////////////////////////////////////////// +//////////////////////////////////////////////// +//////////////////////////////////////////////// + +function multidim2onedim($array, $first_time = true) +{ + static $temp; + + foreach($array as $val) + { + if(is_array($val)) + { + multidim2onedim($val, false); + } + else + { + $temp[] = $val; + } + } + + $return = $temp; + if($first_time === true) + { + $temp = false; + } + return $return; +} + +function innerReplace($array, $replaceArray) +{ + foreach($array as $key => $val) + { + if(isset($array[$key])) + { + $val = preg_replace('#\{([a-z0-9\-_]*?)\}\[([a-z0-9\-_]*?)\]#Ssie', '( ( isset($replaceArray[\'\1\'][\'\2\']) ) ? $replaceArray[\'\1\'][\'\2\'] : \'\' );', $val); + $val = preg_replace('#\{([a-z0-9\-_]*?)\}#Ssie', '( ( isset($replaceArray[\'\1\']) ) ? $replaceArray[\'\1\'] : \'\' );', $val); + + $ocurence = substr_count($val, '%s'); + + if($ocurence > 0) + { + for($i = 0; $i < $ocurence; $i += 1) + { + $ArgArr[] = $array[($key + $i + 1)]; + unset($array[($key + $i + 1)]); + } + $val = vsprintf($val, $ArgArr); + $ArgArr = false; + } + + $temp[] = $val; + } + } + + return $temp; +} + +function ServerStamp($TimeStamp = false) +{ + if($TimeStamp !== false AND $TimeStamp > SERVER_MAINOPEN_TSTAMP) + { + $Stamp = $TimeStamp; + } + else + { + $Stamp = time(); + } + return $Stamp - SERVER_MAINOPEN_TSTAMP; +} + +function CreateAccessLog($RootPath = '', $Prepend2Filename = '') +{ + global $_User, $_SERVER, $_POST; + + // --- Look for or Create LogDir --- + if(isset($_User['id']) && $_User['id'] > 0) + { + $Log_UserID = str_pad($_User['id'], 6, '0', STR_PAD_LEFT); + } + else + { + $Log_UserID = '000000'; + } + $Log_DirName = "{$RootPath}action_logs/{$Log_UserID}"; + + if(!(file_exists($Log_DirName) AND is_dir($Log_DirName))) + { + mkdir($Log_DirName); + file_put_contents($Log_DirName.'/index.php', ''); + } + + // --- Get Current Date and Time --- + $Date = explode('_', date('Y_m_d_H_i_s')); + $CDay = "{$Date[0]}_{$Date[1]}_{$Date[2]}"; + $CTim = ($Date[3] * 3600) + ($Date[4] * 60) + $Date[5]; + + // --- Create Post Hash --- + if(!empty($_POST)) + { + $PackPOST = json_encode($_POST); + $PostHash = md5($PackPOST); + } + else + { + $PackPOST = 'N'; + $PostHash = '8d9c307cb7f3c4a32822a51922d1ceaa'; + } + // --- Create other data --- + $CurrentBrowser = addslashes(trim($_SERVER['HTTP_USER_AGENT'])); + $CurrentScreen = (isset($_User['new_screen_settings']) ? $_User['new_screen_settings'] : ''); + + // --- Get CurrentFile Name --- + $ScriptRequestData = explode('/', $_SERVER['SCRIPT_NAME']); + $FileName = $Prepend2Filename.end($ScriptRequestData).str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['REQUEST_URI']); + $PageHash = md5($FileName); + + // --- Set CurrentLog Name & Path --- + $Log_FileName = "Log_U_{$Log_UserID}_D_{$CDay}.php"; + $Log_FilePath = "{$Log_DirName}/{$Log_FileName}"; + $LastDataFilepath = $Log_DirName.'/GetLastData.php'; + $WriteLogDataFile = false; + if(!file_exists($Log_FilePath)) + { + // This Log is not created yet + $AddDie = true; + $WriteLogDataFile = true; + } + else + { + // This Log was already created + $AddDie = false; + if(file_exists($LastDataFilepath)) + { + // Data about last log are not empty + include($LastDataFilepath); + } + else + { + // Data about last log are empty + $WriteLogDataFile = true; + } + } + + if(!isset($LastLoggedIP)) + { + $LastLoggedIP = ''; + } + if(!isset($LastBrowser)) + { + $LastBrowser = ''; + } + if(!isset($LastScreenSettings)) + { + $LastScreenSettings = ''; + } + if(!isset($LastPageHash)) + { + $LastPageHash = ''; + } + if(!isset($LastPostHash)) + { + $LastPostHash = ''; + } + + $LogFile = fopen($Log_FilePath, 'a'); + $FileSize = filesize($Log_FilePath); + $LogDataNow = ''; + if($AddDie === false) + { + ftruncate($LogFile, $FileSize - 4); + } + else + { + $LogDataNow = '"); + } + if($LastPageHash === $PageHash) + { + $FileName = 'R'; + if($LastPostHash === $PostHash) + { + $PackPOST = ''; + } + } + if(!empty($PackPOST)) + { + $PackPOST = '|'.$PackPOST; + } + $LogDataNow .= "{$CTim}|{$FileName}{$PackPOST}"; + fwrite($LogFile, "{$LogDataNow}\n*/?>"); + fclose($LogFile); +} + +function Handler_MailCache() +{ + global $_Cache; + + if(!empty($_Cache['Messages'])) + { + SendSimpleMultipleMessages($_Cache['Messages']); + } +} + +function Handler_Telemetry($pageurl) +{ + global $_User, $_BenchTool, $_GameConfig, $DisableTelemetry, $_GET, $_POST, $_MemCache; + + if($_GameConfig['TelemetryEnabled'] == 1 AND !empty($_BenchTool) AND $DisableTelemetry !== true) + { + $TimeArray = $_BenchTool->ReturnTimeArray(); + $SimpleArray = $_BenchTool->ReturnSimpleCountArray(); + + $TelemetryData['_t'] = end($TimeArray); + foreach($SimpleArray as $Data) + { + if(strstr($Data['name'], 'telemetry_')) + { + if(isset($Data['result']) && $Data['result'] > 0) + { + $TelemetryData[str_replace('telemetry_', '', $Data['name'])] = $Data['result']; + } + } + } + + $TelemetryPage['page'] = $TelemetryPage['hash'] = $pageurl; + $TelemetryPage['hash'] .= '|'; + foreach($_GET as $Key => $Value) + { + if(in_array($Key, array('mode', 'cmd', 'type'))) + { + if(is_string($Value) OR is_numeric($Value)) + { + $TelemetryPage['get'][$Key] = $Key.'='.preg_replace('#[^a-zA-Z0-9\.\_\-\/]{1,}#si', '*', $Value); + } + else + { + $TelemetryPage['get'][$Key] = $Key.'=(utype)'; + } + $TelemetryPage['hash'] .= $TelemetryPage['get'][$Key].'|'; + } + } + if(!empty($_POST)) + { + $TelemetryPage['post'] = '1'; + } + else + { + $TelemetryPage['post'] = '0'; + } + $TelemetryPage['hash'] .= 'post'.$TelemetryPage['post']; + $TelemetryPage['hash'] = md5($TelemetryPage['hash']); + $TelemetryPage['cacheKey'] = 'Telemetry_pid_'.$TelemetryPage['hash']; + $TelemetryPage['id'] = false; + + if(UNIENGINE_HASAPC) + { + $TelemetryPage['id'] = $_MemCache->$TelemetryPage['cacheKey']; + $FromCache = true; + } + if($TelemetryPage['id'] === false) + { + $FromCache = false; + $SelectPageID = doquery("SELECT `ID` FROM {{table}} WHERE `Hash` = '{$TelemetryPage['hash']}' LIMIT 1;", 'telemetry_pages', true); + if(!($SelectPageID['ID'] > 0)) + { + if(!empty($TelemetryPage['get'])) + { + $TelemetryPage['implodeget'] = implode('&', $TelemetryPage['get']); + } + else + { + $TelemetryPage['implodeget'] = ''; + } + doquery("INSERT INTO {{table}} VALUES (NULL, '{$TelemetryPage['page']}', '{$TelemetryPage['implodeget']}', '{$TelemetryPage['hash']}', {$TelemetryPage['post']});", 'telemetry_pages'); + $SelectPageID = doquery("SELECT LAST_INSERT_ID() as `ID`;", '', true); + $TelemetryPage['id'] = $SelectPageID['ID']; + } + else + { + $TelemetryPage['id'] = $SelectPageID['ID']; + } + } + if($TelemetryPage['id'] > 0) + { + $ThisUserID = (isset($_User['id']) && $_User['id'] > 0) ? $_User['id'] : 0; + + if($FromCache !== true AND UNIENGINE_HASAPC) + { + $_MemCache->$TelemetryPage['cacheKey'] = $TelemetryPage['id']; + } + foreach($TelemetryData as $Key => $Data) + { + $TelemetryData[$Key] = sprintf('%0.6f', $Data); + } + $TelemetryQuery = "INSERT INTO {{table}} VALUES (NULL, {$TelemetryPage['id']}, {$ThisUserID}, UNIX_TIMESTAMP(), '".json_encode($TelemetryData)."');"; + doquery($TelemetryQuery, 'telemetry_data'); + } + } +} + +function Handler_UserDevLogs() +{ + global $UserDev_Log, $_User; + + if(!empty($UserDev_Log)) + { + $UserDev_Log_Query = "INSERT INTO {{table}} (`ID`, `UserID`, `Date`, `Place`, `PlanetID`, `Code`, `ElementID`, `AdditionalData`) VALUES "; + foreach($UserDev_Log as $ThisData) + { + if(empty($ThisData['AdditionalData'])) + { + $ThisData['AdditionalData'] = 'NULL'; + } + else + { + $ThisData['AdditionalData'] = "'{$ThisData['AdditionalData']}'"; + } + if(isset($ThisData['UserID']) && $ThisData['UserID'] > 0) + { + $SetUser = $ThisData['UserID']; + } + else + { + $SetUser = $_User['id']; + } + $ThisData['Date'] = $ThisData['Date'] - SERVER_MAINOPEN_TSTAMP; + $UserDev_Log_Query_Array[] = "(NULL, {$SetUser}, {$ThisData['Date']}, {$ThisData['Place']}, {$ThisData['PlanetID']}, {$ThisData['Code']}, {$ThisData['ElementID']}, {$ThisData['AdditionalData']})"; + } + $UserDev_Log_Query .= implode(', ', $UserDev_Log_Query_Array); + doquery($UserDev_Log_Query, 'user_developmentlog'); + } +} + +function Handler_UserTasksUpdate() +{ + global $_User, $UserTasksUpdate, $GlobalParsedTasks, $_Vars_TasksData; + + if(!empty($UserTasksUpdate)) + { + foreach($UserTasksUpdate as $UserID => $UserData) + { + if($UserID == $_User['id']) + { + $UserParsedTasks = $UserParsedTasksOrg = $_User['tasks_done_parsed']; + } + else + { + $UserParsedTasks = $UserParsedTasksOrg = $GlobalParsedTasks[$UserID]['tasks_done_parsed']; + } + + if(!empty($UserData['done'])) + { + foreach($UserData['done'] as $CatID => $CatData) + { + foreach($CatData as $TaskID => $TaskJobs) + { + $TotalCount = count($TaskJobs); + if(isset($UserParsedTasks['jobs'][$CatID][$TaskID])) + { + $TotalCount += count($UserParsedTasks['jobs'][$CatID][$TaskID]); + } + if($TotalCount == count($_Vars_TasksData[$CatID]['tasks'][$TaskID]['jobs'])) + { + $UserParsedTasks['locked'][$CatID][] = $TaskID; + unset($UserParsedTasks['jobs'][$CatID][$TaskID]); + unset($UserParsedTasks['status'][$CatID][$TaskID]); + unset($UserParsedTasks['jobdata'][$CatID][$TaskID]); + } + else + { + foreach($TaskJobs as $TaskJobDone) + { + $UserParsedTasks['jobs'][$CatID][$TaskID][] = $TaskJobDone; + unset($UserParsedTasks['status'][$CatID][$TaskID][$TaskJobDone]); + unset($UserParsedTasks['jobdata'][$CatID][$TaskID][$TaskJobDone]); + } + } + } + + if(isset($UserParsedTasks['status'][$CatID]) AND empty($UserParsedTasks['status'][$CatID])) + { + unset($UserParsedTasks['status'][$CatID]); + unset($UserParsedTasks['jobdata'][$CatID]); + } + } + } + if(!empty($UserData['status'])) + { + foreach($UserData['status'] as $CatID => $CatData) + { + foreach($CatData as $TaskID => $TaskJobs) + { + foreach($TaskJobs as $JobID => $JobStatus) + { + $UserParsedTasks['status'][$CatID][$TaskID][$JobID] = $JobStatus; + } + } + } + } + if(!empty($UserData['jobdata'])) + { + foreach($UserData['jobdata'] as $CatID => $CatData) + { + foreach($CatData as $TaskID => $TaskJobs) + { + foreach($TaskJobs as $JobID => $JobStatus) + { + $UserParsedTasks['jobdata'][$CatID][$TaskID][$JobID] = $JobStatus; + } + } + } + } + if(empty($UserParsedTasks['status'])) + { + unset($UserParsedTasks['status']); + } + if(empty($UserParsedTasks['jobdata'])) + { + unset($UserParsedTasks['jobdata']); + } + + // Protection against multiplied Tasks and Buggy-Unlock + if(!empty($UserParsedTasks['locked'])) + { + foreach($UserParsedTasks['locked'] as $CatID => $_Vars_TasksData) + { + if(strstr($CatID, 's')) + { + $CatID = str_replace('s', '', $CatID); + } + foreach($_Vars_TasksData as $TaskID) + { + if(!empty($UserParsedTasks[$CatID])) + { + $KeySearch = array_keys($UserParsedTasks[$CatID], $TaskID); + if(!empty($KeySearch[0])) + { + unset($UserParsedTasks[$CatID][$KeySearch[0]]); + } + } + } + if(empty($UserParsedTasks[$CatID])) + { + unset($UserParsedTasks[$CatID]); + } + } + } + + $UserParsedTasks = json_encode($UserParsedTasks); + $UserParsedTasksOrg = json_encode($UserParsedTasksOrg); + + if($UserParsedTasks != $UserParsedTasksOrg) + { + $UserTasks_UpdateArray[] = "({$UserID}, '{$UserParsedTasks}')"; + } + } + if(!empty($UserTasks_UpdateArray)) + { + $UserTasks_UpdateQuery = ''; + $UserTasks_UpdateQuery .= "INSERT INTO {{table}} (`id`, `tasks_done`) VALUES "; + $UserTasks_UpdateQuery .= implode(', ', $UserTasks_UpdateArray); + $UserTasks_UpdateQuery .= " ON DUPLICATE KEY UPDATE `tasks_done` = VALUES(`tasks_done`);"; + doquery($UserTasks_UpdateQuery, 'users'); + } + } +} + +function Alerts_Add($Sender, $Date, $Type, $Code, $Importance, $UserID, $OtherData = '') +{ + global $_SystemAlerts; + + $_SystemAlerts[] = array + ( + 'Sender' => $Sender, + 'Date' => $Date, + 'Type' => $Type, + 'Code' => $Code, + 'Importance' => $Importance, + 'User_ID' => $UserID, + 'Other_Data' => $OtherData + ); +} + +function Handler_SystemAlerts() +{ + global $_SystemAlerts; + + if(!empty($_SystemAlerts)) + { + foreach($_SystemAlerts as $Data) + { + if(!empty($Data['Other_Data'])) + { + $Data['Other_Data'] = mysql_real_escape_string(json_encode($Data['Other_Data'])); + } + $Query_Insert_Values[] = "(NULL, {$Data['Sender']}, {$Data['Date']}, {$Data['Type']}, {$Data['Code']}, {$Data['Importance']}, 0, {$Data['User_ID']}, '{$Data['Other_Data']}')"; + } + + if(!empty($Query_Insert_Values)) + { + $Query_Insert = ''; + $Query_Insert .= "INSERT INTO {{table}} (`ID`, `Sender`, `Date`, `Type`, `Code`, `Importance`, `Status`, `User_ID`, `Other_Data`) VALUES "; + $Query_Insert .= implode(', ', $Query_Insert_Values); + doquery($Query_Insert, 'system_alerts'); + } + } +} + +?> diff --git a/includes/functions/AddBuildingToQueue.php b/includes/functions/AddBuildingToQueue.php index a3ce0c0e8..f3152b356 100644 --- a/includes/functions/AddBuildingToQueue.php +++ b/includes/functions/AddBuildingToQueue.php @@ -1,83 +1,83 @@ - 1) - { - foreach($QueueArray as $QueueElement) - { - $QueueElement = explode(',', $QueueElement); - if($QueueElement[4] == 'build') - { - $TempPlanet[$_Vars_GameElements[$QueueElement[0]]] += 1; - } - else - { - $TempPlanet[$_Vars_GameElements[$QueueElement[0]]] -= 1; - } - } - } - - $BuildTime = GetBuildingTime($CurrentUser, $TempPlanet, $Element); - if($AddMode == true) - { - $BuildLevel = $TempPlanet[$_Vars_GameElements[$Element]] + 1; - } - else - { - $BuildLevel = $TempPlanet[$_Vars_GameElements[$Element]] - 1; - $BuildTime /= 2; - } - - if($QueueID == 1) - { - $BuildEndTime = time() + $BuildTime; - } - else - { - $PrevBuild = explode(',', $QueueArray[$ActualCount - 1]); - $BuildEndTime = $PrevBuild[3] + $BuildTime; - } - $QueueArray[$ActualCount] = "{$Element},{$BuildLevel},{$BuildTime},{$BuildEndTime},{$BuildMode}"; - $NewQueue = implode(';', $QueueArray); - $CurrentPlanet['buildQueue'] = $NewQueue; - } - return $QueueID; -} - -?> \ No newline at end of file + 1) + { + foreach($QueueArray as $QueueElement) + { + $QueueElement = explode(',', $QueueElement); + if($QueueElement[4] == 'build') + { + $TempPlanet[$_Vars_GameElements[$QueueElement[0]]] += 1; + } + else + { + $TempPlanet[$_Vars_GameElements[$QueueElement[0]]] -= 1; + } + } + } + + $BuildTime = GetBuildingTime($CurrentUser, $TempPlanet, $Element); + if($AddMode == true) + { + $BuildLevel = $TempPlanet[$_Vars_GameElements[$Element]] + 1; + } + else + { + $BuildLevel = $TempPlanet[$_Vars_GameElements[$Element]] - 1; + $BuildTime /= 2; + } + + if($QueueID == 1) + { + $BuildEndTime = time() + $BuildTime; + } + else + { + $PrevBuild = explode(',', $QueueArray[$ActualCount - 1]); + $BuildEndTime = $PrevBuild[3] + $BuildTime; + } + $QueueArray[$ActualCount] = "{$Element},{$BuildLevel},{$BuildTime},{$BuildEndTime},{$BuildMode}"; + $NewQueue = implode(';', $QueueArray); + $CurrentPlanet['buildQueue'] = $NewQueue; + } + return $QueueID; +} + +?> diff --git a/includes/functions/AlertSystemUtilities.php b/includes/functions/AlertSystemUtilities.php index 1c0dd3490..c16e11917 100644 --- a/includes/functions/AlertSystemUtilities.php +++ b/includes/functions/AlertSystemUtilities.php @@ -1,204 +1,204 @@ - `FailCount`;"; - $Result_SelectIPs = doquery($Query_SelectIPs, 'user_enterlog'); - - if(mysql_num_rows($Result_SelectIPs) == 0) - { - return false; - } - - $ForIntersection = array(); - $IPLogData = array(); - while($FetchData = mysql_fetch_assoc($Result_SelectIPs)) - { - if(!isset($IPLogData[$FetchData['User_ID']][$FetchData['IP_ID']]['Count'])) - { - $IPLogData[$FetchData['User_ID']][$FetchData['IP_ID']]['Count'] = 0; - } - - $ForIntersection[$FetchData['User_ID']][$FetchData['IP_ID']] = $FetchData['IP_ID']; - $IPLogData[$FetchData['User_ID']][$FetchData['IP_ID']]['Count'] += $FetchData['SumCount']; - if(!isset($IPLogData[$FetchData['User_ID']][$FetchData['IP_ID']]['LastTime']) || $IPLogData[$FetchData['User_ID']][$FetchData['IP_ID']]['LastTime'] < $FetchData['LastTime']) - { - $IPLogData[$FetchData['User_ID']][$FetchData['IP_ID']]['LastTime'] = $FetchData['LastTime']; - } - } - - if(empty($ForIntersection[$FirstUserID]) OR empty($ForIntersection[$SecondUserID])) - { - return false; - } - - $Intersection = array_intersect($ForIntersection[$FirstUserID], $ForIntersection[$SecondUserID]); - if(empty($Intersection)) - { - return false; - } - - if(!empty($ExcludeRules)) - { - if($ExcludeRules['LastTimeDiff'] > 0) - { - foreach($Intersection as $IPID) - { - $LastTimeDiff = $IPLogData[$FirstUserID][$IPID]['LastTime'] - $IPLogData[$SecondUserID][$IPID]['LastTime']; - if($LastTimeDiff < 0) - { - $LastTimeDiff *= -1; - } - if($LastTimeDiff >= $ExcludeRules['LastTimeDiff']) - { - unset($Intersection[$IPID]); - unset($IPLogData[$FirstUserID][$IPID]); - unset($IPLogData[$SecondUserID][$IPID]); - } - } - } - if($ExcludeRules['ThisTimeDiff'] > 0) - { - $ThisTimeStamp = ($ExcludeRules['ThisTimeStamp'] > 0 ? $ExcludeRules['ThisTimeStamp'] : (time() - SERVER_MAINOPEN_TSTAMP)); - foreach($Intersection as $IPID) - { - $ThisTimeMax = ($IPLogData[$FirstUserID][$IPID]['LastTime'] > $IPLogData[$SecondUserID][$IPID]['LastTime'] ? $IPLogData[$FirstUserID][$IPID]['LastTime'] : $IPLogData[$SecondUserID][$IPID]['LastTime']); - if(($ThisTimeStamp - $ThisTimeMax) >= $ExcludeRules['ThisTimeDiff']) - { - unset($Intersection[$IPID]); - unset($IPLogData[$FirstUserID][$IPID]); - unset($IPLogData[$SecondUserID][$IPID]); - } - } - } - - if(empty($Intersection)) - { - return false; - } - } - - return array('Intersect' => $Intersection, 'IPLogData' => $IPLogData); -} - -function AlertUtils_CheckFilters($FiltersData, $CacheSettings = array()) -{ - static $_FiltersCache = array(); - - if(isset($CacheSettings['DontLoad_OnlyIfCacheEmpty']) && $CacheSettings['DontLoad_OnlyIfCacheEmpty'] === true) - { - if(empty($_FiltersCache)) - { - $CacheSettings['DontLoad'] = false; - } - } - - if(!isset($CacheSettings['DontLoad']) || $CacheSettings['DontLoad'] !== true) - { - foreach($FiltersData as $Type => $Value) - { - if($Type == 'users') - { - foreach($Value as $Data) - { - $FilterSearch[] = '{USER_'.$Data.'}'; - } - } - else if($Type == 'ips') - { - foreach($Value as $Data) - { - $FilterSearch[] = '{IP_'.$Data.'}'; - } - } - else if($Type == 'place') - { - $FilterSearch[] = '{PLACE_'.$Value.'}'; - } - else if($Type == 'alertsender') - { - $FilterSearch[] = '{ALERTSENDER_'.$Value.'}'; - } - } - - $Query_GetFilters = ''; - $Query_GetFilters .= "SELECT `ID`, `ActionType`, `EvalCode` FROM {{table}} WHERE `Enabled` = 1 AND "; - $Query_GetFilters .= "(`SearchData` = ''"; - if(!empty($FilterSearch)) - { - foreach($FilterSearch as $Key => $Data) - { - $FilterSearch[$Key] = "`SearchData` LIKE '%{$Data}%'"; - } - $Query_GetFilters .= " OR ".implode(' OR ', $FilterSearch); - } - $Query_GetFilters .= ");"; - $Result_GetFilters = doquery($Query_GetFilters, 'system_alerts_filters'); - - if(mysql_num_rows($Result_GetFilters) > 0) - { - while($Filter = mysql_fetch_assoc($Result_GetFilters)) - { - $Filters[] = $Filter; - if($CacheSettings['Save'] === true) - { - $_FiltersCache[$Filter['ID']] = array - ( - 'ID' => $Filter['ID'], - 'EvalCode' => $Filter['EvalCode'], - 'ActionType' => $Filter['ActionType'] - ); - } - } - } - } - if(isset($CacheSettings['UseCache']) && $CacheSettings['UseCache'] === true) - { - if(!empty($_FiltersCache)) - { - foreach($_FiltersCache as $Filter) - { - $Filters[] = $Filter; - } - } - } - - $Return = array('FilterUsed' => false, 'SendAlert' => true, 'ShowAlert' => true); - - if(!empty($Filters)) - { - foreach($Filters as $Filter) - { - if(!empty($Filter['EvalCode'])) - { - $EvalReturn = false; - $EvalCode = 'if('.stripcslashes($Filter['EvalCode']).'){ $EvalReturn = true; };'; - eval($EvalCode); - - if($EvalReturn === true) - { - $Return['FilterUsed'] = true; - if($Filter['ActionType'] == 1) - { - $Return['SendAlert'] = false; - } - elseif($Filter['ActionType'] == 2) - { - $Return['SendAlert'] = false; - $Return['ShowAlert'] = false; - } - doquery("UPDATE {{table}} SET `UseCount` = `UseCount` + 1 WHERE `ID` = {$Filter['ID']};", 'system_alerts_filters'); - break; - } - } - } - } - - return $Return; -} - -?> \ No newline at end of file + `FailCount`;"; + $Result_SelectIPs = doquery($Query_SelectIPs, 'user_enterlog'); + + if(mysql_num_rows($Result_SelectIPs) == 0) + { + return false; + } + + $ForIntersection = array(); + $IPLogData = array(); + while($FetchData = mysql_fetch_assoc($Result_SelectIPs)) + { + if(!isset($IPLogData[$FetchData['User_ID']][$FetchData['IP_ID']]['Count'])) + { + $IPLogData[$FetchData['User_ID']][$FetchData['IP_ID']]['Count'] = 0; + } + + $ForIntersection[$FetchData['User_ID']][$FetchData['IP_ID']] = $FetchData['IP_ID']; + $IPLogData[$FetchData['User_ID']][$FetchData['IP_ID']]['Count'] += $FetchData['SumCount']; + if(!isset($IPLogData[$FetchData['User_ID']][$FetchData['IP_ID']]['LastTime']) || $IPLogData[$FetchData['User_ID']][$FetchData['IP_ID']]['LastTime'] < $FetchData['LastTime']) + { + $IPLogData[$FetchData['User_ID']][$FetchData['IP_ID']]['LastTime'] = $FetchData['LastTime']; + } + } + + if(empty($ForIntersection[$FirstUserID]) OR empty($ForIntersection[$SecondUserID])) + { + return false; + } + + $Intersection = array_intersect($ForIntersection[$FirstUserID], $ForIntersection[$SecondUserID]); + if(empty($Intersection)) + { + return false; + } + + if(!empty($ExcludeRules)) + { + if($ExcludeRules['LastTimeDiff'] > 0) + { + foreach($Intersection as $IPID) + { + $LastTimeDiff = $IPLogData[$FirstUserID][$IPID]['LastTime'] - $IPLogData[$SecondUserID][$IPID]['LastTime']; + if($LastTimeDiff < 0) + { + $LastTimeDiff *= -1; + } + if($LastTimeDiff >= $ExcludeRules['LastTimeDiff']) + { + unset($Intersection[$IPID]); + unset($IPLogData[$FirstUserID][$IPID]); + unset($IPLogData[$SecondUserID][$IPID]); + } + } + } + if($ExcludeRules['ThisTimeDiff'] > 0) + { + $ThisTimeStamp = ($ExcludeRules['ThisTimeStamp'] > 0 ? $ExcludeRules['ThisTimeStamp'] : (time() - SERVER_MAINOPEN_TSTAMP)); + foreach($Intersection as $IPID) + { + $ThisTimeMax = ($IPLogData[$FirstUserID][$IPID]['LastTime'] > $IPLogData[$SecondUserID][$IPID]['LastTime'] ? $IPLogData[$FirstUserID][$IPID]['LastTime'] : $IPLogData[$SecondUserID][$IPID]['LastTime']); + if(($ThisTimeStamp - $ThisTimeMax) >= $ExcludeRules['ThisTimeDiff']) + { + unset($Intersection[$IPID]); + unset($IPLogData[$FirstUserID][$IPID]); + unset($IPLogData[$SecondUserID][$IPID]); + } + } + } + + if(empty($Intersection)) + { + return false; + } + } + + return array('Intersect' => $Intersection, 'IPLogData' => $IPLogData); +} + +function AlertUtils_CheckFilters($FiltersData, $CacheSettings = array()) +{ + static $_FiltersCache = array(); + + if(isset($CacheSettings['DontLoad_OnlyIfCacheEmpty']) && $CacheSettings['DontLoad_OnlyIfCacheEmpty'] === true) + { + if(empty($_FiltersCache)) + { + $CacheSettings['DontLoad'] = false; + } + } + + if(!isset($CacheSettings['DontLoad']) || $CacheSettings['DontLoad'] !== true) + { + foreach($FiltersData as $Type => $Value) + { + if($Type == 'users') + { + foreach($Value as $Data) + { + $FilterSearch[] = '{USER_'.$Data.'}'; + } + } + else if($Type == 'ips') + { + foreach($Value as $Data) + { + $FilterSearch[] = '{IP_'.$Data.'}'; + } + } + else if($Type == 'place') + { + $FilterSearch[] = '{PLACE_'.$Value.'}'; + } + else if($Type == 'alertsender') + { + $FilterSearch[] = '{ALERTSENDER_'.$Value.'}'; + } + } + + $Query_GetFilters = ''; + $Query_GetFilters .= "SELECT `ID`, `ActionType`, `EvalCode` FROM {{table}} WHERE `Enabled` = 1 AND "; + $Query_GetFilters .= "(`SearchData` = ''"; + if(!empty($FilterSearch)) + { + foreach($FilterSearch as $Key => $Data) + { + $FilterSearch[$Key] = "`SearchData` LIKE '%{$Data}%'"; + } + $Query_GetFilters .= " OR ".implode(' OR ', $FilterSearch); + } + $Query_GetFilters .= ");"; + $Result_GetFilters = doquery($Query_GetFilters, 'system_alerts_filters'); + + if(mysql_num_rows($Result_GetFilters) > 0) + { + while($Filter = mysql_fetch_assoc($Result_GetFilters)) + { + $Filters[] = $Filter; + if($CacheSettings['Save'] === true) + { + $_FiltersCache[$Filter['ID']] = array + ( + 'ID' => $Filter['ID'], + 'EvalCode' => $Filter['EvalCode'], + 'ActionType' => $Filter['ActionType'] + ); + } + } + } + } + if(isset($CacheSettings['UseCache']) && $CacheSettings['UseCache'] === true) + { + if(!empty($_FiltersCache)) + { + foreach($_FiltersCache as $Filter) + { + $Filters[] = $Filter; + } + } + } + + $Return = array('FilterUsed' => false, 'SendAlert' => true, 'ShowAlert' => true); + + if(!empty($Filters)) + { + foreach($Filters as $Filter) + { + if(!empty($Filter['EvalCode'])) + { + $EvalReturn = false; + $EvalCode = 'if('.stripcslashes($Filter['EvalCode']).'){ $EvalReturn = true; };'; + eval($EvalCode); + + if($EvalReturn === true) + { + $Return['FilterUsed'] = true; + if($Filter['ActionType'] == 1) + { + $Return['SendAlert'] = false; + } + elseif($Filter['ActionType'] == 2) + { + $Return['SendAlert'] = false; + $Return['ShowAlert'] = false; + } + doquery("UPDATE {{table}} SET `UseCount` = `UseCount` + 1 WHERE `ID` = {$Filter['ID']};", 'system_alerts_filters'); + break; + } + } + } + } + + return $Return; +} + +?> diff --git a/includes/functions/AlliancePageFunctions.php b/includes/functions/AlliancePageFunctions.php index 3091ea88f..2e5953ea1 100644 --- a/includes/functions/AlliancePageFunctions.php +++ b/includes/functions/AlliancePageFunctions.php @@ -1,224 +1,224 @@ - 1) - { - $CreateChangeRankList = ''; - } - - if($_ThisUserRank['cankick'] === true && !empty($AllowedRanksChange)) - { - $CreateKickButton = ''; - } - - if(empty($AllowedRanksChange) || ($_ThisUserRank['cankick'] !== true && $_ThisUserRank['mlist_mod'] !== true)) - { - $AllowedRanksChange = array(); - } - } - - $CounterLoop = 1; - $_Lang['Rows'] = ''; - while($FetchData = mysql_fetch_assoc($Result_GetMembersList)) - { - $FetchData['i'] = $CounterLoop; - $FetchData['skinpath'] = $_SkinPath; - $FetchData['write'] = $_Lang['Ally_ML_Write']; - if($Admin === true AND !empty($CreateChangeRankList) AND in_array($FetchData['ally_rank_id'], $AllowedRanksChange)) - { - $SetRankSelector = str_replace - ( - array - ( - '{SET_SELECT_'.$FetchData['ally_rank_id'].'}', - '{SET_ID}' - ), - array - ( - 'selected', - $FetchData['id'] - ), - $CreateChangeRankList - ); - $SetRankSelector = preg_replace('#\{SET\_SELECT\_[0-9]+\}#si', '', $SetRankSelector); - - $FetchData['rank'] = $SetRankSelector; - } - else - { - $FetchData['rank'] = $Ally['ally_ranks'][$FetchData['ally_rank_id']]['name']; - } - $FetchData['points'] = prettyNumber($FetchData['total_points']); - $FetchData['reg_time'] = prettyDate('d m Y', $FetchData['ally_register_time'], 1); - - if($_ThisUserRank['mlist_online'] === true) - { - if($FetchData['onlinetime'] >= ($Time - TIME_ONLINE)) - { - $FetchData['onlinetime'] = $_Lang['Ally_ML_isOnline']; - $FetchData['onlinecolor'] = 'lime'; - } - else if($FetchData['onlinetime'] >= ($Time - TIME_HOUR)) - { - $FetchData['onlinetime'] = floor(($Time - $FetchData['onlinetime']) / 60).' '.$_Lang['Ally_ML_Mins']; - $FetchData['onlinecolor'] = 'orange'; - } - else if($FetchData['onlinetime'] >= ($Time - TIME_DAY)) - { - $FetchData['onlinetime'] = $_Lang['Ally_ML_isOffline']; - $FetchData['onlinecolor'] = 'red'; - } - else - { - $FetchData['onlinetime'] = floor(($Time - $FetchData['onlinetime']) / TIME_DAY).' '.$_Lang['Ally_ML_Days']; - $FetchData['onlinecolor'] = 'red'; - } - } - else - { - $FetchData['onlinetime'] = '---'; - $FetchData['onlinecolor'] = 'orange'; - } - if($Admin === true) - { - if(in_array($FetchData['ally_rank_id'], $AllowedRanksChange) && $FetchData['id'] != $_User['id']) - { - $FetchData['actions'] = str_replace('{SET_ID}', $FetchData['id'], $CreateKickButton); - } - else - { - $FetchData['actions'] = ' '; - } - } - - $_Lang['Rows'] .= parsetemplate($RowTPL, $FetchData); - $CounterLoop += 1; - } -} - -function CheckJobsDone($JobType, $UserID) -{ - global $_User, $GlobalParsedTasks; - - if($_User['id'] == $UserID) - { - $CurrentUser = $_User; - } - else - { - if(empty($GlobalParsedTasks[$UserID]['tasks_done_parsed'])) - { - $GetUserTasksDone = doquery("SELECT `tasks_done` FROM {{table}} WHERE `id` = {$UserID} LIMIT 1;", 'users', true); - Tasks_CheckUservar($GetUserTasksDone); - $GlobalParsedTasks[$UserID] = $GetUserTasksDone; - } - $CurrentUser = $GlobalParsedTasks[$UserID]; - $CurrentUser['id'] = $UserID; - } - Tasks_TriggerTask($CurrentUser, $JobType); -} - -?> \ No newline at end of file + 1) + { + $CreateChangeRankList = ''; + } + + if($_ThisUserRank['cankick'] === true && !empty($AllowedRanksChange)) + { + $CreateKickButton = ''; + } + + if(empty($AllowedRanksChange) || ($_ThisUserRank['cankick'] !== true && $_ThisUserRank['mlist_mod'] !== true)) + { + $AllowedRanksChange = array(); + } + } + + $CounterLoop = 1; + $_Lang['Rows'] = ''; + while($FetchData = mysql_fetch_assoc($Result_GetMembersList)) + { + $FetchData['i'] = $CounterLoop; + $FetchData['skinpath'] = $_SkinPath; + $FetchData['write'] = $_Lang['Ally_ML_Write']; + if($Admin === true AND !empty($CreateChangeRankList) AND in_array($FetchData['ally_rank_id'], $AllowedRanksChange)) + { + $SetRankSelector = str_replace + ( + array + ( + '{SET_SELECT_'.$FetchData['ally_rank_id'].'}', + '{SET_ID}' + ), + array + ( + 'selected', + $FetchData['id'] + ), + $CreateChangeRankList + ); + $SetRankSelector = preg_replace('#\{SET\_SELECT\_[0-9]+\}#si', '', $SetRankSelector); + + $FetchData['rank'] = $SetRankSelector; + } + else + { + $FetchData['rank'] = $Ally['ally_ranks'][$FetchData['ally_rank_id']]['name']; + } + $FetchData['points'] = prettyNumber($FetchData['total_points']); + $FetchData['reg_time'] = prettyDate('d m Y', $FetchData['ally_register_time'], 1); + + if($_ThisUserRank['mlist_online'] === true) + { + if($FetchData['onlinetime'] >= ($Time - TIME_ONLINE)) + { + $FetchData['onlinetime'] = $_Lang['Ally_ML_isOnline']; + $FetchData['onlinecolor'] = 'lime'; + } + else if($FetchData['onlinetime'] >= ($Time - TIME_HOUR)) + { + $FetchData['onlinetime'] = floor(($Time - $FetchData['onlinetime']) / 60).' '.$_Lang['Ally_ML_Mins']; + $FetchData['onlinecolor'] = 'orange'; + } + else if($FetchData['onlinetime'] >= ($Time - TIME_DAY)) + { + $FetchData['onlinetime'] = $_Lang['Ally_ML_isOffline']; + $FetchData['onlinecolor'] = 'red'; + } + else + { + $FetchData['onlinetime'] = floor(($Time - $FetchData['onlinetime']) / TIME_DAY).' '.$_Lang['Ally_ML_Days']; + $FetchData['onlinecolor'] = 'red'; + } + } + else + { + $FetchData['onlinetime'] = '---'; + $FetchData['onlinecolor'] = 'orange'; + } + if($Admin === true) + { + if(in_array($FetchData['ally_rank_id'], $AllowedRanksChange) && $FetchData['id'] != $_User['id']) + { + $FetchData['actions'] = str_replace('{SET_ID}', $FetchData['id'], $CreateKickButton); + } + else + { + $FetchData['actions'] = ' '; + } + } + + $_Lang['Rows'] .= parsetemplate($RowTPL, $FetchData); + $CounterLoop += 1; + } +} + +function CheckJobsDone($JobType, $UserID) +{ + global $_User, $GlobalParsedTasks; + + if($_User['id'] == $UserID) + { + $CurrentUser = $_User; + } + else + { + if(empty($GlobalParsedTasks[$UserID]['tasks_done_parsed'])) + { + $GetUserTasksDone = doquery("SELECT `tasks_done` FROM {{table}} WHERE `id` = {$UserID} LIMIT 1;", 'users', true); + Tasks_CheckUservar($GetUserTasksDone); + $GlobalParsedTasks[$UserID] = $GetUserTasksDone; + } + $CurrentUser = $GlobalParsedTasks[$UserID]; + $CurrentUser['id'] = $UserID; + } + Tasks_TriggerTask($CurrentUser, $JobType); +} + +?> diff --git a/includes/functions/BBcodeFunction.php b/includes/functions/BBcodeFunction.php index 1244ea9fe..b70a92ba0 100644 --- a/includes/functions/BBcodeFunction.php +++ b/includes/functions/BBcodeFunction.php @@ -1,125 +1,125 @@ -\1', - '\1', - '\1', - '\1', - 'urlfix(\'\\1\',\'\\2\')', - 'urlfix(\'\\1\',\'\\1\')', - '\2', - '[\1:\2:\3]', - ); - - return preg_replace($pattern, $replace, nl2br(htmlspecialchars(stripslashes($String)))); -} - -function bbcode($string) -{ - $pattern = array - ( - '/\\n/', - '/\\r/', - '/\[list\](.*?)\[\/list\]/ise', - '/\[b\](.*?)\[\/b\]/is', - '/\[strong\](.*?)\[\/strong\]/is', - '/\[i\](.*?)\[\/i\]/is', - '/\[u\](.*?)\[\/u\]/is', - '/\[s\](.*?)\[\/s\]/is', - '/\[del\](.*?)\[\/del\]/is', - '/\[url=(.*?)\](.*?)\[\/url\]/ise', - '/\[url\](.*?)\[\/url\]/ise', - '/\[email=(.*?)\](.*?)\[\/email\]/is', - '/\[img](.*?)\[\/img\]/ise', - '/\[color=(.*?)\](.*?)\[\/color\]/is', - '/\[quote\](.*?)\[\/quote\]/ise', - '/\[code\](.*?)\[\/code\]/ise', - '/\[size=(.*?)\](.*?)\[\/size\]/is', - '/\[background color=(.*?)\](.*?)\[\/background\]/is', - '/\[coord=([0-9]{1,3}):([0-9]{1,3}):([0-9]{1,3})\]/is', - ); - - $replace = array - ( - '', - '', - 'sList(\'\\1\')', - '\1', - '\1', - '\1', - '\1', - '\1', - '\1', - 'urlfix(\'\\1\',\'\\2\')', - 'urlfix(\'\\1\',\'\\1\')', - '\2', - 'imagefix(\'\\1\')', - '\2', - 'sQuote(\'\1\')', - 'sCode(\'\1\')', - '\2', - '
\2
', - '[\1:\2:\3]', - ); - - return preg_replace($pattern, $replace, nl2br(htmlspecialchars(stripslashes($string)))); -} - -function image($string) -{ - $string = str_replace("'", "'", $string); - - return $string; -} - -function sCode($string) -{ - $pattern ='/\\\\"(.*?)\\\"/s'; - $string = preg_replace($pattern, '\3', $string); - return '
' . trim($string) . '
'; -} - -function sList($string) -{ - $tmp = explode('[*]', stripslashes($string)); - $out = null; - foreach($tmp as $list) - { - if(strlen(str_replace('', '', $list)) > 0) - { - $out .= '
  • ' . trim($list) . '
  • '; - } - } - return ''; -} - -function imagefix($img) -{ - if(substr($img, 0, 7) != 'http://') - { - $img = './images/'.$img; - } - return ''.$img.''; -} - -function urlfix($url, $title) -{ - $title = stripslashes($title); - return " {$title}"; -} -?> \ No newline at end of file +\1', + '\1', + '\1', + '\1', + 'urlfix(\'\\1\',\'\\2\')', + 'urlfix(\'\\1\',\'\\1\')', + '\2', + '[\1:\2:\3]', + ); + + return preg_replace($pattern, $replace, nl2br(htmlspecialchars(stripslashes($String)))); +} + +function bbcode($string) +{ + $pattern = array + ( + '/\\n/', + '/\\r/', + '/\[list\](.*?)\[\/list\]/ise', + '/\[b\](.*?)\[\/b\]/is', + '/\[strong\](.*?)\[\/strong\]/is', + '/\[i\](.*?)\[\/i\]/is', + '/\[u\](.*?)\[\/u\]/is', + '/\[s\](.*?)\[\/s\]/is', + '/\[del\](.*?)\[\/del\]/is', + '/\[url=(.*?)\](.*?)\[\/url\]/ise', + '/\[url\](.*?)\[\/url\]/ise', + '/\[email=(.*?)\](.*?)\[\/email\]/is', + '/\[img](.*?)\[\/img\]/ise', + '/\[color=(.*?)\](.*?)\[\/color\]/is', + '/\[quote\](.*?)\[\/quote\]/ise', + '/\[code\](.*?)\[\/code\]/ise', + '/\[size=(.*?)\](.*?)\[\/size\]/is', + '/\[background color=(.*?)\](.*?)\[\/background\]/is', + '/\[coord=([0-9]{1,3}):([0-9]{1,3}):([0-9]{1,3})\]/is', + ); + + $replace = array + ( + '', + '', + 'sList(\'\\1\')', + '\1', + '\1', + '\1', + '\1', + '\1', + '\1', + 'urlfix(\'\\1\',\'\\2\')', + 'urlfix(\'\\1\',\'\\1\')', + '\2', + 'imagefix(\'\\1\')', + '\2', + 'sQuote(\'\1\')', + 'sCode(\'\1\')', + '\2', + '
    \2
    ', + '[\1:\2:\3]', + ); + + return preg_replace($pattern, $replace, nl2br(htmlspecialchars(stripslashes($string)))); +} + +function image($string) +{ + $string = str_replace("'", "'", $string); + + return $string; +} + +function sCode($string) +{ + $pattern ='/\\\\"(.*?)\\\"/s'; + $string = preg_replace($pattern, '\3', $string); + return '
    ' . trim($string) . '
    '; +} + +function sList($string) +{ + $tmp = explode('[*]', stripslashes($string)); + $out = null; + foreach($tmp as $list) + { + if(strlen(str_replace('', '', $list)) > 0) + { + $out .= '
  • ' . trim($list) . '
  • '; + } + } + return ''; +} + +function imagefix($img) +{ + if(substr($img, 0, 7) != 'http://') + { + $img = './images/'.$img; + } + return ''.$img.''; +} + +function urlfix($url, $title) +{ + $title = stripslashes($title); + return " {$title}"; +} +?> diff --git a/includes/functions/BatimentBuildingPage.php b/includes/functions/BatimentBuildingPage.php index ca297f6f8..6c93f3d10 100644 --- a/includes/functions/BatimentBuildingPage.php +++ b/includes/functions/BatimentBuildingPage.php @@ -1,440 +1,440 @@ - $Now) - { - $EnergyMulti = 1.10; - } - else - { - $EnergyMulti = 1; - } - - if(!empty($CurrentPlanet['buildQueue'])) - { - $LockResources = array - ( - 'metal' => 0, - 'crystal' => 0, - 'deuterium' => 0 - ); - - $CurrentQueue = explode(';', $CurrentPlanet['buildQueue']); - foreach($CurrentQueue as $QueueIndex => $ThisBuilding) - { - $ThisBuilding = explode(',', $ThisBuilding); - $ElementID = $ThisBuilding[0]; //ElementID - $BuildMode = $ThisBuilding[4]; //BuildMode - - if($QueueIndex > 0) - { - if($BuildMode == 'destroy') - { - $ForDestroy = true; - } - else - { - $ForDestroy = false; - } - $GetResourcesToLock = GetBuildingPrice($CurrentUser, $CurrentPlanet, $ElementID, true, $ForDestroy); - $LockResources['metal'] += $GetResourcesToLock['metal']; - $LockResources['crystal'] += $GetResourcesToLock['crystal']; - $LockResources['deuterium'] += $GetResourcesToLock['deuterium']; - } - - if(!isset($LevelModifiers[$ElementID])) - { - $LevelModifiers[$ElementID] = 0; - } - if($BuildMode == 'destroy') - { - $LevelModifiers[$ElementID] += 1; - $CurrentPlanet[$_Vars_GameElements[$ElementID]] -= 1; - } - else - { - $LevelModifiers[$ElementID] -= 1; - $CurrentPlanet[$_Vars_GameElements[$ElementID]] += 1; - } - } - } - - foreach($_Vars_ElementCategories['build'] as $Element) - { - if(in_array($Element, $_Vars_ElementCategories['buildOn'][$CurrentPlanet['planet_type']])) - { - $ElementName = $_Lang['tech'][$Element]; - $CurrentMaxFields = CalculateMaxPlanetFields($CurrentPlanet); - if($CurrentPlanet['field_current'] < ($CurrentMaxFields - $Queue['lenght'])) - { - $RoomIsOk = true; - } - else - { - $RoomIsOk = false; - } - - $parse = array(); - $parse['skinpath'] = $_SkinPath; - $parse['i'] = $Element; - $BuildingLevel = $CurrentPlanet[$_Vars_GameElements[$Element]]; - if(isset($LevelModifiers[$Element])) - { - $PlanetLevel = $BuildingLevel + $LevelModifiers[$Element]; - } - else - { - $PlanetLevel = $BuildingLevel; - } - $parse['nivel'] = ($BuildingLevel == 0) ? '' : " ({$_Lang['level']} {$PlanetLevel})"; - - if(in_array($Element, array(1, 2, 3, 4, 12))) - { - // Show energy on BuildingPage - $Prod[4] = null; - $Prod[3] = null; - $ActualNeedDeut = null; - $BuildLevelFactor = 10; - $BuildTemp = $CurrentPlanet['temp_max']; - $CurrentBuildtLvl = $BuildingLevel; - $BuildLevel = ($CurrentBuildtLvl > 0) ? $CurrentBuildtLvl : 0; - - // --- Calculate ThisLevel Income - if($Element == 12) - { - $Prod[3] = (floor(eval($_Vars_ResProduction[$Element]['formule']['deuterium']) * $_GameConfig['resource_multiplier'])); - $ActualNeedDeut = $Prod[3]; - } - if($Element == 4 OR $Element == 12) - { - // If it's Power Station - $Prod[4] = (floor(eval($_Vars_ResProduction[$Element]['formule']['energy']) * $EnergyMulti)); - } - else - { - // If it's Mine - $Prod[4] = (floor(eval($_Vars_ResProduction[$Element]['formule']['energy']))); - } - $ActualNeed = $Prod[4]; - - // --- Calculate NextLevel Income - $BuildLevel += 1; - if($Element == 12) - { - $Prod[3] = (floor(eval($_Vars_ResProduction[$Element]['formule']['deuterium']) * $_GameConfig['resource_multiplier'])); - } - if($Element == 4 OR $Element == 12) - { - // If it's Power Station - $Prod[4] = (floor(eval($_Vars_ResProduction[$Element]['formule']['energy']) * $EnergyMulti)); - } - else - { - // If it's Mine - $Prod[4] = (floor(eval($_Vars_ResProduction[$Element]['formule']['energy']))); - } - - $EnergyNeed = prettyColorNumber(floor($Prod[4] - $ActualNeed)); - - if($Element >= 1 AND $Element <= 3) - { - $parse['build_need_diff'] = "({$_Lang['Energy']}: {$EnergyNeed})"; - } - else if($Element == 4 OR $Element == 12) - { - $DeuteriumNeeded = prettyColorNumber(floor($Prod[3] - $ActualNeedDeut)); - if($Element != 12) - { - $parse['build_need_diff'] = "({$_Lang['Energy']}: +{$EnergyNeed})"; - } - else - { - $parse['build_need_diff'] = "({$_Lang['Energy']}: +{$EnergyNeed} | {$_Lang['Deuterium']}: {$DeuteriumNeeded})"; - } - } - $BuildLevel = 0; - } - - $parse['n'] = $ElementName; - $parse['descriptions'] = $_Lang['res']['descriptions'][$Element]; - $parse['click'] = ''; - $NextBuildLevel = $CurrentPlanet[$_Vars_GameElements[$Element]] + 1; - $skip = false; - - if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $Element)) - { - if(!empty($LockResources)) - { - foreach($LockResources as $Key => $Value) - { - $CurrentPlanet[$Key] -= $Value; - } - } - $HaveRessources = IsElementBuyable($CurrentUser, $CurrentPlanet, $Element, true, false); - $ElementBuildTime = GetBuildingTime($CurrentUser, $CurrentPlanet, $Element); - $parse['time'] = ShowBuildTime($ElementBuildTime); - $parse['price'] = GetElementPrice($CurrentUser, $CurrentPlanet, $Element); - $parse['rest_price'] = GetRestPrice($CurrentUser, $CurrentPlanet, $Element); - if(!empty($LockResources)) - { - foreach($LockResources as $Key => $Value) - { - $CurrentPlanet[$Key] += $Value; - } - } - - if(isset($LevelModifiers[$Element]) && $LevelModifiers[$Element] != 0) - { - $parse['AddLevelPrice'] = "[{$_Lang['level']}: {$NextBuildLevel}]
    "; - } - - if($Element == 31) - { - // Block Lab Upgrade is Research running (and Config dont allow that) - if($CurrentUser['techQueue_Planet'] > 0 AND $CurrentUser['techQueue_EndTime'] > 0 AND $_GameConfig['BuildLabWhileRun'] != 1) - { - $parse['click'] = "{$_Lang['in_working']}"; - } - } - if(!empty($_Vars_MaxElementLevel[$Element])) - { - if($NextBuildLevel > $_Vars_MaxElementLevel[$Element]) - { - $parse['click'] = "{$_Lang['onlyOneLevel']}"; - $skip = true; - } - } - - if(isset($_Vars_PremiumBuildings[$Element]) && $_Vars_PremiumBuildings[$Element] == 1) - { - $parse['rest_price'] = "
    {$_Lang['Rest_ress']}: {$_Lang['DarkEnergy']}"; - $parse['price'] = "{$_Lang['Requires']}: {$_Lang['DarkEnergy']} "; - if($CurrentUser['darkEnergy'] < $_Vars_PremiumBuildingPrices[$Element]) - { - if($skip == false) - { - $parse['click'] = "{$_Lang['BuildFirstLevel']}"; - } - $parse['price'] .= " ".prettyNumber($_Vars_PremiumBuildingPrices[$Element])." "; - $parse['rest_price'] .= " ".prettyNumber($CurrentUser['darkEnergy'] - $_Vars_PremiumBuildingPrices[$Element]).""; - } - else - { - $parse['price'] .= " ".prettyNumber($_Vars_PremiumBuildingPrices[$Element])." "; - $parse['rest_price'] .= " ".prettyNumber($CurrentUser['darkEnergy'] - $_Vars_PremiumBuildingPrices[$Element]).""; - } - $parse['rest_price'] .= ''; - } - - if(isOnVacation($CurrentUser)) - { - $parse['click'] = "{$_Lang['ListBox_Disallow_VacationMode']}"; - } - - if($parse['click'] != '') - { - // Don't do anything here - } - else if($RoomIsOk AND $CanBuildElement) - { - if($Queue['lenght'] == 0) - { - if($NextBuildLevel == 1) - { - if($HaveRessources == true) - { - $parse['click'] = "{$_Lang['BuildFirstLevel']}"; - } - else - { - $parse['click'] = "{$_Lang['BuildFirstLevel']}"; - } - } - else - { - if($HaveRessources == true) - { - $parse['click'] = "{$_Lang['BuildNextLevel']} {$NextBuildLevel}"; - } - else - { - $parse['click'] = "{$_Lang['BuildNextLevel']} {$NextBuildLevel}"; - } - } - } - else - { - if($HaveRessources == true) - { - $ThisColor = 'lime'; - } - else - { - $ThisColor = 'orange'; - } - - $parse['click'] = "{$_Lang['InBuildQueue']}
    ({$_Lang['level']} {$NextBuildLevel})
    "; - } - } - else if($RoomIsOk AND !$CanBuildElement) - { - $parse['click'] = "{$_Lang['QueueIsFull']}"; - } - else - { - if($CurrentPlanet['planet_type'] == 3) - { - $parse['click'] = "{$_Lang['NoMoreSpace_Moon']}"; - } - else - { - $parse['click'] = "{$_Lang['NoMoreSpace']}"; - } - } - } - else - { - if($CurrentUser['settings_ExpandedBuildView'] == 0) - { - continue; - } - $parse['click'] = ' '; - $parse['TechRequirementsPlace'] = GetElementTechReq($CurrentUser, $CurrentPlanet, $Element); - } - - $BuildingPage .= parsetemplate($SubTemplate, $parse); - } - } - - if(!empty($LevelModifiers)) - { - foreach($LevelModifiers as $ElementID => $Modifier) - { - $CurrentPlanet[$_Vars_GameElements[$ElementID]] += $Modifier; - } - } - - $parse = $_Lang; - - if($Queue['lenght'] > 0) - { - include($_EnginePath.'includes/functions/InsertBuildListScript.php'); - $parse['BuildListScript'] = InsertBuildListScript('buildings'); - $parse['BuildList'] = $Queue['buildlist']; - } - else - { - $parse['BuildListScript'] = ''; - $parse['BuildList'] = ''; - } - - $parse['planet_field_current'] = $CurrentPlanet['field_current']; - $parse['planet_field_max'] = CalculateMaxPlanetFields($CurrentPlanet); - $parse['field_libre'] = $parse['planet_field_max'] - $CurrentPlanet['field_current']; - - $parse['BuildingsList'] = $BuildingPage; - - display(parsetemplate(gettemplate('buildings_builds'), $parse), $_Lang['Builds']); -} - -?> \ No newline at end of file + $Now) + { + $EnergyMulti = 1.10; + } + else + { + $EnergyMulti = 1; + } + + if(!empty($CurrentPlanet['buildQueue'])) + { + $LockResources = array + ( + 'metal' => 0, + 'crystal' => 0, + 'deuterium' => 0 + ); + + $CurrentQueue = explode(';', $CurrentPlanet['buildQueue']); + foreach($CurrentQueue as $QueueIndex => $ThisBuilding) + { + $ThisBuilding = explode(',', $ThisBuilding); + $ElementID = $ThisBuilding[0]; //ElementID + $BuildMode = $ThisBuilding[4]; //BuildMode + + if($QueueIndex > 0) + { + if($BuildMode == 'destroy') + { + $ForDestroy = true; + } + else + { + $ForDestroy = false; + } + $GetResourcesToLock = GetBuildingPrice($CurrentUser, $CurrentPlanet, $ElementID, true, $ForDestroy); + $LockResources['metal'] += $GetResourcesToLock['metal']; + $LockResources['crystal'] += $GetResourcesToLock['crystal']; + $LockResources['deuterium'] += $GetResourcesToLock['deuterium']; + } + + if(!isset($LevelModifiers[$ElementID])) + { + $LevelModifiers[$ElementID] = 0; + } + if($BuildMode == 'destroy') + { + $LevelModifiers[$ElementID] += 1; + $CurrentPlanet[$_Vars_GameElements[$ElementID]] -= 1; + } + else + { + $LevelModifiers[$ElementID] -= 1; + $CurrentPlanet[$_Vars_GameElements[$ElementID]] += 1; + } + } + } + + foreach($_Vars_ElementCategories['build'] as $Element) + { + if(in_array($Element, $_Vars_ElementCategories['buildOn'][$CurrentPlanet['planet_type']])) + { + $ElementName = $_Lang['tech'][$Element]; + $CurrentMaxFields = CalculateMaxPlanetFields($CurrentPlanet); + if($CurrentPlanet['field_current'] < ($CurrentMaxFields - $Queue['lenght'])) + { + $RoomIsOk = true; + } + else + { + $RoomIsOk = false; + } + + $parse = array(); + $parse['skinpath'] = $_SkinPath; + $parse['i'] = $Element; + $BuildingLevel = $CurrentPlanet[$_Vars_GameElements[$Element]]; + if(isset($LevelModifiers[$Element])) + { + $PlanetLevel = $BuildingLevel + $LevelModifiers[$Element]; + } + else + { + $PlanetLevel = $BuildingLevel; + } + $parse['nivel'] = ($BuildingLevel == 0) ? '' : " ({$_Lang['level']} {$PlanetLevel})"; + + if(in_array($Element, array(1, 2, 3, 4, 12))) + { + // Show energy on BuildingPage + $Prod[4] = null; + $Prod[3] = null; + $ActualNeedDeut = null; + $BuildLevelFactor = 10; + $BuildTemp = $CurrentPlanet['temp_max']; + $CurrentBuildtLvl = $BuildingLevel; + $BuildLevel = ($CurrentBuildtLvl > 0) ? $CurrentBuildtLvl : 0; + + // --- Calculate ThisLevel Income + if($Element == 12) + { + $Prod[3] = (floor(eval($_Vars_ResProduction[$Element]['formule']['deuterium']) * $_GameConfig['resource_multiplier'])); + $ActualNeedDeut = $Prod[3]; + } + if($Element == 4 OR $Element == 12) + { + // If it's Power Station + $Prod[4] = (floor(eval($_Vars_ResProduction[$Element]['formule']['energy']) * $EnergyMulti)); + } + else + { + // If it's Mine + $Prod[4] = (floor(eval($_Vars_ResProduction[$Element]['formule']['energy']))); + } + $ActualNeed = $Prod[4]; + + // --- Calculate NextLevel Income + $BuildLevel += 1; + if($Element == 12) + { + $Prod[3] = (floor(eval($_Vars_ResProduction[$Element]['formule']['deuterium']) * $_GameConfig['resource_multiplier'])); + } + if($Element == 4 OR $Element == 12) + { + // If it's Power Station + $Prod[4] = (floor(eval($_Vars_ResProduction[$Element]['formule']['energy']) * $EnergyMulti)); + } + else + { + // If it's Mine + $Prod[4] = (floor(eval($_Vars_ResProduction[$Element]['formule']['energy']))); + } + + $EnergyNeed = prettyColorNumber(floor($Prod[4] - $ActualNeed)); + + if($Element >= 1 AND $Element <= 3) + { + $parse['build_need_diff'] = "({$_Lang['Energy']}: {$EnergyNeed})"; + } + else if($Element == 4 OR $Element == 12) + { + $DeuteriumNeeded = prettyColorNumber(floor($Prod[3] - $ActualNeedDeut)); + if($Element != 12) + { + $parse['build_need_diff'] = "({$_Lang['Energy']}: +{$EnergyNeed})"; + } + else + { + $parse['build_need_diff'] = "({$_Lang['Energy']}: +{$EnergyNeed} | {$_Lang['Deuterium']}: {$DeuteriumNeeded})"; + } + } + $BuildLevel = 0; + } + + $parse['n'] = $ElementName; + $parse['descriptions'] = $_Lang['res']['descriptions'][$Element]; + $parse['click'] = ''; + $NextBuildLevel = $CurrentPlanet[$_Vars_GameElements[$Element]] + 1; + $skip = false; + + if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $Element)) + { + if(!empty($LockResources)) + { + foreach($LockResources as $Key => $Value) + { + $CurrentPlanet[$Key] -= $Value; + } + } + $HaveRessources = IsElementBuyable($CurrentUser, $CurrentPlanet, $Element, true, false); + $ElementBuildTime = GetBuildingTime($CurrentUser, $CurrentPlanet, $Element); + $parse['time'] = ShowBuildTime($ElementBuildTime); + $parse['price'] = GetElementPrice($CurrentUser, $CurrentPlanet, $Element); + $parse['rest_price'] = GetRestPrice($CurrentUser, $CurrentPlanet, $Element); + if(!empty($LockResources)) + { + foreach($LockResources as $Key => $Value) + { + $CurrentPlanet[$Key] += $Value; + } + } + + if(isset($LevelModifiers[$Element]) && $LevelModifiers[$Element] != 0) + { + $parse['AddLevelPrice'] = "[{$_Lang['level']}: {$NextBuildLevel}]
    "; + } + + if($Element == 31) + { + // Block Lab Upgrade is Research running (and Config dont allow that) + if($CurrentUser['techQueue_Planet'] > 0 AND $CurrentUser['techQueue_EndTime'] > 0 AND $_GameConfig['BuildLabWhileRun'] != 1) + { + $parse['click'] = "{$_Lang['in_working']}"; + } + } + if(!empty($_Vars_MaxElementLevel[$Element])) + { + if($NextBuildLevel > $_Vars_MaxElementLevel[$Element]) + { + $parse['click'] = "{$_Lang['onlyOneLevel']}"; + $skip = true; + } + } + + if(isset($_Vars_PremiumBuildings[$Element]) && $_Vars_PremiumBuildings[$Element] == 1) + { + $parse['rest_price'] = "
    {$_Lang['Rest_ress']}: {$_Lang['DarkEnergy']}"; + $parse['price'] = "{$_Lang['Requires']}: {$_Lang['DarkEnergy']} "; + if($CurrentUser['darkEnergy'] < $_Vars_PremiumBuildingPrices[$Element]) + { + if($skip == false) + { + $parse['click'] = "{$_Lang['BuildFirstLevel']}"; + } + $parse['price'] .= " ".prettyNumber($_Vars_PremiumBuildingPrices[$Element])." "; + $parse['rest_price'] .= " ".prettyNumber($CurrentUser['darkEnergy'] - $_Vars_PremiumBuildingPrices[$Element]).""; + } + else + { + $parse['price'] .= " ".prettyNumber($_Vars_PremiumBuildingPrices[$Element])." "; + $parse['rest_price'] .= " ".prettyNumber($CurrentUser['darkEnergy'] - $_Vars_PremiumBuildingPrices[$Element]).""; + } + $parse['rest_price'] .= ''; + } + + if(isOnVacation($CurrentUser)) + { + $parse['click'] = "{$_Lang['ListBox_Disallow_VacationMode']}"; + } + + if($parse['click'] != '') + { + // Don't do anything here + } + else if($RoomIsOk AND $CanBuildElement) + { + if($Queue['lenght'] == 0) + { + if($NextBuildLevel == 1) + { + if($HaveRessources == true) + { + $parse['click'] = "{$_Lang['BuildFirstLevel']}"; + } + else + { + $parse['click'] = "{$_Lang['BuildFirstLevel']}"; + } + } + else + { + if($HaveRessources == true) + { + $parse['click'] = "{$_Lang['BuildNextLevel']} {$NextBuildLevel}"; + } + else + { + $parse['click'] = "{$_Lang['BuildNextLevel']} {$NextBuildLevel}"; + } + } + } + else + { + if($HaveRessources == true) + { + $ThisColor = 'lime'; + } + else + { + $ThisColor = 'orange'; + } + + $parse['click'] = "{$_Lang['InBuildQueue']}
    ({$_Lang['level']} {$NextBuildLevel})
    "; + } + } + else if($RoomIsOk AND !$CanBuildElement) + { + $parse['click'] = "{$_Lang['QueueIsFull']}"; + } + else + { + if($CurrentPlanet['planet_type'] == 3) + { + $parse['click'] = "{$_Lang['NoMoreSpace_Moon']}"; + } + else + { + $parse['click'] = "{$_Lang['NoMoreSpace']}"; + } + } + } + else + { + if($CurrentUser['settings_ExpandedBuildView'] == 0) + { + continue; + } + $parse['click'] = ' '; + $parse['TechRequirementsPlace'] = GetElementTechReq($CurrentUser, $CurrentPlanet, $Element); + } + + $BuildingPage .= parsetemplate($SubTemplate, $parse); + } + } + + if(!empty($LevelModifiers)) + { + foreach($LevelModifiers as $ElementID => $Modifier) + { + $CurrentPlanet[$_Vars_GameElements[$ElementID]] += $Modifier; + } + } + + $parse = $_Lang; + + if($Queue['lenght'] > 0) + { + include($_EnginePath.'includes/functions/InsertBuildListScript.php'); + $parse['BuildListScript'] = InsertBuildListScript('buildings'); + $parse['BuildList'] = $Queue['buildlist']; + } + else + { + $parse['BuildListScript'] = ''; + $parse['BuildList'] = ''; + } + + $parse['planet_field_current'] = $CurrentPlanet['field_current']; + $parse['planet_field_max'] = CalculateMaxPlanetFields($CurrentPlanet); + $parse['field_libre'] = $parse['planet_field_max'] - $CurrentPlanet['field_current']; + + $parse['BuildingsList'] = $BuildingPage; + + display(parsetemplate(gettemplate('buildings_builds'), $parse), $_Lang['Builds']); +} + +?> diff --git a/includes/functions/BuildFleetEventTable.php b/includes/functions/BuildFleetEventTable.php index a88ff05ee..f756e434d 100644 --- a/includes/functions/BuildFleetEventTable.php +++ b/includes/functions/BuildFleetEventTable.php @@ -1,254 +1,254 @@ - 'attack', - 2 => 'federation', - 3 => 'transport', - 4 => 'deploy', - 5 => 'hold', - 6 => 'espionage', - 7 => 'colony', - 8 => 'harvest', - 9 => 'destroy', - 10 => 'missile', - ); - $FleetStatus = array(0 => 'flight', 1 => 'holding', 2 => 'return'); - - if($Template === false) - { - global $_User; - - GlobalTemplate_AppendToAfterBody(gettemplate('_FleetTable_files')); - $Template = gettemplate('_FleetTable_row'); - if(!empty($_User['settings_FleetColors'])) - { - $TPL_FleetColors_Row = gettemplate('_FleetTable_fleetColors_row'); - $FleetColors = json_decode($_User['settings_FleetColors'], true); - foreach($FleetColors as $TypeKey => $Missions) - { - if($TypeKey == 'ownfly') - { - $ThisType = 'flight'; - $ThisOwn = 'own'; - $CheckHold = true; - } - else if($TypeKey == 'owncb') - { - $ThisType = 'return'; - $ThisOwn = 'own'; - $CheckHold = false; - } - else if($TypeKey == 'nonown') - { - $ThisType = 'flight'; - $ThisOwn = ''; - $CheckHold = true; - } - - foreach($Missions as $MissionID => $MissionColor) - { - if(!empty($MissionColor)) - { - $MissionColors_Styles[] = parsetemplate($TPL_FleetColors_Row, array - ( - 'MissionType' => $ThisType, - 'MissionName' => $ThisOwn.$FleetStyle[$MissionID], - 'MissionColor' => $MissionColor, - )); - if($CheckHold === true AND $MissionID == 5) - { - $MissionColors_Styles[] = parsetemplate($TPL_FleetColors_Row, array - ( - 'MissionType' => 'holding', - 'MissionName' => $ThisOwn.$FleetStyle[$MissionID], - 'MissionColor' => $MissionColor, - )); - } - } - } - } - - if(!empty($MissionColors_Styles)) - { - GlobalTemplate_AppendToAfterBody(parsetemplate(gettemplate('_FleetTable_fleetColors'), array('InsertStyles' => implode(' ', $MissionColors_Styles)))); - } - } - } - if($ThisDate === false) - { - $ThisDate = date('d/m | '); - } - - if($InsertJSChronoApplet_GlobalIncluded !== true) - { - if($InsertJSChronoApplet_Included === false) - { - include('InsertJavaScriptChronoApplet.php'); - $InsertJSChronoApplet_Included = true; - } - } - - if($Owner == true) - { - $FleetPrefix = 'own'; - } - else - { - $FleetPrefix = ''; - } - - $MissionType = $FleetRow['fleet_mission']; - $FleetContent = CreateFleetPopupedFleetLink($FleetRow, (($Owner === true) ? $_Lang['ov_fleet'] : $_Lang['ov_fleet2'])); - $FleetMission = $_Lang['type_mission'][$MissionType]; - - $StartType = $FleetRow['fleet_start_type']; - $TargetType = $FleetRow['fleet_end_type']; - - if($Status != 2) - { - if($StartType == 1) - { - $StartID = $_Lang['ov_planet_to']; - } - else if($StartType == 3) - { - $StartID = $_Lang['ov_moon_to']; - } - $StartID .= $FleetRow['start_name'].' '; - $StartID .= GetStartAdressLink($FleetRow, 'white', $Phalanx); - - if($MissionType != 15) - { - if($TargetType == 1) - { - $TargetID = $_Lang['ov_planet_to_target']; - } - else if($TargetType == 2) - { - $TargetID = $_Lang['ov_debris_to_target']; - } - else if($TargetType == 3) - { - $TargetID = $_Lang['ov_moon_to_target']; - } - } - else - { - $TargetID = $_Lang['ov_explo_to_target']; - } - $TargetID .= $FleetRow['end_name'].' '; - $TargetID .= GetTargetAdressLink($FleetRow, 'white', $Phalanx); - } - else - { - if($StartType == 1) - { - $StartID = $_Lang['ov_back_planet']; - } - else if($StartType == 3) - { - $StartID = $_Lang['ov_back_moon']; - } - $StartID .= $FleetRow['start_name'].' '; - $StartID .= GetStartAdressLink($FleetRow, 'white', $Phalanx); - - if($MissionType != 15) - { - if($TargetType == 1) - { - $TargetID = $_Lang['ov_planet_from']; - } - else if($TargetType == 2) - { - $TargetID = $_Lang['ov_debris_from']; - } - else if($TargetType == 3) - { - $TargetID = $_Lang['ov_moon_from']; - } - } - else - { - $TargetID = $_Lang['ov_explo_from']; - } - $TargetID .= $FleetRow['end_name'].' '; - $TargetID .= GetTargetAdressLink($FleetRow, 'white', $Phalanx); - } - - if($Owner == true) - { - if($Phalanx === false) - { - $EventString = $_Lang['ov_une']; - } - else - { - $EventString = $_Lang['ov_une_phalanx']; - } - $EventString .= $FleetContent; - } - else - { - $EventString = $_Lang['ov_une_hostile']; - $EventString .= $FleetContent; - $EventString .= $_Lang['ov_hostile']; - $EventString .= BuildHostileFleetPlayerLink($FleetRow , $Phalanx); - } - - if($Status == 0) - { - $Time = $FleetRow['fleet_start_time']; - $Rest = $Time - time(); - $EventString .= $_Lang['ov_vennant']; - $EventString .= $StartID; - $EventString .= $_Lang['ov_atteint']; - $EventString .= $TargetID; - $EventString .= $_Lang['ov_mission']; - } - else if($Status == 1) - { - $Time = $FleetRow['fleet_end_stay']; - $Rest = $Time - time(); - $EventString .= $_Lang['ov_vennant']; - $EventString .= $StartID; - if($FleetRow['fleet_mission'] == 5) - { - $EventString .= $_Lang['ov_onorbit_stay']; - } - else - { - $EventString .= $_Lang['ov_explo_stay']; - } - $EventString .= $TargetID; - $EventString .= $_Lang['ov_explo_mission']; - } - else if($Status == 2) - { - $Time = $FleetRow['fleet_end_time']; - $Rest = $Time - time(); - $EventString .= $_Lang['ov_rentrant']; - $EventString .= $TargetID; - $EventString .= $StartID; - $EventString .= $_Lang['ov_mission']; - } - $EventString .= $FleetMission; - - $bloc['fleet_status'] = $FleetStatus[$Status]; - $bloc['fleet_prefix'] = $FleetPrefix; - $bloc['fleet_style'] = $FleetStyle[$MissionType]; - $bloc['fleet_order'] = $Label.$Record; - $bloc['fleet_countdown'] = pretty_time($Rest, true); - $bloc['fleet_time'] = str_replace($ThisDate, '', date('d/m | H:i:s', $Time)); - $bloc['fleet_descr'] = $EventString; - GlobalTemplate_AppendToAfterBody(InsertJavaScriptChronoApplet($Label, $Record, $Rest)); - - return parsetemplate($Template, $bloc); -} - -?> \ No newline at end of file + 'attack', + 2 => 'federation', + 3 => 'transport', + 4 => 'deploy', + 5 => 'hold', + 6 => 'espionage', + 7 => 'colony', + 8 => 'harvest', + 9 => 'destroy', + 10 => 'missile', + ); + $FleetStatus = array(0 => 'flight', 1 => 'holding', 2 => 'return'); + + if($Template === false) + { + global $_User; + + GlobalTemplate_AppendToAfterBody(gettemplate('_FleetTable_files')); + $Template = gettemplate('_FleetTable_row'); + if(!empty($_User['settings_FleetColors'])) + { + $TPL_FleetColors_Row = gettemplate('_FleetTable_fleetColors_row'); + $FleetColors = json_decode($_User['settings_FleetColors'], true); + foreach($FleetColors as $TypeKey => $Missions) + { + if($TypeKey == 'ownfly') + { + $ThisType = 'flight'; + $ThisOwn = 'own'; + $CheckHold = true; + } + else if($TypeKey == 'owncb') + { + $ThisType = 'return'; + $ThisOwn = 'own'; + $CheckHold = false; + } + else if($TypeKey == 'nonown') + { + $ThisType = 'flight'; + $ThisOwn = ''; + $CheckHold = true; + } + + foreach($Missions as $MissionID => $MissionColor) + { + if(!empty($MissionColor)) + { + $MissionColors_Styles[] = parsetemplate($TPL_FleetColors_Row, array + ( + 'MissionType' => $ThisType, + 'MissionName' => $ThisOwn.$FleetStyle[$MissionID], + 'MissionColor' => $MissionColor, + )); + if($CheckHold === true AND $MissionID == 5) + { + $MissionColors_Styles[] = parsetemplate($TPL_FleetColors_Row, array + ( + 'MissionType' => 'holding', + 'MissionName' => $ThisOwn.$FleetStyle[$MissionID], + 'MissionColor' => $MissionColor, + )); + } + } + } + } + + if(!empty($MissionColors_Styles)) + { + GlobalTemplate_AppendToAfterBody(parsetemplate(gettemplate('_FleetTable_fleetColors'), array('InsertStyles' => implode(' ', $MissionColors_Styles)))); + } + } + } + if($ThisDate === false) + { + $ThisDate = date('d/m | '); + } + + if($InsertJSChronoApplet_GlobalIncluded !== true) + { + if($InsertJSChronoApplet_Included === false) + { + include('InsertJavaScriptChronoApplet.php'); + $InsertJSChronoApplet_Included = true; + } + } + + if($Owner == true) + { + $FleetPrefix = 'own'; + } + else + { + $FleetPrefix = ''; + } + + $MissionType = $FleetRow['fleet_mission']; + $FleetContent = CreateFleetPopupedFleetLink($FleetRow, (($Owner === true) ? $_Lang['ov_fleet'] : $_Lang['ov_fleet2'])); + $FleetMission = $_Lang['type_mission'][$MissionType]; + + $StartType = $FleetRow['fleet_start_type']; + $TargetType = $FleetRow['fleet_end_type']; + + if($Status != 2) + { + if($StartType == 1) + { + $StartID = $_Lang['ov_planet_to']; + } + else if($StartType == 3) + { + $StartID = $_Lang['ov_moon_to']; + } + $StartID .= $FleetRow['start_name'].' '; + $StartID .= GetStartAdressLink($FleetRow, 'white', $Phalanx); + + if($MissionType != 15) + { + if($TargetType == 1) + { + $TargetID = $_Lang['ov_planet_to_target']; + } + else if($TargetType == 2) + { + $TargetID = $_Lang['ov_debris_to_target']; + } + else if($TargetType == 3) + { + $TargetID = $_Lang['ov_moon_to_target']; + } + } + else + { + $TargetID = $_Lang['ov_explo_to_target']; + } + $TargetID .= $FleetRow['end_name'].' '; + $TargetID .= GetTargetAdressLink($FleetRow, 'white', $Phalanx); + } + else + { + if($StartType == 1) + { + $StartID = $_Lang['ov_back_planet']; + } + else if($StartType == 3) + { + $StartID = $_Lang['ov_back_moon']; + } + $StartID .= $FleetRow['start_name'].' '; + $StartID .= GetStartAdressLink($FleetRow, 'white', $Phalanx); + + if($MissionType != 15) + { + if($TargetType == 1) + { + $TargetID = $_Lang['ov_planet_from']; + } + else if($TargetType == 2) + { + $TargetID = $_Lang['ov_debris_from']; + } + else if($TargetType == 3) + { + $TargetID = $_Lang['ov_moon_from']; + } + } + else + { + $TargetID = $_Lang['ov_explo_from']; + } + $TargetID .= $FleetRow['end_name'].' '; + $TargetID .= GetTargetAdressLink($FleetRow, 'white', $Phalanx); + } + + if($Owner == true) + { + if($Phalanx === false) + { + $EventString = $_Lang['ov_une']; + } + else + { + $EventString = $_Lang['ov_une_phalanx']; + } + $EventString .= $FleetContent; + } + else + { + $EventString = $_Lang['ov_une_hostile']; + $EventString .= $FleetContent; + $EventString .= $_Lang['ov_hostile']; + $EventString .= BuildHostileFleetPlayerLink($FleetRow , $Phalanx); + } + + if($Status == 0) + { + $Time = $FleetRow['fleet_start_time']; + $Rest = $Time - time(); + $EventString .= $_Lang['ov_vennant']; + $EventString .= $StartID; + $EventString .= $_Lang['ov_atteint']; + $EventString .= $TargetID; + $EventString .= $_Lang['ov_mission']; + } + else if($Status == 1) + { + $Time = $FleetRow['fleet_end_stay']; + $Rest = $Time - time(); + $EventString .= $_Lang['ov_vennant']; + $EventString .= $StartID; + if($FleetRow['fleet_mission'] == 5) + { + $EventString .= $_Lang['ov_onorbit_stay']; + } + else + { + $EventString .= $_Lang['ov_explo_stay']; + } + $EventString .= $TargetID; + $EventString .= $_Lang['ov_explo_mission']; + } + else if($Status == 2) + { + $Time = $FleetRow['fleet_end_time']; + $Rest = $Time - time(); + $EventString .= $_Lang['ov_rentrant']; + $EventString .= $TargetID; + $EventString .= $StartID; + $EventString .= $_Lang['ov_mission']; + } + $EventString .= $FleetMission; + + $bloc['fleet_status'] = $FleetStatus[$Status]; + $bloc['fleet_prefix'] = $FleetPrefix; + $bloc['fleet_style'] = $FleetStyle[$MissionType]; + $bloc['fleet_order'] = $Label.$Record; + $bloc['fleet_countdown'] = pretty_time($Rest, true); + $bloc['fleet_time'] = str_replace($ThisDate, '', date('d/m | H:i:s', $Time)); + $bloc['fleet_descr'] = $EventString; + GlobalTemplate_AppendToAfterBody(InsertJavaScriptChronoApplet($Label, $Record, $Rest)); + + return parsetemplate($Template, $bloc); +} + +?> diff --git a/includes/functions/BuildingSavePlanetRecord.php b/includes/functions/BuildingSavePlanetRecord.php index 1cf0aa385..661cf5eec 100644 --- a/includes/functions/BuildingSavePlanetRecord.php +++ b/includes/functions/BuildingSavePlanetRecord.php @@ -1,13 +1,13 @@ - \ No newline at end of file + diff --git a/includes/functions/Cache_Message.php b/includes/functions/Cache_Message.php index 3c710ea2c..4cbeb2957 100644 --- a/includes/functions/Cache_Message.php +++ b/includes/functions/Cache_Message.php @@ -1,46 +1,46 @@ - $OwnerID, - 'id_sender' => $Sender, - 'type' => $Type, - 'time' => $Time, - 'from' => $From, - 'subject' => $Subject, - 'text' => $Message, - 'Thread_ID' => $Thread_ID, - 'Thread_IsLast' => $Thread_IsLast - ); - } - } - else - { - $_Cache['Messages'][] = array - ( - 'id_owner' => $Owners, - 'id_sender' => $Sender, - 'type' => $Type, - 'time' => $Time, - 'from' => $From, - 'subject' => $Subject, - 'text' => $Message, - 'Thread_ID' => $Thread_ID, - 'Thread_IsLast' => $Thread_IsLast - ); - } -} - -?> \ No newline at end of file + $OwnerID, + 'id_sender' => $Sender, + 'type' => $Type, + 'time' => $Time, + 'from' => $From, + 'subject' => $Subject, + 'text' => $Message, + 'Thread_ID' => $Thread_ID, + 'Thread_IsLast' => $Thread_IsLast + ); + } + } + else + { + $_Cache['Messages'][] = array + ( + 'id_owner' => $Owners, + 'id_sender' => $Sender, + 'type' => $Type, + 'time' => $Time, + 'from' => $From, + 'subject' => $Subject, + 'text' => $Message, + 'Thread_ID' => $Thread_ID, + 'Thread_IsLast' => $Thread_IsLast + ); + } +} + +?> diff --git a/includes/functions/CalcInterplanetaryAttack.php b/includes/functions/CalcInterplanetaryAttack.php index eec8c1fa7..a4faf9ca0 100644 --- a/includes/functions/CalcInterplanetaryAttack.php +++ b/includes/functions/CalcInterplanetaryAttack.php @@ -1,157 +1,157 @@ - $Count) - { - $ElementsCount += 1; - $ResourceCost = $_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal'] + $_Vars_Prices[$ID]['deuterium']; - $HullVals[$ID] = floor((($_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal']) / 10) * $HullUpgrade); - $DefsPerSqMeter[$ID] = round(((5 * pow(10, -12) * pow($Count, 1.6)) + 0.5) * (2000 / $ResourceCost), 2); - $TotalDefSystemsCount += $Count; - if($PrimaryTarget > 0) - { - if(($PrimaryTarget + 400) == $ID) - { - $TotalDefSystemsCount -= $Count; - $Proportions[$ID] = (mt_rand(7000, 8000) / 10000); - $ProportionLevel1 = 1 - $Proportions[$ID]; - } - } - } - - foreach($DefSystemsPlanet as $ID => $Count) - { - if($PrimaryTarget > 0) - { - if(($PrimaryTarget + 400) == $ID) - { - continue; - } - } - $Proportions[$ID] = ($Count/$TotalDefSystemsCount) * $ProportionLevel1; - } - arsort($Proportions); - - $MissileForce = floor($_Vars_CombatData[$IPMissileID]['attack'] * $ForceUpgrade); - $MissileRange = floor((log(($AttackerMiliTech + 1), 2) + 1) * 100); - - $Skip = array(); - $SkipCount = 0; - - $SecurityLoop = 500; - - while(true) - { - $SecurityLoop -= 1; - if($SecurityLoop < 0) - { - break; - } - foreach($Proportions as $ID => &$Proportion) - { - if(in_array($ID, $Skip)) - { - continue; - } - $Missiles = floor($Proportion * $LeftMissiles); - if($Missiles <= 0) - { - $Proportion = 1; - continue; - } - if($MissileForce >= $HullVals[$ID]) - { - $Missiles4EnoughForce = 1; - } - else - { - $Missiles4EnoughForce = ceil($HullVals[$ID]/$MissileForce); - } - if($Missiles4EnoughForce > $Missiles) - { - if($Missiles == $LeftMissiles) - { - $Skip[] = $ID; - $SkipCount += 1; - } - continue; - } - $MissilesNeeden = ceil($DefSystemsPlanet[$ID] / ($DefsPerSqMeter[$ID] * $MissileRange)) * $Missiles4EnoughForce; - if($MissilesNeeden <= $Missiles) - { - $Destroyed[$ID] = $DefSystemsPlanet[$ID]; - $UsedMissiles = $MissilesNeeden; - $Skip[] = $ID; - $SkipCount += 1; - } - else - { - if(!isset($Destroyed[$ID])) - { - $Destroyed[$ID] = 0; - } - $TempMissiles = floor($Missiles / $Missiles4EnoughForce); - $Destroyed[$ID] += floor($DefsPerSqMeter[$ID] * $MissileRange * $TempMissiles); - $UsedMissiles = $Missiles; - } - $LeftMissiles -= $UsedMissiles; - $Proportion = 1; - } - if($SkipCount == $ElementsCount OR $LeftMissiles <= 0) - { - break; - } - } - - $DestroyedTotal = 0; - $Metal = 0; - $Crystal = 0; - $Deuterium = 0; - - foreach($DefSystemsPlanet as $ID => $Count) - { - $ThisDef_Destroyed = (isset($Destroyed[$ID]) ? $Destroyed[$ID] : 0); - if($ThisDef_Destroyed > $Count) - { - $ThisDef_Destroyed = $Count; - $Destroyed[$ID] = $Count; - } - $LeftDefs[$ID] = $Count - $ThisDef_Destroyed; - $DestroyedTotal += $ThisDef_Destroyed; - $Metal += $ThisDef_Destroyed * $_Vars_Prices[$ID]['metal']; - $Crystal += $ThisDef_Destroyed * $_Vars_Prices[$ID]['crystal']; - $Deuterium += $ThisDef_Destroyed * $_Vars_Prices[$ID]['deuterium']; - } - - $DebrisField['metal'] = floor($Metal * ($DebrisPercent / 100)); - $DebrisField['crystal'] = floor($Crystal * ($DebrisPercent / 100)); - - $return['LeftDefs'] = $LeftDefs; //How much defence systems left on a Planet - $return['Destroyed'] = $Destroyed; //How much defence systems has been lost - $return['DestroyedTotal'] = $DestroyedTotal; //How much defence systems has been lost (in one number) - $return['Metal_loss'] = $Metal; //How much metal has been lost (for each def sys) - $return['Crystal_loss'] = $Crystal; //How much crystal has been lost (for each def sys) - $return['Deuterium_loss'] = $Deuterium; //How much deuterium has been lost (for each def sys) - $return['IPM_Range'] = $MissileRange; // What is the Range of Missiles - $return['Debris'] = $DebrisField; // Create DebrisField - - return $return; -} - -?> \ No newline at end of file + $Count) + { + $ElementsCount += 1; + $ResourceCost = $_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal'] + $_Vars_Prices[$ID]['deuterium']; + $HullVals[$ID] = floor((($_Vars_Prices[$ID]['metal'] + $_Vars_Prices[$ID]['crystal']) / 10) * $HullUpgrade); + $DefsPerSqMeter[$ID] = round(((5 * pow(10, -12) * pow($Count, 1.6)) + 0.5) * (2000 / $ResourceCost), 2); + $TotalDefSystemsCount += $Count; + if($PrimaryTarget > 0) + { + if(($PrimaryTarget + 400) == $ID) + { + $TotalDefSystemsCount -= $Count; + $Proportions[$ID] = (mt_rand(7000, 8000) / 10000); + $ProportionLevel1 = 1 - $Proportions[$ID]; + } + } + } + + foreach($DefSystemsPlanet as $ID => $Count) + { + if($PrimaryTarget > 0) + { + if(($PrimaryTarget + 400) == $ID) + { + continue; + } + } + $Proportions[$ID] = ($Count/$TotalDefSystemsCount) * $ProportionLevel1; + } + arsort($Proportions); + + $MissileForce = floor($_Vars_CombatData[$IPMissileID]['attack'] * $ForceUpgrade); + $MissileRange = floor((log(($AttackerMiliTech + 1), 2) + 1) * 100); + + $Skip = array(); + $SkipCount = 0; + + $SecurityLoop = 500; + + while(true) + { + $SecurityLoop -= 1; + if($SecurityLoop < 0) + { + break; + } + foreach($Proportions as $ID => &$Proportion) + { + if(in_array($ID, $Skip)) + { + continue; + } + $Missiles = floor($Proportion * $LeftMissiles); + if($Missiles <= 0) + { + $Proportion = 1; + continue; + } + if($MissileForce >= $HullVals[$ID]) + { + $Missiles4EnoughForce = 1; + } + else + { + $Missiles4EnoughForce = ceil($HullVals[$ID]/$MissileForce); + } + if($Missiles4EnoughForce > $Missiles) + { + if($Missiles == $LeftMissiles) + { + $Skip[] = $ID; + $SkipCount += 1; + } + continue; + } + $MissilesNeeden = ceil($DefSystemsPlanet[$ID] / ($DefsPerSqMeter[$ID] * $MissileRange)) * $Missiles4EnoughForce; + if($MissilesNeeden <= $Missiles) + { + $Destroyed[$ID] = $DefSystemsPlanet[$ID]; + $UsedMissiles = $MissilesNeeden; + $Skip[] = $ID; + $SkipCount += 1; + } + else + { + if(!isset($Destroyed[$ID])) + { + $Destroyed[$ID] = 0; + } + $TempMissiles = floor($Missiles / $Missiles4EnoughForce); + $Destroyed[$ID] += floor($DefsPerSqMeter[$ID] * $MissileRange * $TempMissiles); + $UsedMissiles = $Missiles; + } + $LeftMissiles -= $UsedMissiles; + $Proportion = 1; + } + if($SkipCount == $ElementsCount OR $LeftMissiles <= 0) + { + break; + } + } + + $DestroyedTotal = 0; + $Metal = 0; + $Crystal = 0; + $Deuterium = 0; + + foreach($DefSystemsPlanet as $ID => $Count) + { + $ThisDef_Destroyed = (isset($Destroyed[$ID]) ? $Destroyed[$ID] : 0); + if($ThisDef_Destroyed > $Count) + { + $ThisDef_Destroyed = $Count; + $Destroyed[$ID] = $Count; + } + $LeftDefs[$ID] = $Count - $ThisDef_Destroyed; + $DestroyedTotal += $ThisDef_Destroyed; + $Metal += $ThisDef_Destroyed * $_Vars_Prices[$ID]['metal']; + $Crystal += $ThisDef_Destroyed * $_Vars_Prices[$ID]['crystal']; + $Deuterium += $ThisDef_Destroyed * $_Vars_Prices[$ID]['deuterium']; + } + + $DebrisField['metal'] = floor($Metal * ($DebrisPercent / 100)); + $DebrisField['crystal'] = floor($Crystal * ($DebrisPercent / 100)); + + $return['LeftDefs'] = $LeftDefs; //How much defence systems left on a Planet + $return['Destroyed'] = $Destroyed; //How much defence systems has been lost + $return['DestroyedTotal'] = $DestroyedTotal; //How much defence systems has been lost (in one number) + $return['Metal_loss'] = $Metal; //How much metal has been lost (for each def sys) + $return['Crystal_loss'] = $Crystal; //How much crystal has been lost (for each def sys) + $return['Deuterium_loss'] = $Deuterium; //How much deuterium has been lost (for each def sys) + $return['IPM_Range'] = $MissileRange; // What is the Range of Missiles + $return['Debris'] = $DebrisField; // Create DebrisField + + return $return; +} + +?> diff --git a/includes/functions/CancelBuildingFromQueue.php b/includes/functions/CancelBuildingFromQueue.php index d67ce2073..6c9ce310d 100644 --- a/includes/functions/CancelBuildingFromQueue.php +++ b/includes/functions/CancelBuildingFromQueue.php @@ -1,108 +1,108 @@ - 1) - { - array_shift($QueueArray); - // Now update all other elements - $TempPlanet = $CurrentPlanet; - foreach($QueueArray as &$Data) - { - $Data = explode(',', $Data); - $TempTime = GetBuildingTime($CurrentUser, $TempPlanet, $Data[0]); - if($Data[4] == 'build') - { - $TempPlanet[$_Vars_GameElements[$Data[0]]] += 1; - } - else - { - $TempTime /= 2; - $TempPlanet[$_Vars_GameElements[$Data[0]]] -= 1; - } - $RemovedTime += ($Data[2] - $TempTime); - $Data[1] = $TempPlanet[$_Vars_GameElements[$Data[0]]]; - $Data[2] = $TempTime; - $Data[3] -= $RemovedTime; - $Data = implode(',', $Data); - } - $NewQueue = implode(';', $QueueArray); - $ReturnValue = true; - } - else - { - $NewQueue = '0'; - $ReturnValue = false; - } - $BuildEndTime = '0'; - } - - // Now let's return used resources - // First - check mode - if($BuildMode == 'destroy') - { - $ForDestroy = true; - } - else - { - $ForDestroy = false; - } - - if($Element != false) - { - $Needed = GetBuildingPrice($CurrentUser, $CurrentPlanet, $Element, true, $ForDestroy); - $CurrentPlanet['metal'] += $Needed['metal']; - $CurrentPlanet['crystal'] += $Needed['crystal']; - $CurrentPlanet['deuterium'] += $Needed['deuterium']; - - if($ForDestroy) - { - $SetCode = 2; - } - else - { - $SetCode = 1; - } - $UserDev_Log[] = array('PlanetID' => $CurrentPlanet['id'], 'Date' => $Now, 'Place' => 2, 'Code' => $SetCode, 'ElementID' => $Element); - } - } - else - { - $NewQueue = '0'; - $BuildEndTime = '0'; - $ReturnValue = false; - } - - $CurrentPlanet['buildQueue'] = $NewQueue; - $CurrentPlanet['buildQueue_firstEndTime'] = $BuildEndTime; - - return $Element; -} - -?> \ No newline at end of file + 1) + { + array_shift($QueueArray); + // Now update all other elements + $TempPlanet = $CurrentPlanet; + foreach($QueueArray as &$Data) + { + $Data = explode(',', $Data); + $TempTime = GetBuildingTime($CurrentUser, $TempPlanet, $Data[0]); + if($Data[4] == 'build') + { + $TempPlanet[$_Vars_GameElements[$Data[0]]] += 1; + } + else + { + $TempTime /= 2; + $TempPlanet[$_Vars_GameElements[$Data[0]]] -= 1; + } + $RemovedTime += ($Data[2] - $TempTime); + $Data[1] = $TempPlanet[$_Vars_GameElements[$Data[0]]]; + $Data[2] = $TempTime; + $Data[3] -= $RemovedTime; + $Data = implode(',', $Data); + } + $NewQueue = implode(';', $QueueArray); + $ReturnValue = true; + } + else + { + $NewQueue = '0'; + $ReturnValue = false; + } + $BuildEndTime = '0'; + } + + // Now let's return used resources + // First - check mode + if($BuildMode == 'destroy') + { + $ForDestroy = true; + } + else + { + $ForDestroy = false; + } + + if($Element != false) + { + $Needed = GetBuildingPrice($CurrentUser, $CurrentPlanet, $Element, true, $ForDestroy); + $CurrentPlanet['metal'] += $Needed['metal']; + $CurrentPlanet['crystal'] += $Needed['crystal']; + $CurrentPlanet['deuterium'] += $Needed['deuterium']; + + if($ForDestroy) + { + $SetCode = 2; + } + else + { + $SetCode = 1; + } + $UserDev_Log[] = array('PlanetID' => $CurrentPlanet['id'], 'Date' => $Now, 'Place' => 2, 'Code' => $SetCode, 'ElementID' => $Element); + } + } + else + { + $NewQueue = '0'; + $BuildEndTime = '0'; + $ReturnValue = false; + } + + $CurrentPlanet['buildQueue'] = $NewQueue; + $CurrentPlanet['buildQueue_firstEndTime'] = $BuildEndTime; + + return $Element; +} + +?> diff --git a/includes/functions/ChatUtilities.php b/includes/functions/ChatUtilities.php index 4221b1b4b..dd184814a 100644 --- a/includes/functions/ChatUtilities.php +++ b/includes/functions/ChatUtilities.php @@ -1,66 +1,66 @@ - $RankData) - { - if($RankID != $ThisUser['ally_rank_id']) - { - continue; - } - foreach($RankData as $DataID => $DataVal) - { - $Temp2[$_Vars_AllyRankLabels[$DataID]] = $DataVal; - } - } - if($Temp2['canusechat'] !== true) - { - return false; - } - } - } - else if($Result_CheckRoom['AccessType'] == 2) - { - // This is GameTeam Room - if($ThisUser['authlevel'] < $Result_CheckRoom['AccessCheck']) - { - return false; - } - } - } - - return true; -} - -?> \ No newline at end of file + $RankData) + { + if($RankID != $ThisUser['ally_rank_id']) + { + continue; + } + foreach($RankData as $DataID => $DataVal) + { + $Temp2[$_Vars_AllyRankLabels[$DataID]] = $DataVal; + } + } + if($Temp2['canusechat'] !== true) + { + return false; + } + } + } + else if($Result_CheckRoom['AccessType'] == 2) + { + // This is GameTeam Room + if($ThisUser['authlevel'] < $Result_CheckRoom['AccessCheck']) + { + return false; + } + } + } + + return true; +} + +?> diff --git a/includes/functions/CheckLabInQueue.php b/includes/functions/CheckLabInQueue.php index 2acfaaa8d..b701099d7 100644 --- a/includes/functions/CheckLabInQueue.php +++ b/includes/functions/CheckLabInQueue.php @@ -1,28 +1,28 @@ - \ No newline at end of file + diff --git a/includes/functions/CheckPlanetUsedFields.php b/includes/functions/CheckPlanetUsedFields.php index 59b7a4ceb..6b90ee892 100644 --- a/includes/functions/CheckPlanetUsedFields.php +++ b/includes/functions/CheckPlanetUsedFields.php @@ -1,20 +1,20 @@ - \ No newline at end of file + diff --git a/includes/functions/CheckUserSession.php b/includes/functions/CheckUserSession.php index 73d799b59..e70bc427e 100644 --- a/includes/functions/CheckUserSession.php +++ b/includes/functions/CheckUserSession.php @@ -1,104 +1,104 @@ - $Now) - { - if(strstr($_SERVER['SCRIPT_NAME'], 'logout.php') !== false || strstr($_SERVER['SCRIPT_NAME'], 'contact.php') !== false) - { - $GetScriptNameExplode = explode('/', $_SERVER['SCRIPT_NAME']); - $GetScriptName = end($GetScriptNameExplode); - if($GetScriptName == 'logout.php' || $GetScriptName == 'contact.php') - { - $DontBlockIfBanned = true; - } - } - - if(!isset($DontBlockIfBanned)) - { - includeLang('bannedUser'); - include("{$_EnginePath}/includes/functions/InsertJavaScriptChronoApplet.php"); - $_SkinPath = DEFAULT_SKINPATH; - - $Query_GetBanInfo = ''; - $Query_GetBanInfo .= "SELECT `Ban`.*, `users`.`username` AS `GiverName` FROM {{table}} AS `Ban` "; - $Query_GetBanInfo .= "LEFT JOIN `{{prefix}}users` AS `users` ON `users`.`id` = `Ban`.`GiverID` AND `Ban`.`GiverID` > 0 "; - $Query_GetBanInfo .= "WHERE `UserID` = '{$Result['id']}' AND `Active` = 1 ORDER BY `ID` DESC LIMIT 1;"; - $Ban = doquery($Query_GetBanInfo, 'bans', true); - - $Parse = $_Lang; - $Parse['Insert_StartTime'] = prettyDate('d m Y \o H:i:s', $Ban['StartTime'], 1); - $Parse['Insert_EndTime'] = prettyDate('d m Y \o H:i:s', $Ban['EndTime'], 1); - - $Parse['ChronoApplet'] = InsertJavaScriptChronoApplet('ban', '', $Ban['EndTime'], true); - $Parse['Insert_EndTimer'] = pretty_time($Ban['EndTime'] - $Now, true, 'D'); - if(!empty($Ban['Reason'])) - { - $Parse['Insert_Reason'] = $Ban['Reason']; - } - else - { - $Parse['Insert_Reason'] = $_Lang['Ban_Reason_NotSpecified']; - } - $Parse['Insert_Giver'] = ($Ban['GiverID'] > 0 ? "{$Ban['GiverName']}" : "{$_Lang['ban_bysys']}"); - $Parse['Insert_VacationInfo'] = ($Ban['With_Vacation'] == 1 ? $_Lang['Ban_WithVacation'] : $_Lang['Ban_WithoutVacation']); - if($Ban['Fleets_Retreated_Own'] == 1 AND $Ban['Fleets_Retreated_Others'] == 1) - { - $Parse['Insert_FleetsInfo'] = $_Lang['Ban_RetreatedAll']; - } - else if($Ban['Fleets_Retreated_Own'] == 1) - { - $Parse['Insert_FleetsInfo'] = $_Lang['Ban_RetreatedOwn']; - } - else if($Ban['Fleets_Retreated_Others'] == 1) - { - $Parse['Insert_FleetsInfo'] = $_Lang['Ban_RetreatedOthers']; - } - else - { - $Parse['Insert_FleetsInfo'] = $_Lang['Ban_RetreatedNone']; - } - - if($Result['block_cookies'] == 1) - { - setcookie(COOKIE_BLOCK, (COOKIE_BLOCK_VAL.md5($Result['id'])), $Now + (TIME_YEAR * 30), '', '', false, true); - } - $_DontShowMenus = true; - display(parsetemplate(gettemplate('baninfo'), $Parse), $_Lang['Ban_Header'], false); - } - } - else - { - doquery("UPDATE {{table}} SET `is_banned` = 0, `ban_endtime` = 0 WHERE `id` = {$Result['id']};", 'users'); - doquery("UPDATE {{table}} SET `Active` = 0, `Expired` = 1 WHERE `Active` = 1 AND `UserID` = {$Result['id']};", 'bans'); - } - } - $Return = $Result; - } - else - { - $Return = array(); - } - - // Online Record Handler - $OnlineUsers = doquery("SELECT COUNT(`id`) AS `Count` FROM {{table}} WHERE `onlinetime` >= (UNIX_TIMESTAMP() - ".TIME_ONLINE.");", 'users', true); - if($OnlineUsers['Count'] > $_GameConfig['rekord']) - { - doquery("UPDATE {{table}} SET `config_value` = '{$OnlineUsers['Count']}' WHERE `config_name` = 'rekord';", 'config'); - $_GameConfig['rekord'] = $OnlineUsers['Count']; - $_MemCache->GameConfig = $_GameConfig; - } - - return $Return; -} - -?> \ No newline at end of file + $Now) + { + if(strstr($_SERVER['SCRIPT_NAME'], 'logout.php') !== false || strstr($_SERVER['SCRIPT_NAME'], 'contact.php') !== false) + { + $GetScriptNameExplode = explode('/', $_SERVER['SCRIPT_NAME']); + $GetScriptName = end($GetScriptNameExplode); + if($GetScriptName == 'logout.php' || $GetScriptName == 'contact.php') + { + $DontBlockIfBanned = true; + } + } + + if(!isset($DontBlockIfBanned)) + { + includeLang('bannedUser'); + include("{$_EnginePath}/includes/functions/InsertJavaScriptChronoApplet.php"); + $_SkinPath = DEFAULT_SKINPATH; + + $Query_GetBanInfo = ''; + $Query_GetBanInfo .= "SELECT `Ban`.*, `users`.`username` AS `GiverName` FROM {{table}} AS `Ban` "; + $Query_GetBanInfo .= "LEFT JOIN `{{prefix}}users` AS `users` ON `users`.`id` = `Ban`.`GiverID` AND `Ban`.`GiverID` > 0 "; + $Query_GetBanInfo .= "WHERE `UserID` = '{$Result['id']}' AND `Active` = 1 ORDER BY `ID` DESC LIMIT 1;"; + $Ban = doquery($Query_GetBanInfo, 'bans', true); + + $Parse = $_Lang; + $Parse['Insert_StartTime'] = prettyDate('d m Y \o H:i:s', $Ban['StartTime'], 1); + $Parse['Insert_EndTime'] = prettyDate('d m Y \o H:i:s', $Ban['EndTime'], 1); + + $Parse['ChronoApplet'] = InsertJavaScriptChronoApplet('ban', '', $Ban['EndTime'], true); + $Parse['Insert_EndTimer'] = pretty_time($Ban['EndTime'] - $Now, true, 'D'); + if(!empty($Ban['Reason'])) + { + $Parse['Insert_Reason'] = $Ban['Reason']; + } + else + { + $Parse['Insert_Reason'] = $_Lang['Ban_Reason_NotSpecified']; + } + $Parse['Insert_Giver'] = ($Ban['GiverID'] > 0 ? "{$Ban['GiverName']}" : "{$_Lang['ban_bysys']}"); + $Parse['Insert_VacationInfo'] = ($Ban['With_Vacation'] == 1 ? $_Lang['Ban_WithVacation'] : $_Lang['Ban_WithoutVacation']); + if($Ban['Fleets_Retreated_Own'] == 1 AND $Ban['Fleets_Retreated_Others'] == 1) + { + $Parse['Insert_FleetsInfo'] = $_Lang['Ban_RetreatedAll']; + } + else if($Ban['Fleets_Retreated_Own'] == 1) + { + $Parse['Insert_FleetsInfo'] = $_Lang['Ban_RetreatedOwn']; + } + else if($Ban['Fleets_Retreated_Others'] == 1) + { + $Parse['Insert_FleetsInfo'] = $_Lang['Ban_RetreatedOthers']; + } + else + { + $Parse['Insert_FleetsInfo'] = $_Lang['Ban_RetreatedNone']; + } + + if($Result['block_cookies'] == 1) + { + setcookie(COOKIE_BLOCK, (COOKIE_BLOCK_VAL.md5($Result['id'])), $Now + (TIME_YEAR * 30), '', '', false, true); + } + $_DontShowMenus = true; + display(parsetemplate(gettemplate('baninfo'), $Parse), $_Lang['Ban_Header'], false); + } + } + else + { + doquery("UPDATE {{table}} SET `is_banned` = 0, `ban_endtime` = 0 WHERE `id` = {$Result['id']};", 'users'); + doquery("UPDATE {{table}} SET `Active` = 0, `Expired` = 1 WHERE `Active` = 1 AND `UserID` = {$Result['id']};", 'bans'); + } + } + $Return = $Result; + } + else + { + $Return = array(); + } + + // Online Record Handler + $OnlineUsers = doquery("SELECT COUNT(`id`) AS `Count` FROM {{table}} WHERE `onlinetime` >= (UNIX_TIMESTAMP() - ".TIME_ONLINE.");", 'users', true); + if($OnlineUsers['Count'] > $_GameConfig['rekord']) + { + doquery("UPDATE {{table}} SET `config_value` = '{$OnlineUsers['Count']}' WHERE `config_name` = 'rekord';", 'config'); + $_GameConfig['rekord'] = $OnlineUsers['Count']; + $_MemCache->GameConfig = $_GameConfig; + } + + return $Return; +} + +?> diff --git a/includes/functions/CheckUserSessionCookie.php b/includes/functions/CheckUserSessionCookie.php index 5517a887c..e4b64fb5a 100644 --- a/includes/functions/CheckUserSessionCookie.php +++ b/includes/functions/CheckUserSessionCookie.php @@ -1,98 +1,98 @@ - \ No newline at end of file + diff --git a/includes/functions/ConvertBattleReport.php b/includes/functions/ConvertBattleReport.php index 7193dde08..b357d1260 100644 --- a/includes/functions/ConvertBattleReport.php +++ b/includes/functions/ConvertBattleReport.php @@ -1,277 +1,277 @@ -{$_Lang['BattleReportConverter_CannotConvert']}", $_Lang['Title_System']); - } - $ReportData = json_decode($Report['report'], true); - - // All Rounds - $Rounds = $ReportData['rounds']; - $RoundsCount = count($Rounds); - - // Battle Result - $Result = $ReportData['init']['result']; - $Stolen['met'] = $ReportData['init']['met']; - $Stolen['cry'] = $ReportData['init']['cry']; - $Stolen['deu'] = $ReportData['init']['deu']; - $Debris['met'] = $ReportData['init']['deb_met']; - $Debris['cry'] = $ReportData['init']['deb_cry']; - $MoonChance = $ReportData['init']['moon_chance']; - $TotalMoonChance = $ReportData['init']['total_moon_chance']; - $CreatedMoon = $ReportData['init']['moon_created']; - $MoonDestroyed = $ReportData['init']['moon_destroyed']; - $DestroyMoonChance = $ReportData['init']['moon_des_chance']; - $FleetDestroyed = $ReportData['init']['fleet_destroyed']; - $DestroyFleetChance = $ReportData['init']['fleet_des_chance']; - $IsOnMoon = $ReportData['init']['onMoon']; - $LostUnits['atk'] = $ReportData['init']['atk_lost']; - $LostUnits['def'] = $ReportData['init']['def_lost']; - - // Misc. - $GenerateTime = $ReportData['init']['time']; - - // Users data - $Users = $ReportData['init']['usr']; - - //////////////////////////////////////////////////////////////////////////////////// - // Let's convert the Battle Report! - - $ReportCode = '[align=center][size=medium][b]'.sprintf($_Lang['sys_attack_title'], prettyDate("d m Y - H:i:s", $Date, 1)).'[/b][/size]'."\n\n"; - - $TempColors = $Settings['colorArray']; - foreach($_Vars_ElementCategories['fleet'] as $ElementID) - { - $UnitColors[$ElementID] = array_shift($TempColors); - $TempColors[] = $UnitColors[$ElementID]; - } - $TempColors = $Settings['colorArray']; - foreach($_Vars_ElementCategories['defense'] as $ElementID) - { - $UnitColors[$ElementID] = array_shift($TempColors); - $TempColors[] = $UnitColors[$ElementID]; - } - - foreach($Rounds as $Number => $Data) - { - if($Number != 1 AND $Number != $RoundsCount) - { - if($AddedAfterXRound !== true) - { - $ReportCode .= sprintf($_Lang['Conv_after_x_rounds'], ($RoundsCount - 1)); - $ReportCode .= "\n\n\n"; - $AddedAfterXRound = true; - } - continue; - } - if($Number == 2 AND $RoundsCount == 2) - { - $ReportCode .= $_Lang['Conv_in_next_round']; - $ReportCode .= "\n\n\n"; - } - - foreach($Users as $TypeKey => $UsersData) - { - foreach($UsersData as $UserID => $UserData) - { - $ThisLists_Fleet = false; - $ThisLists_Defense = false; - - if(empty($UsersParsed[$TypeKey][$UserID])) - { - if(empty($UserData['username'])) - { - $UserData['username'] = $_Lang['Conv_def_abandoned_'.($IsOnMoon ? '3' : '1')]; - } - $UsersParsed[$TypeKey][$UserID]['name'] = sprintf('[u]'.($TypeKey == 'atk' ? $_Lang['Conv_att_user'] : $_Lang['Conv_def_user']).'[/u]', $UserData['username'], (empty($UserData['ally']) ? '' : "[b][color=orange][{$UserData['ally']}][/color][/b]"), 'x', 'xxx', 'xx'); - $UsersParsed[$TypeKey][$UserID]['tech'] = $_Lang['Conv_tech']; - } - $ReportCode .= "{$UsersParsed[$TypeKey][$UserID]['name']}\n[size=xx-small]{$UsersParsed[$TypeKey][$UserID]['tech']}[/size]\n"; - - if($Number == 1 AND !empty($Data[$TypeKey]['ships'][$UserID])) - { - $InitState[$TypeKey][$UserID] = String2Array($Data[$TypeKey]['ships'][$UserID]); - } - if(!empty($InitState[$TypeKey][$UserID])) - { - if($Number == 1) - { - $Data[$TypeKey]['ships'][$UserID] = $InitState[$TypeKey][$UserID]; - } - else - { - $Data[$TypeKey]['ships'][$UserID] = String2Array($Data[$TypeKey]['ships'][$UserID]); - } - - foreach($InitState[$TypeKey][$UserID] as $ShipID => $ShipInitCount) - { - if($ThisLists_Fleet === false AND in_array($ShipID, $_Vars_ElementCategories['fleet'])) - { - $ReportCode .= "\n[u][i]{$_Lang['Conv_fleet']}[/i][/u]\n"; - $ThisLists_Fleet = true; - } - if($ThisLists_Defense === false AND in_array($ShipID, $_Vars_ElementCategories['defense'])) - { - $ReportCode .= "\n[u][i]{$_Lang['Conv_defense']}[/i][/u]\n"; - $ThisLists_Defense = true; - } - $DiffCounter = ''; - $CurrentCount = (isset($Data[$TypeKey]['ships'][$UserID][$ShipID]) ? $Data[$TypeKey]['ships'][$UserID][$ShipID] : 0); - if($CurrentCount < $ShipInitCount) - { - $DiffCounter = ' (- '.prettyNumber($ShipInitCount - $CurrentCount).')'; - if($CurrentCount == 0) - { - $DiffCounter = "[color=red]{$DiffCounter}[/color]"; - } - } - $ReportCode .= "[b][color=#{$UnitColors[$ShipID]}]{$_Lang['tech'][$ShipID]}: ".prettyNumber($CurrentCount)."[/color]{$DiffCounter}[/b]\n"; - } - $ReportCode .= "\n"; - } - else - { - $ReportCode .= "\n[b][color=red]{$_Lang['sys_destroyed']}[/color][/b]\n"; - } - } - $ReportCode .= "\n"; - } - } - - $ReportCode .= "\n"; - - $AtkLostColStart = $AtkLostColEnd = $DefLostColStart = $DefLostColEnd = ''; - if($LostUnits['atk'] > $LostUnits['def']) - { - $AtkLostColStart = '[color=red]'; - $AtkLostColEnd = '[/color]'; - } - else if($LostUnits['atk'] == $LostUnits['def']) - { - $AtkLostColStart = '[color=orange]'; - $AtkLostColEnd = '[/color]'; - $DefLostColStart = '[color=orange]'; - $DefLostColEnd = '[/color]'; - } - else - { - $DefLostColStart = '[color=red]'; - $DefLostColEnd = '[/color]'; - } - $TotalLostUnits = $LostUnits['atk'] + $LostUnits['def']; - - $StrAttackerUnits = sprintf($_Lang['Conv_atk_lostUnits'], $AtkLostColStart.prettyNumber($LostUnits['atk']).$AtkLostColEnd, ($TotalLostUnits > 0 ? sprintf('%0.2f', ($LostUnits['atk'] / $TotalLostUnits) * 100) : '0.00')); - $StrDefenderUnits = sprintf($_Lang['Conv_def_lostUnits'], $DefLostColStart.prettyNumber($LostUnits['def']).$DefLostColEnd, ($TotalLostUnits > 0 ? sprintf('%0.2f', ($LostUnits['def'] / $TotalLostUnits) * 100) : '0.00')); - $StrRuins = sprintf($_Lang['Conv_DebrisField'], '[b]'.prettyNumber($Debris['met']).'[/b]', $_Lang['Metal_rec'], '[b]'.prettyNumber($Debris['cry']).'[/b]', $_Lang['Crystal_rec']); - $DebrisField = "{$StrAttackerUnits}\n{$StrDefenderUnits}\n{$StrRuins}"; - - $MoonCreationChanceText = false; - if($MoonChance !== false) - { - if($TotalMoonChance > $MoonChance) - { - $MoonCreationChanceText = sprintf($_Lang['Conv_moon_high'], $MoonChance, prettyNumber($TotalMoonChance)); - } - else - { - $MoonCreationChanceText = sprintf($_Lang['Conv_moon_reg'], $MoonChance); - } - } - - if($CreatedMoon === true) - { - $MoonCreationText = $_Lang['Conv_moonbuild']; - } - else - { - $MoonCreationText = false; - } - - $MoonDestroyText = ''; - switch($Result) - { - case COMBAT_ATK: - { - // Attacker won the battle - $Pillage = sprintf($_Lang['sys_stealed_ressources'], '[b]'.prettyNumber($Stolen['met']).'[/b]', $_Lang['Metal_rec'], '[b]'.prettyNumber($Stolen['cry']).'[/b]', $_Lang['Crystal_rec'], '[b]'.prettyNumber($Stolen['deu']).'[/b]', $_Lang['Deuterium_rec']); - $ReportCode .= "[b]{$_Lang['sys_attacker_won']}[/b]\n{$Pillage}\n"; - $ReportCode .= $DebrisField."\n"; - if($MoonDestroyed !== false) - { - if($MoonDestroyed === 1 AND $FleetDestroyed !== true) - { - $MoonDestroyText = $_Lang['sys_destruction_onlymoon']; - } - else if($MoonDestroyed === 1 AND $FleetDestroyed == true) - { - $MoonDestroyText = $_Lang['sys_destruction_both']; - } - else if($MoonDestroyed === 0 AND $FleetDestroyed == true) - { - $MoonDestroyText = $_Lang['sys_destruction_onlyfleet']; - } - else - { - $MoonDestroyText = $_Lang['sys_destruction_nothing']; - } - - $MoonDestroyText = ''; - $MoonDestroyText .= "[b]{$MoonDestroyText}[/b]\n"; - $MoonDestroyText .= sprintf($_Lang['sys_destruc_lune'], '[b]'.$DestroyMoonChance.'[/b]')."\n"; - $MoonDestroyText .= sprintf($_Lang['sys_destruc_rip'], '[b]'.$DestroyFleetChance.'[/b]')."\n"; - } - break; - } - case COMBAT_DEF: - { - // Defender won the battle - $ReportCode .= "[b]{$_Lang['sys_defender_won']}[/b]\n"; - $ReportCode .= $DebrisField."\n"; - break; - } - case COMBAT_DRAW: - { - // It's a draw! - $ReportCode .= "[b]{$_Lang['sys_both_won']}[/b]\n"; - $ReportCode .= $DebrisField."\n"; - break; - } - } - if($MoonCreationChanceText) - { - $ReportCode .= $MoonCreationChanceText."\n"; - } - if($MoonCreationText) - { - $ReportCode .= $MoonCreationText."\n"; - } - if($IsOnMoon) - { - $ReportCode .= $_Lang['Conv_battleonMoon']."\n"; - } - - $ReportCode .= $MoonDestroyText; - - $ReportCode .= sprintf($_Lang['sys_rapport_build_time'], '[b]'.$GenerateTime.'[/b]'); - $ReportCode .= "\n".$_Lang['Conv_generated_by']; - $ReportCode .= '[/align]'; - - return $ReportCode; -} - -?> \ No newline at end of file +{$_Lang['BattleReportConverter_CannotConvert']}", $_Lang['Title_System']); + } + $ReportData = json_decode($Report['report'], true); + + // All Rounds + $Rounds = $ReportData['rounds']; + $RoundsCount = count($Rounds); + + // Battle Result + $Result = $ReportData['init']['result']; + $Stolen['met'] = $ReportData['init']['met']; + $Stolen['cry'] = $ReportData['init']['cry']; + $Stolen['deu'] = $ReportData['init']['deu']; + $Debris['met'] = $ReportData['init']['deb_met']; + $Debris['cry'] = $ReportData['init']['deb_cry']; + $MoonChance = $ReportData['init']['moon_chance']; + $TotalMoonChance = $ReportData['init']['total_moon_chance']; + $CreatedMoon = $ReportData['init']['moon_created']; + $MoonDestroyed = $ReportData['init']['moon_destroyed']; + $DestroyMoonChance = $ReportData['init']['moon_des_chance']; + $FleetDestroyed = $ReportData['init']['fleet_destroyed']; + $DestroyFleetChance = $ReportData['init']['fleet_des_chance']; + $IsOnMoon = $ReportData['init']['onMoon']; + $LostUnits['atk'] = $ReportData['init']['atk_lost']; + $LostUnits['def'] = $ReportData['init']['def_lost']; + + // Misc. + $GenerateTime = $ReportData['init']['time']; + + // Users data + $Users = $ReportData['init']['usr']; + + //////////////////////////////////////////////////////////////////////////////////// + // Let's convert the Battle Report! + + $ReportCode = '[align=center][size=medium][b]'.sprintf($_Lang['sys_attack_title'], prettyDate("d m Y - H:i:s", $Date, 1)).'[/b][/size]'."\n\n"; + + $TempColors = $Settings['colorArray']; + foreach($_Vars_ElementCategories['fleet'] as $ElementID) + { + $UnitColors[$ElementID] = array_shift($TempColors); + $TempColors[] = $UnitColors[$ElementID]; + } + $TempColors = $Settings['colorArray']; + foreach($_Vars_ElementCategories['defense'] as $ElementID) + { + $UnitColors[$ElementID] = array_shift($TempColors); + $TempColors[] = $UnitColors[$ElementID]; + } + + foreach($Rounds as $Number => $Data) + { + if($Number != 1 AND $Number != $RoundsCount) + { + if($AddedAfterXRound !== true) + { + $ReportCode .= sprintf($_Lang['Conv_after_x_rounds'], ($RoundsCount - 1)); + $ReportCode .= "\n\n\n"; + $AddedAfterXRound = true; + } + continue; + } + if($Number == 2 AND $RoundsCount == 2) + { + $ReportCode .= $_Lang['Conv_in_next_round']; + $ReportCode .= "\n\n\n"; + } + + foreach($Users as $TypeKey => $UsersData) + { + foreach($UsersData as $UserID => $UserData) + { + $ThisLists_Fleet = false; + $ThisLists_Defense = false; + + if(empty($UsersParsed[$TypeKey][$UserID])) + { + if(empty($UserData['username'])) + { + $UserData['username'] = $_Lang['Conv_def_abandoned_'.($IsOnMoon ? '3' : '1')]; + } + $UsersParsed[$TypeKey][$UserID]['name'] = sprintf('[u]'.($TypeKey == 'atk' ? $_Lang['Conv_att_user'] : $_Lang['Conv_def_user']).'[/u]', $UserData['username'], (empty($UserData['ally']) ? '' : "[b][color=orange][{$UserData['ally']}][/color][/b]"), 'x', 'xxx', 'xx'); + $UsersParsed[$TypeKey][$UserID]['tech'] = $_Lang['Conv_tech']; + } + $ReportCode .= "{$UsersParsed[$TypeKey][$UserID]['name']}\n[size=xx-small]{$UsersParsed[$TypeKey][$UserID]['tech']}[/size]\n"; + + if($Number == 1 AND !empty($Data[$TypeKey]['ships'][$UserID])) + { + $InitState[$TypeKey][$UserID] = String2Array($Data[$TypeKey]['ships'][$UserID]); + } + if(!empty($InitState[$TypeKey][$UserID])) + { + if($Number == 1) + { + $Data[$TypeKey]['ships'][$UserID] = $InitState[$TypeKey][$UserID]; + } + else + { + $Data[$TypeKey]['ships'][$UserID] = String2Array($Data[$TypeKey]['ships'][$UserID]); + } + + foreach($InitState[$TypeKey][$UserID] as $ShipID => $ShipInitCount) + { + if($ThisLists_Fleet === false AND in_array($ShipID, $_Vars_ElementCategories['fleet'])) + { + $ReportCode .= "\n[u][i]{$_Lang['Conv_fleet']}[/i][/u]\n"; + $ThisLists_Fleet = true; + } + if($ThisLists_Defense === false AND in_array($ShipID, $_Vars_ElementCategories['defense'])) + { + $ReportCode .= "\n[u][i]{$_Lang['Conv_defense']}[/i][/u]\n"; + $ThisLists_Defense = true; + } + $DiffCounter = ''; + $CurrentCount = (isset($Data[$TypeKey]['ships'][$UserID][$ShipID]) ? $Data[$TypeKey]['ships'][$UserID][$ShipID] : 0); + if($CurrentCount < $ShipInitCount) + { + $DiffCounter = ' (- '.prettyNumber($ShipInitCount - $CurrentCount).')'; + if($CurrentCount == 0) + { + $DiffCounter = "[color=red]{$DiffCounter}[/color]"; + } + } + $ReportCode .= "[b][color=#{$UnitColors[$ShipID]}]{$_Lang['tech'][$ShipID]}: ".prettyNumber($CurrentCount)."[/color]{$DiffCounter}[/b]\n"; + } + $ReportCode .= "\n"; + } + else + { + $ReportCode .= "\n[b][color=red]{$_Lang['sys_destroyed']}[/color][/b]\n"; + } + } + $ReportCode .= "\n"; + } + } + + $ReportCode .= "\n"; + + $AtkLostColStart = $AtkLostColEnd = $DefLostColStart = $DefLostColEnd = ''; + if($LostUnits['atk'] > $LostUnits['def']) + { + $AtkLostColStart = '[color=red]'; + $AtkLostColEnd = '[/color]'; + } + else if($LostUnits['atk'] == $LostUnits['def']) + { + $AtkLostColStart = '[color=orange]'; + $AtkLostColEnd = '[/color]'; + $DefLostColStart = '[color=orange]'; + $DefLostColEnd = '[/color]'; + } + else + { + $DefLostColStart = '[color=red]'; + $DefLostColEnd = '[/color]'; + } + $TotalLostUnits = $LostUnits['atk'] + $LostUnits['def']; + + $StrAttackerUnits = sprintf($_Lang['Conv_atk_lostUnits'], $AtkLostColStart.prettyNumber($LostUnits['atk']).$AtkLostColEnd, ($TotalLostUnits > 0 ? sprintf('%0.2f', ($LostUnits['atk'] / $TotalLostUnits) * 100) : '0.00')); + $StrDefenderUnits = sprintf($_Lang['Conv_def_lostUnits'], $DefLostColStart.prettyNumber($LostUnits['def']).$DefLostColEnd, ($TotalLostUnits > 0 ? sprintf('%0.2f', ($LostUnits['def'] / $TotalLostUnits) * 100) : '0.00')); + $StrRuins = sprintf($_Lang['Conv_DebrisField'], '[b]'.prettyNumber($Debris['met']).'[/b]', $_Lang['Metal_rec'], '[b]'.prettyNumber($Debris['cry']).'[/b]', $_Lang['Crystal_rec']); + $DebrisField = "{$StrAttackerUnits}\n{$StrDefenderUnits}\n{$StrRuins}"; + + $MoonCreationChanceText = false; + if($MoonChance !== false) + { + if($TotalMoonChance > $MoonChance) + { + $MoonCreationChanceText = sprintf($_Lang['Conv_moon_high'], $MoonChance, prettyNumber($TotalMoonChance)); + } + else + { + $MoonCreationChanceText = sprintf($_Lang['Conv_moon_reg'], $MoonChance); + } + } + + if($CreatedMoon === true) + { + $MoonCreationText = $_Lang['Conv_moonbuild']; + } + else + { + $MoonCreationText = false; + } + + $MoonDestroyText = ''; + switch($Result) + { + case COMBAT_ATK: + { + // Attacker won the battle + $Pillage = sprintf($_Lang['sys_stealed_ressources'], '[b]'.prettyNumber($Stolen['met']).'[/b]', $_Lang['Metal_rec'], '[b]'.prettyNumber($Stolen['cry']).'[/b]', $_Lang['Crystal_rec'], '[b]'.prettyNumber($Stolen['deu']).'[/b]', $_Lang['Deuterium_rec']); + $ReportCode .= "[b]{$_Lang['sys_attacker_won']}[/b]\n{$Pillage}\n"; + $ReportCode .= $DebrisField."\n"; + if($MoonDestroyed !== false) + { + if($MoonDestroyed === 1 AND $FleetDestroyed !== true) + { + $MoonDestroyText = $_Lang['sys_destruction_onlymoon']; + } + else if($MoonDestroyed === 1 AND $FleetDestroyed == true) + { + $MoonDestroyText = $_Lang['sys_destruction_both']; + } + else if($MoonDestroyed === 0 AND $FleetDestroyed == true) + { + $MoonDestroyText = $_Lang['sys_destruction_onlyfleet']; + } + else + { + $MoonDestroyText = $_Lang['sys_destruction_nothing']; + } + + $MoonDestroyText = ''; + $MoonDestroyText .= "[b]{$MoonDestroyText}[/b]\n"; + $MoonDestroyText .= sprintf($_Lang['sys_destruc_lune'], '[b]'.$DestroyMoonChance.'[/b]')."\n"; + $MoonDestroyText .= sprintf($_Lang['sys_destruc_rip'], '[b]'.$DestroyFleetChance.'[/b]')."\n"; + } + break; + } + case COMBAT_DEF: + { + // Defender won the battle + $ReportCode .= "[b]{$_Lang['sys_defender_won']}[/b]\n"; + $ReportCode .= $DebrisField."\n"; + break; + } + case COMBAT_DRAW: + { + // It's a draw! + $ReportCode .= "[b]{$_Lang['sys_both_won']}[/b]\n"; + $ReportCode .= $DebrisField."\n"; + break; + } + } + if($MoonCreationChanceText) + { + $ReportCode .= $MoonCreationChanceText."\n"; + } + if($MoonCreationText) + { + $ReportCode .= $MoonCreationText."\n"; + } + if($IsOnMoon) + { + $ReportCode .= $_Lang['Conv_battleonMoon']."\n"; + } + + $ReportCode .= $MoonDestroyText; + + $ReportCode .= sprintf($_Lang['sys_rapport_build_time'], '[b]'.$GenerateTime.'[/b]'); + $ReportCode .= "\n".$_Lang['Conv_generated_by']; + $ReportCode .= '[/align]'; + + return $ReportCode; +} + +?> diff --git a/includes/functions/CreateBattleReport.php b/includes/functions/CreateBattleReport.php index 0ac9f1c8a..c210afe19 100644 --- a/includes/functions/CreateBattleReport.php +++ b/includes/functions/CreateBattleReport.php @@ -1,64 +1,64 @@ - 0) - { - $GetHash = doquery("SELECT `Hash` FROM {{table}} WHERE `ID` = {$Result['ID']};", 'battle_reports', true); - return array('ID' => $Result['ID'], 'Hash' => $GetHash['Hash']); - } - } - } - else - { - $Result = doquery("INSERT INTO {{table}} SET `time` = UNIX_TIMESTAMP() + (10*60), `report` = '{$CreateArray}', `owner` = {$AttackerID};", 'sim_battle_reports'); - - if($Result == true) - { - $Result = doquery("SELECT LAST_INSERT_ID() as `ID`;", '', true); - if($Result['ID'] > 0) - { - return $Result['ID']; - } - } - } - - return false; -} - -?> \ No newline at end of file + 0) + { + $GetHash = doquery("SELECT `Hash` FROM {{table}} WHERE `ID` = {$Result['ID']};", 'battle_reports', true); + return array('ID' => $Result['ID'], 'Hash' => $GetHash['Hash']); + } + } + } + else + { + $Result = doquery("INSERT INTO {{table}} SET `time` = UNIX_TIMESTAMP() + (10*60), `report` = '{$CreateArray}', `owner` = {$AttackerID};", 'sim_battle_reports'); + + if($Result == true) + { + $Result = doquery("SELECT LAST_INSERT_ID() as `ID`;", '', true); + if($Result['ID'] > 0) + { + return $Result['ID']; + } + } + } + + return false; +} + +?> diff --git a/includes/functions/CreateOneMoonRecord.php b/includes/functions/CreateOneMoonRecord.php index eefb85e73..8f25ccac4 100644 --- a/includes/functions/CreateOneMoonRecord.php +++ b/includes/functions/CreateOneMoonRecord.php @@ -1,75 +1,75 @@ -= 2000 && $SetDiameter <= 10000)) - { - $Diameter_Min = 2000 + ($Chance * 100); - $Diameter_Max = 6000 + ($Chance * 200); - $Diameter = rand($Diameter_Min, $Diameter_Max); - } - else - { - $Diameter = $SetDiameter; - } - $RandTemp = rand(10, 45); - $mintemp = $MoonPlanet['temp_min'] - $RandTemp; - $maxtemp = $MoonPlanet['temp_max'] - $RandTemp; - - if(empty($MoonName)) - { - $MoonName = $_Lang['sys_moon']; - } - - $QryInsertMoonInPlanet = "INSERT INTO {{table}} SET "; - $QryInsertMoonInPlanet .= "`name` = '$MoonName', "; - $QryInsertMoonInPlanet .= "`id_owner` = '{$Owner}', "; - $QryInsertMoonInPlanet .= "`galaxy` = '{$Galaxy}', "; - $QryInsertMoonInPlanet .= "`system` = '{$System}', "; - $QryInsertMoonInPlanet .= "`planet` = '{$Planet}', "; - $QryInsertMoonInPlanet .= "`last_update` = UNIX_TIMESTAMP(), "; - $QryInsertMoonInPlanet .= "`planet_type` = 3, "; - $QryInsertMoonInPlanet .= "`image` = 'mond', "; - $QryInsertMoonInPlanet .= "`diameter` = '{$Diameter}', "; - $QryInsertMoonInPlanet .= "`field_max` = 1, "; - $QryInsertMoonInPlanet .= "`temp_min` = '{$maxtemp}', "; - $QryInsertMoonInPlanet .= "`temp_max` = '{$mintemp}', "; - $QryInsertMoonInPlanet .= "`metal` = 0, "; - $QryInsertMoonInPlanet .= "`metal_perhour` = 0, "; - $QryInsertMoonInPlanet .= "`metal_max` = '".BASE_STORAGE_SIZE."', "; - $QryInsertMoonInPlanet .= "`crystal` = 0, "; - $QryInsertMoonInPlanet .= "`crystal_perhour` = 0, "; - $QryInsertMoonInPlanet .= "`crystal_max` = '".BASE_STORAGE_SIZE."', "; - $QryInsertMoonInPlanet .= "`deuterium` = 0, "; - $QryInsertMoonInPlanet .= "`deuterium_perhour` = 0, "; - $QryInsertMoonInPlanet .= "`deuterium_max` = '".BASE_STORAGE_SIZE."';"; - doquery($QryInsertMoonInPlanet, 'planets'); - - // Select CreatedMoon ID - $QrySelectPlanet = "SELECT `id` FROM {{table}} WHERE `galaxy` = '{$Galaxy}' AND `system` = '{$System}' AND `planet` = '{$Planet}' AND `planet_type` = 3;"; - $GetPlanetID = doquery($QrySelectPlanet, 'planets', true); - - $QryUpdateMoonInGalaxy = "UPDATE {{table}} SET "; - $QryUpdateMoonInGalaxy .= "`id_moon` = '{$GetPlanetID['id']}' "; - $QryUpdateMoonInGalaxy .= "WHERE `galaxy_id` = {$MoonGalaxy['galaxy_id']};"; - doquery($QryUpdateMoonInGalaxy, 'galaxy'); - - return $GetPlanetID['id']; - } - } - - return false; -} - -?> \ No newline at end of file += 2000 && $SetDiameter <= 10000)) + { + $Diameter_Min = 2000 + ($Chance * 100); + $Diameter_Max = 6000 + ($Chance * 200); + $Diameter = rand($Diameter_Min, $Diameter_Max); + } + else + { + $Diameter = $SetDiameter; + } + $RandTemp = rand(10, 45); + $mintemp = $MoonPlanet['temp_min'] - $RandTemp; + $maxtemp = $MoonPlanet['temp_max'] - $RandTemp; + + if(empty($MoonName)) + { + $MoonName = $_Lang['sys_moon']; + } + + $QryInsertMoonInPlanet = "INSERT INTO {{table}} SET "; + $QryInsertMoonInPlanet .= "`name` = '$MoonName', "; + $QryInsertMoonInPlanet .= "`id_owner` = '{$Owner}', "; + $QryInsertMoonInPlanet .= "`galaxy` = '{$Galaxy}', "; + $QryInsertMoonInPlanet .= "`system` = '{$System}', "; + $QryInsertMoonInPlanet .= "`planet` = '{$Planet}', "; + $QryInsertMoonInPlanet .= "`last_update` = UNIX_TIMESTAMP(), "; + $QryInsertMoonInPlanet .= "`planet_type` = 3, "; + $QryInsertMoonInPlanet .= "`image` = 'mond', "; + $QryInsertMoonInPlanet .= "`diameter` = '{$Diameter}', "; + $QryInsertMoonInPlanet .= "`field_max` = 1, "; + $QryInsertMoonInPlanet .= "`temp_min` = '{$maxtemp}', "; + $QryInsertMoonInPlanet .= "`temp_max` = '{$mintemp}', "; + $QryInsertMoonInPlanet .= "`metal` = 0, "; + $QryInsertMoonInPlanet .= "`metal_perhour` = 0, "; + $QryInsertMoonInPlanet .= "`metal_max` = '".BASE_STORAGE_SIZE."', "; + $QryInsertMoonInPlanet .= "`crystal` = 0, "; + $QryInsertMoonInPlanet .= "`crystal_perhour` = 0, "; + $QryInsertMoonInPlanet .= "`crystal_max` = '".BASE_STORAGE_SIZE."', "; + $QryInsertMoonInPlanet .= "`deuterium` = 0, "; + $QryInsertMoonInPlanet .= "`deuterium_perhour` = 0, "; + $QryInsertMoonInPlanet .= "`deuterium_max` = '".BASE_STORAGE_SIZE."';"; + doquery($QryInsertMoonInPlanet, 'planets'); + + // Select CreatedMoon ID + $QrySelectPlanet = "SELECT `id` FROM {{table}} WHERE `galaxy` = '{$Galaxy}' AND `system` = '{$System}' AND `planet` = '{$Planet}' AND `planet_type` = 3;"; + $GetPlanetID = doquery($QrySelectPlanet, 'planets', true); + + $QryUpdateMoonInGalaxy = "UPDATE {{table}} SET "; + $QryUpdateMoonInGalaxy .= "`id_moon` = '{$GetPlanetID['id']}' "; + $QryUpdateMoonInGalaxy .= "WHERE `galaxy_id` = {$MoonGalaxy['galaxy_id']};"; + doquery($QryUpdateMoonInGalaxy, 'galaxy'); + + return $GetPlanetID['id']; + } + } + + return false; +} + +?> diff --git a/includes/functions/CreateOnePlanetRecord.php b/includes/functions/CreateOnePlanetRecord.php index d2f506d87..2a913bf15 100644 --- a/includes/functions/CreateOnePlanetRecord.php +++ b/includes/functions/CreateOnePlanetRecord.php @@ -1,217 +1,217 @@ - 0) - { - $RegisterDays = floor((time() - SERVER_MAINOPEN_TSTAMP) / (24*60*60)); - } - else - { - $RegisterDays = 0; - } - if($RegisterDays >= 1) - { - $Calc['metal'] = round(1000 * pow($RegisterDays / 0.2, 2)); - $Calc['crystal'] = round($Calc['metal'] / 2); - $Calc['deuterium'] = round($Calc['metal'] / 4); - foreach($Calc as &$Val) - { - if($Val > MAX_REFUND_VALUE) - { - $Val = MAX_REFUND_VALUE; - } - } - } - else - { - $Calc['metal'] = BUILD_METAL; - $Calc['crystal'] = BUILD_CRISTAL; - $Calc['deuterium'] = BUILD_DEUTERIUM; - } - - return $Calc; -} - -function PlanetSizeRandomiser($Position, $HomeWorld = false) -{ - global $_GameConfig; - - if(!$HomeWorld) - { - $ClassicBase = 150; - $SettingSize = $_GameConfig['initial_fields']; - $PlanetRatio = floor(($ClassicBase / $SettingSize) * 10000) / 100; - $RandomMin = array(90, 125, 125, 205, 205, 205, 205, 205, 225, 205, 165, 155, 145, 80, 125); - $RandomMax = array(91, 135, 135, 280, 280, 270, 220, 220, 230, 225, 180, 170, 200, 420, 190); - $CalculMin = floor($RandomMin[$Position - 1] + ($RandomMin[$Position - 1] * $PlanetRatio) / 100); - $CalculMax = floor($RandomMax[$Position - 1] + ($RandomMax[$Position - 1] * $PlanetRatio) / 100); - $RandomSize = mt_rand($CalculMin, $CalculMax); - $MaxAddon = mt_rand(0, 110); - $MinAddon = mt_rand(0, 60); - $Addon = ($MaxAddon - $MinAddon); - $PlanetFields = ($RandomSize + $Addon); - } - else - { - $PlanetFields = $_GameConfig['initial_fields']; - } - $PlanetSize = ($PlanetFields ^ (14 / 1.5)) * 75; - - $return['diameter'] = $PlanetSize; - $return['field_max'] = $PlanetFields; - return $return; -} - -function CreateOnePlanetRecord($Galaxy, $System, $Position, $PlanetOwnerID, $PlanetName = '', $HomeWorld = false, $AdditionalResources = false, $GetPlanetData = false, $DontCheckExistence = false) -{ - global $_Lang, $_GameConfig; - - // First, check if there is no planet on that position - if($DontCheckExistence !== true) - { - $QrySelectPlanet = "SELECT `id` FROM {{table}} WHERE `galaxy` = '{$Galaxy}' AND `system` = '{$System}' AND `planet` = '{$Position}';"; - $PlanetExist = doquery($QrySelectPlanet, 'planets', true); - } - else - { - $PlanetExist = false; - } - - // If this position is free, let's make a new planet! - if(!$PlanetExist) - { - $planet = PlanetSizeRandomiser($Position, $HomeWorld); - $planet['diameter'] = ($planet['field_max'] ^ (14 / 1.5)) * 75 ; - if($HomeWorld) - { - $Res = CalculateBasicResourceSet(); - $planet['metal'] = $Res['metal']; - $planet['crystal'] = $Res['crystal']; - $planet['deuterium'] = $Res['deuterium']; - } - else - { - $planet['metal'] = BUILD_METAL; - $planet['crystal'] = BUILD_CRISTAL; - $planet['deuterium'] = BUILD_DEUTERIUM; - if($AdditionalResources !== false) - { - $planet['metal'] += $AdditionalResources['metal']; - $planet['crystal'] += $AdditionalResources['crystal']; - $planet['deuterium'] += $AdditionalResources['deuterium']; - } - } - $planet['metal_perhour'] = $_GameConfig['metal_basic_income']; - $planet['crystal_perhour'] = $_GameConfig['crystal_basic_income']; - $planet['deuterium_perhour'] = $_GameConfig['deuterium_basic_income']; - $planet['metal_max'] = BASE_STORAGE_SIZE; - $planet['crystal_max'] = BASE_STORAGE_SIZE; - $planet['deuterium_max'] = BASE_STORAGE_SIZE; - - if($Position == 1 || $Position == 2 || $Position == 3) - { - $PlanetType = array('trocken'); - $PlanetDesign = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10'); - $planet['temp_min'] = rand(0, 100); - } - else if($Position == 4 || $Position == 5 || $Position == 6) - { - $PlanetType = array('dschjungel'); - $PlanetDesign = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10'); - $planet['temp_min'] = rand(-25, 75); - } - else if($Position == 7 || $Position == 8 || $Position == 9) - { - $PlanetType = array('normaltemp'); - $PlanetDesign = array('01', '02', '03', '04', '05', '06', '07'); - $planet['temp_min'] = rand(-50, 50); - } - else if($Position == 10 || $Position == 11 || $Position == 12) - { - $PlanetType = array('wasser'); - $PlanetDesign = array('01', '02', '03', '04', '05', '06', '07', '08', '09'); - $planet['temp_min'] = rand(-75, 25); - } - else if($Position == 13 || $Position == 14 || $Position == 15) - { - $PlanetType = array('eis'); - $PlanetDesign = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10'); - $planet['temp_min'] = rand(-100, 10); - } - else - { - $PlanetType = array('dschjungel', 'gas', 'normaltemp', 'trocken', 'wasser', 'wuesten', 'eis'); - $PlanetDesign = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '00',); - $planet['temp_min'] = rand(-120, 0); - } - - $PlanetClass = array('planet'); - $planet['temp_maxi'] = rand(30, 100); - $planet['temp_max'] = $planet['temp_min'] + $planet['temp_maxi']; - $planet['image'] = $PlanetType[rand(0, count($PlanetType) -1)]; - $planet['image'] .= $PlanetClass[rand(0, count($PlanetClass) - 1)]; - $planet['image'] .= $PlanetDesign[rand(0, count($PlanetDesign) - 1)]; - $planet['name'] = ($PlanetName == '') ? $_Lang['sys_colo_defaultname'] : $PlanetName; - - $QryInsertPlanet = "INSERT INTO {{table}} SET "; - $QryInsertPlanet .= "`name` = '{$planet['name']}', "; - $QryInsertPlanet .= "`id_owner` = '{$PlanetOwnerID}', "; - $QryInsertPlanet .= "`galaxy` = '{$Galaxy}', "; - $QryInsertPlanet .= "`system` = '{$System}', "; - $QryInsertPlanet .= "`planet` = '{$Position}', "; - $QryInsertPlanet .= "`last_update` = UNIX_TIMESTAMP(), "; - $QryInsertPlanet .= "`planet_type` = 1, "; - $QryInsertPlanet .= "`image` = '{$planet['image']}', "; - $QryInsertPlanet .= "`diameter` = '{$planet['diameter']}', "; - $QryInsertPlanet .= "`field_max` = '{$planet['field_max']}', "; - $QryInsertPlanet .= "`temp_min` = '{$planet['temp_min']}', "; - $QryInsertPlanet .= "`temp_max` = '{$planet['temp_max']}', "; - $QryInsertPlanet .= "`metal` = '{$planet['metal']}', "; - $QryInsertPlanet .= "`metal_perhour` = '{$planet['metal_perhour']}', "; - $QryInsertPlanet .= "`metal_max` = '{$planet['metal_max']}', "; - $QryInsertPlanet .= "`crystal` = '{$planet['crystal']}', "; - $QryInsertPlanet .= "`crystal_perhour` = '{$planet['crystal_perhour']}', "; - $QryInsertPlanet .= "`crystal_max` = '{$planet['crystal_max']}', "; - $QryInsertPlanet .= "`deuterium` = '{$planet['deuterium']}', "; - $QryInsertPlanet .= "`deuterium_perhour` = '{$planet['deuterium_perhour']}', "; - $QryInsertPlanet .= "`deuterium_max` = '{$planet['deuterium_max']}';"; - doquery($QryInsertPlanet, 'planets'); - - // Select CreatedPlanet ID - $QrySelectPlanet = "SELECT `id` FROM {{table}} WHERE `galaxy` = '{$Galaxy}' AND `system` = '{$System}' AND `planet` = '{$Position}' AND `id_owner` = '{$PlanetOwnerID}';"; - $GetPlanetID = doquery($QrySelectPlanet , 'planets', true); - - // Select Galaxy, if there was a planet on that place already - $QrySelectGalaxy = "SELECT * FROM {{table}} WHERE `galaxy` = '{$Galaxy}' AND `system` = '{$System}' AND `planet` = '{$Position}';"; - $GetGalaxyID = doquery($QrySelectGalaxy, 'galaxy', true); - - if($GetGalaxyID['galaxy_id'] > 0) - { - // Update Galaxy Record - $QryUpdateGalaxy = "UPDATE {{table}} SET `id_planet` = {$GetPlanetID['id']} WHERE `galaxy_id` = {$GetGalaxyID['galaxy_id']};"; - doquery($QryUpdateGalaxy, 'galaxy'); - } - else - { - // Create new Galaxy Record - $QryInsertGalaxy = "INSERT INTO {{table}} SET `galaxy` = '{$Galaxy}', `system` = '{$System}', `planet` = '{$Position}', `id_planet` = {$GetPlanetID['id']};"; - doquery($QryInsertGalaxy, 'galaxy'); - } - - if($GetPlanetData) - { - return array('ID' => $GetPlanetID['id'], 'temp_max' => $planet['temp_max'], 'metal' => $planet['metal'], 'crystal' => $planet['crystal'], 'deuterium' => $planet['deuterium']); - } - else - { - return $GetPlanetID['id']; - } - } - else - { - return false; - } -} - -?> \ No newline at end of file + 0) + { + $RegisterDays = floor((time() - SERVER_MAINOPEN_TSTAMP) / (24*60*60)); + } + else + { + $RegisterDays = 0; + } + if($RegisterDays >= 1) + { + $Calc['metal'] = round(1000 * pow($RegisterDays / 0.2, 2)); + $Calc['crystal'] = round($Calc['metal'] / 2); + $Calc['deuterium'] = round($Calc['metal'] / 4); + foreach($Calc as &$Val) + { + if($Val > MAX_REFUND_VALUE) + { + $Val = MAX_REFUND_VALUE; + } + } + } + else + { + $Calc['metal'] = BUILD_METAL; + $Calc['crystal'] = BUILD_CRISTAL; + $Calc['deuterium'] = BUILD_DEUTERIUM; + } + + return $Calc; +} + +function PlanetSizeRandomiser($Position, $HomeWorld = false) +{ + global $_GameConfig; + + if(!$HomeWorld) + { + $ClassicBase = 150; + $SettingSize = $_GameConfig['initial_fields']; + $PlanetRatio = floor(($ClassicBase / $SettingSize) * 10000) / 100; + $RandomMin = array(90, 125, 125, 205, 205, 205, 205, 205, 225, 205, 165, 155, 145, 80, 125); + $RandomMax = array(91, 135, 135, 280, 280, 270, 220, 220, 230, 225, 180, 170, 200, 420, 190); + $CalculMin = floor($RandomMin[$Position - 1] + ($RandomMin[$Position - 1] * $PlanetRatio) / 100); + $CalculMax = floor($RandomMax[$Position - 1] + ($RandomMax[$Position - 1] * $PlanetRatio) / 100); + $RandomSize = mt_rand($CalculMin, $CalculMax); + $MaxAddon = mt_rand(0, 110); + $MinAddon = mt_rand(0, 60); + $Addon = ($MaxAddon - $MinAddon); + $PlanetFields = ($RandomSize + $Addon); + } + else + { + $PlanetFields = $_GameConfig['initial_fields']; + } + $PlanetSize = ($PlanetFields ^ (14 / 1.5)) * 75; + + $return['diameter'] = $PlanetSize; + $return['field_max'] = $PlanetFields; + return $return; +} + +function CreateOnePlanetRecord($Galaxy, $System, $Position, $PlanetOwnerID, $PlanetName = '', $HomeWorld = false, $AdditionalResources = false, $GetPlanetData = false, $DontCheckExistence = false) +{ + global $_Lang, $_GameConfig; + + // First, check if there is no planet on that position + if($DontCheckExistence !== true) + { + $QrySelectPlanet = "SELECT `id` FROM {{table}} WHERE `galaxy` = '{$Galaxy}' AND `system` = '{$System}' AND `planet` = '{$Position}';"; + $PlanetExist = doquery($QrySelectPlanet, 'planets', true); + } + else + { + $PlanetExist = false; + } + + // If this position is free, let's make a new planet! + if(!$PlanetExist) + { + $planet = PlanetSizeRandomiser($Position, $HomeWorld); + $planet['diameter'] = ($planet['field_max'] ^ (14 / 1.5)) * 75 ; + if($HomeWorld) + { + $Res = CalculateBasicResourceSet(); + $planet['metal'] = $Res['metal']; + $planet['crystal'] = $Res['crystal']; + $planet['deuterium'] = $Res['deuterium']; + } + else + { + $planet['metal'] = BUILD_METAL; + $planet['crystal'] = BUILD_CRISTAL; + $planet['deuterium'] = BUILD_DEUTERIUM; + if($AdditionalResources !== false) + { + $planet['metal'] += $AdditionalResources['metal']; + $planet['crystal'] += $AdditionalResources['crystal']; + $planet['deuterium'] += $AdditionalResources['deuterium']; + } + } + $planet['metal_perhour'] = $_GameConfig['metal_basic_income']; + $planet['crystal_perhour'] = $_GameConfig['crystal_basic_income']; + $planet['deuterium_perhour'] = $_GameConfig['deuterium_basic_income']; + $planet['metal_max'] = BASE_STORAGE_SIZE; + $planet['crystal_max'] = BASE_STORAGE_SIZE; + $planet['deuterium_max'] = BASE_STORAGE_SIZE; + + if($Position == 1 || $Position == 2 || $Position == 3) + { + $PlanetType = array('trocken'); + $PlanetDesign = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10'); + $planet['temp_min'] = rand(0, 100); + } + else if($Position == 4 || $Position == 5 || $Position == 6) + { + $PlanetType = array('dschjungel'); + $PlanetDesign = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10'); + $planet['temp_min'] = rand(-25, 75); + } + else if($Position == 7 || $Position == 8 || $Position == 9) + { + $PlanetType = array('normaltemp'); + $PlanetDesign = array('01', '02', '03', '04', '05', '06', '07'); + $planet['temp_min'] = rand(-50, 50); + } + else if($Position == 10 || $Position == 11 || $Position == 12) + { + $PlanetType = array('wasser'); + $PlanetDesign = array('01', '02', '03', '04', '05', '06', '07', '08', '09'); + $planet['temp_min'] = rand(-75, 25); + } + else if($Position == 13 || $Position == 14 || $Position == 15) + { + $PlanetType = array('eis'); + $PlanetDesign = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10'); + $planet['temp_min'] = rand(-100, 10); + } + else + { + $PlanetType = array('dschjungel', 'gas', 'normaltemp', 'trocken', 'wasser', 'wuesten', 'eis'); + $PlanetDesign = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '00',); + $planet['temp_min'] = rand(-120, 0); + } + + $PlanetClass = array('planet'); + $planet['temp_maxi'] = rand(30, 100); + $planet['temp_max'] = $planet['temp_min'] + $planet['temp_maxi']; + $planet['image'] = $PlanetType[rand(0, count($PlanetType) -1)]; + $planet['image'] .= $PlanetClass[rand(0, count($PlanetClass) - 1)]; + $planet['image'] .= $PlanetDesign[rand(0, count($PlanetDesign) - 1)]; + $planet['name'] = ($PlanetName == '') ? $_Lang['sys_colo_defaultname'] : $PlanetName; + + $QryInsertPlanet = "INSERT INTO {{table}} SET "; + $QryInsertPlanet .= "`name` = '{$planet['name']}', "; + $QryInsertPlanet .= "`id_owner` = '{$PlanetOwnerID}', "; + $QryInsertPlanet .= "`galaxy` = '{$Galaxy}', "; + $QryInsertPlanet .= "`system` = '{$System}', "; + $QryInsertPlanet .= "`planet` = '{$Position}', "; + $QryInsertPlanet .= "`last_update` = UNIX_TIMESTAMP(), "; + $QryInsertPlanet .= "`planet_type` = 1, "; + $QryInsertPlanet .= "`image` = '{$planet['image']}', "; + $QryInsertPlanet .= "`diameter` = '{$planet['diameter']}', "; + $QryInsertPlanet .= "`field_max` = '{$planet['field_max']}', "; + $QryInsertPlanet .= "`temp_min` = '{$planet['temp_min']}', "; + $QryInsertPlanet .= "`temp_max` = '{$planet['temp_max']}', "; + $QryInsertPlanet .= "`metal` = '{$planet['metal']}', "; + $QryInsertPlanet .= "`metal_perhour` = '{$planet['metal_perhour']}', "; + $QryInsertPlanet .= "`metal_max` = '{$planet['metal_max']}', "; + $QryInsertPlanet .= "`crystal` = '{$planet['crystal']}', "; + $QryInsertPlanet .= "`crystal_perhour` = '{$planet['crystal_perhour']}', "; + $QryInsertPlanet .= "`crystal_max` = '{$planet['crystal_max']}', "; + $QryInsertPlanet .= "`deuterium` = '{$planet['deuterium']}', "; + $QryInsertPlanet .= "`deuterium_perhour` = '{$planet['deuterium_perhour']}', "; + $QryInsertPlanet .= "`deuterium_max` = '{$planet['deuterium_max']}';"; + doquery($QryInsertPlanet, 'planets'); + + // Select CreatedPlanet ID + $QrySelectPlanet = "SELECT `id` FROM {{table}} WHERE `galaxy` = '{$Galaxy}' AND `system` = '{$System}' AND `planet` = '{$Position}' AND `id_owner` = '{$PlanetOwnerID}';"; + $GetPlanetID = doquery($QrySelectPlanet , 'planets', true); + + // Select Galaxy, if there was a planet on that place already + $QrySelectGalaxy = "SELECT * FROM {{table}} WHERE `galaxy` = '{$Galaxy}' AND `system` = '{$System}' AND `planet` = '{$Position}';"; + $GetGalaxyID = doquery($QrySelectGalaxy, 'galaxy', true); + + if($GetGalaxyID['galaxy_id'] > 0) + { + // Update Galaxy Record + $QryUpdateGalaxy = "UPDATE {{table}} SET `id_planet` = {$GetPlanetID['id']} WHERE `galaxy_id` = {$GetGalaxyID['galaxy_id']};"; + doquery($QryUpdateGalaxy, 'galaxy'); + } + else + { + // Create new Galaxy Record + $QryInsertGalaxy = "INSERT INTO {{table}} SET `galaxy` = '{$Galaxy}', `system` = '{$System}', `planet` = '{$Position}', `id_planet` = {$GetPlanetID['id']};"; + doquery($QryInsertGalaxy, 'galaxy'); + } + + if($GetPlanetData) + { + return array('ID' => $GetPlanetID['id'], 'temp_max' => $planet['temp_max'], 'metal' => $planet['metal'], 'crystal' => $planet['crystal'], 'deuterium' => $planet['deuterium']); + } + else + { + return $GetPlanetID['id']; + } + } + else + { + return false; + } +} + +?> diff --git a/includes/functions/CreateSFBInfobox.php b/includes/functions/CreateSFBInfobox.php index ae33df986..6b725c08f 100644 --- a/includes/functions/CreateSFBInfobox.php +++ b/includes/functions/CreateSFBInfobox.php @@ -1,102 +1,102 @@ - time()) - { - global $_Vars_FleetMissions; - $_Lang = includeLang('sfbInfos', true); - - if($AppearanceSettings['standAlone'] === true) - { - $TPL = gettemplate('sfb_body_standalone'); - $_Lang['_Width'] = $AppearanceSettings['Width']; - $_Lang['_MarginBottom'] = $AppearanceSettings['MarginBottom']; - } - else - { - $TPL = gettemplate('sfb_body_part'); - $_Lang['_Colspan'] = $AppearanceSettings['Colspan'] - 1; - } - $_Lang['_AdminLink'] = $AppearanceSettings['AdminLink']; - $_Lang['_Icon'] = (empty($AppearanceSettings['Icon']) ? 'warningIcon' : $AppearanceSettings['Icon']); - - if($SFBData['BlockMissions'] == '0') - { - $_Lang['_MissionsInfo'] = $_Lang['sfb_Mission_All']; - if($SFBData['DontBlockIfIdle'] == 1) - { - $_Lang['_MissionsInfo'] .= $_Lang['sfb_Mission_AggresiveDontBlockIdle']; - } - } - else - { - $ExplodeMissions = explode(',', $SFBData['BlockMissions']); - $CivilCount = 0; - $AggresiveCount = 0; - foreach($ExplodeMissions as $MissionID) - { - if(!in_array($MissionID, $_Vars_FleetMissions['all'])) - { - continue; - } - $SFBData['Missions'][] = $_Lang['sfb_Mission__'.$MissionID]; - if(in_array($MissionID, $_Vars_FleetMissions['civil'])) - { - $CivilCount += 1; - } - else - { - $AggresiveCount += 1; - } - } - if($CivilCount == count($_Vars_FleetMissions['civil']) AND $AggresiveCount == 0) - { - $_Lang['_MissionsInfo'] = $_Lang['sfb_Mission_Civil']; - } - else if($AggresiveCount == count($_Vars_FleetMissions['military']) AND $CivilCount == 0) - { - $_Lang['_MissionsInfo'] = $_Lang['sfb_Mission_Aggresive']; - } - else - { - $_Lang['_MissionsInfo'] = sprintf($_Lang['sfb_Mission_Other'], implode(', ', $SFBData['Missions'])); - } - if($SFBData['DontBlockIfIdle'] == 1) - { - if($CivilCount > 0) - { - $_Lang['_MissionsInfo'] .= $_Lang['sfb_Mission_AggresiveDontBlockIdle']; - } - else - { - $_Lang['_MissionsInfo'] .= $_Lang['sfb_Mission_DontBlockIdle']; - } - } - } - if(!empty($SFBData['Reason'])) - { - global $_GameConfig, $_EnginePath; - if($_GameConfig['enable_bbcode'] == 1) - { - include_once($_EnginePath.'includes/functions/BBcodeFunction.php'); - $SFBData['Reason'] = trim(nl2br(bbcode(image(strip_tags(str_replace("'", ''', $SFBData['Reason']), '

    '))))); - } - else - { - $SFBData['Reason'] = trim(nl2br(strip_tags($SFBData['Reason'], '

    '))); - } - $SFBData['Reason'] = "\"{$SFBData['Reason']}\""; - } - else - { - $SFBData['Reason'] = $_Lang['sfb_NoReason']; - } - - $_Lang['_Text'] = sprintf($_Lang['sfb_GlobalText'], prettyDate('d m Y', $SFBData['EndTime'], 1), date('H:i:s', $SFBData['EndTime']), $_Lang['_MissionsInfo'], $SFBData['Reason']); - - return parsetemplate($TPL, $_Lang); - } -} - -?> \ No newline at end of file + time()) + { + global $_Vars_FleetMissions; + $_Lang = includeLang('sfbInfos', true); + + if($AppearanceSettings['standAlone'] === true) + { + $TPL = gettemplate('sfb_body_standalone'); + $_Lang['_Width'] = $AppearanceSettings['Width']; + $_Lang['_MarginBottom'] = $AppearanceSettings['MarginBottom']; + } + else + { + $TPL = gettemplate('sfb_body_part'); + $_Lang['_Colspan'] = $AppearanceSettings['Colspan'] - 1; + } + $_Lang['_AdminLink'] = $AppearanceSettings['AdminLink']; + $_Lang['_Icon'] = (empty($AppearanceSettings['Icon']) ? 'warningIcon' : $AppearanceSettings['Icon']); + + if($SFBData['BlockMissions'] == '0') + { + $_Lang['_MissionsInfo'] = $_Lang['sfb_Mission_All']; + if($SFBData['DontBlockIfIdle'] == 1) + { + $_Lang['_MissionsInfo'] .= $_Lang['sfb_Mission_AggresiveDontBlockIdle']; + } + } + else + { + $ExplodeMissions = explode(',', $SFBData['BlockMissions']); + $CivilCount = 0; + $AggresiveCount = 0; + foreach($ExplodeMissions as $MissionID) + { + if(!in_array($MissionID, $_Vars_FleetMissions['all'])) + { + continue; + } + $SFBData['Missions'][] = $_Lang['sfb_Mission__'.$MissionID]; + if(in_array($MissionID, $_Vars_FleetMissions['civil'])) + { + $CivilCount += 1; + } + else + { + $AggresiveCount += 1; + } + } + if($CivilCount == count($_Vars_FleetMissions['civil']) AND $AggresiveCount == 0) + { + $_Lang['_MissionsInfo'] = $_Lang['sfb_Mission_Civil']; + } + else if($AggresiveCount == count($_Vars_FleetMissions['military']) AND $CivilCount == 0) + { + $_Lang['_MissionsInfo'] = $_Lang['sfb_Mission_Aggresive']; + } + else + { + $_Lang['_MissionsInfo'] = sprintf($_Lang['sfb_Mission_Other'], implode(', ', $SFBData['Missions'])); + } + if($SFBData['DontBlockIfIdle'] == 1) + { + if($CivilCount > 0) + { + $_Lang['_MissionsInfo'] .= $_Lang['sfb_Mission_AggresiveDontBlockIdle']; + } + else + { + $_Lang['_MissionsInfo'] .= $_Lang['sfb_Mission_DontBlockIdle']; + } + } + } + if(!empty($SFBData['Reason'])) + { + global $_GameConfig, $_EnginePath; + if($_GameConfig['enable_bbcode'] == 1) + { + include_once($_EnginePath.'includes/functions/BBcodeFunction.php'); + $SFBData['Reason'] = trim(nl2br(bbcode(image(strip_tags(str_replace("'", ''', $SFBData['Reason']), '

    '))))); + } + else + { + $SFBData['Reason'] = trim(nl2br(strip_tags($SFBData['Reason'], '

    '))); + } + $SFBData['Reason'] = "\"{$SFBData['Reason']}\""; + } + else + { + $SFBData['Reason'] = $_Lang['sfb_NoReason']; + } + + $_Lang['_Text'] = sprintf($_Lang['sfb_GlobalText'], prettyDate('d m Y', $SFBData['EndTime'], 1), date('H:i:s', $SFBData['EndTime']), $_Lang['_MissionsInfo'], $SFBData['Reason']); + + return parsetemplate($TPL, $_Lang); + } +} + +?> diff --git a/includes/functions/DefensesBuildingPage.php b/includes/functions/DefensesBuildingPage.php index a3850c50e..f890180c0 100644 --- a/includes/functions/DefensesBuildingPage.php +++ b/includes/functions/DefensesBuildingPage.php @@ -1,373 +1,373 @@ - 0, 407 => 0); - $Missiles = array(502 => 0, 503 => 0); - - $AddedSomething = false; - - $CurrentPlanet = doquery("SELECT * FROM {{table}} WHERE `id` = {$CurrentPlanet['id']} LIMIT 1;", 'planets', true); - $BuildQueueList = $CurrentPlanet['shipyardQueue']; - $BuildArray = explode (';', $BuildQueueList); - $BuildArrayCount = count($BuildArray); - for($QElement = 0; $QElement < $BuildArrayCount; $QElement += 1) - { - $ElmentArray = explode(',', $BuildArray[$QElement]); - if($ElmentArray[0] == 502 AND $ElmentArray[1] > 0) - { - $Missiles[502] += $ElmentArray[1]; - $AddedMissilesFromQueue = true; - } - else if($ElmentArray[0] == 503 AND $ElmentArray[1] > 0) - { - $Missiles[503] += $ElmentArray[1]; - $AddedMissilesFromQueue = true; - } - else if($ElmentArray[0] == 408 AND $ElmentArray[1] > 0) - { - $Shields[408] += $ElmentArray[1]; - $AddedShieldsFromQueue = true; - } - else if($ElmentArray[0] == 407 AND $ElmentArray[1] > 0) - { - $Shields[407] += $ElmentArray[1]; - $AddedShieldsFromQueue = true; - } - } - - if($CurrentPlanet['shipyardQueue'] == '0') - { - $CurrentPlanet['shipyardQueue'] = ''; - } - - if($CurrentPlanet) - { - include($_EnginePath.'includes/functions/GetElementRessources.php'); - foreach($_POST['fmenge'] as $Element => $Count) - { - $Element = intval($Element); - $Count = floor(floatval(str_replace('.', '', $Count))); - if(in_array($Element, $_Vars_ElementCategories['defense'])) - { - if($Count > $QueueSize) - { - $Count = $QueueSize; - } - if($Count >= 1) - { - if($Element == 407) - { - if($CurrentPlanet[$_Vars_GameElements[407]] >= 1 OR $Shields[407] > 0) - { - $Count = 0; - } - else - { - $Count = 1; - } - } - if($Element == 408) - { - if($CurrentPlanet[$_Vars_GameElements[408]] >= 1 OR $Shields[408] > 0) - { - $Count = 0; - } - else - { - $Count = 1; - } - } - if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $Element)) - { - $MaxElements = GetMaxConstructibleElements($Element, $CurrentPlanet); - if($Element == 502 OR $Element == 503) - { - $ActuMissiles = $Missiles[502] + (2 * $Missiles[503]); - $MissilesSpace = $MaxMissiles - $ActuMissiles; - if($Element == 502) - { - if($Count > $MissilesSpace) - { - $Count = $MissilesSpace; - } - } - else - { - if($Count > floor($MissilesSpace / 2 )) - { - $Count = floor($MissilesSpace / 2); - } - } - if($Count > $MaxElements) - { - $Count = $MaxElements; - } - $Missiles[$Element] += $Count; - } - else - { - if($Count > $MaxElements) - { - $Count = $MaxElements; - } - } - $Ressource = GetElementRessources($Element, $Count); - if($Count > 0) - { - $AddedSomething = true; - - if(!isset($UpdateAchievements[$Element])) - { - $UpdateAchievements[$Element] = 0; - } - $UpdateAchievements[$Element] += $Count; - $CurrentPlanet['metal'] -= $Ressource['metal']; - $CurrentPlanet['crystal'] -= $Ressource['crystal']; - $CurrentPlanet['deuterium'] -= $Ressource['deuterium']; - $CurrentPlanet['shipyardQueue'] .= "{$Element},{$Count};"; - - $DevLog_Array[] = "{$Element},{$Count}"; - } - } - } - } - } - - if($AddedSomething) - { - // Update Achievements - foreach($UpdateAchievements as $Key => $Value) - { - $QryAchievementsKey[] = "`build_{$Key}`"; - $QryAchievementsArr[] = "`build_{$Key}` = `build_{$Key}` + VALUES(`build_{$Key}`)"; - } - $QryAchievements = "INSERT INTO {{table}} (`A_UserID`, ".implode(', ', $QryAchievementsKey).") VALUES ({$CurrentUser['id']}, ".implode(', ', $UpdateAchievements).")"; - $QryAchievements .= " ON DUPLICATE KEY UPDATE "; - $QryAchievements .= implode(', ', $QryAchievementsArr); - $QryAchievements .= ';'; - doquery($QryAchievements, 'achievements_stats'); - - // Update DevLog - $UserDev_Log[] = array('PlanetID' => $CurrentPlanet['id'], 'Date' => $Now, 'Place' => 7, 'Code' => '0', 'ElementID' => '0', 'AdditionalData' => implode(';', $DevLog_Array)); - } - } - } - } - - $TabIndex = 0; - $PageTable = ''; - - $ElementRowTPL = gettemplate('buildings_fleet_row'); - $ElementRowInputTPL = gettemplate('buildings_fleet_row_input'); - - foreach($_Vars_ElementCategories['defense'] as $Element) - { - $Row = array(); - - $Row['Element'] = $Element; - $Row['skinpath'] = $_SkinPath; - $Row['ElementName'] = $_Lang['tech'][$Element]; - $ElementCount = $CurrentPlanet[$_Vars_GameElements[$Element]]; - $Row['ElementNbre'] = ($ElementCount == 0) ? '' : " ({$_Lang['dispo']}: " . prettyNumber($ElementCount) . ")"; - $Row['Description'] = $_Lang['res']['descriptions'][$Element]; - - if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $Element)) - { - $CanBuildOne = IsElementBuyable($CurrentUser, $CurrentPlanet, $Element, false); - $BuildOneElementTime = GetBuildingTime($CurrentUser, $CurrentPlanet, $Element); - - $Row['GetElementPrice'] = GetElementPrice($CurrentUser, $CurrentPlanet, $Element, false); - $Row['ShowBuildTime'] = ShowBuildTime($BuildOneElementTime); - - if($Element == 502 OR $Element == 503) - { - if($AddedMissilesFromQueue == false) - { - $BuildQueueList = $CurrentPlanet['shipyardQueue']; - $BuildArray = explode (';', $BuildQueueList); - $BuildArrayCount= count($BuildArray); - for($QElement = 0; $QElement < $BuildArrayCount; $QElement += 1) - { - $ElmentArray = explode (',', $BuildArray[$QElement] ); - if($ElmentArray[0] == 502 AND $ElmentArray[1] > 0) - { - $Missiles[502] += $ElmentArray[1]; - } - else if($ElmentArray[0] == 503 AND $ElmentArray[1] > 0) - { - $Missiles[503] += $ElmentArray[1]; - } - } - } - $CurrentMissiles = $Missiles[502] + ($Missiles[503] * 2); - - if($Element == 502) - { - $MissileSize = 1; - } - else - { - $MissileSize = 2; - } - - $CanBuildXMissiles = floor(($MaxMissiles - $CurrentMissiles)/$MissileSize); - if($CanBuildXMissiles > 0) - { - $Row['MissilesInfo'] = "

    {$_Lang['CanBuildXMissiles']}: {$CanBuildXMissiles}"; - } - else - { - $Row['MissilesInfo'] = "

    {$_Lang['NoMoreSpaceForThisMissiles']}"; - } - } - - if(isOnVacation($CurrentUser)) - { - $CanBuildOne = false; - } - - if($CanBuildOne) - { - $InQueue = strpos($CurrentPlanet['shipyardQueue'], $Element.','); - $IsBuildp = ($CurrentPlanet[$_Vars_GameElements[407]] >= 1) ? TRUE : FALSE; - $IsBuildg = ($CurrentPlanet[$_Vars_GameElements[408]] >= 1) ? TRUE : FALSE; - $BuildIt = TRUE; - if($Element == 407 OR $Element == 408) - { - $BuildIt = false; - if($Element == 407 AND !$IsBuildp AND $InQueue === FALSE) - { - $BuildIt = TRUE; - } - if($Element == 408 AND !$IsBuildg AND $InQueue === FALSE) - { - $BuildIt = TRUE; - } - } - $IsBuild = ($CurrentPlanet[$_Vars_GameElements[408]] >= 1) ? true : false; - if($Element == 408) - { - $BuildIt = false; - if($InQueue === false AND !$IsBuild) - { - $BuildIt = true; - } - } - if(!$BuildIt) - { - $Row['Input'] = "{$_Lang['only_one']}"; - } - else - { - $Row['InputData'] = array(); - $TabIndex += 1; - $MaxElements = GetMaxConstructibleElements($Element, $CurrentPlanet); - - if($Element == 502 OR $Element == 503) - { - if($CanBuildXMissiles > 0) - { - if($MaxElements < $CanBuildXMissiles) - { - $CanBuildXMissiles = $MaxElements; - } - $Row['InputData']['MaxElements'] = $CanBuildXMissiles; - - $MaxElements = $CanBuildXMissiles; - } - else - { - $Row['Input'] = "{$_Lang['noMoreSpaceInSilo']}"; - $DoNotShowSelectors = true; - } - } - else - { - if($Element == 407 OR $Element == 408) - { - if($MaxElements > 1) - { - $MaxElements = 1; - } - } - } - if($DoNotShowSelectors == false) - { - $Row['InputData']['youCanBuild'] = $_Lang['youCanBuild']; - $Row['InputData']['MaxElements'] = prettyNumber($MaxElements); - $Row['InputData']['Element'] = $Element; - $Row['InputData']['ElementName'] = $Row['ElementName']; - $Row['InputData']['TabIndex'] = $TabIndex; - $Row['InputData']['Max'] = $_Lang['max']; - - $Row['Input'] = parsetemplate($ElementRowInputTPL, $Row['InputData']); - } - } - } - else - { - $Row['Input'] = ' '; - if(isOnVacation($CurrentUser)) - { - $Row['Input'] = ''.$_Lang['ListBox_Disallow_VacationMode'].''; - } - } - } - else - { - if($CurrentUser['settings_ExpandedBuildView'] == 0) - { - continue; - } - $Row['Input'] = ' '; - $Row['TechRequirementsPlace'] = GetElementTechReq($CurrentUser, $CurrentPlanet, $Element); - } - - $PageTable .= parsetemplate($ElementRowTPL, $Row); - } - - $BuildQueue = ''; - if($CurrentPlanet['shipyardQueue'] != '') - { - include($_EnginePath.'includes/functions/ElementBuildListBox.php'); - $BuildQueue = ElementBuildListBox($CurrentUser, $CurrentPlanet); - } - $parse = $_Lang; - $parse['buildlist'] = $PageTable; - $parse['buildinglist'] = $BuildQueue; - $parse['QueueSize'] = $QueueSize; - - display(parsetemplate(gettemplate('buildings_defense'), $parse), $_Lang['Defense']); -} -?> \ No newline at end of file + 0, 407 => 0); + $Missiles = array(502 => 0, 503 => 0); + + $AddedSomething = false; + + $CurrentPlanet = doquery("SELECT * FROM {{table}} WHERE `id` = {$CurrentPlanet['id']} LIMIT 1;", 'planets', true); + $BuildQueueList = $CurrentPlanet['shipyardQueue']; + $BuildArray = explode (';', $BuildQueueList); + $BuildArrayCount = count($BuildArray); + for($QElement = 0; $QElement < $BuildArrayCount; $QElement += 1) + { + $ElmentArray = explode(',', $BuildArray[$QElement]); + if($ElmentArray[0] == 502 AND $ElmentArray[1] > 0) + { + $Missiles[502] += $ElmentArray[1]; + $AddedMissilesFromQueue = true; + } + else if($ElmentArray[0] == 503 AND $ElmentArray[1] > 0) + { + $Missiles[503] += $ElmentArray[1]; + $AddedMissilesFromQueue = true; + } + else if($ElmentArray[0] == 408 AND $ElmentArray[1] > 0) + { + $Shields[408] += $ElmentArray[1]; + $AddedShieldsFromQueue = true; + } + else if($ElmentArray[0] == 407 AND $ElmentArray[1] > 0) + { + $Shields[407] += $ElmentArray[1]; + $AddedShieldsFromQueue = true; + } + } + + if($CurrentPlanet['shipyardQueue'] == '0') + { + $CurrentPlanet['shipyardQueue'] = ''; + } + + if($CurrentPlanet) + { + include($_EnginePath.'includes/functions/GetElementRessources.php'); + foreach($_POST['fmenge'] as $Element => $Count) + { + $Element = intval($Element); + $Count = floor(floatval(str_replace('.', '', $Count))); + if(in_array($Element, $_Vars_ElementCategories['defense'])) + { + if($Count > $QueueSize) + { + $Count = $QueueSize; + } + if($Count >= 1) + { + if($Element == 407) + { + if($CurrentPlanet[$_Vars_GameElements[407]] >= 1 OR $Shields[407] > 0) + { + $Count = 0; + } + else + { + $Count = 1; + } + } + if($Element == 408) + { + if($CurrentPlanet[$_Vars_GameElements[408]] >= 1 OR $Shields[408] > 0) + { + $Count = 0; + } + else + { + $Count = 1; + } + } + if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $Element)) + { + $MaxElements = GetMaxConstructibleElements($Element, $CurrentPlanet); + if($Element == 502 OR $Element == 503) + { + $ActuMissiles = $Missiles[502] + (2 * $Missiles[503]); + $MissilesSpace = $MaxMissiles - $ActuMissiles; + if($Element == 502) + { + if($Count > $MissilesSpace) + { + $Count = $MissilesSpace; + } + } + else + { + if($Count > floor($MissilesSpace / 2 )) + { + $Count = floor($MissilesSpace / 2); + } + } + if($Count > $MaxElements) + { + $Count = $MaxElements; + } + $Missiles[$Element] += $Count; + } + else + { + if($Count > $MaxElements) + { + $Count = $MaxElements; + } + } + $Ressource = GetElementRessources($Element, $Count); + if($Count > 0) + { + $AddedSomething = true; + + if(!isset($UpdateAchievements[$Element])) + { + $UpdateAchievements[$Element] = 0; + } + $UpdateAchievements[$Element] += $Count; + $CurrentPlanet['metal'] -= $Ressource['metal']; + $CurrentPlanet['crystal'] -= $Ressource['crystal']; + $CurrentPlanet['deuterium'] -= $Ressource['deuterium']; + $CurrentPlanet['shipyardQueue'] .= "{$Element},{$Count};"; + + $DevLog_Array[] = "{$Element},{$Count}"; + } + } + } + } + } + + if($AddedSomething) + { + // Update Achievements + foreach($UpdateAchievements as $Key => $Value) + { + $QryAchievementsKey[] = "`build_{$Key}`"; + $QryAchievementsArr[] = "`build_{$Key}` = `build_{$Key}` + VALUES(`build_{$Key}`)"; + } + $QryAchievements = "INSERT INTO {{table}} (`A_UserID`, ".implode(', ', $QryAchievementsKey).") VALUES ({$CurrentUser['id']}, ".implode(', ', $UpdateAchievements).")"; + $QryAchievements .= " ON DUPLICATE KEY UPDATE "; + $QryAchievements .= implode(', ', $QryAchievementsArr); + $QryAchievements .= ';'; + doquery($QryAchievements, 'achievements_stats'); + + // Update DevLog + $UserDev_Log[] = array('PlanetID' => $CurrentPlanet['id'], 'Date' => $Now, 'Place' => 7, 'Code' => '0', 'ElementID' => '0', 'AdditionalData' => implode(';', $DevLog_Array)); + } + } + } + } + + $TabIndex = 0; + $PageTable = ''; + + $ElementRowTPL = gettemplate('buildings_fleet_row'); + $ElementRowInputTPL = gettemplate('buildings_fleet_row_input'); + + foreach($_Vars_ElementCategories['defense'] as $Element) + { + $Row = array(); + + $Row['Element'] = $Element; + $Row['skinpath'] = $_SkinPath; + $Row['ElementName'] = $_Lang['tech'][$Element]; + $ElementCount = $CurrentPlanet[$_Vars_GameElements[$Element]]; + $Row['ElementNbre'] = ($ElementCount == 0) ? '' : " ({$_Lang['dispo']}: " . prettyNumber($ElementCount) . ")"; + $Row['Description'] = $_Lang['res']['descriptions'][$Element]; + + if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $Element)) + { + $CanBuildOne = IsElementBuyable($CurrentUser, $CurrentPlanet, $Element, false); + $BuildOneElementTime = GetBuildingTime($CurrentUser, $CurrentPlanet, $Element); + + $Row['GetElementPrice'] = GetElementPrice($CurrentUser, $CurrentPlanet, $Element, false); + $Row['ShowBuildTime'] = ShowBuildTime($BuildOneElementTime); + + if($Element == 502 OR $Element == 503) + { + if($AddedMissilesFromQueue == false) + { + $BuildQueueList = $CurrentPlanet['shipyardQueue']; + $BuildArray = explode (';', $BuildQueueList); + $BuildArrayCount= count($BuildArray); + for($QElement = 0; $QElement < $BuildArrayCount; $QElement += 1) + { + $ElmentArray = explode (',', $BuildArray[$QElement] ); + if($ElmentArray[0] == 502 AND $ElmentArray[1] > 0) + { + $Missiles[502] += $ElmentArray[1]; + } + else if($ElmentArray[0] == 503 AND $ElmentArray[1] > 0) + { + $Missiles[503] += $ElmentArray[1]; + } + } + } + $CurrentMissiles = $Missiles[502] + ($Missiles[503] * 2); + + if($Element == 502) + { + $MissileSize = 1; + } + else + { + $MissileSize = 2; + } + + $CanBuildXMissiles = floor(($MaxMissiles - $CurrentMissiles)/$MissileSize); + if($CanBuildXMissiles > 0) + { + $Row['MissilesInfo'] = "

    {$_Lang['CanBuildXMissiles']}: {$CanBuildXMissiles}"; + } + else + { + $Row['MissilesInfo'] = "

    {$_Lang['NoMoreSpaceForThisMissiles']}"; + } + } + + if(isOnVacation($CurrentUser)) + { + $CanBuildOne = false; + } + + if($CanBuildOne) + { + $InQueue = strpos($CurrentPlanet['shipyardQueue'], $Element.','); + $IsBuildp = ($CurrentPlanet[$_Vars_GameElements[407]] >= 1) ? TRUE : FALSE; + $IsBuildg = ($CurrentPlanet[$_Vars_GameElements[408]] >= 1) ? TRUE : FALSE; + $BuildIt = TRUE; + if($Element == 407 OR $Element == 408) + { + $BuildIt = false; + if($Element == 407 AND !$IsBuildp AND $InQueue === FALSE) + { + $BuildIt = TRUE; + } + if($Element == 408 AND !$IsBuildg AND $InQueue === FALSE) + { + $BuildIt = TRUE; + } + } + $IsBuild = ($CurrentPlanet[$_Vars_GameElements[408]] >= 1) ? true : false; + if($Element == 408) + { + $BuildIt = false; + if($InQueue === false AND !$IsBuild) + { + $BuildIt = true; + } + } + if(!$BuildIt) + { + $Row['Input'] = "{$_Lang['only_one']}"; + } + else + { + $Row['InputData'] = array(); + $TabIndex += 1; + $MaxElements = GetMaxConstructibleElements($Element, $CurrentPlanet); + + if($Element == 502 OR $Element == 503) + { + if($CanBuildXMissiles > 0) + { + if($MaxElements < $CanBuildXMissiles) + { + $CanBuildXMissiles = $MaxElements; + } + $Row['InputData']['MaxElements'] = $CanBuildXMissiles; + + $MaxElements = $CanBuildXMissiles; + } + else + { + $Row['Input'] = "{$_Lang['noMoreSpaceInSilo']}"; + $DoNotShowSelectors = true; + } + } + else + { + if($Element == 407 OR $Element == 408) + { + if($MaxElements > 1) + { + $MaxElements = 1; + } + } + } + if($DoNotShowSelectors == false) + { + $Row['InputData']['youCanBuild'] = $_Lang['youCanBuild']; + $Row['InputData']['MaxElements'] = prettyNumber($MaxElements); + $Row['InputData']['Element'] = $Element; + $Row['InputData']['ElementName'] = $Row['ElementName']; + $Row['InputData']['TabIndex'] = $TabIndex; + $Row['InputData']['Max'] = $_Lang['max']; + + $Row['Input'] = parsetemplate($ElementRowInputTPL, $Row['InputData']); + } + } + } + else + { + $Row['Input'] = ' '; + if(isOnVacation($CurrentUser)) + { + $Row['Input'] = ''.$_Lang['ListBox_Disallow_VacationMode'].''; + } + } + } + else + { + if($CurrentUser['settings_ExpandedBuildView'] == 0) + { + continue; + } + $Row['Input'] = ' '; + $Row['TechRequirementsPlace'] = GetElementTechReq($CurrentUser, $CurrentPlanet, $Element); + } + + $PageTable .= parsetemplate($ElementRowTPL, $Row); + } + + $BuildQueue = ''; + if($CurrentPlanet['shipyardQueue'] != '') + { + include($_EnginePath.'includes/functions/ElementBuildListBox.php'); + $BuildQueue = ElementBuildListBox($CurrentUser, $CurrentPlanet); + } + $parse = $_Lang; + $parse['buildlist'] = $PageTable; + $parse['buildinglist'] = $BuildQueue; + $parse['QueueSize'] = $QueueSize; + + display(parsetemplate(gettemplate('buildings_defense'), $parse), $_Lang['Defense']); +} +?> diff --git a/includes/functions/DeleteSelectedPlanetorMoon.php b/includes/functions/DeleteSelectedPlanetorMoon.php index 104ff36e6..d95ef7e8a 100644 --- a/includes/functions/DeleteSelectedPlanetorMoon.php +++ b/includes/functions/DeleteSelectedPlanetorMoon.php @@ -1,77 +1,77 @@ - false, 'reason' => 'planetID'); - } - if($_User['techQueue_EndTime'] > 0 AND $_User['techQueue_Planet'] == $_Planet['id']) - { - return array('result' => false, 'reason' => 'tech'); - } - $Query = "SELECT COUNT(`fleet_id`) as `Count` FROM {{table}} WHERE `fleet_start_id` = {$_Planet['id']} OR `fleet_end_id` = {$_Planet['id']};"; - $Fleets = doquery($Query, 'fleets', true); - if($Fleets['Count'] > 0) - { - return array('result' => false, 'reason' => 'fleet_current'); - } - if($_Planet['planet_type'] == 1 AND $_GalaxyRow['id_moon'] > 0) - { - $Query = "SELECT COUNT(`fleet_id`) as `Count` FROM {{table}} WHERE `fleet_start_id` = {$_GalaxyRow['id_moon']} OR `fleet_end_id` = {$_GalaxyRow['id_moon']};"; - $Fleets = doquery($Query, 'fleets', true); - if($Fleets['Count'] > 0) - { - return array('result' => false, 'reason' => 'fleet_moon'); - } - } - - // Abandon Planet here - if($_User['settings_mainPlanetID'] == $_Planet['id']) - { - $Query_UpdateUser_Set[] = "`settings_mainPlanetID` = `id_planet`"; - } - - $Query_UpdateUser_Set[] = "`current_planet` = `id_planet`"; - $Query_UpdateUser = ''; - $Query_UpdateUser .= "UPDATE {{table}} SET "; - $Query_UpdateUser .= implode(', ', $Query_UpdateUser_Set); - $Query_UpdateUser .= " WHERE `id` = {$_User['id']} LIMIT 1;"; - doquery($Query_UpdateUser, 'users'); - - $PlanetIDs[] = $_Planet['id']; - if($_Planet['planet_type'] == 1 AND $_GalaxyRow['id_moon'] > 0) - { - $PlanetIDs[] = $_GalaxyRow['id_moon']; - } - - $PlanetCount = count($PlanetIDs); - $PlanetImplode = implode(',', $PlanetIDs); - if(PLANET_ABANDONTIME > 0 AND $_Planet['planet_type'] == 1) - { - $Query_UpdatePlanets = ''; - $Query_UpdatePlanets .= "UPDATE {{table}} "; - $Query_UpdatePlanets .= "SET `id_owner` = 0, `abandon_time` = UNIX_TIMESTAMP() "; - $Query_UpdatePlanets .= "WHERE `id` IN ({$PlanetImplode}) LIMIT {$PlanetCount};"; - doquery($Query_UpdatePlanets, 'planets'); - } - else - { - if($_Planet['planet_type'] == 1) - { - doquery("DELETE FROM {{table}} WHERE `galaxy_id` = {$_GalaxyRow['galaxy_id']} LIMIT 1;", 'galaxy'); - } - else - { - doquery("UPDATE {{table}} SET `id_moon` = 0 WHERE `galaxy_id` = {$_GalaxyRow['galaxy_id']} LIMIT 1;", 'galaxy'); - } - doquery("DELETE FROM {{table}} WHERE `id` IN ({$PlanetImplode}) LIMIT {$PlanetCount};", 'planets'); - } - - return array('result' => true, 'ids' => $PlanetIDs); -} - -?> \ No newline at end of file + false, 'reason' => 'planetID'); + } + if($_User['techQueue_EndTime'] > 0 AND $_User['techQueue_Planet'] == $_Planet['id']) + { + return array('result' => false, 'reason' => 'tech'); + } + $Query = "SELECT COUNT(`fleet_id`) as `Count` FROM {{table}} WHERE `fleet_start_id` = {$_Planet['id']} OR `fleet_end_id` = {$_Planet['id']};"; + $Fleets = doquery($Query, 'fleets', true); + if($Fleets['Count'] > 0) + { + return array('result' => false, 'reason' => 'fleet_current'); + } + if($_Planet['planet_type'] == 1 AND $_GalaxyRow['id_moon'] > 0) + { + $Query = "SELECT COUNT(`fleet_id`) as `Count` FROM {{table}} WHERE `fleet_start_id` = {$_GalaxyRow['id_moon']} OR `fleet_end_id` = {$_GalaxyRow['id_moon']};"; + $Fleets = doquery($Query, 'fleets', true); + if($Fleets['Count'] > 0) + { + return array('result' => false, 'reason' => 'fleet_moon'); + } + } + + // Abandon Planet here + if($_User['settings_mainPlanetID'] == $_Planet['id']) + { + $Query_UpdateUser_Set[] = "`settings_mainPlanetID` = `id_planet`"; + } + + $Query_UpdateUser_Set[] = "`current_planet` = `id_planet`"; + $Query_UpdateUser = ''; + $Query_UpdateUser .= "UPDATE {{table}} SET "; + $Query_UpdateUser .= implode(', ', $Query_UpdateUser_Set); + $Query_UpdateUser .= " WHERE `id` = {$_User['id']} LIMIT 1;"; + doquery($Query_UpdateUser, 'users'); + + $PlanetIDs[] = $_Planet['id']; + if($_Planet['planet_type'] == 1 AND $_GalaxyRow['id_moon'] > 0) + { + $PlanetIDs[] = $_GalaxyRow['id_moon']; + } + + $PlanetCount = count($PlanetIDs); + $PlanetImplode = implode(',', $PlanetIDs); + if(PLANET_ABANDONTIME > 0 AND $_Planet['planet_type'] == 1) + { + $Query_UpdatePlanets = ''; + $Query_UpdatePlanets .= "UPDATE {{table}} "; + $Query_UpdatePlanets .= "SET `id_owner` = 0, `abandon_time` = UNIX_TIMESTAMP() "; + $Query_UpdatePlanets .= "WHERE `id` IN ({$PlanetImplode}) LIMIT {$PlanetCount};"; + doquery($Query_UpdatePlanets, 'planets'); + } + else + { + if($_Planet['planet_type'] == 1) + { + doquery("DELETE FROM {{table}} WHERE `galaxy_id` = {$_GalaxyRow['galaxy_id']} LIMIT 1;", 'galaxy'); + } + else + { + doquery("UPDATE {{table}} SET `id_moon` = 0 WHERE `galaxy_id` = {$_GalaxyRow['galaxy_id']} LIMIT 1;", 'galaxy'); + } + doquery("DELETE FROM {{table}} WHERE `id` IN ({$PlanetImplode}) LIMIT {$PlanetCount};", 'planets'); + } + + return array('result' => true, 'ids' => $PlanetIDs); +} + +?> diff --git a/includes/functions/DeleteSelectedUser.php b/includes/functions/DeleteSelectedUser.php index 61b44665c..e055c11d7 100644 --- a/includes/functions/DeleteSelectedUser.php +++ b/includes/functions/DeleteSelectedUser.php @@ -1,273 +1,273 @@ - array - ( - 'id', 'username', 'password', 'email', 'email_2', 'user_lastip', 'ip_at_reg', 'register_time', 'onlinetime', 'user_agent', - 'ally_id', 'multiIP_DeclarationID', - ), - 'a' => array - ( - 'ally_owner', 'ally_ChatRoom_ID' - ), - ); - foreach($Query_GetUsers_Fields as $Prefix => $Fields) - { - foreach($Fields as $Key => $Value) - { - if(is_string($Key)) - { - $Temp[] = "`{$Prefix}`.`{$Key}` AS `{$Value}`"; - } - else - { - $Temp[] = "`{$Prefix}`.`{$Value}`"; - } - } - } - $Query_GetUsers_Fields = implode(', ', $Temp); - $Query_GetUsers .= "SELECT {$Query_GetUsers_Fields} FROM `{{table}}` AS `u` "; - $Query_GetUsers .= "LEFT JOIN `{{prefix}}alliance` AS `a` ON `u`.`ally_id` = `a`.`id` "; - $Query_GetUsers .= "WHERE `u`.`id` IN ({$UsersImplode}) LIMIT {$Query_GetUsers_Limit};"; - - $Query_GetPlanets = "SELECT `id` FROM {{table}} WHERE `id_owner` IN ({$UsersImplode}) AND `planet_type` = 1;"; - $Query_GetDeclarations = "SELECT `id`, `users` FROM {{table}} WHERE `id` IN (%s) LIMIT %s;"; - - $Query_DeletePlanets = "DELETE FROM {{table}} WHERE `id_owner` IN ({$UsersImplode});"; - $Query_DeleteGalaxyData = "DELETE FROM {{table}} WHERE `id_planet` IN (%s) LIMIT %s;"; - $Query_DeleteFleets = "DELETE FROM {{table}} WHERE `fleet_owner` IN ({$UsersImplode});"; - $Query_DeleteMessages = "DELETE FROM {{table}} WHERE `id_owner` IN ({$UsersImplode}) OR `id_sender` IN ({$UsersImplode});"; - $Query_DeleteStats = "DELETE FROM {{table}} WHERE `stat_type` = 1 AND `id_owner` IN ({$UsersImplode}) LIMIT {$Query_GetUsers_Limit};"; - $Query_DeleteRecords = "DELETE FROM {{table}} WHERE `id_owner` IN ({$UsersImplode});"; - $Query_DeleteAchievements = "DELETE FROM {{table}} WHERE `A_UserID` IN ({$UsersImplode}) LIMIT {$Query_GetUsers_Limit};"; - $Query_DeleteNotes = "DELETE FROM {{table}} WHERE `owner` IN ({$UsersImplode});"; - $Query_DeleteFleetShortcuts = "DELETE FROM {{table}} WHERE `id_owner` IN ({$UsersImplode});"; - $Query_DeleteBuddyLinks = "DELETE FROM {{table}} WHERE `sender` IN ({$UsersImplode}) OR `owner` IN ({$UsersImplode});"; - $Query_DeleteChatMessages = "DELETE FROM {{table}} WHERE `UID` IN ({$UsersImplode});"; - $Query_DeleteUsers = "DELETE FROM {{table}} WHERE `id` IN ({$UsersImplode}) LIMIT {$Query_GetUsers_Limit};"; - $Query_DeleteAllys = "DELETE FROM {{table}} WHERE `id` IN (%s) LIMIT %s;"; - $Query_DeleteAllyPacts = "DELETE FROM {{table}} WHERE `AllyID_Sender` IN (%s) OR `AllyID_Owner` IN (%s);"; - $Query_DeleteAllyInvites = "DELETE FROM {{table}} WHERE %s;"; - $Query_DeleteAllyStats = "DELETE FROM {{table}} WHERE `stat_type` = 2 AND `id_owner` IN (%s) LIMIT %s;"; - $Query_DeleteAllyChatRooms = "DELETE FROM {{table}} WHERE `ID` IN (%s) LIMIT %s;"; - $Query_DeleteAllyChatMessages = "DELETE FROM {{table}} WHERE `RID` IN (%s);"; - $Query_DeleteAllyChatOnline = "DELETE FROM {{table}} WHERE `RID` IN (%s);"; - - $Query_UpdateUsersCount = "UPDATE {{table}} SET `config_value` = `config_value` - {$Query_GetUsers_Limit} WHERE `config_name` = 'users_amount' LIMIT 1;"; - $Query_UpdateAllyUsers = "UPDATE {{table}} SET `ally_id` = 0, `ally_register_time` = 0, `ally_rank_id` = 0, `ally_request` = 0, `ally_request_text` = '' WHERE `ally_id` IN (%s) OR `ally_request` IN (%s);"; - $Query_UpdateAllyData = "INSERT INTO {{table}} (`id`, `ally_members`) VALUES %s ON DUPLICATE KEY UPDATE `ally_members` = `ally_members` - VALUES(`ally_members`);"; - $Query_UpdateDeclarationsStatus = "UPDATE {{table}} SET `status` = -2 WHERE `id` IN (%s) LIMIT %s;"; - $Query_UpdateDeclarationsUsers = "UPDATE {{table}} SET `multi_validated` = 0 WHERE `id` IN (%s) LIMIT %s;"; - $Query_UpdateDeclarationsContent= "INSERT INTO {{table}} (`id`, `users`) VALUES %s ON DUPLICATE KEY UPDATE `users` = VALUES(`users`);"; - - $Query_InsertData .= "INSERT INTO {{table}} (`id`, `username`, `password`, `email`, `email2`, `last_ip`, `reg_ip`, `register_time`, `last_online`, `user_agent`, `delete_time`) VALUES "; - - // Delete all data - $Result_GetUsers = doquery($Query_GetUsers, 'users'); - if(mysql_num_rows($Result_GetUsers) > 0) - { - // --- Save necessary UserData - $SaveData = array(); - $AllysToUpdate = array(); - $AllysToDelete = array(); - $GetDeclataions = array(); - $UsersInDeclarations = array(); - while($Data = mysql_fetch_assoc($Result_GetUsers)) - { - $SaveData[] = $Data; - if($Data['ally_id'] > 0) - { - if($Data['id'] == $Data['ally_owner']) - { - $AllysToDelete[] = $Data['ally_id']; - if($Data['ally_ChatRoom_ID'] > 0) - { - $DeleteChatRoomsInfo[] = $Data['ally_ChatRoom_ID']; - } - unset($AllysToUpdate[$Data['ally_id']]); - } - else - { - $AllysToUpdate[$Data['ally_id']] += 1; - } - } - if($Data['multiIP_DeclarationID'] > 0) - { - if(!in_array($Data['multiIP_DeclarationID'], $GetDeclataions)) - { - $GetDeclataions[] = $Data['multiIP_DeclarationID']; - } - $UsersInDeclarations[$Data['multiIP_DeclarationID']][] = $Data['id']; - } - } - - // --- Delete Planets - $GalaxyImplode = array(); - $Result_GetPlanets = doquery($Query_GetPlanets, 'planets'); - while($Data = mysql_fetch_assoc($Result_GetPlanets)) - { - $GalaxyImplode[] = $Data['id']; - } - if(!empty($GalaxyImplode)) - { - $GalaxyLimit = count($GalaxyImplode); - $GalaxyImplode = implode(',', $GalaxyImplode); - doquery($Query_DeletePlanets, 'planets'); - doquery(sprintf($Query_DeleteGalaxyData, $GalaxyImplode, $GalaxyLimit), 'galaxy'); - } - - // --- Handle Allys Update or Deletion - $Query_DeleteAllyInvites_Where = array(); - $Query_DeleteAllyInvites_Where[] = "`OwnerID` IN ({$UsersImplode})"; - $Query_DeleteAllyInvites_Where[] = "`SenderID` IN ({$UsersImplode})"; - if(!empty($AllysToDelete)) - { - $AllysToDelete_Count = count($AllysToDelete); - $AllysToDelete = implode(',', $AllysToDelete); - doquery(sprintf($Query_DeleteAllys, $AllysToDelete, $AllysToDelete_Count), 'alliance'); - doquery(sprintf($Query_DeleteAllyPacts, $AllysToDelete, $AllysToDelete), 'ally_pacts'); - doquery(sprintf($Query_UpdateAllyUsers, $AllysToDelete, $AllysToDelete), 'users'); - doquery(sprintf($Query_DeleteAllyStats, $AllysToDelete, $AllysToDelete_Count), 'statpoints'); - $Query_DeleteAllyInvites_Where[] = "`AllyID` IN ({$AllysToDelete})"; - } - if(!empty($AllysToUpdate)) - { - $AllysToUpdate_Values = array(); - foreach($AllysToUpdate as $AllyID => $AllyCount) - { - $AllysToUpdate_Values[] = "({$AllyID}, {$AllyCount})"; - } - doquery(sprintf($Query_UpdateAllyData, implode(',', $AllysToUpdate_Values)), 'alliance'); - } - if(!empty($Query_DeleteAllyInvites_Where)) - { - doquery(sprintf($Query_DeleteAllyInvites, implode(' OR ', $Query_DeleteAllyInvites_Where)), 'ally_invites'); - } - - // --- Handle AllyChat Deletion - if(!empty($DeleteChatRoomsInfo)) - { - $DleeteChatRooms_Count = count($DeleteChatRoomsInfo); - $DeleteChatRooms = implode(',', $DeleteChatRoomsInfo); - doquery(sprintf($Query_DeleteAllyChatRooms, $DeleteChatRooms, $DleeteChatRooms_Count), 'chat_rooms'); - doquery(sprintf($Query_DeleteAllyChatMessages, $DeleteChatRooms), 'chat_messages'); - doquery(sprintf($Query_DeleteAllyChatOnline, $DeleteChatRooms), 'chat_online'); - } - - // --- Handle Fleets (first, retread all, then delete - this will prevent ACS failures) - FleetControl_Retreat("`fleet_owner` IN ({$UsersImplode}) OR `fleet_target_owner` IN ({$UsersImplode})", true); - doquery($Query_DeleteFleets, 'fleets'); - - // --- Handle MultiDeclarations - if(!empty($GetDeclataions)) - { - $UsersToUpdate = array(); - $DeclarationsToUpdate_Status = array(); - $DeclarationsToUpdate_Content = array(); - - $GetDeclataions_Count = count($GetDeclataions); - $GetDeclataions = implode(',', $GetDeclataions); - $Result_GetDeclarations = doquery(sprintf($Query_GetDeclarations, $GetDeclataions, $GetDeclataions_Count), 'declarations'); - if(mysql_num_rows($Result_GetDeclarations) > 0) - { - while($Data = mysql_fetch_assoc($Result_GetDeclarations)) - { - $Data['users'] = explode(',', $Data['users']); - foreach($Data['users'] as $ThisUser) - { - $ThisUser = str_replace('|', '', $ThisUser); - if($ThisUser > 0) - { - $Data['thisUsers'][$ThisUser] = $ThisUser; - if(empty($Data['thisOwner'])) - { - $Data['thisOwner'] = $ThisUser; - } - } - } - foreach($UsersInDeclarations[$Data['id']] as $ThisUser) - { - unset($Data['thisUsers'][$ThisUser]); - } - $ThisUsersCount = count($Data['thisUsers']); - if($ThisUsersCount <= 1 OR in_array($Data['thisOwner'], $UsersInDeclarations[$Data['id']])) - { - $DeclarationsToUpdate_Status[] = $Data['id']; - if($ThisUsersCount > 0) - { - $UsersToUpdate = array_merge($UsersToUpdate, $Data['thisUsers']); - $Message = array(); - $Message['msg_id'] = '079'; - $Message['args'] = array(); - $Message = json_encode($Message); - Cache_Message($Data['thisUsers'], 0, $Now, 70, '007', '020', $Message); - } - } - else - { - $DeclarationsToUpdate_Content[$Data['id']] = $Data['thisUsers']; - } - } - - if(!empty($DeclarationsToUpdate_Status)) - { - doquery(sprintf($Query_UpdateDeclarationsStatus, implode(',', $DeclarationsToUpdate_Status), count($DeclarationsToUpdate_Status)), 'declarations'); - } - if(!empty($UsersToUpdate)) - { - doquery(sprintf($Query_UpdateDeclarationsUsers, implode(',', $UsersToUpdate), count($UsersToUpdate)), 'users'); - } - if(!empty($DeclarationsToUpdate_Content)) - { - $Query_UpdateDeclarationsContent_Array = array(); - foreach($DeclarationsToUpdate_Content as $ThisID => $ThisUsers) - { - foreach($ThisUsers as &$Value) - { - $Value = "|{$Value}|"; - } - $ThisUsers = implode(',', $ThisUsers); - $Query_UpdateDeclarationsContent_Array[] = "({$ThisID}, '{$ThisUsers}')"; - } - doquery(sprintf($Query_UpdateDeclarationsContent, implode(',', $Query_UpdateDeclarationsContent_Array)), 'declarations'); - } - } - } - - // --- Rest of Deleting - doquery($Query_DeleteMessages, 'messages'); - doquery($Query_DeleteStats, 'statpoints'); - doquery($Query_DeleteRecords, 'records'); - doquery($Query_DeleteAchievements, 'achievements_stats'); - doquery($Query_DeleteNotes, 'notes'); - doquery($Query_DeleteFleetShortcuts, 'fleet_shortcuts'); - doquery($Query_DeleteBuddyLinks, 'buddy'); - doquery($Query_DeleteChatMessages, 'chat_messages'); - doquery($Query_DeleteUsers, 'users'); - - // --- Do necessary Updates - doquery($Query_UpdateUsersCount, 'config'); - $_GameConfig['users_amount'] -= $Query_GetUsers_Limit; - $_MemCache->GameConfig = $_GameConfig; - - // --- Save some historical Data - foreach($SaveData as $Data) - { - $Query_InsertData_Array[] = "({$Data['id']}, '{$Data['username']}', '{$Data['password']}', '{$Data['email']}', '{$Data['email_2']}', '{$Data['user_lastip']}', '{$Data['ip_at_reg']}', {$Data['register_time']}, {$Data['onlinetime']}, '{$Data['user_agent']}', {$Now})"; - } - $Query_InsertData .= implode(',', $Query_InsertData_Array); - doquery($Query_InsertData, 'deleted_users'); - } -} - -?> \ No newline at end of file + array + ( + 'id', 'username', 'password', 'email', 'email_2', 'user_lastip', 'ip_at_reg', 'register_time', 'onlinetime', 'user_agent', + 'ally_id', 'multiIP_DeclarationID', + ), + 'a' => array + ( + 'ally_owner', 'ally_ChatRoom_ID' + ), + ); + foreach($Query_GetUsers_Fields as $Prefix => $Fields) + { + foreach($Fields as $Key => $Value) + { + if(is_string($Key)) + { + $Temp[] = "`{$Prefix}`.`{$Key}` AS `{$Value}`"; + } + else + { + $Temp[] = "`{$Prefix}`.`{$Value}`"; + } + } + } + $Query_GetUsers_Fields = implode(', ', $Temp); + $Query_GetUsers .= "SELECT {$Query_GetUsers_Fields} FROM `{{table}}` AS `u` "; + $Query_GetUsers .= "LEFT JOIN `{{prefix}}alliance` AS `a` ON `u`.`ally_id` = `a`.`id` "; + $Query_GetUsers .= "WHERE `u`.`id` IN ({$UsersImplode}) LIMIT {$Query_GetUsers_Limit};"; + + $Query_GetPlanets = "SELECT `id` FROM {{table}} WHERE `id_owner` IN ({$UsersImplode}) AND `planet_type` = 1;"; + $Query_GetDeclarations = "SELECT `id`, `users` FROM {{table}} WHERE `id` IN (%s) LIMIT %s;"; + + $Query_DeletePlanets = "DELETE FROM {{table}} WHERE `id_owner` IN ({$UsersImplode});"; + $Query_DeleteGalaxyData = "DELETE FROM {{table}} WHERE `id_planet` IN (%s) LIMIT %s;"; + $Query_DeleteFleets = "DELETE FROM {{table}} WHERE `fleet_owner` IN ({$UsersImplode});"; + $Query_DeleteMessages = "DELETE FROM {{table}} WHERE `id_owner` IN ({$UsersImplode}) OR `id_sender` IN ({$UsersImplode});"; + $Query_DeleteStats = "DELETE FROM {{table}} WHERE `stat_type` = 1 AND `id_owner` IN ({$UsersImplode}) LIMIT {$Query_GetUsers_Limit};"; + $Query_DeleteRecords = "DELETE FROM {{table}} WHERE `id_owner` IN ({$UsersImplode});"; + $Query_DeleteAchievements = "DELETE FROM {{table}} WHERE `A_UserID` IN ({$UsersImplode}) LIMIT {$Query_GetUsers_Limit};"; + $Query_DeleteNotes = "DELETE FROM {{table}} WHERE `owner` IN ({$UsersImplode});"; + $Query_DeleteFleetShortcuts = "DELETE FROM {{table}} WHERE `id_owner` IN ({$UsersImplode});"; + $Query_DeleteBuddyLinks = "DELETE FROM {{table}} WHERE `sender` IN ({$UsersImplode}) OR `owner` IN ({$UsersImplode});"; + $Query_DeleteChatMessages = "DELETE FROM {{table}} WHERE `UID` IN ({$UsersImplode});"; + $Query_DeleteUsers = "DELETE FROM {{table}} WHERE `id` IN ({$UsersImplode}) LIMIT {$Query_GetUsers_Limit};"; + $Query_DeleteAllys = "DELETE FROM {{table}} WHERE `id` IN (%s) LIMIT %s;"; + $Query_DeleteAllyPacts = "DELETE FROM {{table}} WHERE `AllyID_Sender` IN (%s) OR `AllyID_Owner` IN (%s);"; + $Query_DeleteAllyInvites = "DELETE FROM {{table}} WHERE %s;"; + $Query_DeleteAllyStats = "DELETE FROM {{table}} WHERE `stat_type` = 2 AND `id_owner` IN (%s) LIMIT %s;"; + $Query_DeleteAllyChatRooms = "DELETE FROM {{table}} WHERE `ID` IN (%s) LIMIT %s;"; + $Query_DeleteAllyChatMessages = "DELETE FROM {{table}} WHERE `RID` IN (%s);"; + $Query_DeleteAllyChatOnline = "DELETE FROM {{table}} WHERE `RID` IN (%s);"; + + $Query_UpdateUsersCount = "UPDATE {{table}} SET `config_value` = `config_value` - {$Query_GetUsers_Limit} WHERE `config_name` = 'users_amount' LIMIT 1;"; + $Query_UpdateAllyUsers = "UPDATE {{table}} SET `ally_id` = 0, `ally_register_time` = 0, `ally_rank_id` = 0, `ally_request` = 0, `ally_request_text` = '' WHERE `ally_id` IN (%s) OR `ally_request` IN (%s);"; + $Query_UpdateAllyData = "INSERT INTO {{table}} (`id`, `ally_members`) VALUES %s ON DUPLICATE KEY UPDATE `ally_members` = `ally_members` - VALUES(`ally_members`);"; + $Query_UpdateDeclarationsStatus = "UPDATE {{table}} SET `status` = -2 WHERE `id` IN (%s) LIMIT %s;"; + $Query_UpdateDeclarationsUsers = "UPDATE {{table}} SET `multi_validated` = 0 WHERE `id` IN (%s) LIMIT %s;"; + $Query_UpdateDeclarationsContent= "INSERT INTO {{table}} (`id`, `users`) VALUES %s ON DUPLICATE KEY UPDATE `users` = VALUES(`users`);"; + + $Query_InsertData .= "INSERT INTO {{table}} (`id`, `username`, `password`, `email`, `email2`, `last_ip`, `reg_ip`, `register_time`, `last_online`, `user_agent`, `delete_time`) VALUES "; + + // Delete all data + $Result_GetUsers = doquery($Query_GetUsers, 'users'); + if(mysql_num_rows($Result_GetUsers) > 0) + { + // --- Save necessary UserData + $SaveData = array(); + $AllysToUpdate = array(); + $AllysToDelete = array(); + $GetDeclataions = array(); + $UsersInDeclarations = array(); + while($Data = mysql_fetch_assoc($Result_GetUsers)) + { + $SaveData[] = $Data; + if($Data['ally_id'] > 0) + { + if($Data['id'] == $Data['ally_owner']) + { + $AllysToDelete[] = $Data['ally_id']; + if($Data['ally_ChatRoom_ID'] > 0) + { + $DeleteChatRoomsInfo[] = $Data['ally_ChatRoom_ID']; + } + unset($AllysToUpdate[$Data['ally_id']]); + } + else + { + $AllysToUpdate[$Data['ally_id']] += 1; + } + } + if($Data['multiIP_DeclarationID'] > 0) + { + if(!in_array($Data['multiIP_DeclarationID'], $GetDeclataions)) + { + $GetDeclataions[] = $Data['multiIP_DeclarationID']; + } + $UsersInDeclarations[$Data['multiIP_DeclarationID']][] = $Data['id']; + } + } + + // --- Delete Planets + $GalaxyImplode = array(); + $Result_GetPlanets = doquery($Query_GetPlanets, 'planets'); + while($Data = mysql_fetch_assoc($Result_GetPlanets)) + { + $GalaxyImplode[] = $Data['id']; + } + if(!empty($GalaxyImplode)) + { + $GalaxyLimit = count($GalaxyImplode); + $GalaxyImplode = implode(',', $GalaxyImplode); + doquery($Query_DeletePlanets, 'planets'); + doquery(sprintf($Query_DeleteGalaxyData, $GalaxyImplode, $GalaxyLimit), 'galaxy'); + } + + // --- Handle Allys Update or Deletion + $Query_DeleteAllyInvites_Where = array(); + $Query_DeleteAllyInvites_Where[] = "`OwnerID` IN ({$UsersImplode})"; + $Query_DeleteAllyInvites_Where[] = "`SenderID` IN ({$UsersImplode})"; + if(!empty($AllysToDelete)) + { + $AllysToDelete_Count = count($AllysToDelete); + $AllysToDelete = implode(',', $AllysToDelete); + doquery(sprintf($Query_DeleteAllys, $AllysToDelete, $AllysToDelete_Count), 'alliance'); + doquery(sprintf($Query_DeleteAllyPacts, $AllysToDelete, $AllysToDelete), 'ally_pacts'); + doquery(sprintf($Query_UpdateAllyUsers, $AllysToDelete, $AllysToDelete), 'users'); + doquery(sprintf($Query_DeleteAllyStats, $AllysToDelete, $AllysToDelete_Count), 'statpoints'); + $Query_DeleteAllyInvites_Where[] = "`AllyID` IN ({$AllysToDelete})"; + } + if(!empty($AllysToUpdate)) + { + $AllysToUpdate_Values = array(); + foreach($AllysToUpdate as $AllyID => $AllyCount) + { + $AllysToUpdate_Values[] = "({$AllyID}, {$AllyCount})"; + } + doquery(sprintf($Query_UpdateAllyData, implode(',', $AllysToUpdate_Values)), 'alliance'); + } + if(!empty($Query_DeleteAllyInvites_Where)) + { + doquery(sprintf($Query_DeleteAllyInvites, implode(' OR ', $Query_DeleteAllyInvites_Where)), 'ally_invites'); + } + + // --- Handle AllyChat Deletion + if(!empty($DeleteChatRoomsInfo)) + { + $DleeteChatRooms_Count = count($DeleteChatRoomsInfo); + $DeleteChatRooms = implode(',', $DeleteChatRoomsInfo); + doquery(sprintf($Query_DeleteAllyChatRooms, $DeleteChatRooms, $DleeteChatRooms_Count), 'chat_rooms'); + doquery(sprintf($Query_DeleteAllyChatMessages, $DeleteChatRooms), 'chat_messages'); + doquery(sprintf($Query_DeleteAllyChatOnline, $DeleteChatRooms), 'chat_online'); + } + + // --- Handle Fleets (first, retread all, then delete - this will prevent ACS failures) + FleetControl_Retreat("`fleet_owner` IN ({$UsersImplode}) OR `fleet_target_owner` IN ({$UsersImplode})", true); + doquery($Query_DeleteFleets, 'fleets'); + + // --- Handle MultiDeclarations + if(!empty($GetDeclataions)) + { + $UsersToUpdate = array(); + $DeclarationsToUpdate_Status = array(); + $DeclarationsToUpdate_Content = array(); + + $GetDeclataions_Count = count($GetDeclataions); + $GetDeclataions = implode(',', $GetDeclataions); + $Result_GetDeclarations = doquery(sprintf($Query_GetDeclarations, $GetDeclataions, $GetDeclataions_Count), 'declarations'); + if(mysql_num_rows($Result_GetDeclarations) > 0) + { + while($Data = mysql_fetch_assoc($Result_GetDeclarations)) + { + $Data['users'] = explode(',', $Data['users']); + foreach($Data['users'] as $ThisUser) + { + $ThisUser = str_replace('|', '', $ThisUser); + if($ThisUser > 0) + { + $Data['thisUsers'][$ThisUser] = $ThisUser; + if(empty($Data['thisOwner'])) + { + $Data['thisOwner'] = $ThisUser; + } + } + } + foreach($UsersInDeclarations[$Data['id']] as $ThisUser) + { + unset($Data['thisUsers'][$ThisUser]); + } + $ThisUsersCount = count($Data['thisUsers']); + if($ThisUsersCount <= 1 OR in_array($Data['thisOwner'], $UsersInDeclarations[$Data['id']])) + { + $DeclarationsToUpdate_Status[] = $Data['id']; + if($ThisUsersCount > 0) + { + $UsersToUpdate = array_merge($UsersToUpdate, $Data['thisUsers']); + $Message = array(); + $Message['msg_id'] = '079'; + $Message['args'] = array(); + $Message = json_encode($Message); + Cache_Message($Data['thisUsers'], 0, $Now, 70, '007', '020', $Message); + } + } + else + { + $DeclarationsToUpdate_Content[$Data['id']] = $Data['thisUsers']; + } + } + + if(!empty($DeclarationsToUpdate_Status)) + { + doquery(sprintf($Query_UpdateDeclarationsStatus, implode(',', $DeclarationsToUpdate_Status), count($DeclarationsToUpdate_Status)), 'declarations'); + } + if(!empty($UsersToUpdate)) + { + doquery(sprintf($Query_UpdateDeclarationsUsers, implode(',', $UsersToUpdate), count($UsersToUpdate)), 'users'); + } + if(!empty($DeclarationsToUpdate_Content)) + { + $Query_UpdateDeclarationsContent_Array = array(); + foreach($DeclarationsToUpdate_Content as $ThisID => $ThisUsers) + { + foreach($ThisUsers as &$Value) + { + $Value = "|{$Value}|"; + } + $ThisUsers = implode(',', $ThisUsers); + $Query_UpdateDeclarationsContent_Array[] = "({$ThisID}, '{$ThisUsers}')"; + } + doquery(sprintf($Query_UpdateDeclarationsContent, implode(',', $Query_UpdateDeclarationsContent_Array)), 'declarations'); + } + } + } + + // --- Rest of Deleting + doquery($Query_DeleteMessages, 'messages'); + doquery($Query_DeleteStats, 'statpoints'); + doquery($Query_DeleteRecords, 'records'); + doquery($Query_DeleteAchievements, 'achievements_stats'); + doquery($Query_DeleteNotes, 'notes'); + doquery($Query_DeleteFleetShortcuts, 'fleet_shortcuts'); + doquery($Query_DeleteBuddyLinks, 'buddy'); + doquery($Query_DeleteChatMessages, 'chat_messages'); + doquery($Query_DeleteUsers, 'users'); + + // --- Do necessary Updates + doquery($Query_UpdateUsersCount, 'config'); + $_GameConfig['users_amount'] -= $Query_GetUsers_Limit; + $_MemCache->GameConfig = $_GameConfig; + + // --- Save some historical Data + foreach($SaveData as $Data) + { + $Query_InsertData_Array[] = "({$Data['id']}, '{$Data['username']}', '{$Data['password']}', '{$Data['email']}', '{$Data['email_2']}', '{$Data['user_lastip']}', '{$Data['ip_at_reg']}', {$Data['register_time']}, {$Data['onlinetime']}, '{$Data['user_agent']}', {$Now})"; + } + $Query_InsertData .= implode(',', $Query_InsertData_Array); + doquery($Query_InsertData, 'deleted_users'); + } +} + +?> diff --git a/includes/functions/ElementBuildListBox.php b/includes/functions/ElementBuildListBox.php index 46ee773a0..f6952936d 100644 --- a/includes/functions/ElementBuildListBox.php +++ b/includes/functions/ElementBuildListBox.php @@ -1,37 +1,37 @@ - $Element) - { - if($Element != '') - { - $Element = explode(',', $Element); - $ElementTime = GetBuildingTime($CurrentUser, $CurrentPlanet, $Element[0]); - $QueueTime += $ElementTime * $Element[1]; - $TimePerType[] = $ElementTime; - $NamePerType[] = "'".html_entity_decode($_Lang['tech'][$Element[0]])."'"; - $NbrePerType[] = $Element[1]; - } - } - - $parse = $_Lang; - $parse['a'] = implode(',', $NbrePerType); - $parse['b'] = implode(',', $NamePerType); - $parse['c'] = implode(',', $TimePerType); - $parse['b_hangar_id_plus'] = $CurrentPlanet['shipyardQueue_additionalWorkTime']; - - $parse['pretty_time_b_hangar'] = pretty_time($QueueTime - $CurrentPlanet['shipyardQueue_additionalWorkTime']); - - return parsetemplate(gettemplate('buildings_script'), $parse); -} - -?> \ No newline at end of file + $Element) + { + if($Element != '') + { + $Element = explode(',', $Element); + $ElementTime = GetBuildingTime($CurrentUser, $CurrentPlanet, $Element[0]); + $QueueTime += $ElementTime * $Element[1]; + $TimePerType[] = $ElementTime; + $NamePerType[] = "'".html_entity_decode($_Lang['tech'][$Element[0]])."'"; + $NbrePerType[] = $Element[1]; + } + } + + $parse = $_Lang; + $parse['a'] = implode(',', $NbrePerType); + $parse['b'] = implode(',', $NamePerType); + $parse['c'] = implode(',', $TimePerType); + $parse['b_hangar_id_plus'] = $CurrentPlanet['shipyardQueue_additionalWorkTime']; + + $parse['pretty_time_b_hangar'] = pretty_time($QueueTime - $CurrentPlanet['shipyardQueue_additionalWorkTime']); + + return parsetemplate(gettemplate('buildings_script'), $parse); +} + +?> diff --git a/includes/functions/FilterMessages.php b/includes/functions/FilterMessages.php index d01e7268e..32bf14b1c 100644 --- a/includes/functions/FilterMessages.php +++ b/includes/functions/FilterMessages.php @@ -1,28 +1,28 @@ - \ No newline at end of file + diff --git a/includes/functions/Filters.php b/includes/functions/Filters.php index 59b22ce83..faa4c0502 100644 --- a/includes/functions/Filters.php +++ b/includes/functions/Filters.php @@ -1,543 +1,543 @@ - 0) - { - $Query['whereData'][] = $Value; - } - } - $Query['whereJoin'] = function($Array){ return implode(', ', $Array); }; - $Query['querySelect'] = 'id'; - $Query['querySelectArray'][] = 'id'; - $Query['queryString'] = "FROM {{table}} WHERE `id` IN ({whereJoin}) {whereAddition}"; - $Query['queryTable'] = 'users'; - } - else if($Type === 'uname') - { - $ThisRegexp = ($Flags['strict'] === true ? REGEXP_USERNAME_ABSOLUTE : REGEXP_USERNAME); - foreach($Search as $Value) - { - if(preg_match($ThisRegexp, $Value)) - { - $Query['whereData'][] = $Value; - } - } - if($Flags['strict'] === true) - { - $Query['whereJoin'] = function($Array) - { - foreach($Array as $Value) - { - $Return[] = "`username` = '{$Value}'"; - } - return implode(' OR ', $Return); - }; - } - else - { - $Query['whereJoin'] = function($Array) - { - foreach($Array as $Value) - { - $Value = preg_replace(REGEXP_SANITIZELIKE_SEARCH, REGEXP_SANITIZELIKE_REPLACE, $Value); - $Return[] = "`username` LIKE '%{$Value}%'"; - } - return implode(' OR ', $Return); - }; - } - $Query['querySelect'] = 'id'; - $Query['querySelectArray'][] = 'id'; - $Query['queryString'] = "FROM {{table}} WHERE ({whereJoin}) {whereAddition}"; - $Query['queryTable'] = 'users'; - } - else if($Type === 'aid') - { - foreach($Search as $Value) - { - $Value = intval($Value); - if($Value > 0) - { - $Query['whereData'][] = $Value; - } - } - $Query['whereJoin'] = function($Array){ return implode(', ', $Array); }; - $Query['querySelect'] = 'id'; - $Query['querySelectArray'][] = 'id'; - if($Flags['allyRequest'] === true) - { - $ThisWhere = "(`ally_request` IN ({whereJoin}))"; - } - else if($Flags['allyRequest'] === false) - { - $ThisWhere = "(`ally_id` IN ({whereJoin}))"; - } - else - { - $ThisWhere = "(`ally_id` IN ({whereJoin}) OR `ally_request` IN ({whereJoin}))"; - } - - $Query['queryString'] = "FROM {{table}} WHERE {$ThisWhere} {whereAddition}"; - $Query['queryTable'] = 'users'; - } - else if($Type === 'astring') - { - foreach($Search as $Value) - { - if(preg_match(REGEXP_ALLYNAMEANDTAG, $Value)) - { - $Query['whereData'][] = $Value; - } - } - $Query['whereJoin'] = function($Array) - { - foreach($Array as $Value) - { - $Value = preg_replace(REGEXP_SANITIZELIKE_SEARCH, REGEXP_SANITIZELIKE_REPLACE, $Value); - $Return[] = "`ally`.`ally_name` LIKE '%{$Value}%' OR `ally`.`ally_tag` LIKE '%{$Value}%'"; - } - return implode(' OR ', $Return); - }; - $Query['querySelect'] = '`users`.`id`'; - $Query['querySelectArray'][] = 'id'; - if($Flags['allyRequest'] === true) - { - $ThisJoin = "JOIN `{{prefix}}users` AS `users` ON `ally`.`id` = `users`.`ally_request`"; - } - else if($Flags['allyRequest'] === false) - { - $ThisJoin = "JOIN `{{prefix}}users` AS `users` ON `ally`.`id` = `users`.`ally_id`"; - } - else - { - $Query['querySelect'] = '`users1`.`id` AS `id1`, `users2`.`id` AS `id2`'; - $Query['querySelectArray'] = array('id1', 'id2'); - $ThisJoin = "LEFT JOIN `{{prefix}}users` AS `users1` ON `ally`.`id` = `users1`.`ally_id` "; - $ThisJoin .= "LEFT JOIN `{{prefix}}users` AS `users2` ON `ally`.`id` = `users2`.`ally_request` "; - } - $Query['queryString'] = "FROM {{table}} AS `ally` {$ThisJoin} WHERE ({whereJoin}) {whereAddition}"; - $Query['queryTable'] = 'alliance'; - $Query['whereAdditionAlias'] = 'users'; - } - else if($Type === 'aname') - { - $ThisRegexp = ($Flags['strict'] === true ? REGEXP_ALLYNAME_ABSOLUTE : REGEXP_ALLYNAMEANDTAG); - foreach($Search as $Value) - { - if(preg_match($ThisRegexp, $Value)) - { - $Query['whereData'][] = $Value; - } - } - if($Flags['strict'] === true) - { - $Query['whereJoin'] = function($Array) - { - foreach($Array as $Value) - { - $Return[] = "`ally`.`ally_name` = '{$Value}'"; - } - return implode(' OR ', $Return); - }; - } - else - { - $Query['whereJoin'] = function($Array) - { - foreach($Array as $Value) - { - $Value = preg_replace(REGEXP_SANITIZELIKE_SEARCH, REGEXP_SANITIZELIKE_REPLACE, $Value); - $Return[] = "`ally`.`ally_name` LIKE '%{$Value}%'"; - } - return implode(' OR ', $Return); - }; - } - $Query['querySelect'] = '`users`.`id`'; - $Query['querySelectArray'][] = 'id'; - if($Flags['allyRequest'] === true) - { - $ThisJoin = "JOIN `{{prefix}}users` AS `users` ON `ally`.`id` = `users`.`ally_request`"; - } - else if($Flags['allyRequest'] === false) - { - $ThisJoin = "JOIN `{{prefix}}users` AS `users` ON `ally`.`id` = `users`.`ally_id`"; - } - else - { - $Query['querySelect'] = '`users1`.`id` AS `id1`, `users2`.`id` AS `id2`'; - $Query['querySelectArray'] = array('id1', 'id2'); - $ThisJoin = "LEFT JOIN `{{prefix}}users` AS `users1` ON `ally`.`id` = `users1`.`ally_id` "; - $ThisJoin .= "LEFT JOIN `{{prefix}}users` AS `users2` ON `ally`.`id` = `users2`.`ally_request` "; - } - $Query['queryString'] = "FROM {{table}} AS `ally` {$ThisJoin} WHERE ({whereJoin}) {whereAddition}"; - $Query['queryTable'] = 'alliance'; - $Query['whereAdditionAlias'] = 'users'; - } - else if($Type === 'atag') - { - $ThisRegexp = ($Flags['strict'] === true ? REGEXP_ALLYTAG_ABSOLUTE : REGEXP_ALLYTAG); - foreach($Search as $Value) - { - if(preg_match($ThisRegexp, $Value)) - { - $Query['whereData'][] = $Value; - } - } - if($Flags['strict'] === true) - { - $Query['whereJoin'] = function($Array) - { - foreach($Array as $Value) - { - $Return[] = "`ally`.`ally_tag` = '{$Value}'"; - } - return implode(' OR ', $Return); - }; - } - else - { - $Query['whereJoin'] = function($Array) - { - foreach($Array as $Value) - { - $Value = preg_replace(REGEXP_SANITIZELIKE_SEARCH, REGEXP_SANITIZELIKE_REPLACE, $Value); - $Return[] = "`ally`.`ally_tag` LIKE '%{$Value}%'"; - } - return implode(' OR ', $Return); - }; - } - $Query['querySelect'] = '`users`.`id`'; - $Query['querySelectArray'][] = 'id'; - if($Flags['allyRequest'] === true) - { - $ThisJoin = "JOIN `{{prefix}}users` AS `users` ON `ally`.`id` = `users`.`ally_request`"; - } - else if($Flags['allyRequest'] === false) - { - $ThisJoin = "JOIN `{{prefix}}users` AS `users` ON `ally`.`id` = `users`.`ally_id`"; - } - else - { - $Query['querySelect'] = '`users1`.`id` AS `id1`, `users2`.`id` AS `id2`'; - $Query['querySelectArray'] = array('id1', 'id2'); - $ThisJoin = "LEFT JOIN `{{prefix}}users` AS `users1` ON `ally`.`id` = `users1`.`ally_id` "; - $ThisJoin .= "LEFT JOIN `{{prefix}}users` AS `users2` ON `ally`.`id` = `users2`.`ally_request` "; - } - $Query['queryString'] = "FROM {{table}} AS `ally` {$ThisJoin} WHERE ({whereJoin}) {whereAddition}"; - $Query['queryTable'] = 'alliance'; - $Query['whereAdditionAlias'] = 'users'; - } - else if($Type === 'ipid') - { - foreach($Search as $Value) - { - $Value = round($Value); - if($Value > 0) - { - $Query['whereData'][] = $Value; - } - } - $Query['whereJoin'] = function($Array){ return implode(', ', $Array); }; - $Query['querySelect'] = '`users`.`id`'; - $Query['querySelectArray'][] = 'id'; - $Query['queryString'] = "FROM {{table}} AS `enterlog` JOIN `{{prefix}}users` AS `users` ON `users`.`id` = `enterlog`.`User_ID` WHERE `enterlog`.`IP_ID` IN ({whereJoin}) {whereAddition}"; - $Query['queryTable'] = 'user_enterlog'; - $Query['whereAdditionAlias'] = 'users'; - } - else if($Type === 'ipstring') - { - foreach($Search as $Value) - { - if(preg_match(REGEXP_IP, $Value)) - { - $Query['whereData'][] = $Value; - } - } - if($Flags['utableOnly'] === true) - { - if($Flags['strict'] === true) - { - $Query['whereJoin'] = function($Array) - { - foreach($Array as $Value) - { - $Return[] = "`user_lastip` = '{$Value}' OR `ip_at_reg` = '{$Value}'"; - } - return implode(' OR ', $Return); - }; - } - else - { - $Query['whereJoin'] = function($Array) - { - foreach($Array as $Value) - { - $Value = preg_replace(REGEXP_SANITIZELIKE_SEARCH, REGEXP_SANITIZELIKE_REPLACE, $Value); - $Return[] = "`user_lastip` LIKE '%{$Value}%' OR `ip_at_reg` LIKE '%{$Value}%'"; - } - return implode(' OR ', $Return); - }; - } - $Query['querySelect'] = 'id'; - $Query['querySelectArray'][] = 'id'; - $Query['queryString'] = "FROM {{table}} WHERE ({whereJoin}) {whereAddition}"; - $Query['queryTable'] = 'users'; - } - else - { - if($Flags['strict'] === true) - { - $Query['whereJoin'] = function($Array) - { - foreach($Array as $Value) - { - $Value = md5($Value); - $Return[] = "`iptable`.`ValueHash` = '{$Value}'"; - } - return implode(' OR ', $Return); - }; - } - else - { - $Query['whereJoin'] = function($Array) - { - foreach($Array as $Value) - { - $Value = preg_replace(REGEXP_SANITIZELIKE_SEARCH, REGEXP_SANITIZELIKE_REPLACE, $Value); - $Return[] = "`iptable`.`Value` LIKE '%{$Value}%'"; - } - return implode(' OR ', $Return); - }; - } - $Query['querySelect'] = '`users`.`id`'; - $Query['querySelectArray'][] = 'id'; - $Query['queryString'] = "FROM {{table}} AS `iptable` LEFT JOIN `{{prefix}}user_enterlog` AS `enterlog` ON `enterlog`.`IP_ID` = `iptable`.`ID` JOIN `{{prefix}}users` AS `users` ON `enterlog`.`User_ID` = `users`.`id` WHERE (`iptable`.`Type` = 'ip' AND ({whereJoin})) {whereAddition} GROUP BY `User_ID`"; - $Query['queryTable'] = 'used_ip_and_ua'; - $Query['whereAdditionAlias'] = 'users'; - } - } - else if($Type === 'umail') - { - $ThisRegexp = ($Flags['strict'] === true ? REGEXP_EMAIL_SIGNS : REGEXP_EMAIL_SIGNS); - foreach($Search as $Value) - { - if(preg_match($ThisRegexp, $Value)) - { - $Query['whereData'][] = $Value; - } - } - if($Flags['strict'] === true) - { - $Query['whereJoin'] = function($Array) - { - foreach($Array as $Value) - { - $Return[] = "`email` = '{$Value}' OR `email_2` = '{$Value}'"; - } - return implode(' OR ', $Return); - }; - } - else - { - $Query['whereJoin'] = function($Array) - { - foreach($Array as $Value) - { - $Value = preg_replace(REGEXP_SANITIZELIKE_SEARCH, REGEXP_SANITIZELIKE_REPLACE, $Value); - $Return[] = "`email` LIKE '%{$Value}%' OR `email_2` LIKE '%{$Value}%'"; - } - return implode(' OR ', $Return); - }; - } - $Query['querySelect'] = 'id'; - $Query['querySelectArray'][] = 'id'; - $Query['queryString'] = "FROM {{table}} WHERE ({whereJoin}) {whereAddition}"; - $Query['queryTable'] = 'users'; - } - } - else - { - // WHERE Statement is unnecessary - $Query['querySelect'] = 'id'; - $Query['querySelectArray'][] = 'id'; - $Query['queryString'] = "FROM {{table}} {whereAddition}"; - $Query['queryTable'] = 'users'; - } - - // Check, if we can go further - if(!empty($Search) && empty($Query['whereData'])) - { - // All given data was rejected - return false; - } - - // Additional Flags - // > user is an Artificial Intelligence (AI) - if($Flags['isAI'] === true) - { - $Query['whereAddition'][] = '`isAI` = 1'; - } - else if($Flags['isAI'] === false) - { - $Query['whereAddition'][] = '`isAI` = 0'; - } - // > user is On Vacation - if($Flags['onVacation'] === true) - { - $Query['whereAddition'][] = '`is_onvacation` = 1'; - } - else if($Flags['onVacation'] === false) - { - $Query['whereAddition'][] = '`is_onvacation` = 0'; - } - // > user is Deleting his Account - if($Flags['inDeletion'] === true) - { - $Query['whereAddition'][] = '`is_ondeletion` = 1'; - } - else if($Flags['inDeletion'] === false) - { - $Query['whereAddition'][] = '`is_ondeletion` = 0'; - } - // > user is Banned - if($Flags['isBanned'] === true) - { - $Query['whereAddition'][] = '`is_banned` = 1'; - } - else if($Flags['isBanned'] === false) - { - $Query['whereAddition'][] = '`is_banned` = 0'; - } - // > user has Activated his Account - if($Flags['isActive'] === true) - { - $Query['whereAddition'][] = '`activation_code` = \'\''; - } - else if($Flags['isActive'] === false) - { - $Query['whereAddition'][] = '`activation_code` != \'\''; - } - // > user is in Any Ally - if(!in_array($Type, array('aid', 'astring', 'aname', 'atag'))) - { - if($Flags['inAlly'] === true) - { - $Query['whereAddition'][] = '(`ally_id` > 0 OR `ally_request` > 0)'; - } - elseif($Flags['inAlly'] === false) - { - $Query['whereAddition'][] = '(`ally_id` = 0 AND `ally_request` = 0)'; - } - } - // > user is Online (Active in last TIME_ONLINE seconds) - if($Flags['isOnline'] === true) - { - $Query['whereAddition'][] = '`onlinetime` >= (UNIX_TIMESTAMP() - '.TIME_ONLINE.')'; - } - else if($Flags['isOnline'] === false) - { - $Query['whereAddition'][] = '`onlinetime` < (UNIX_TIMESTAMP() - '.TIME_ONLINE.')'; - } - - // Prepare SQL Statement - if(empty($Query['whereAddition']) AND empty($Query['whereJoin']) AND empty($Query['whereData'])) - { - // Don't load any data here, we don't want to load whole table - return true; - } - - if(!empty($Query['whereAddition'])) - { - if(!empty($Query['whereAdditionAlias'])) - { - foreach($Query['whereAddition'] as &$Value) - { - $Value = preg_replace('#\`(.*?)\`#si', "`{$Query['whereAdditionAlias']}`.`$1`", $Value); - } - } - $Replacement = '('.implode(' AND ', $Query['whereAddition']).')'; - if(!empty($Query['whereJoin']) OR !empty($Query['whereData'])) - { - $Replacement = ' AND '.$Replacement; - } - else - { - $Replacement = ' WHERE '.$Replacement; - } - $Query['queryString'] = str_replace('{whereAddition}', $Replacement, $Query['queryString']); - } - else - { - $Query['queryString'] = str_replace('{whereAddition}', '', $Query['queryString']); - } - if(!empty($Query['whereJoin'])) - { - $Query['queryString'] = str_replace('{whereJoin}', $Query['whereJoin']($Query['whereData']), $Query['queryString']); - } - else - { - $Query['queryString'] = str_replace('{whereData}', (isset($Query['whereData']) ? $Query['whereData'] : null), $Query['queryString']); - } - - $Query['queryString'] = "SELECT {$Query['querySelect']} {$Query['queryString']}; -- FilterQuery"; - - $Result = doquery($Query['queryString'], $Query['queryTable']); - if(mysql_num_rows($Result) > 0) - { - $SelectArrayCount = count($Query['querySelectArray']); - $NeedValueCheck = ($SelectArrayCount > 1 ? true : false); - while($Data = mysql_fetch_assoc($Result)) - { - foreach($Query['querySelectArray'] AS $FieldName) - { - if($NeedValueCheck === true) - { - if($Data[$FieldName] <= 0) - { - continue; - } - } - $Return[] = $Data[$FieldName]; - } - } - if($NeedValueCheck === true) - { - $Return = array_unique($Return); - } - return $Return; - } - // Nothing found - return null; -} - -?> \ No newline at end of file + 0) + { + $Query['whereData'][] = $Value; + } + } + $Query['whereJoin'] = function($Array){ return implode(', ', $Array); }; + $Query['querySelect'] = 'id'; + $Query['querySelectArray'][] = 'id'; + $Query['queryString'] = "FROM {{table}} WHERE `id` IN ({whereJoin}) {whereAddition}"; + $Query['queryTable'] = 'users'; + } + else if($Type === 'uname') + { + $ThisRegexp = ($Flags['strict'] === true ? REGEXP_USERNAME_ABSOLUTE : REGEXP_USERNAME); + foreach($Search as $Value) + { + if(preg_match($ThisRegexp, $Value)) + { + $Query['whereData'][] = $Value; + } + } + if($Flags['strict'] === true) + { + $Query['whereJoin'] = function($Array) + { + foreach($Array as $Value) + { + $Return[] = "`username` = '{$Value}'"; + } + return implode(' OR ', $Return); + }; + } + else + { + $Query['whereJoin'] = function($Array) + { + foreach($Array as $Value) + { + $Value = preg_replace(REGEXP_SANITIZELIKE_SEARCH, REGEXP_SANITIZELIKE_REPLACE, $Value); + $Return[] = "`username` LIKE '%{$Value}%'"; + } + return implode(' OR ', $Return); + }; + } + $Query['querySelect'] = 'id'; + $Query['querySelectArray'][] = 'id'; + $Query['queryString'] = "FROM {{table}} WHERE ({whereJoin}) {whereAddition}"; + $Query['queryTable'] = 'users'; + } + else if($Type === 'aid') + { + foreach($Search as $Value) + { + $Value = intval($Value); + if($Value > 0) + { + $Query['whereData'][] = $Value; + } + } + $Query['whereJoin'] = function($Array){ return implode(', ', $Array); }; + $Query['querySelect'] = 'id'; + $Query['querySelectArray'][] = 'id'; + if($Flags['allyRequest'] === true) + { + $ThisWhere = "(`ally_request` IN ({whereJoin}))"; + } + else if($Flags['allyRequest'] === false) + { + $ThisWhere = "(`ally_id` IN ({whereJoin}))"; + } + else + { + $ThisWhere = "(`ally_id` IN ({whereJoin}) OR `ally_request` IN ({whereJoin}))"; + } + + $Query['queryString'] = "FROM {{table}} WHERE {$ThisWhere} {whereAddition}"; + $Query['queryTable'] = 'users'; + } + else if($Type === 'astring') + { + foreach($Search as $Value) + { + if(preg_match(REGEXP_ALLYNAMEANDTAG, $Value)) + { + $Query['whereData'][] = $Value; + } + } + $Query['whereJoin'] = function($Array) + { + foreach($Array as $Value) + { + $Value = preg_replace(REGEXP_SANITIZELIKE_SEARCH, REGEXP_SANITIZELIKE_REPLACE, $Value); + $Return[] = "`ally`.`ally_name` LIKE '%{$Value}%' OR `ally`.`ally_tag` LIKE '%{$Value}%'"; + } + return implode(' OR ', $Return); + }; + $Query['querySelect'] = '`users`.`id`'; + $Query['querySelectArray'][] = 'id'; + if($Flags['allyRequest'] === true) + { + $ThisJoin = "JOIN `{{prefix}}users` AS `users` ON `ally`.`id` = `users`.`ally_request`"; + } + else if($Flags['allyRequest'] === false) + { + $ThisJoin = "JOIN `{{prefix}}users` AS `users` ON `ally`.`id` = `users`.`ally_id`"; + } + else + { + $Query['querySelect'] = '`users1`.`id` AS `id1`, `users2`.`id` AS `id2`'; + $Query['querySelectArray'] = array('id1', 'id2'); + $ThisJoin = "LEFT JOIN `{{prefix}}users` AS `users1` ON `ally`.`id` = `users1`.`ally_id` "; + $ThisJoin .= "LEFT JOIN `{{prefix}}users` AS `users2` ON `ally`.`id` = `users2`.`ally_request` "; + } + $Query['queryString'] = "FROM {{table}} AS `ally` {$ThisJoin} WHERE ({whereJoin}) {whereAddition}"; + $Query['queryTable'] = 'alliance'; + $Query['whereAdditionAlias'] = 'users'; + } + else if($Type === 'aname') + { + $ThisRegexp = ($Flags['strict'] === true ? REGEXP_ALLYNAME_ABSOLUTE : REGEXP_ALLYNAMEANDTAG); + foreach($Search as $Value) + { + if(preg_match($ThisRegexp, $Value)) + { + $Query['whereData'][] = $Value; + } + } + if($Flags['strict'] === true) + { + $Query['whereJoin'] = function($Array) + { + foreach($Array as $Value) + { + $Return[] = "`ally`.`ally_name` = '{$Value}'"; + } + return implode(' OR ', $Return); + }; + } + else + { + $Query['whereJoin'] = function($Array) + { + foreach($Array as $Value) + { + $Value = preg_replace(REGEXP_SANITIZELIKE_SEARCH, REGEXP_SANITIZELIKE_REPLACE, $Value); + $Return[] = "`ally`.`ally_name` LIKE '%{$Value}%'"; + } + return implode(' OR ', $Return); + }; + } + $Query['querySelect'] = '`users`.`id`'; + $Query['querySelectArray'][] = 'id'; + if($Flags['allyRequest'] === true) + { + $ThisJoin = "JOIN `{{prefix}}users` AS `users` ON `ally`.`id` = `users`.`ally_request`"; + } + else if($Flags['allyRequest'] === false) + { + $ThisJoin = "JOIN `{{prefix}}users` AS `users` ON `ally`.`id` = `users`.`ally_id`"; + } + else + { + $Query['querySelect'] = '`users1`.`id` AS `id1`, `users2`.`id` AS `id2`'; + $Query['querySelectArray'] = array('id1', 'id2'); + $ThisJoin = "LEFT JOIN `{{prefix}}users` AS `users1` ON `ally`.`id` = `users1`.`ally_id` "; + $ThisJoin .= "LEFT JOIN `{{prefix}}users` AS `users2` ON `ally`.`id` = `users2`.`ally_request` "; + } + $Query['queryString'] = "FROM {{table}} AS `ally` {$ThisJoin} WHERE ({whereJoin}) {whereAddition}"; + $Query['queryTable'] = 'alliance'; + $Query['whereAdditionAlias'] = 'users'; + } + else if($Type === 'atag') + { + $ThisRegexp = ($Flags['strict'] === true ? REGEXP_ALLYTAG_ABSOLUTE : REGEXP_ALLYTAG); + foreach($Search as $Value) + { + if(preg_match($ThisRegexp, $Value)) + { + $Query['whereData'][] = $Value; + } + } + if($Flags['strict'] === true) + { + $Query['whereJoin'] = function($Array) + { + foreach($Array as $Value) + { + $Return[] = "`ally`.`ally_tag` = '{$Value}'"; + } + return implode(' OR ', $Return); + }; + } + else + { + $Query['whereJoin'] = function($Array) + { + foreach($Array as $Value) + { + $Value = preg_replace(REGEXP_SANITIZELIKE_SEARCH, REGEXP_SANITIZELIKE_REPLACE, $Value); + $Return[] = "`ally`.`ally_tag` LIKE '%{$Value}%'"; + } + return implode(' OR ', $Return); + }; + } + $Query['querySelect'] = '`users`.`id`'; + $Query['querySelectArray'][] = 'id'; + if($Flags['allyRequest'] === true) + { + $ThisJoin = "JOIN `{{prefix}}users` AS `users` ON `ally`.`id` = `users`.`ally_request`"; + } + else if($Flags['allyRequest'] === false) + { + $ThisJoin = "JOIN `{{prefix}}users` AS `users` ON `ally`.`id` = `users`.`ally_id`"; + } + else + { + $Query['querySelect'] = '`users1`.`id` AS `id1`, `users2`.`id` AS `id2`'; + $Query['querySelectArray'] = array('id1', 'id2'); + $ThisJoin = "LEFT JOIN `{{prefix}}users` AS `users1` ON `ally`.`id` = `users1`.`ally_id` "; + $ThisJoin .= "LEFT JOIN `{{prefix}}users` AS `users2` ON `ally`.`id` = `users2`.`ally_request` "; + } + $Query['queryString'] = "FROM {{table}} AS `ally` {$ThisJoin} WHERE ({whereJoin}) {whereAddition}"; + $Query['queryTable'] = 'alliance'; + $Query['whereAdditionAlias'] = 'users'; + } + else if($Type === 'ipid') + { + foreach($Search as $Value) + { + $Value = round($Value); + if($Value > 0) + { + $Query['whereData'][] = $Value; + } + } + $Query['whereJoin'] = function($Array){ return implode(', ', $Array); }; + $Query['querySelect'] = '`users`.`id`'; + $Query['querySelectArray'][] = 'id'; + $Query['queryString'] = "FROM {{table}} AS `enterlog` JOIN `{{prefix}}users` AS `users` ON `users`.`id` = `enterlog`.`User_ID` WHERE `enterlog`.`IP_ID` IN ({whereJoin}) {whereAddition}"; + $Query['queryTable'] = 'user_enterlog'; + $Query['whereAdditionAlias'] = 'users'; + } + else if($Type === 'ipstring') + { + foreach($Search as $Value) + { + if(preg_match(REGEXP_IP, $Value)) + { + $Query['whereData'][] = $Value; + } + } + if($Flags['utableOnly'] === true) + { + if($Flags['strict'] === true) + { + $Query['whereJoin'] = function($Array) + { + foreach($Array as $Value) + { + $Return[] = "`user_lastip` = '{$Value}' OR `ip_at_reg` = '{$Value}'"; + } + return implode(' OR ', $Return); + }; + } + else + { + $Query['whereJoin'] = function($Array) + { + foreach($Array as $Value) + { + $Value = preg_replace(REGEXP_SANITIZELIKE_SEARCH, REGEXP_SANITIZELIKE_REPLACE, $Value); + $Return[] = "`user_lastip` LIKE '%{$Value}%' OR `ip_at_reg` LIKE '%{$Value}%'"; + } + return implode(' OR ', $Return); + }; + } + $Query['querySelect'] = 'id'; + $Query['querySelectArray'][] = 'id'; + $Query['queryString'] = "FROM {{table}} WHERE ({whereJoin}) {whereAddition}"; + $Query['queryTable'] = 'users'; + } + else + { + if($Flags['strict'] === true) + { + $Query['whereJoin'] = function($Array) + { + foreach($Array as $Value) + { + $Value = md5($Value); + $Return[] = "`iptable`.`ValueHash` = '{$Value}'"; + } + return implode(' OR ', $Return); + }; + } + else + { + $Query['whereJoin'] = function($Array) + { + foreach($Array as $Value) + { + $Value = preg_replace(REGEXP_SANITIZELIKE_SEARCH, REGEXP_SANITIZELIKE_REPLACE, $Value); + $Return[] = "`iptable`.`Value` LIKE '%{$Value}%'"; + } + return implode(' OR ', $Return); + }; + } + $Query['querySelect'] = '`users`.`id`'; + $Query['querySelectArray'][] = 'id'; + $Query['queryString'] = "FROM {{table}} AS `iptable` LEFT JOIN `{{prefix}}user_enterlog` AS `enterlog` ON `enterlog`.`IP_ID` = `iptable`.`ID` JOIN `{{prefix}}users` AS `users` ON `enterlog`.`User_ID` = `users`.`id` WHERE (`iptable`.`Type` = 'ip' AND ({whereJoin})) {whereAddition} GROUP BY `User_ID`"; + $Query['queryTable'] = 'used_ip_and_ua'; + $Query['whereAdditionAlias'] = 'users'; + } + } + else if($Type === 'umail') + { + $ThisRegexp = ($Flags['strict'] === true ? REGEXP_EMAIL_SIGNS : REGEXP_EMAIL_SIGNS); + foreach($Search as $Value) + { + if(preg_match($ThisRegexp, $Value)) + { + $Query['whereData'][] = $Value; + } + } + if($Flags['strict'] === true) + { + $Query['whereJoin'] = function($Array) + { + foreach($Array as $Value) + { + $Return[] = "`email` = '{$Value}' OR `email_2` = '{$Value}'"; + } + return implode(' OR ', $Return); + }; + } + else + { + $Query['whereJoin'] = function($Array) + { + foreach($Array as $Value) + { + $Value = preg_replace(REGEXP_SANITIZELIKE_SEARCH, REGEXP_SANITIZELIKE_REPLACE, $Value); + $Return[] = "`email` LIKE '%{$Value}%' OR `email_2` LIKE '%{$Value}%'"; + } + return implode(' OR ', $Return); + }; + } + $Query['querySelect'] = 'id'; + $Query['querySelectArray'][] = 'id'; + $Query['queryString'] = "FROM {{table}} WHERE ({whereJoin}) {whereAddition}"; + $Query['queryTable'] = 'users'; + } + } + else + { + // WHERE Statement is unnecessary + $Query['querySelect'] = 'id'; + $Query['querySelectArray'][] = 'id'; + $Query['queryString'] = "FROM {{table}} {whereAddition}"; + $Query['queryTable'] = 'users'; + } + + // Check, if we can go further + if(!empty($Search) && empty($Query['whereData'])) + { + // All given data was rejected + return false; + } + + // Additional Flags + // > user is an Artificial Intelligence (AI) + if($Flags['isAI'] === true) + { + $Query['whereAddition'][] = '`isAI` = 1'; + } + else if($Flags['isAI'] === false) + { + $Query['whereAddition'][] = '`isAI` = 0'; + } + // > user is On Vacation + if($Flags['onVacation'] === true) + { + $Query['whereAddition'][] = '`is_onvacation` = 1'; + } + else if($Flags['onVacation'] === false) + { + $Query['whereAddition'][] = '`is_onvacation` = 0'; + } + // > user is Deleting his Account + if($Flags['inDeletion'] === true) + { + $Query['whereAddition'][] = '`is_ondeletion` = 1'; + } + else if($Flags['inDeletion'] === false) + { + $Query['whereAddition'][] = '`is_ondeletion` = 0'; + } + // > user is Banned + if($Flags['isBanned'] === true) + { + $Query['whereAddition'][] = '`is_banned` = 1'; + } + else if($Flags['isBanned'] === false) + { + $Query['whereAddition'][] = '`is_banned` = 0'; + } + // > user has Activated his Account + if($Flags['isActive'] === true) + { + $Query['whereAddition'][] = '`activation_code` = \'\''; + } + else if($Flags['isActive'] === false) + { + $Query['whereAddition'][] = '`activation_code` != \'\''; + } + // > user is in Any Ally + if(!in_array($Type, array('aid', 'astring', 'aname', 'atag'))) + { + if($Flags['inAlly'] === true) + { + $Query['whereAddition'][] = '(`ally_id` > 0 OR `ally_request` > 0)'; + } + elseif($Flags['inAlly'] === false) + { + $Query['whereAddition'][] = '(`ally_id` = 0 AND `ally_request` = 0)'; + } + } + // > user is Online (Active in last TIME_ONLINE seconds) + if($Flags['isOnline'] === true) + { + $Query['whereAddition'][] = '`onlinetime` >= (UNIX_TIMESTAMP() - '.TIME_ONLINE.')'; + } + else if($Flags['isOnline'] === false) + { + $Query['whereAddition'][] = '`onlinetime` < (UNIX_TIMESTAMP() - '.TIME_ONLINE.')'; + } + + // Prepare SQL Statement + if(empty($Query['whereAddition']) AND empty($Query['whereJoin']) AND empty($Query['whereData'])) + { + // Don't load any data here, we don't want to load whole table + return true; + } + + if(!empty($Query['whereAddition'])) + { + if(!empty($Query['whereAdditionAlias'])) + { + foreach($Query['whereAddition'] as &$Value) + { + $Value = preg_replace('#\`(.*?)\`#si', "`{$Query['whereAdditionAlias']}`.`$1`", $Value); + } + } + $Replacement = '('.implode(' AND ', $Query['whereAddition']).')'; + if(!empty($Query['whereJoin']) OR !empty($Query['whereData'])) + { + $Replacement = ' AND '.$Replacement; + } + else + { + $Replacement = ' WHERE '.$Replacement; + } + $Query['queryString'] = str_replace('{whereAddition}', $Replacement, $Query['queryString']); + } + else + { + $Query['queryString'] = str_replace('{whereAddition}', '', $Query['queryString']); + } + if(!empty($Query['whereJoin'])) + { + $Query['queryString'] = str_replace('{whereJoin}', $Query['whereJoin']($Query['whereData']), $Query['queryString']); + } + else + { + $Query['queryString'] = str_replace('{whereData}', (isset($Query['whereData']) ? $Query['whereData'] : null), $Query['queryString']); + } + + $Query['queryString'] = "SELECT {$Query['querySelect']} {$Query['queryString']}; -- FilterQuery"; + + $Result = doquery($Query['queryString'], $Query['queryTable']); + if(mysql_num_rows($Result) > 0) + { + $SelectArrayCount = count($Query['querySelectArray']); + $NeedValueCheck = ($SelectArrayCount > 1 ? true : false); + while($Data = mysql_fetch_assoc($Result)) + { + foreach($Query['querySelectArray'] AS $FieldName) + { + if($NeedValueCheck === true) + { + if($Data[$FieldName] <= 0) + { + continue; + } + } + $Return[] = $Data[$FieldName]; + } + } + if($NeedValueCheck === true) + { + $Return = array_unique($Return); + } + return $Return; + } + // Nothing found + return null; +} + +?> diff --git a/includes/functions/FleetBuildingPage.php b/includes/functions/FleetBuildingPage.php index f69c96b7f..4913578dd 100644 --- a/includes/functions/FleetBuildingPage.php +++ b/includes/functions/FleetBuildingPage.php @@ -1,196 +1,196 @@ - $Count) - { - $Element = intval($Element); - $Count = floor(floatval(str_replace('.', '', $Count))); - if(in_array($Element, $_Vars_ElementCategories['fleet'])) - { - if($Count > 0) - { - if($Count > $QueueSize) - { - $Count = $QueueSize; - } - // Check if this Ship is Accessible (Tech) - if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $Element)) - { - // Check Max Constructible Element Count - $MaxElements = GetMaxConstructibleElements($Element, $CurrentPlanet); - if($Count > $MaxElements) - { - $Count = $MaxElements; - } - - $Ressource = GetElementRessources($Element, $Count); - if($Count > 0) - { - $AddedSomething = true; - - if(!isset($UpdateAchievements[$Element])) - { - $UpdateAchievements[$Element] = 0; - } - $UpdateAchievements[$Element] += $Count; - $addToBHangar = "{$Element},{$Count};"; - $CurrentPlanet['metal'] -= $Ressource['metal']; - $CurrentPlanet['crystal'] -= $Ressource['crystal']; - $CurrentPlanet['deuterium'] -= $Ressource['deuterium']; - $CurrentPlanet['shipyardQueue'] .= $addToBHangar; - - $DevLog_Array[] = "{$Element},{$Count}"; - } - } - } - } - } - - if($AddedSomething) - { - // Update Achievements - foreach($UpdateAchievements as $Key => $Value) - { - $QryAchievementsKey[] = "`build_{$Key}`"; - $QryAchievementsArr[] = "`build_{$Key}` = `build_{$Key}` + VALUES(`build_{$Key}`)"; - } - $QryAchievements = "INSERT INTO {{table}} (`A_UserID`, ".implode(', ', $QryAchievementsKey).") VALUES ({$CurrentUser['id']}, ".implode(', ', $UpdateAchievements).")"; - $QryAchievements .= " ON DUPLICATE KEY UPDATE "; - $QryAchievements .= implode(', ', $QryAchievementsArr); - $QryAchievements .= ';'; - doquery($QryAchievements, 'achievements_stats'); - - // Update DevLog - $UserDev_Log[] = array('PlanetID' => $CurrentPlanet['id'], 'Date' => $Now, 'Place' => 6, 'Code' => '0', 'ElementID' => '0', 'AdditionalData' => implode(';', $DevLog_Array)); - } - } - } - } - - $TabIndex = 0; - - $ElementRowTPL = gettemplate('buildings_fleet_row'); - $ElementRowInputTPL = gettemplate('buildings_fleet_row_input'); - - $PageTable = ''; - foreach($_Vars_ElementCategories['fleet'] as $Element) - { - $Row = array(); - - $Row['Element'] = $Element; - $Row['skinpath'] = $_SkinPath; - $Row['ElementName'] = $_Lang['tech'][$Element]; - $ElementCount = $CurrentPlanet[$_Vars_GameElements[$Element]]; - $Row['ElementNbre'] = ($ElementCount == 0) ? '' : " ({$_Lang['dispo']}: " . prettyNumber($ElementCount) . ")"; - $Row['Description'] = $_Lang['res']['descriptions'][$Element]; - if($Element == 212) - { - $BuildLevelFactor = 10; - $BuildLevel = 1; - $BuildTemp = $CurrentPlanet['temp_max']; - $Row['SateliteInfo'] = '
    '.sprintf($_Lang['SatelitesEnergy'], prettyNumber(floor(eval($_Vars_ResProduction[$Element]['formule']['energy'])))); - } - - if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $Element)) - { - $CanBuildOne = IsElementBuyable($CurrentUser, $CurrentPlanet, $Element, false); - $BuildOneElementTime = GetBuildingTime($CurrentUser, $CurrentPlanet, $Element); - - $Row['GetElementPrice'] = GetElementPrice($CurrentUser, $CurrentPlanet, $Element, false); - $Row['ShowBuildTime'] = ShowBuildTime($BuildOneElementTime); - - if(isOnVacation($CurrentUser)) - { - $CanBuildOne = false; - } - - if($CanBuildOne) - { - $Row['InputData'] = array(); - $TabIndex += 1; - $MaxElements = GetMaxConstructibleElements($Element, $CurrentPlanet); - - $Row['InputData']['youCanBuild'] = $_Lang['youCanBuild']; - $Row['InputData']['MaxElements'] = prettyNumber($MaxElements); - $Row['InputData']['Element'] = $Element; - $Row['InputData']['ElementName'] = $Row['ElementName']; - $Row['InputData']['TabIndex'] = $TabIndex; - $Row['InputData']['Max'] = $_Lang['max']; - - $Row['Input'] = parsetemplate($ElementRowInputTPL, $Row['InputData']); - } - else - { - $Row['Input'] = ' '; - if(isOnVacation($CurrentUser)) - { - $Row['Input'] = ''.$_Lang['ListBox_Disallow_VacationMode'].''; - } - } - } - else - { - if($CurrentUser['settings_ExpandedBuildView'] == 0) - { - continue; - } - $Row['Input'] = ' '; - $Row['TechRequirementsPlace'] = GetElementTechReq($CurrentUser, $CurrentPlanet, $Element); - } - - $PageTable .= parsetemplate($ElementRowTPL, $Row); - } - - $BuildQueue = ''; - if($CurrentPlanet['shipyardQueue'] != '') - { - include($_EnginePath.'includes/functions/ElementBuildListBox.php'); - $BuildQueue = ElementBuildListBox($CurrentUser, $CurrentPlanet); - } - - $parse = $_Lang; - - $parse['buildlist'] = $PageTable; - $parse['buildinglist'] = $BuildQueue; - $parse['QueueSize'] = $QueueSize; - - display(parsetemplate(gettemplate('buildings_fleet'), $parse), $_Lang['Hangar']); -} - -?> \ No newline at end of file + $Count) + { + $Element = intval($Element); + $Count = floor(floatval(str_replace('.', '', $Count))); + if(in_array($Element, $_Vars_ElementCategories['fleet'])) + { + if($Count > 0) + { + if($Count > $QueueSize) + { + $Count = $QueueSize; + } + // Check if this Ship is Accessible (Tech) + if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $Element)) + { + // Check Max Constructible Element Count + $MaxElements = GetMaxConstructibleElements($Element, $CurrentPlanet); + if($Count > $MaxElements) + { + $Count = $MaxElements; + } + + $Ressource = GetElementRessources($Element, $Count); + if($Count > 0) + { + $AddedSomething = true; + + if(!isset($UpdateAchievements[$Element])) + { + $UpdateAchievements[$Element] = 0; + } + $UpdateAchievements[$Element] += $Count; + $addToBHangar = "{$Element},{$Count};"; + $CurrentPlanet['metal'] -= $Ressource['metal']; + $CurrentPlanet['crystal'] -= $Ressource['crystal']; + $CurrentPlanet['deuterium'] -= $Ressource['deuterium']; + $CurrentPlanet['shipyardQueue'] .= $addToBHangar; + + $DevLog_Array[] = "{$Element},{$Count}"; + } + } + } + } + } + + if($AddedSomething) + { + // Update Achievements + foreach($UpdateAchievements as $Key => $Value) + { + $QryAchievementsKey[] = "`build_{$Key}`"; + $QryAchievementsArr[] = "`build_{$Key}` = `build_{$Key}` + VALUES(`build_{$Key}`)"; + } + $QryAchievements = "INSERT INTO {{table}} (`A_UserID`, ".implode(', ', $QryAchievementsKey).") VALUES ({$CurrentUser['id']}, ".implode(', ', $UpdateAchievements).")"; + $QryAchievements .= " ON DUPLICATE KEY UPDATE "; + $QryAchievements .= implode(', ', $QryAchievementsArr); + $QryAchievements .= ';'; + doquery($QryAchievements, 'achievements_stats'); + + // Update DevLog + $UserDev_Log[] = array('PlanetID' => $CurrentPlanet['id'], 'Date' => $Now, 'Place' => 6, 'Code' => '0', 'ElementID' => '0', 'AdditionalData' => implode(';', $DevLog_Array)); + } + } + } + } + + $TabIndex = 0; + + $ElementRowTPL = gettemplate('buildings_fleet_row'); + $ElementRowInputTPL = gettemplate('buildings_fleet_row_input'); + + $PageTable = ''; + foreach($_Vars_ElementCategories['fleet'] as $Element) + { + $Row = array(); + + $Row['Element'] = $Element; + $Row['skinpath'] = $_SkinPath; + $Row['ElementName'] = $_Lang['tech'][$Element]; + $ElementCount = $CurrentPlanet[$_Vars_GameElements[$Element]]; + $Row['ElementNbre'] = ($ElementCount == 0) ? '' : " ({$_Lang['dispo']}: " . prettyNumber($ElementCount) . ")"; + $Row['Description'] = $_Lang['res']['descriptions'][$Element]; + if($Element == 212) + { + $BuildLevelFactor = 10; + $BuildLevel = 1; + $BuildTemp = $CurrentPlanet['temp_max']; + $Row['SateliteInfo'] = '
    '.sprintf($_Lang['SatelitesEnergy'], prettyNumber(floor(eval($_Vars_ResProduction[$Element]['formule']['energy'])))); + } + + if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $Element)) + { + $CanBuildOne = IsElementBuyable($CurrentUser, $CurrentPlanet, $Element, false); + $BuildOneElementTime = GetBuildingTime($CurrentUser, $CurrentPlanet, $Element); + + $Row['GetElementPrice'] = GetElementPrice($CurrentUser, $CurrentPlanet, $Element, false); + $Row['ShowBuildTime'] = ShowBuildTime($BuildOneElementTime); + + if(isOnVacation($CurrentUser)) + { + $CanBuildOne = false; + } + + if($CanBuildOne) + { + $Row['InputData'] = array(); + $TabIndex += 1; + $MaxElements = GetMaxConstructibleElements($Element, $CurrentPlanet); + + $Row['InputData']['youCanBuild'] = $_Lang['youCanBuild']; + $Row['InputData']['MaxElements'] = prettyNumber($MaxElements); + $Row['InputData']['Element'] = $Element; + $Row['InputData']['ElementName'] = $Row['ElementName']; + $Row['InputData']['TabIndex'] = $TabIndex; + $Row['InputData']['Max'] = $_Lang['max']; + + $Row['Input'] = parsetemplate($ElementRowInputTPL, $Row['InputData']); + } + else + { + $Row['Input'] = ' '; + if(isOnVacation($CurrentUser)) + { + $Row['Input'] = ''.$_Lang['ListBox_Disallow_VacationMode'].''; + } + } + } + else + { + if($CurrentUser['settings_ExpandedBuildView'] == 0) + { + continue; + } + $Row['Input'] = ' '; + $Row['TechRequirementsPlace'] = GetElementTechReq($CurrentUser, $CurrentPlanet, $Element); + } + + $PageTable .= parsetemplate($ElementRowTPL, $Row); + } + + $BuildQueue = ''; + if($CurrentPlanet['shipyardQueue'] != '') + { + include($_EnginePath.'includes/functions/ElementBuildListBox.php'); + $BuildQueue = ElementBuildListBox($CurrentUser, $CurrentPlanet); + } + + $parse = $_Lang; + + $parse['buildlist'] = $PageTable; + $parse['buildinglist'] = $BuildQueue; + $parse['QueueSize'] = $QueueSize; + + display(parsetemplate(gettemplate('buildings_fleet'), $parse), $_Lang['Hangar']); +} + +?> diff --git a/includes/functions/FleetControl_Retreat.php b/includes/functions/FleetControl_Retreat.php index 22cc7c5bd..e33cd8ea3 100644 --- a/includes/functions/FleetControl_Retreat.php +++ b/includes/functions/FleetControl_Retreat.php @@ -1,431 +1,431 @@ - 0) - { - // Parse Fleets - while($Fleet = mysql_fetch_assoc($SelectFleets)) - { - if($Fleet['fleet_mission'] == 10) - { - // Rockets can't be retreated - $Return['Errors'][$Fleet['fleet_id']] = 1; - continue; - } - if($Fleet['fleet_mess'] == 0) - { - $Return['Types'][$Fleet['fleet_id']] = 1; - $UpdateFleets[$Fleet['fleet_id']] = array - ( - 'fleet_id' => $Fleet['fleet_id'], - 'fleet_start_time' => "{$UnixTS} - 1", - 'fleet_end_stay' => '0', - 'fleet_end_time' => ($InstandRetreat ? $UnixTS : "(2 * {$UnixTS}) - {$Fleet['fleet_send_time']} + 1"), - 'fleet_target_owner' => $Fleet['fleet_owner'], - 'fleet_mess' => 1, - ); - $UpdateArchive[$Fleet['fleet_id']] = array - ( - 'Fleet_ID' => $Fleet['fleet_id'], - 'Fleet_TurnedBack' => 'true', - 'Fleet_TurnedBack_Time' => $UnixTS, - 'Fleet_TurnedBack_EndTime' => ($InstandRetreat ? $UnixTS : "(2 * {$UnixTS}) - {$Fleet['fleet_send_time']} + 1"), - ); - if($Fleet['fleet_mission'] == 5) - { - $UpdateFleets[$Fleet['fleet_id']]['fleet_mess'] = 2; - } - if($Fleet['fleet_mission'] == 2) - { - $UpdateFleets[$Fleet['fleet_id']]['fleet_mission'] = 1; - $UpdateArchive[$Fleet['fleet_id']]['Fleet_Mission_Changed'] = 'true'; - - $GetACSDataBy[] = $Fleet['fleet_id']; - $FleetsOwners[$Fleet['fleet_id']] = $Fleet['fleet_owner']; - } - else - { - if(!empty($Fleet['fleets_id'])) - { - $ExplodeFleets = explode(',', str_replace('|', '', $Fleet['fleets_id'])); - foreach($ExplodeFleets as $FleetID) - { - if($FleetID > 0) - { - $Return['Types'][$FleetID] = 5; - $UpdateFleets[$FleetID] = array - ( - 'fleet_id' => $FleetID, - 'fleet_start_time' => "{$UnixTS} - 1", - 'fleet_end_stay' => '0', - 'fleet_end_time' => ($InstandRetreat ? $UnixTS : '0'), - 'fleet_target_owner' => $Fleet['fleet_owner'], - 'fleet_mess' => 1, - 'fleet_mission' => 1, - ); - $UpdateArchive[$FleetID] = array - ( - 'Fleet_ID' => $FleetID, - 'Fleet_TurnedBack' => 'true', - 'Fleet_TurnedBack_Time' => $UnixTS, - 'Fleet_TurnedBack_EndTime' => ($InstandRetreat ? $UnixTS : '0'), - 'Fleet_Mission_Changed' => 'true', - ); - } - } - $DeleteACS[] = $Fleet['fleet_id']; - } - } - } - else if($Fleet['fleet_mess'] == 1) - { - if($Fleet['fleet_mission'] == 5 && $Fleet['fleet_end_stay'] > $Now) - { - $Return['Types'][$Fleet['fleet_id']] = 2; - $UpdateFleets[$Fleet['fleet_id']] = array - ( - 'fleet_id' => $Fleet['fleet_id'], - 'fleet_end_stay' => $UnixTS, - 'fleet_end_time' => ($InstandRetreat ? $UnixTS : "{$UnixTS} + ({$Fleet['fleet_start_time']} - {$Fleet['fleet_send_time']}) + 1"), - 'fleet_mess' => 2, - ); - $UpdateArchive[$Fleet['fleet_id']] = array - ( - 'Fleet_ID' => $Fleet['fleet_id'], - 'Fleet_TurnedBack' => 'true', - 'Fleet_TurnedBack_Time' => $UnixTS, - 'Fleet_TurnedBack_EndTime' => ($InstandRetreat ? $UnixTS : "{$UnixTS} + ({$Fleet['fleet_start_time']} - {$Fleet['fleet_send_time']}) + 1"), - ); - } - else - { - if($InstandRetreat) - { - $Return['Types'][$Fleet['fleet_id']] = 3; - $UpdateFleets[$Fleet['fleet_id']] = array - ( - 'fleet_id' => $Fleet['fleet_id'], - 'fleet_end_time' => $UnixTS, - 'fleet_mess' => 2, - ); - $UpdateArchive[$Fleet['fleet_id']] = array - ( - 'Fleet_ID' => $Fleet['fleet_id'], - 'Fleet_TurnedBack' => 'true', - 'Fleet_TurnedBack_Time' => $UnixTS, - 'Fleet_TurnedBack_EndTime' => $UnixTS, - ); - if($Fleet['fleet_mission'] == 5) - { - $UpdateFleets[$Fleet['fleet_id']]['fleet_end_stay'] = $UnixTS; - $UpdateFleets[$Fleet['fleet_id']]['fleet_mess'] = 2; - } - } - else - { - $Return['Errors'][$Fleet['fleet_id']] = 2; - } - } - } - else if($Fleet['fleet_mess'] == 2) - { - if($InstandRetreat) - { - $Return['Types'][$Fleet['fleet_id']] = 4; - $UpdateFleets[$Fleet['fleet_id']] = array - ( - 'fleet_id' => $Fleet['fleet_id'], - 'fleet_end_stay' => $Fleet['fleet_end_stay'], - 'fleet_end_time' => $UnixTS, - ); - $UpdateArchive[$Fleet['fleet_id']] = array - ( - 'Fleet_ID' => $Fleet['fleet_id'], - 'Fleet_TurnedBack' => 'true', - 'Fleet_TurnedBack_Time' => $UnixTS, - 'Fleet_TurnedBack_EndTime' => $UnixTS, - ); - } - else - { - $Return['Errors'][$Fleet['fleet_id']] = 2; - } - } - } - - // Check if some ACS needs Update - if(!empty($GetACSDataBy)) - { - foreach($GetACSDataBy as $FleetID) - { - $GetACSWhere[] = "`fleets_id` LIKE '%|{$FleetID}|%'"; - } - $Query_SelectACS = "SELECT `id`, `fleets_id`, `user_joined`, `main_fleet_id` FROM {{table}} WHERE ".implode(' OR ', $GetACSWhere).";"; - $SelectACS = doquery($Query_SelectACS, 'acs'); - if(mysql_num_rows($SelectACS) > 0) - { - while($ACS = mysql_fetch_assoc($SelectACS)) - { - if(in_array($ACS['main_fleet_id'], $DeleteACS)) - { - continue; - } - $ParsedFleets = $ParsedUsers = array(); - $TempFleets = explode(',', str_replace('|', '', $ACS['fleets_id'])); - $TempUsers = explode(',', str_replace('|', '', $ACS['user_joined'])); - foreach($TempFleets as $ElementID) - { - if($ElementID > 0) - { - $ACSFleetsMap[$ElementID] = $ACS['id']; - $ParsedFleets[$ElementID] = $ElementID; - } - } - foreach($TempUsers as $ElementID) - { - if($ElementID > 0) - { - $ParsedUsers[$ElementID] = $ElementID; - } - } - - $ACSData[$ACS['id']] = array('id' => $ACS['id'], 'fleets_id' => $ParsedFleets, 'fleets_count' => count($ParsedFleets), 'user_joined' => $ParsedUsers, 'users_count' => count($ParsedUsers)); - if($ACSData[$ACS['id']]['fleets_count'] > 1 && $ACSData[$ACS['id']]['users_count'] > 1) - { - foreach($ParsedFleets as $FleetID) - { - if(!($FleetsOwners[$FleetID] > 0)) - { - $GetFleetOwners[$FleetID] = $FleetID; - } - } - } - } - if(!empty($GetFleetOwners)) - { - $Query_SelectFleetOwners = "SELECT `fleet_id`, `fleet_owner` FROM {{table}} WHERE `fleet_id` IN (".implode(', ', $GetFleetOwners).");"; - $SelectFleetOwners = doquery($Query_SelectFleetOwners, 'fleets'); - while($Owners = mysql_fetch_assoc($SelectFleetOwners)) - { - $FleetsOwners[$Owners['fleet_id']] = $Owners['fleet_owner']; - } - } - - foreach($GetACSDataBy as $FleetID) - { - $ACSPointer = &$ACSData[$ACSFleetsMap[$FleetID]]; - if(empty($ACSPointer)) - { - continue; - } - if($ACSPointer['fleets_count'] == 1) - { - $UpdateACS[$ACSPointer['id']] = array - ( - 'id' => $ACSPointer['id'], - 'fleets_id' => array(), - 'user_joined' => array(), - 'fleets_count' => '0', - ); - $ACSPointer['fleets_id'] = array(); - $ACSPointer['fleets_count'] = 0; - } - else - { - unset($ACSPointer['fleets_id'][$FleetID]); - if($ACSPointer['users_count'] == 1) - { - if(empty($UpdateACS[$ACSPointer['id']])) - { - $UpdateACS[$ACSPointer['id']] = array - ( - 'id' => $ACSPointer['id'], - 'fleets_id' => $ACSPointer['fleets_id'], - 'fleets_count' => $ACSPointer['fleets_count'] - 1, - ); - } - else - { - $UpdateACS[$ACSPointer['id']]['fleets_id'] = $ACSPointer['fleets_id']; - $UpdateACS[$ACSPointer['id']]['fleets_count'] -= 1; - } - $ACSPointer['fleets_count'] -= 1; - } - else - { - $OwnerFound = false; - foreach($ACSPointer['fleets_id'] as $FleetID2) - { - if($FleetsOwners[$FleetID2] == $FleetsOwners[$FleetID]) - { - $OwnerFound = true; - break; - } - } - if(empty($UpdateACS[$ACSPointer['id']])) - { - $UpdateACS[$ACSPointer['id']] = array - ( - 'id' => $ACSPointer['id'], - 'fleets_id' => $ACSPointer['fleets_id'], - 'fleets_count' => $ACSPointer['fleets_count'] - 1, - ); - } - else - { - $UpdateACS[$ACSPointer['id']]['fleets_id'] = $ACSPointer['fleets_id']; - $UpdateACS[$ACSPointer['id']]['fleets_count'] -= 1; - } - $ACSPointer['fleets_count'] -= 1; - if($OwnerFound !== true) - { - unset($ACSPointer['user_joined'][$FleetsOwners[$FleetID]]); - $UpdateACS[$ACSPointer['id']]['user_joined'] = $ACSPointer['user_joined']; - $ACSPointer['users_count'] -= 1; - } - } - } - } - } - } - - // Make Updates - if(!empty($UpdateFleets)) - { - $Query_UpdateFleets = "INSERT INTO {{table}} (`fleet_id`, `fleet_start_time`, `fleet_end_stay`, `fleet_end_time`, `fleet_target_owner`, `fleet_mess`, `fleet_mission`) VALUES "; - $Pattern_UpdateFleets = array('fleet_id' => null, 'fleet_start_time' => null, 'fleet_end_stay' => null, 'fleet_end_time' => null, 'fleet_target_owner' => null, 'fleet_mess' => null, 'fleet_mission' => null); - foreach($UpdateFleets as $Data) - { - $Data = array_merge($Pattern_UpdateFleets, $Data); - foreach($Data as &$Values) - { - if($Values === null) - { - $Values = '"!nupd!"'; - } - } - $Array_UpdateFleets[] = "({$Data['fleet_id']}, {$Data['fleet_start_time']}, {$Data['fleet_end_stay']}, {$Data['fleet_end_time']}, {$Data['fleet_target_owner']}, {$Data['fleet_mess']}, {$Data['fleet_mission']})"; - } - $Query_UpdateFleets .= implode(', ', $Array_UpdateFleets); - $Query_UpdateFleets .= " ON DUPLICATE KEY UPDATE "; - $Query_UpdateFleets .= "`fleet_start_time` = IF(VALUES(`fleet_start_time`) = \"!nupd!\", `fleet_start_time`, VALUES(`fleet_start_time`)), "; - $Query_UpdateFleets .= "`fleet_end_stay` = IF(VALUES(`fleet_end_stay`) > 0, VALUES(`fleet_end_stay`), 0), "; - $Query_UpdateFleets .= "`fleet_end_time` = IF(VALUES(`fleet_end_time`) > 0, VALUES(`fleet_end_time`), (2 * UNIX_TIMESTAMP()) - `fleet_send_time` + 1), "; - $Query_UpdateFleets .= "`fleet_target_owner` = IF(VALUES(`fleet_target_owner`) = \"!nupd!\", `fleet_target_owner`, VALUES(`fleet_target_owner`)), "; - $Query_UpdateFleets .= "`fleet_mess` = IF(VALUES(`fleet_mess`) = \"!nupd!\", `fleet_mess`, VALUES(`fleet_mess`)), "; - $Query_UpdateFleets .= "`fleet_mission` = IF(VALUES(`fleet_mission`) = \"!nupd!\", `fleet_mission`, VALUES(`fleet_mission`));"; - doquery($Query_UpdateFleets, 'fleets'); - - $Return['Updates']['Fleets'] = count($UpdateFleets); - } - if(!empty($UpdateArchive)) - { - $Query_UpdateArchive= "INSERT INTO {{table}} (`Fleet_ID`, `Fleet_TurnedBack`, `Fleet_TurnedBack_Time`, `Fleet_TurnedBack_EndTime`, `Fleet_Mission_Changed`) VALUES "; - $Pattern_UpdateArchive = array('Fleet_ID' => null, 'Fleet_TurnedBack' => null, 'Fleet_TurnedBack_Time' => null, 'Fleet_TurnedBack_EndTime' => null, 'Fleet_Mission_Changed' => null); - foreach($UpdateArchive as $Data) - { - $Data = array_merge($Pattern_UpdateArchive, $Data); - foreach($Data as &$Values) - { - if($Values === null) - { - $Values = '"!nupd!"'; - } - } - $Array_UpdateArchive[] = "({$Data['Fleet_ID']}, {$Data['Fleet_TurnedBack']}, {$Data['Fleet_TurnedBack_Time']}, {$Data['Fleet_TurnedBack_EndTime']}, {$Data['Fleet_Mission_Changed']})"; - } - $Query_UpdateArchive .= implode(', ', $Array_UpdateArchive); - $Query_UpdateArchive .= " ON DUPLICATE KEY UPDATE "; - $Query_UpdateArchive .= "`Fleet_TurnedBack` = IF(VALUES(`Fleet_TurnedBack`) = \"!nupd!\", `Fleet_TurnedBack`, VALUES(`Fleet_TurnedBack`)), "; - $Query_UpdateArchive .= "`Fleet_TurnedBack_Time` = IF(VALUES(`Fleet_TurnedBack_Time`) = \"!nupd!\", `Fleet_TurnedBack_Time`, VALUES(`Fleet_TurnedBack_Time`)), "; - $Query_UpdateArchive .= "`Fleet_TurnedBack_EndTime` = IF(VALUES(`Fleet_TurnedBack_EndTime`) > 0, VALUES(`Fleet_TurnedBack_EndTime`), (2 * UNIX_TIMESTAMP()) - `Fleet_Time_Send` + 1), "; - $Query_UpdateArchive .= "`Fleet_Mission_Changed` = IF(VALUES(`Fleet_Mission_Changed`) = \"!nupd!\", `Fleet_Mission_Changed`, VALUES(`Fleet_Mission_Changed`));"; - doquery($Query_UpdateArchive, 'fleet_archive'); - - $Return['Updates']['Archives'] = count($UpdateArchive); - } - if(!empty($UpdateACS)) - { - $Query_UpdateACS= "INSERT INTO {{table}} (`id`, `fleets_id`, `user_joined`, `fleets_count`) VALUES "; - $Pattern_UpdateACS = array('id' => null, 'fleets_id' => null, 'user_joined' => null, 'fleets_count' => null); - foreach($UpdateACS as $Data) - { - $Data = array_merge($Pattern_UpdateACS, $Data); - foreach($Data as &$Values) - { - if($Values === null) - { - $Values = '!nupd!'; - } - } - if($Data['fleets_id'] != '!nupd!') - { - foreach($Data['fleets_id'] as $ElementID) - { - $Data['parsed_fleets'][] = "|{$ElementID}|"; - } - if(!empty($Data['parsed_fleets'])) - { - $Data['fleets_id'] = implode(',', $Data['parsed_fleets']); - } - else - { - $Data['fleets_id'] = ''; - } - } - if($Data['user_joined'] != '!nupd!') - { - foreach($Data['user_joined'] as $ElementID) - { - $Data['parsed_users'][] = "|{$ElementID}|"; - } - if(!empty($Data['parsed_users'])) - { - $Data['user_joined'] = implode(',', $Data['parsed_users']); - } - else - { - $Data['user_joined'] = ''; - } - } - $Array_UpdateACS[] = "({$Data['id']}, \"{$Data['fleets_id']}\", \"{$Data['user_joined']}\", {$Data['fleets_count']})"; - } - $Query_UpdateACS .= implode(', ', $Array_UpdateACS); - $Query_UpdateACS .= " ON DUPLICATE KEY UPDATE "; - $Query_UpdateACS .= "`fleets_id` = IF(VALUES(`fleets_id`) = \"!nupd!\", `fleets_id`, VALUES(`fleets_id`)), "; - $Query_UpdateACS .= "`user_joined` = IF(VALUES(`user_joined`) = \"!nupd!\", `user_joined`, VALUES(`user_joined`)), "; - $Query_UpdateACS .= "`fleets_count` = IF(VALUES(`fleets_count`) > 0, VALUES(`fleets_count`), 0);"; - doquery($Query_UpdateACS, 'acs'); - - $Return['Updates']['ACS'] = count($UpdateACS); - } - if(!empty($DeleteACS)) - { - doquery("DELETE FROM {{table}} WHERE `main_fleet_id` IN (".implode(', ', $DeleteACS).");", 'acs'); - - $Return['Deletes']['ACS'] = count($DeleteACS); - } - $Return['Rows'] = $RowsCount; - } - else - { - $Return['Rows'] = 0; - } - - return $Return; -} - -?> \ No newline at end of file + 0) + { + // Parse Fleets + while($Fleet = mysql_fetch_assoc($SelectFleets)) + { + if($Fleet['fleet_mission'] == 10) + { + // Rockets can't be retreated + $Return['Errors'][$Fleet['fleet_id']] = 1; + continue; + } + if($Fleet['fleet_mess'] == 0) + { + $Return['Types'][$Fleet['fleet_id']] = 1; + $UpdateFleets[$Fleet['fleet_id']] = array + ( + 'fleet_id' => $Fleet['fleet_id'], + 'fleet_start_time' => "{$UnixTS} - 1", + 'fleet_end_stay' => '0', + 'fleet_end_time' => ($InstandRetreat ? $UnixTS : "(2 * {$UnixTS}) - {$Fleet['fleet_send_time']} + 1"), + 'fleet_target_owner' => $Fleet['fleet_owner'], + 'fleet_mess' => 1, + ); + $UpdateArchive[$Fleet['fleet_id']] = array + ( + 'Fleet_ID' => $Fleet['fleet_id'], + 'Fleet_TurnedBack' => 'true', + 'Fleet_TurnedBack_Time' => $UnixTS, + 'Fleet_TurnedBack_EndTime' => ($InstandRetreat ? $UnixTS : "(2 * {$UnixTS}) - {$Fleet['fleet_send_time']} + 1"), + ); + if($Fleet['fleet_mission'] == 5) + { + $UpdateFleets[$Fleet['fleet_id']]['fleet_mess'] = 2; + } + if($Fleet['fleet_mission'] == 2) + { + $UpdateFleets[$Fleet['fleet_id']]['fleet_mission'] = 1; + $UpdateArchive[$Fleet['fleet_id']]['Fleet_Mission_Changed'] = 'true'; + + $GetACSDataBy[] = $Fleet['fleet_id']; + $FleetsOwners[$Fleet['fleet_id']] = $Fleet['fleet_owner']; + } + else + { + if(!empty($Fleet['fleets_id'])) + { + $ExplodeFleets = explode(',', str_replace('|', '', $Fleet['fleets_id'])); + foreach($ExplodeFleets as $FleetID) + { + if($FleetID > 0) + { + $Return['Types'][$FleetID] = 5; + $UpdateFleets[$FleetID] = array + ( + 'fleet_id' => $FleetID, + 'fleet_start_time' => "{$UnixTS} - 1", + 'fleet_end_stay' => '0', + 'fleet_end_time' => ($InstandRetreat ? $UnixTS : '0'), + 'fleet_target_owner' => $Fleet['fleet_owner'], + 'fleet_mess' => 1, + 'fleet_mission' => 1, + ); + $UpdateArchive[$FleetID] = array + ( + 'Fleet_ID' => $FleetID, + 'Fleet_TurnedBack' => 'true', + 'Fleet_TurnedBack_Time' => $UnixTS, + 'Fleet_TurnedBack_EndTime' => ($InstandRetreat ? $UnixTS : '0'), + 'Fleet_Mission_Changed' => 'true', + ); + } + } + $DeleteACS[] = $Fleet['fleet_id']; + } + } + } + else if($Fleet['fleet_mess'] == 1) + { + if($Fleet['fleet_mission'] == 5 && $Fleet['fleet_end_stay'] > $Now) + { + $Return['Types'][$Fleet['fleet_id']] = 2; + $UpdateFleets[$Fleet['fleet_id']] = array + ( + 'fleet_id' => $Fleet['fleet_id'], + 'fleet_end_stay' => $UnixTS, + 'fleet_end_time' => ($InstandRetreat ? $UnixTS : "{$UnixTS} + ({$Fleet['fleet_start_time']} - {$Fleet['fleet_send_time']}) + 1"), + 'fleet_mess' => 2, + ); + $UpdateArchive[$Fleet['fleet_id']] = array + ( + 'Fleet_ID' => $Fleet['fleet_id'], + 'Fleet_TurnedBack' => 'true', + 'Fleet_TurnedBack_Time' => $UnixTS, + 'Fleet_TurnedBack_EndTime' => ($InstandRetreat ? $UnixTS : "{$UnixTS} + ({$Fleet['fleet_start_time']} - {$Fleet['fleet_send_time']}) + 1"), + ); + } + else + { + if($InstandRetreat) + { + $Return['Types'][$Fleet['fleet_id']] = 3; + $UpdateFleets[$Fleet['fleet_id']] = array + ( + 'fleet_id' => $Fleet['fleet_id'], + 'fleet_end_time' => $UnixTS, + 'fleet_mess' => 2, + ); + $UpdateArchive[$Fleet['fleet_id']] = array + ( + 'Fleet_ID' => $Fleet['fleet_id'], + 'Fleet_TurnedBack' => 'true', + 'Fleet_TurnedBack_Time' => $UnixTS, + 'Fleet_TurnedBack_EndTime' => $UnixTS, + ); + if($Fleet['fleet_mission'] == 5) + { + $UpdateFleets[$Fleet['fleet_id']]['fleet_end_stay'] = $UnixTS; + $UpdateFleets[$Fleet['fleet_id']]['fleet_mess'] = 2; + } + } + else + { + $Return['Errors'][$Fleet['fleet_id']] = 2; + } + } + } + else if($Fleet['fleet_mess'] == 2) + { + if($InstandRetreat) + { + $Return['Types'][$Fleet['fleet_id']] = 4; + $UpdateFleets[$Fleet['fleet_id']] = array + ( + 'fleet_id' => $Fleet['fleet_id'], + 'fleet_end_stay' => $Fleet['fleet_end_stay'], + 'fleet_end_time' => $UnixTS, + ); + $UpdateArchive[$Fleet['fleet_id']] = array + ( + 'Fleet_ID' => $Fleet['fleet_id'], + 'Fleet_TurnedBack' => 'true', + 'Fleet_TurnedBack_Time' => $UnixTS, + 'Fleet_TurnedBack_EndTime' => $UnixTS, + ); + } + else + { + $Return['Errors'][$Fleet['fleet_id']] = 2; + } + } + } + + // Check if some ACS needs Update + if(!empty($GetACSDataBy)) + { + foreach($GetACSDataBy as $FleetID) + { + $GetACSWhere[] = "`fleets_id` LIKE '%|{$FleetID}|%'"; + } + $Query_SelectACS = "SELECT `id`, `fleets_id`, `user_joined`, `main_fleet_id` FROM {{table}} WHERE ".implode(' OR ', $GetACSWhere).";"; + $SelectACS = doquery($Query_SelectACS, 'acs'); + if(mysql_num_rows($SelectACS) > 0) + { + while($ACS = mysql_fetch_assoc($SelectACS)) + { + if(in_array($ACS['main_fleet_id'], $DeleteACS)) + { + continue; + } + $ParsedFleets = $ParsedUsers = array(); + $TempFleets = explode(',', str_replace('|', '', $ACS['fleets_id'])); + $TempUsers = explode(',', str_replace('|', '', $ACS['user_joined'])); + foreach($TempFleets as $ElementID) + { + if($ElementID > 0) + { + $ACSFleetsMap[$ElementID] = $ACS['id']; + $ParsedFleets[$ElementID] = $ElementID; + } + } + foreach($TempUsers as $ElementID) + { + if($ElementID > 0) + { + $ParsedUsers[$ElementID] = $ElementID; + } + } + + $ACSData[$ACS['id']] = array('id' => $ACS['id'], 'fleets_id' => $ParsedFleets, 'fleets_count' => count($ParsedFleets), 'user_joined' => $ParsedUsers, 'users_count' => count($ParsedUsers)); + if($ACSData[$ACS['id']]['fleets_count'] > 1 && $ACSData[$ACS['id']]['users_count'] > 1) + { + foreach($ParsedFleets as $FleetID) + { + if(!($FleetsOwners[$FleetID] > 0)) + { + $GetFleetOwners[$FleetID] = $FleetID; + } + } + } + } + if(!empty($GetFleetOwners)) + { + $Query_SelectFleetOwners = "SELECT `fleet_id`, `fleet_owner` FROM {{table}} WHERE `fleet_id` IN (".implode(', ', $GetFleetOwners).");"; + $SelectFleetOwners = doquery($Query_SelectFleetOwners, 'fleets'); + while($Owners = mysql_fetch_assoc($SelectFleetOwners)) + { + $FleetsOwners[$Owners['fleet_id']] = $Owners['fleet_owner']; + } + } + + foreach($GetACSDataBy as $FleetID) + { + $ACSPointer = &$ACSData[$ACSFleetsMap[$FleetID]]; + if(empty($ACSPointer)) + { + continue; + } + if($ACSPointer['fleets_count'] == 1) + { + $UpdateACS[$ACSPointer['id']] = array + ( + 'id' => $ACSPointer['id'], + 'fleets_id' => array(), + 'user_joined' => array(), + 'fleets_count' => '0', + ); + $ACSPointer['fleets_id'] = array(); + $ACSPointer['fleets_count'] = 0; + } + else + { + unset($ACSPointer['fleets_id'][$FleetID]); + if($ACSPointer['users_count'] == 1) + { + if(empty($UpdateACS[$ACSPointer['id']])) + { + $UpdateACS[$ACSPointer['id']] = array + ( + 'id' => $ACSPointer['id'], + 'fleets_id' => $ACSPointer['fleets_id'], + 'fleets_count' => $ACSPointer['fleets_count'] - 1, + ); + } + else + { + $UpdateACS[$ACSPointer['id']]['fleets_id'] = $ACSPointer['fleets_id']; + $UpdateACS[$ACSPointer['id']]['fleets_count'] -= 1; + } + $ACSPointer['fleets_count'] -= 1; + } + else + { + $OwnerFound = false; + foreach($ACSPointer['fleets_id'] as $FleetID2) + { + if($FleetsOwners[$FleetID2] == $FleetsOwners[$FleetID]) + { + $OwnerFound = true; + break; + } + } + if(empty($UpdateACS[$ACSPointer['id']])) + { + $UpdateACS[$ACSPointer['id']] = array + ( + 'id' => $ACSPointer['id'], + 'fleets_id' => $ACSPointer['fleets_id'], + 'fleets_count' => $ACSPointer['fleets_count'] - 1, + ); + } + else + { + $UpdateACS[$ACSPointer['id']]['fleets_id'] = $ACSPointer['fleets_id']; + $UpdateACS[$ACSPointer['id']]['fleets_count'] -= 1; + } + $ACSPointer['fleets_count'] -= 1; + if($OwnerFound !== true) + { + unset($ACSPointer['user_joined'][$FleetsOwners[$FleetID]]); + $UpdateACS[$ACSPointer['id']]['user_joined'] = $ACSPointer['user_joined']; + $ACSPointer['users_count'] -= 1; + } + } + } + } + } + } + + // Make Updates + if(!empty($UpdateFleets)) + { + $Query_UpdateFleets = "INSERT INTO {{table}} (`fleet_id`, `fleet_start_time`, `fleet_end_stay`, `fleet_end_time`, `fleet_target_owner`, `fleet_mess`, `fleet_mission`) VALUES "; + $Pattern_UpdateFleets = array('fleet_id' => null, 'fleet_start_time' => null, 'fleet_end_stay' => null, 'fleet_end_time' => null, 'fleet_target_owner' => null, 'fleet_mess' => null, 'fleet_mission' => null); + foreach($UpdateFleets as $Data) + { + $Data = array_merge($Pattern_UpdateFleets, $Data); + foreach($Data as &$Values) + { + if($Values === null) + { + $Values = '"!nupd!"'; + } + } + $Array_UpdateFleets[] = "({$Data['fleet_id']}, {$Data['fleet_start_time']}, {$Data['fleet_end_stay']}, {$Data['fleet_end_time']}, {$Data['fleet_target_owner']}, {$Data['fleet_mess']}, {$Data['fleet_mission']})"; + } + $Query_UpdateFleets .= implode(', ', $Array_UpdateFleets); + $Query_UpdateFleets .= " ON DUPLICATE KEY UPDATE "; + $Query_UpdateFleets .= "`fleet_start_time` = IF(VALUES(`fleet_start_time`) = \"!nupd!\", `fleet_start_time`, VALUES(`fleet_start_time`)), "; + $Query_UpdateFleets .= "`fleet_end_stay` = IF(VALUES(`fleet_end_stay`) > 0, VALUES(`fleet_end_stay`), 0), "; + $Query_UpdateFleets .= "`fleet_end_time` = IF(VALUES(`fleet_end_time`) > 0, VALUES(`fleet_end_time`), (2 * UNIX_TIMESTAMP()) - `fleet_send_time` + 1), "; + $Query_UpdateFleets .= "`fleet_target_owner` = IF(VALUES(`fleet_target_owner`) = \"!nupd!\", `fleet_target_owner`, VALUES(`fleet_target_owner`)), "; + $Query_UpdateFleets .= "`fleet_mess` = IF(VALUES(`fleet_mess`) = \"!nupd!\", `fleet_mess`, VALUES(`fleet_mess`)), "; + $Query_UpdateFleets .= "`fleet_mission` = IF(VALUES(`fleet_mission`) = \"!nupd!\", `fleet_mission`, VALUES(`fleet_mission`));"; + doquery($Query_UpdateFleets, 'fleets'); + + $Return['Updates']['Fleets'] = count($UpdateFleets); + } + if(!empty($UpdateArchive)) + { + $Query_UpdateArchive= "INSERT INTO {{table}} (`Fleet_ID`, `Fleet_TurnedBack`, `Fleet_TurnedBack_Time`, `Fleet_TurnedBack_EndTime`, `Fleet_Mission_Changed`) VALUES "; + $Pattern_UpdateArchive = array('Fleet_ID' => null, 'Fleet_TurnedBack' => null, 'Fleet_TurnedBack_Time' => null, 'Fleet_TurnedBack_EndTime' => null, 'Fleet_Mission_Changed' => null); + foreach($UpdateArchive as $Data) + { + $Data = array_merge($Pattern_UpdateArchive, $Data); + foreach($Data as &$Values) + { + if($Values === null) + { + $Values = '"!nupd!"'; + } + } + $Array_UpdateArchive[] = "({$Data['Fleet_ID']}, {$Data['Fleet_TurnedBack']}, {$Data['Fleet_TurnedBack_Time']}, {$Data['Fleet_TurnedBack_EndTime']}, {$Data['Fleet_Mission_Changed']})"; + } + $Query_UpdateArchive .= implode(', ', $Array_UpdateArchive); + $Query_UpdateArchive .= " ON DUPLICATE KEY UPDATE "; + $Query_UpdateArchive .= "`Fleet_TurnedBack` = IF(VALUES(`Fleet_TurnedBack`) = \"!nupd!\", `Fleet_TurnedBack`, VALUES(`Fleet_TurnedBack`)), "; + $Query_UpdateArchive .= "`Fleet_TurnedBack_Time` = IF(VALUES(`Fleet_TurnedBack_Time`) = \"!nupd!\", `Fleet_TurnedBack_Time`, VALUES(`Fleet_TurnedBack_Time`)), "; + $Query_UpdateArchive .= "`Fleet_TurnedBack_EndTime` = IF(VALUES(`Fleet_TurnedBack_EndTime`) > 0, VALUES(`Fleet_TurnedBack_EndTime`), (2 * UNIX_TIMESTAMP()) - `Fleet_Time_Send` + 1), "; + $Query_UpdateArchive .= "`Fleet_Mission_Changed` = IF(VALUES(`Fleet_Mission_Changed`) = \"!nupd!\", `Fleet_Mission_Changed`, VALUES(`Fleet_Mission_Changed`));"; + doquery($Query_UpdateArchive, 'fleet_archive'); + + $Return['Updates']['Archives'] = count($UpdateArchive); + } + if(!empty($UpdateACS)) + { + $Query_UpdateACS= "INSERT INTO {{table}} (`id`, `fleets_id`, `user_joined`, `fleets_count`) VALUES "; + $Pattern_UpdateACS = array('id' => null, 'fleets_id' => null, 'user_joined' => null, 'fleets_count' => null); + foreach($UpdateACS as $Data) + { + $Data = array_merge($Pattern_UpdateACS, $Data); + foreach($Data as &$Values) + { + if($Values === null) + { + $Values = '!nupd!'; + } + } + if($Data['fleets_id'] != '!nupd!') + { + foreach($Data['fleets_id'] as $ElementID) + { + $Data['parsed_fleets'][] = "|{$ElementID}|"; + } + if(!empty($Data['parsed_fleets'])) + { + $Data['fleets_id'] = implode(',', $Data['parsed_fleets']); + } + else + { + $Data['fleets_id'] = ''; + } + } + if($Data['user_joined'] != '!nupd!') + { + foreach($Data['user_joined'] as $ElementID) + { + $Data['parsed_users'][] = "|{$ElementID}|"; + } + if(!empty($Data['parsed_users'])) + { + $Data['user_joined'] = implode(',', $Data['parsed_users']); + } + else + { + $Data['user_joined'] = ''; + } + } + $Array_UpdateACS[] = "({$Data['id']}, \"{$Data['fleets_id']}\", \"{$Data['user_joined']}\", {$Data['fleets_count']})"; + } + $Query_UpdateACS .= implode(', ', $Array_UpdateACS); + $Query_UpdateACS .= " ON DUPLICATE KEY UPDATE "; + $Query_UpdateACS .= "`fleets_id` = IF(VALUES(`fleets_id`) = \"!nupd!\", `fleets_id`, VALUES(`fleets_id`)), "; + $Query_UpdateACS .= "`user_joined` = IF(VALUES(`user_joined`) = \"!nupd!\", `user_joined`, VALUES(`user_joined`)), "; + $Query_UpdateACS .= "`fleets_count` = IF(VALUES(`fleets_count`) > 0, VALUES(`fleets_count`), 0);"; + doquery($Query_UpdateACS, 'acs'); + + $Return['Updates']['ACS'] = count($UpdateACS); + } + if(!empty($DeleteACS)) + { + doquery("DELETE FROM {{table}} WHERE `main_fleet_id` IN (".implode(', ', $DeleteACS).");", 'acs'); + + $Return['Deletes']['ACS'] = count($DeleteACS); + } + $Return['Rows'] = $RowsCount; + } + else + { + $Return['Rows'] = 0; + } + + return $Return; +} + +?> diff --git a/includes/functions/FlyingFleetHandler.php b/includes/functions/FlyingFleetHandler.php index e9f2423d5..770d0e0cd 100644 --- a/includes/functions/FlyingFleetHandler.php +++ b/includes/functions/FlyingFleetHandler.php @@ -1,1070 +1,1070 @@ -simpleCountStart(false, 'telemetry__f0'); } - - $UserStatsPattern = array - ( - 'raids_won' => '0', - 'raids_draw' => '0', - 'raids_lost' => '0', - 'raids_acs_won' => '0', - 'raids_inAlly' => '0', - 'raids_missileAttack' => '0', - 'moons_destroyed' => '0', - 'moons_created' => '0', - 'other_expeditions_count' => '0', - ); - - $FleetArchive_Fields = array - ( - 'Owner', 'Mission', 'Mission_Changed', 'Array', 'Array_Changes', 'Time_Send', 'Time_Start', 'Time_Stay', - 'Time_End', 'Time_ACSAdd', 'Start_ID', 'Start_Galaxy', 'Start_System', 'Start_Planet', 'Start_Type', - 'Start_Type_Changed', 'Start_ID_Changed', 'Start_Res_Metal', 'Start_Res_Crystal', 'Start_Res_Deuterium', - 'End_ID', 'End_ID_Galaxy', 'End_Galaxy', 'End_System', 'End_Planet', 'End_Type', 'End_Type_Changed', - 'End_ID_Changed', 'End_Res_Metal', 'End_Res_Crystal', 'End_Res_Deuterium', 'End_Owner', 'End_Owner_IdleHours', - 'Calculated_Mission', 'Calculated_Mission_Time', 'Calculated_ComeBack', 'Calculated_ComeBack_Time', 'Destroyed', - 'Destroyed_Reason', 'TurnedBack', 'TurnedBack_Time', 'TurnedBack_EndTime', 'ACSID', 'ReportID', 'DefenderReportIDs', - 'Info_HadSameIP_Ever', 'Info_HadSameIP_Ever_Filtred', 'Info_HadSameIP_OnSend', 'Info_HasLostShips', 'Info_UsedTeleport' - ); - foreach($FleetArchive_Fields as $Key => $Value) - { - $FleetArchive_Fields[$Key] = 'Fleet_'.$Value; - $FleetArchive_Pattern[$FleetArchive_Fields[$Key]] = null; - } - - foreach($_Vars_ElementCategories['fleet'] as $ElementID) - { - $ThisKey1 = 'destroyed_'.$ElementID; - $CreateAchievementKeys[] = "`{$ThisKey1}`"; - $UserStatsPattern[$ThisKey1] = '0'; - $UserStatsUpQuery[] = "`{$ThisKey1}` = `{$ThisKey1}` + VALUES(`{$ThisKey1}`)"; - - $ThisKey2 = 'lost_'.$ElementID; - $CreateAchievementKeys[] = "`{$ThisKey2}`"; - $UserStatsPattern[$ThisKey2] = '0'; - $UserStatsUpQuery[] = "`{$ThisKey2}` = `{$ThisKey2}` + VALUES(`{$ThisKey2}`)"; - } - foreach($_Vars_ElementCategories['defense'] as $ElementID) - { - if($ElementID >= 500) - { - // Exclude missiles - break; - } - $ThisKey1 = 'destroyed_'.$ElementID; - $CreateAchievementKeys[] = "`{$ThisKey1}`"; - $UserStatsPattern[$ThisKey1] = '0'; - $UserStatsUpQuery[] = "`{$ThisKey1}` = `{$ThisKey1}` + VALUES(`{$ThisKey1}`)"; - - $ThisKey2 = 'lost_'.$ElementID; - $CreateAchievementKeys[] = "`{$ThisKey2}`"; - $UserStatsPattern[$ThisKey2] = '0'; - $UserStatsUpQuery[] = "`{$ThisKey2}` = `{$ThisKey2}` + VALUES(`{$ThisKey2}`)"; - } - $CreateAchievementKeys = implode(', ', $CreateAchievementKeys); - $UserStatsData = false; - - // --- Get all "not own" Fleets, which can interact with own Target - $InsertGalaxyIDs = array(); - $InsertGalaxyPos = array(); - $AdditionalIDs = array(); - $NotOwnFleetsGetter_FleetEndIDs = array(); - - if(!empty($IncludeFleetsFromEndIDs)) - { - $NotOwnFleetsGetter_FleetEndIDs = array_merge($NotOwnFleetsGetter_FleetEndIDs, $IncludeFleetsFromEndIDs); - } - - // Get all not own ACS MainFleets (we participate in that ACS) - $Query_GetACS = ''; - $Query_GetACS .= "SELECT `main_fleet_id`, `end_target_id` FROM {{table}} "; - $Query_GetACS .= "WHERE `owner_id` != {$planet['id_owner']} AND `user_joined` LIKE '%|{$planet['id_owner']}|%'; -- FlyingFleetHandler.php [#01]"; - $Result_GetACS = doquery($Query_GetACS, 'acs'); - if(mysql_num_rows($Result_GetACS) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_GetACS)) - { - if($FetchData['end_target_id'] == $planet['id']) - { - continue; - } - else - { - $AdditionalIDs[] = $FetchData['main_fleet_id']; - } - } - } - - // Select all my Recycling & Colonizing Fleets to check if other fleets do not fly to this position too - $Query_MyGalaxyFleets = ''; - $Query_MyGalaxyFleets .= "SELECT `fleet_mission`, `fleet_end_id_galaxy`, `fleet_end_galaxy`, `fleet_end_system`, `fleet_end_planet` FROM {{table}} "; - $Query_MyGalaxyFleets .= "WHERE `fleet_mission` IN (7, 8) AND `fleet_owner` = {$planet['id_owner']}; -- FlyingFleetHandler.php [#02]"; - $Result_MyGalaxyFleets = doquery($Query_MyGalaxyFleets, 'fleets'); - if(mysql_num_rows($Result_MyGalaxyFleets) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_MyGalaxyFleets)) - { - if($FetchData['fleet_mission'] == 7) - { - // Colonization - $ThisArray = array - ( - 'g' => $FetchData['fleet_end_galaxy'], - 's' => $FetchData['fleet_end_system'], - 'p' => $FetchData['fleet_end_planet'] - ); - if(!in_array($ThisArray, $InsertGalaxyPos)) - { - $InsertGalaxyPos[] = $ThisArray; - } - } - else if($FetchData['fleet_mission'] == 8) - { - // Debris recycling - if(!in_array($FetchData['fleet_end_id_galaxy'], $InsertGalaxyIDs)) - { - $InsertGalaxyIDs[] = $FetchData['fleet_end_id_galaxy']; - } - } - } - } - - // Get all EndIDs from my fleets or ACS flights which I have joined - $Query_GetMyFleets = ''; - $Query_GetMyFleets .= "SELECT `fleet_end_id` FROM {{table}} WHERE ( "; - $Query_GetMyFleets .= "`fleet_owner` = {$planet['id_owner']} "; - if(!empty($AdditionalIDs)) - { - // We need to add position from all ACS flights we participate in - $ImplodeAddIDS = implode(',', $AdditionalIDs); - $Query_GetMyFleets .= "OR `fleet_id` IN ({$ImplodeAddIDS}) "; - } - $Query_GetMyFleets .= ") AND `fleet_end_id` > 0 AND `fleet_mission` IN (1, 6, 7, 9, 10) "; - $Query_GetMyFleets .= "AND (`fleet_start_time` <= UNIX_TIMESTAMP() OR `fleet_end_time` <= UNIX_TIMESTAMP()); -- FlyingFleetHandler.php [#03]"; - $Result_GetMyFleets = doquery($Query_GetMyFleets, 'fleets'); - if(mysql_num_rows($Result_GetMyFleets) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_GetMyFleets)) - { - if(!in_array($FetchData['fleet_end_id'], $NotOwnFleetsGetter_FleetEndIDs)) - { - $NotOwnFleetsGetter_FleetEndIDs[] = $FetchData['fleet_end_id']; - } - } - } - - if(!empty($NotOwnFleetsGetter_FleetEndIDs) OR !empty($InsertGalaxyIDs) OR !empty($InsertGalaxyPos)) - { - // Get All non-mine Fleets (FleetIDs) - if(!empty($NotOwnFleetsGetter_FleetEndIDs)) - { - $NotOwnFleetsGetter_FleetEndIDs = implode(',', $NotOwnFleetsGetter_FleetEndIDs); - $QryPreCounterWhere[] = "(`fleet_start_id` IN ({$NotOwnFleetsGetter_FleetEndIDs}) OR `fleet_end_id` IN ({$NotOwnFleetsGetter_FleetEndIDs}))"; - } - if(!empty($InsertGalaxyIDs)) - { - $InsertGalaxyIDs = implode(',', $InsertGalaxyIDs); - $QryPreCounterWhere[] = "`fleet_end_id_galaxy` IN ({$InsertGalaxyIDs})"; - } - if(!empty($InsertGalaxyPos)) - { - foreach($InsertGalaxyPos as $ThisPos) - { - $TempPos[] = "(`fleet_end_galaxy` = {$ThisPos['g']} AND `fleet_end_system` = {$ThisPos['s']} AND `fleet_end_planet` = {$ThisPos['p']})"; - } - $TempPos = implode(' OR ', $TempPos); - $QryPreCounterWhere[] = "(`fleet_mission` = 7 AND ({$TempPos}))"; - } - $Query_GetNotOwnFleets = ''; - $Query_GetNotOwnFleets .= "SELECT `fleet_id` FROM {{table}} "; - $Query_GetNotOwnFleets .= "WHERE ( ".implode(' OR ', $QryPreCounterWhere)." ) "; - $Query_GetNotOwnFleets .= "AND `fleet_owner` != {$planet['id_owner']} "; - $Query_GetNotOwnFleets .= "; -- FlyingFleetHandler.php [#04]"; - $Result_GetNotOwnFleets = doquery($Query_GetNotOwnFleets, 'fleets'); - if(mysql_num_rows($Result_GetNotOwnFleets) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_GetNotOwnFleets)) - { - if(!in_array($FetchData['fleet_id'], $AdditionalIDs)) - { - $AdditionalIDs[] = $FetchData['fleet_id']; - } - } - } - } - - // ------------------------------------------------------------------------------------- - // --- Main Fleet Getter Query --------------------------------------------------------- - // ------------------------------------------------------------------------------------- - $Fields[] = "{{table}}.*"; - $Fields[] = "`usr`.`username`, `usr`.`ally_id`, `usr`.`tech_espionage`"; - $Fields[] = "`usr`.`morale_level`, `usr`.`morale_points`, `usr`.`morale_droptime`, `usr`.`morale_lastupdate`"; - $Fields[] = "`usr`.`tech_weapons`, `usr`.`tech_armour`, `usr`.`tech_shielding`, `usr`.`tech_laser`, `usr`.`tech_ion`, `usr`.`tech_plasma`"; - $Fields[] = "`usr`.`tech_antimatter`, `usr`.`tech_disintegration`, `usr`.`tech_graviton`"; - $Fields[] = "`ally`.`ally_tag`"; - $Fields[] = "`fleets_count`"; - $Fields[] = "{{prefix}}acs.`id` AS `acs_id`, {{prefix}}acs.`fleets_id`"; - $Fields[] = "`planet1`.`name` AS `attacking_planet_name`, `planet1`.`id_owner` AS `attacking_planet_owner`"; - $Fields[] = "`planet2`.`name` AS `endtarget_planet_name`, `planet2`.`id_owner` AS `endtarget_planet_owner`"; - $Fields = implode(', ', $Fields); - - $Query_GetAllFleets = ''; - $Query_GetAllFleets .= "SELECT {$Fields} FROM {{table}} "; - $Query_GetAllFleets .= "LEFT JOIN {{prefix}}users AS `usr` ON `usr`.`id` = {{table}}.fleet_owner "; - $Query_GetAllFleets .= "LEFT JOIN {{prefix}}alliance AS `ally` ON `usr`.`ally_id` = `ally`.`id` "; - $Query_GetAllFleets .= "LEFT JOIN {{prefix}}acs ON {{prefix}}acs.main_fleet_id = {{table}}.fleet_id "; - $Query_GetAllFleets .= "LEFT JOIN {{prefix}}planets AS `planet1` ON `planet1`.`id` = `fleet_start_id` "; - $Query_GetAllFleets .= "LEFT JOIN {{prefix}}planets AS `planet2` ON `planet2`.`id` = `fleet_end_id` "; - $Query_GetAllFleets .= "WHERE "; - $Query_GetAllFleets .= "( `fleet_start_time` <= UNIX_TIMESTAMP() OR `fleet_end_time` <= UNIX_TIMESTAMP() ) AND "; - $Query_GetAllFleets .= "( `fleet_start_id` = {$planet['id']} OR `fleet_end_id` = {$planet['id']} "; - if(!empty($AdditionalIDs)) - { - $Query_GetAllFleets .= "OR `fleet_id` IN (".implode(',', $AdditionalIDs).") "; - } - $Query_GetAllFleets .= "OR `fleet_owner` = {$planet['id_owner']} OR `fleet_target_owner` = {$planet['id_owner']} ); -- FlyingFleetHandler.php [#05]"; - $Result_GetAllFleets = doquery($Query_GetAllFleets, 'fleets'); - - if(!empty($_BenchTool)){ $_BenchTool->simpleCountStop(); } - - if(mysql_num_rows($Result_GetAllFleets) > 0) - { - if(!empty($_BenchTool)){ $_BenchTool->simpleCountStart(false, 'telemetry__f1'); } - - include('MissionCheckCalculation.php'); - $FleetCalcTimestamp = time(); - $RowNo = 0; - $PrepareData = array(); - - while($ThisFleet = mysql_fetch_assoc($Result_GetAllFleets)) - { - $PrepareReturn = MissionCheckCalculation($ThisFleet, $FleetCalcTimestamp); - foreach($PrepareReturn as $Key => $Value) - { - if($Key == 'timeSort') - { - $_FleetCache['fleetRowStatus'][$ThisFleet['fleet_id']]['calcCount'] = 0; - foreach($Value as $Key2 => $Value2) - { - $FleetTimes[$Key2] = array('rowNo' => $RowNo, 'type' => $Value2); - $_FleetCache['fleetRowStatus'][$ThisFleet['fleet_id']]['calcCount'] += 1; - } - } - else if($Key == 'acsFleets') - { - foreach($Value as $Key2 => $Value2) - { - $PrepareData[$Key][$Key2] = $Value2; - } - } - else if($Key == 'taskData') - { - foreach($Value as $Value2) - { - if(empty($PrepareData[$Key]) OR !in_array($Value2, $PrepareData[$Key])) - { - $PrepareData[$Key][] = $Value2; - } - } - } - else - { - if(empty($PrepareData[$Key]) OR !in_array($Value, $PrepareData[$Key])) - { - $PrepareData[$Key][] = $Value; - } - } - } - $RowNo += 1; - } - if(!empty($FleetTimes)) - { - ksort($FleetTimes, SORT_STRING); - include('RestoreFleetToPlanet.php'); - - $QueryData_LockTables = array - ( - 'fleet_archive' => null, - 'fleets' => 'get_ids', - 'acs' => null, - 'battle_reports' => null, - 'errors' => null, - 'fleets' => null, - 'planets' => null, - 'galaxy' => null, - 'users*' => null, - 'users' => 'users', - 'alliance' => 'ally', - 'achievements_stats' => null, - 'user_developmentlog' => null - ); - foreach($QueryData_LockTables as $LockTables_Key => $LockTables_Value) - { - $LockTables_Key = str_replace('*', '', $LockTables_Key); - if($LockTables_Value === null) - { - $QueryData_LockTablesJoin[] = "`{{prefix}}{$LockTables_Key}` WRITE"; - } - else - { - $QueryData_LockTablesJoin[] = "`{{prefix}}{$LockTables_Key}` AS `{$LockTables_Value}` WRITE"; - } - } - $QueryData_LockTablesJoin = implode(', ', $QueryData_LockTablesJoin); - $Query_LockTables = "LOCK TABLE {$QueryData_LockTablesJoin}; -- FlyingFleetHandler.php [#06]"; - doquery($Query_LockTables, ''); - - // --- Prepare $_FleetCache --- - if(!empty($PrepareData['users'])) - { - global $_User; - if(in_array($_User['id'], $PrepareData['users'])) - { - $Temp1 = array_keys($PrepareData['users'], $_User['id']); - unset($PrepareData['users'][$Temp1[0]]); - $_FleetCache['users'][$_User['id']] = $_User; - if($_User['techQueue_EndTime'] > 0) - { - $PrepareData['planets'][] = $_User['techQueue_Planet']; - } - if($_User['ally_id'] > 0) - { - $Query_GetMyAllyTag = "SELECT `ally_tag` FROM {{table}} AS `ally` WHERE `id` = {$_User['ally_id']} LIMIT 1; -- FlyingFleetHandler.php [#07]"; - $Result_GetMyAllyTag = doquery($Query_GetMyAllyTag, 'alliance', true); - $_FleetCache['users'][$_User['id']]['ally_tag'] = $Result_GetMyAllyTag['ally_tag']; - } - } - if(!empty($PrepareData['users'])) - { - $Temp1 = implode(',', $PrepareData['users']); - $Temp2 = count($PrepareData['users']); - $Query_PrepUsers = ''; - $Query_PrepUsers .= "SELECT `users`.*, `ally`.`ally_tag` FROM {{table}} AS `users` "; - $Query_PrepUsers .= "LEFT JOIN `{{prefix}}alliance` AS `ally` ON `users`.`ally_id` = `ally`.`id` "; - $Query_PrepUsers .= "WHERE `users`.`id` IN ({$Temp1}) LIMIT {$Temp2}; -- FlyingFleetHandler.php [#08]"; - $Result_PrepUsers = doquery($Query_PrepUsers, 'users'); - while($FetchData = mysql_fetch_assoc($Result_PrepUsers)) - { - $_FleetCache['users'][$FetchData['id']] = $FetchData; - if($FetchData['techQueue_EndTime'] > 0) - { - $PrepareData['planets'][] = $FetchData['techQueue_Planet']; - } - } - } - } - if(!empty($PrepareData['addPlanets'])) - { - $Temp1 = implode(',', $PrepareData['addPlanets']); - $Temp2 = count($PrepareData['addPlanets']); - $Query_PrepAddPlanets = "SELECT `id_planet`, `id_moon` FROM {{table}} WHERE `id_moon` IN ({$Temp1}) LIMIT {$Temp2}; -- FlyingFleetHandler.php [#09]"; - $Result_PrepAddPlanets = doquery($Query_PrepAddPlanets, 'galaxy'); - while($FetchData = mysql_fetch_assoc($Result_PrepAddPlanets)) - { - $_FleetCache['moonPlanets'][$FetchData['id_moon']] = $FetchData['id_planet']; - $PrepareData['planets'][] = $FetchData['id_planet']; - $PrepareData['defFleets'][] = $FetchData['id_planet']; - } - } - if(!empty($PrepareData['planets'])) - { - if(in_array($planet['id'], $PrepareData['planets'])) - { - $Temp1 = array_keys($PrepareData['planets'], $planet['id']); - unset($PrepareData['planets'][$Temp1[0]]); - $_FleetCache['planets'][$planet['id']] = $planet; - } - if(!empty($PrepareData['planets'])) - { - $Temp1 = implode(',', $PrepareData['planets']); - $Temp2 = count($PrepareData['planets']); - $Query_PrepPlanets = "SELECT * FROM {{table}} WHERE `id` IN ({$Temp1}) LIMIT {$Temp2}; -- FlyingFleetHandler.php [#10]"; - $Result_PrepPlanets = doquery($Query_PrepPlanets, 'planets'); - while($FetchData = mysql_fetch_assoc($Result_PrepPlanets)) - { - $_FleetCache['planets'][$FetchData['id']] = $FetchData; - } - } - } - if(!empty($PrepareData['defFleets'])) - { - $Temp1 = implode(',', $PrepareData['defFleets']); - $Query_PrepDefFleets = ''; - $Query_PrepDefFleets .= "SELECT `fleet_id`, `fleet_owner`, `fleet_array`, `fleet_end_id`, `username`, `ally_tag`, "; - $Query_PrepDefFleets .= "`morale_level`, `morale_droptime`, `morale_lastupdate`, "; - $Query_PrepDefFleets .= "`tech_weapons`, `tech_armour`, `tech_shielding`, `tech_laser`, `tech_ion`, `tech_plasma`, `tech_antimatter`, "; - $Query_PrepDefFleets .= "`tech_disintegration`, `tech_graviton`, `fleet_start_galaxy`, `fleet_start_system`, `fleet_start_planet` "; - $Query_PrepDefFleets .= "FROM {{table}} "; - $Query_PrepDefFleets .= "LEFT JOIN {{prefix}}users AS `users` ON `users`.`id` = `fleet_owner` "; - $Query_PrepDefFleets .= "LEFT JOIN {{prefix}}alliance AS `ally` ON `users`.`ally_id` = `ally`.`id` "; - $Query_PrepDefFleets .= "WHERE "; - $Query_PrepDefFleets .= "`fleet_end_id` IN ({$Temp1}) AND "; - $Query_PrepDefFleets .= "`fleet_mission` = 5 AND "; - $Query_PrepDefFleets .= "`fleet_start_time` <= UNIX_TIMESTAMP() AND "; - $Query_PrepDefFleets .= "`fleet_end_stay` > UNIX_TIMESTAMP(); -- FlyingFleetHandler.php [#11]"; - $Result_PrepDefFleets = doquery($Query_PrepDefFleets, 'fleets'); - while($FetchData = mysql_fetch_assoc($Result_PrepDefFleets)) - { - $_FleetCache['defFleets'][$FetchData['fleet_end_id']][$FetchData['fleet_id']] = $FetchData; - } - } - if(!empty($PrepareData['acsFleets'])) - { - $Temp1 = array(); - $Temp3 = array(); - foreach($PrepareData['acsFleets'] as $ACSFleetID => $Fleets) - { - foreach($Fleets as $FleetID) - { - $Temp1[] = $FleetID; - $Temp3[$FleetID] = $ACSFleetID; - } - } - $Temp2 = count($Temp1); - $Temp1 = implode(',', $Temp1); - $Query_PrepACSFleets = ''; - $Query_PrepACSFleets .= "SELECT `fleet_id`, `fleet_owner`, `fleet_array`, `username`, `ally_id`, `ally_tag`, "; - $Query_PrepACSFleets .= "`morale_level`, `morale_points`, `morale_droptime`, `morale_lastupdate`, "; - $Query_PrepACSFleets .= "`fleet_start_galaxy`, `fleet_start_system`, `fleet_start_planet`, `fleet_resource_metal`, `fleet_resource_crystal`, `fleet_resource_deuterium`, "; - $Query_PrepACSFleets .= "`tech_weapons`, `tech_armour`, `tech_shielding`, `tech_laser`, `tech_ion`, `tech_plasma`, `tech_antimatter`, `tech_disintegration`, `tech_graviton` "; - $Query_PrepACSFleets .= "FROM {{table}} "; - $Query_PrepACSFleets .= "LEFT JOIN {{prefix}}users as `users` ON `users`.`id` = `fleet_owner` "; - $Query_PrepACSFleets .= "LEFT JOIN {{prefix}}alliance AS `ally` ON `users`.`ally_id` = `ally`.`id` "; - $Query_PrepACSFleets .= "WHERE `fleet_id` IN ({$Temp1}) LIMIT {$Temp2}; -- FlyingFleetHandler.php [#12]"; - $Result_PrepACSFleets = doquery($Query_PrepACSFleets, 'fleets'); - while($FetchData = mysql_fetch_assoc($Result_PrepACSFleets)) - { - $_FleetCache['acsFleets'][$Temp3[$FetchData['fleet_id']]][] = $FetchData; - $PrepareData['taskData'][] = $FetchData['fleet_owner']; - } - } - if(!empty($PrepareData['taskData'])) - { - global $_User; - $Temp1 = array(); - foreach($PrepareData['taskData'] as $UserID) - { - if($UserID == $_User['id']) - { - $_FleetCache['userTasks'][$UserID] = $_User['tasks_done']; - } - elseif(!empty($PrepareData['users']) AND in_array($UserID, $PrepareData['users'])) - { - $_FleetCache['userTasks'][$UserID] = $_FleetCache['users'][$UserID]['tasks_done']; - } - else - { - $Temp1[] = $UserID; - } - } - if(!empty($Temp1)) - { - $Temp2 = count($Temp1); - $Temp1 = implode(',', $Temp1); - $Query_PrepUserTasks = ''; - $Query_PrepUserTasks .= "SELECT `id`, `tasks_done` FROM {{table}} "; - $Query_PrepUserTasks .= "WHERE `id` IN ({$Temp1}) LIMIT {$Temp2}; -- FlyingFleetHandler.php [#13]"; - $Result_PrepUserTasks = doquery($Query_PrepUserTasks, 'users'); - while($FetchData = mysql_fetch_assoc($Result_PrepUserTasks)) - { - $_FleetCache['userTasks'][$FetchData['id']] = $FetchData['tasks_done']; - } - } - } - if(!empty($PrepareData['galaxy'])) - { - if(in_array($_GalaxyRow['galaxy_id'], $PrepareData['galaxy'])) - { - $Temp1 = array_keys($PrepareData['galaxy'], $_GalaxyRow['galaxy_id']); - unset($PrepareData['galaxy'][$Temp1[0]]); - $_FleetCache['galaxy'][$_GalaxyRow['galaxy_id']] = $_GalaxyRow; - $_FleetCache['galaxyMap']['byPlanet'][$_GalaxyRow['id_planet']] = $_GalaxyRow['galaxy_id']; - if($_GalaxyRow['id_moon'] > 0) - { - $_FleetCache['galaxyMap']['byMoon'][$_GalaxyRow['id_moon']] = $_GalaxyRow['galaxy_id']; - } - } - if(!empty($PrepareData['galaxy'])) - { - $Temp1 = implode(',', $PrepareData['galaxy']); - $Temp2 = count($PrepareData['galaxy']); - $Query_PrepGalaxy = ''; - $Query_PrepGalaxy .= "SELECT `galaxy_id`, `id_planet`, `id_moon`, `metal`, `crystal` FROM {{table}} "; - $Query_PrepGalaxy .= "WHERE `galaxy_id` IN ({$Temp1}) LIMIT {$Temp2}; -- FlyingFleetHandler.php [#14]"; - $Result_PrepGalaxy = doquery($Query_PrepGalaxy, 'galaxy'); - while($FetchData = mysql_fetch_assoc($Result_PrepGalaxy)) - { - $_FleetCache['galaxy'][$FetchData['galaxy_id']] = $FetchData; - $_FleetCache['galaxyMap']['byPlanet'][$FetchData['id_planet']] = $FetchData['galaxy_id']; - if($FetchData['id_moon'] > 0) - { - $_FleetCache['galaxyMap']['byMoon'][$FetchData['id_moon']] = $FetchData['galaxy_id']; - } - } - } - } - // --- - $Fleets2Delete = array(); - $ACS2Delete = array(); - foreach($FleetTimes as $CalculationData) - { - // Investigate if mysql_data_seek should be replaced by HashMap of Fleets (for O(1) access to FleetRow instead of O(n)) - // May cause bad impact on memory usage - mysql_data_seek($Result_GetAllFleets, $CalculationData['rowNo']); - $CurrentFleet = mysql_fetch_assoc($Result_GetAllFleets); - $CurrentFleet['calcType'] = $CalculationData['type']; - - if(!empty($ChangeCoordinatesForFleets)) - { - $FoundKey = array_search($CurrentFleet['fleet_start_id'], $ChangeCoordinatesForFleets); - if($FoundKey > 0) - { - $ExplodeFoundKey = explode('<|>', $FoundKey); - $CurrentFleet['fleet_start_id'] = $ExplodeFoundKey[0]; - $CurrentFleet['attacking_planet_name'] = $ExplodeFoundKey[1]; - $CurrentFleet['fleet_start_type'] = 1; - } - else - { - $FoundKey = array_search($CurrentFleet['fleet_end_id'], $ChangeCoordinatesForFleets); - if($FoundKey > 0) - { - $ExplodeFoundKey = explode('<|>', $FoundKey); - $CurrentFleet['fleet_end_id'] = $ExplodeFoundKey[0]; - $CurrentFleet['endtarget_planet_name'] = $ExplodeFoundKey[1]; - $CurrentFleet['fleet_end_type'] = 1; - if($CurrentFleet['fleet_mission'] == 9) - { - $CurrentFleet['fleet_mission'] = 1; - } - } - } - } - - $MissionReturn = false; - switch($CurrentFleet['fleet_mission']) - { - case 1: - { - if($CurrentFleet['fleets_count'] > 0) - { - // Mission : Group Attack - if(!isset($Inc_MissionGroupAttack)) - { - $Inc_MissionGroupAttack = true; - include('MissionCaseGroupAttack.php'); - } - if(!isset($Inc_Function_CreateOneMoonRecord)) - { - $Inc_Function_CreateOneMoonRecord = true; - include('CreateOneMoonRecord.php'); - } - $MissionReturn = MissionCaseGroupAttack($CurrentFleet, $_FleetCache); - if(!empty($MissionReturn['DeleteACS'])) - { - $ACS2Delete[] = $MissionReturn['DeleteACS']; - } - } - else - { - // Mission : Attack - if(!isset($Inc_MissionAttack)) - { - $Inc_MissionAttack = true; - include('MissionCaseAttack.php'); - } - if(!isset($Inc_Function_CreateOneMoonRecord)) - { - $Inc_Function_CreateOneMoonRecord = true; - include('CreateOneMoonRecord.php'); - } - $MissionReturn = MissionCaseAttack($CurrentFleet, $_FleetCache); - if($CurrentFleet['acs_id'] > 0) - { - $ACS2Delete[] = $CurrentFleet['acs_id']; - } - } - break; - } - case 2: - { - // Mission : Attack in Group (Joined fleet) - // Make ReturnUpdate only if main fleet (GroupAttack Leader) was calculated - if($CurrentFleet['calcType'] == 3) - { - if(!isset($Inc_MissionAttack)) - { - $Inc_MissionAttack = true; - include('MissionCaseAttack.php'); - } - $MissionReturn = MissionCaseAttack($CurrentFleet, $_FleetCache); - } - break; - } - case 3: - { - // Mission: Transport - if(!isset($Inc_MissionTransport)) - { - $Inc_MissionTransport = true; - include('MissionCaseTransport.php'); - } - if($CurrentFleet['calcType'] == 1 && !isset($Inc_Function_StoreGoodsToPlanet)) - { - $Inc_Function_StoreGoodsToPlanet = true; - include('StoreGoodsToPlanet.php'); - } - $MissionReturn = MissionCaseTransport($CurrentFleet, $_FleetCache); - break; - } - case 4: - { - // Mission: Stay - if(!isset($Inc_MissionStay)) - { - $Inc_MissionStay = true; - include('MissionCaseStay.php'); - } - $MissionReturn = MissionCaseStay($CurrentFleet, $_FleetCache); - break; - } - case 5: - { - // Mission: Stay and Defend (for allys) - if(!isset($Inc_MissionStayAlly)) - { - $Inc_MissionStayAlly = true; - include('MissionCaseStayAlly.php'); - } - $MissionReturn = MissionCaseStayAlly($CurrentFleet, $_FleetCache); - break; - } - case 6: - { - // Mission: Spy - if(!isset($Inc_MissionSpy)) - { - $Inc_MissionSpy = true; - include('MissionCaseSpy.php'); - } - $MissionReturn = MissionCaseSpy($CurrentFleet, $_FleetCache); - break; - } - case 7: - { - // Mission: Colonisation - if(!isset($Inc_MissionColonisation)) - { - $Inc_MissionColonisation = true; - include('MissionCaseColonisation.php'); - include('CreateOnePlanetRecord.php'); - } - $MissionReturn = MissionCaseColonisation($CurrentFleet, $_FleetCache); - break; - } - case 8: - { - // Mission: Recycling - if(!isset($Inc_MissionRecycling)) - { - $Inc_MissionRecycling = true; - include('MissionCaseRecycling.php'); - } - $MissionReturn = MissionCaseRecycling($CurrentFleet, $_FleetCache); - break; - } - case 9: - { - // Mission: Moon destruction - if(!isset($Inc_MissionDestruction)) - { - $Inc_MissionDestruction = true; - include('MissionCaseDestruction.php'); - } - if(!isset($Inc_Function_CreateOneMoonRecord)) - { - $Inc_Function_CreateOneMoonRecord = true; - include('CreateOneMoonRecord.php'); - } - $MissionReturn = MissionCaseDestruction($CurrentFleet, $_FleetCache); - if(isset($MissionReturn['MoonDestroyed']) && $MissionReturn['MoonDestroyed'] === true) - { - if($CurrentFleet['fleet_end_id'] == $planet['id']) - { - $FleetHandlerReturn['ThisMoonDestroyed'] = true; - } - } - break; - } - case 10: - { - // Mission: Interplanetar Attack - if(!isset($Inc_MissionMIP)) - { - $Inc_MissionMIP = true; - include('MissionCaseMIP.php'); - } - $MissionReturn = MissionCaseMIP($CurrentFleet, $_FleetCache); - break; - } - case 15: - { - // Mission: Expedition - if(!isset($Inc_MissionExpedition)) - { - $Inc_MissionExpedition = true; - include('MissionCaseExpedition.php'); - } - $MissionReturn = MissionCaseExpedition($CurrentFleet); - break; - } - default: - { - // Bad mission number!!! - $Fleets2Delete[] = $CurrentFleet['fleet_id']; - break; - } - } - - if(!empty($MissionReturn['FleetsToDelete'])) - { - foreach($MissionReturn['FleetsToDelete'] as $ThisID) - { - if(!in_array($ThisID, $Fleets2Delete)) - { - $Fleets2Delete[] = $ThisID; - } - } - } - - if(!empty($MissionReturn['FleetArchive'])) - { - foreach($MissionReturn['FleetArchive'] as $FleetID => $ArchiveData) - { - $ThisResult = array_merge($FleetArchive_Pattern, $ArchiveData); - if(!isset($Updater_FleetArchive[$FleetID])) - { - $Updater_FleetArchive[$FleetID] = $ThisResult; - } - else - { - $Pointer = &$Updater_FleetArchive[$FleetID]; - foreach($ThisResult as $Key => $Value) - { - if($Value !== null) - { - if($Pointer[$Key] !== null) - { - if(substr($Pointer[$Key], 0, 1) != '!') - { - if(substr($Value, 0, 2) == '"+') - { - $Value = rtrim($Pointer[$Key], '"').str_replace('"+', '', $Value); - } - $Pointer[$Key] = $Value; - } - } - else - { - $Pointer[$Key] = $Value; - } - } - } - } - } - } - } - - // $_FleetCache Handler - if(!empty($_FleetCache['updatePlanets'])) - { - foreach($_FleetCache['updatePlanets'] as $ThisID => $ThisData) - { - if($ThisData === true) - { - $Results['planets'][] = &$_FleetCache['planets'][$ThisID]; - } - } - $Results['users'] = &$_FleetCache['users']; - HandlePlanetUpdate_MultiUpdate($Results, array(), true, true); - $Results = null; - } - if(!empty($_FleetCache['addToPlanets']['data'])) - { - $TempArray = array(); - $TempArray3 = array(); - $TempArray4 = array(); - foreach($_FleetCache['addToPlanets']['data'] as $ThisID => $ThisData) - { - $TempArray2 = array(); - foreach($_FleetCache['addToPlanets']['fields'] as $ThisField) - { - $TempArray2[] = (empty($ThisData[$ThisField]) ? '0' : $ThisData[$ThisField]); - } - $TempArray2 = implode(', ', $TempArray2); - $TempArray[] = "({$ThisID}, {$TempArray2})"; - } - foreach($_FleetCache['addToPlanets']['fields'] as $ThisField) - { - $TempArray3[] = "`{$ThisField}`"; - $TempArray4[] = "`{$ThisField}` = `{$ThisField}` + VALUES(`{$ThisField}`)"; - } - $TempArray = implode(', ', $TempArray); - $TempArray3 = implode(', ', $TempArray3); - $TempArray4 = implode(', ', $TempArray4); - $Query_AddToPlanets = ''; - $Query_AddToPlanets .= "INSERT INTO {{table}} (`id`, {$TempArray3}) VALUES {$TempArray}"; - $Query_AddToPlanets .= " ON DUPLICATE KEY UPDATE {$TempArray4}; -- FlyingFleetHandler.php [#15]"; - doquery($Query_AddToPlanets, 'planets'); - } - if(!empty($_FleetCache['galaxy']) AND $_FleetCache['updated']['galaxy'] === true) - { - $TempArray = array(); - foreach($_FleetCache['galaxy'] as $ThisID => $ThisData) - { - if($ThisData['updated'] === true) - { - $TempArray[] = "({$ThisID}, {$ThisData['metal']}, {$ThisData['crystal']})"; - } - } - if(!empty($TempArray)) - { - $Query_UpdCachedGalaxy = ''; - $Query_UpdCachedGalaxy .= "INSERT INTO {{table}} (`galaxy_id`, `metal`, `crystal`) VALUES "; - $Query_UpdCachedGalaxy .= implode(', ', $TempArray); - $Query_UpdCachedGalaxy .= " ON DUPLICATE KEY UPDATE "; - $Query_UpdCachedGalaxy .= "`metal` = VALUES(`metal`), "; - $Query_UpdCachedGalaxy .= "`crystal` = VALUES(`crystal`); -- FlyingFleetHandler.php [#16]"; - doquery($Query_UpdCachedGalaxy, 'galaxy'); - } - } - if(!empty($_FleetCache['deleteMoons'])) - { - $Temp2 = count($_FleetCache['deleteMoons']); - $Temp1 = implode(',', $_FleetCache['deleteMoons']); - $Query_DeleteMoons = "DELETE FROM {{table}} WHERE `id` IN ({$Temp1}) LIMIT {$Temp2}; -- FlyingFleetHandler.php [#17]"; - doquery($Query_DeleteMoons, 'planets'); - } - if(!empty($_FleetCache['moonGalaxyUpdate'])) - { - $Temp2 = count($_FleetCache['moonGalaxyUpdate']); - $Temp1 = implode(',', $_FleetCache['moonGalaxyUpdate']); - $Query_UpdMoonGalaxy = "UPDATE {{table}} SET `id_moon` = 0 WHERE `id_planet` IN ({$Temp1}) LIMIT {$Temp2}; -- FlyingFleetHandler.php [#18]"; - doquery($Query_UpdMoonGalaxy, 'galaxy'); - } - if(!empty($_FleetCache['moonUserUpdate'])) - { - $TempArray = array(); - foreach($_FleetCache['moonUserUpdate'] as $ThisUser => $ThisID) - { - $TempArray[] = "({$ThisUser}, {$ThisID})"; - } - $TempArray = implode(',', $TempArray); - $Query_UpdMoonUser = ''; - $Query_UpdMoonUser .= "INSERT INTO {{table}} (`id`, `current_planet`) VALUES {$TempArray} "; - $Query_UpdMoonUser .= "ON DUPLICATE KEY UPDATE `current_planet` = VALUES(`current_planet`); -- FlyingFleetHandler.php [#19]"; - doquery($Query_UpdMoonUser, 'users'); - } - if(!empty($_FleetCache['MoraleCache'])) - { - $TempArray = array(); - foreach($_FleetCache['MoraleCache'] as $ThisUserID => $ThisData) - { - $TempArray[] = "({$ThisUserID}, {$ThisData['level']}, {$ThisData['droptime']}, {$ThisData['lastupdate']})"; - } - $TempArray = implode(',', $TempArray); - $Query_UpdUserMorale = ''; - $Query_UpdUserMorale .= "INSERT INTO {{table}} (`id`, `morale_level`, `morale_droptime`, `morale_lastupdate`) VALUES {$TempArray} "; - $Query_UpdUserMorale .= "ON DUPLICATE KEY UPDATE "; - $Query_UpdUserMorale .= "`morale_level` = VALUES(`morale_level`), "; - $Query_UpdUserMorale .= "`morale_droptime` = VALUES(`morale_droptime`), "; - $Query_UpdUserMorale .= "`morale_lastupdate` = VALUES(`morale_lastupdate`); -- FlyingFleetHandler.php [#20]"; - doquery($Query_UpdUserMorale, 'users'); - } - - if(!empty($_FleetCache['updateFleets'])) - { - $TempArray = array(); - foreach($_FleetCache['updateFleets'] as $ThisID => $ThisData) - { - if(empty($ThisData['fleet_array'])) - { - $ThisData['fleet_array'] = "''"; - $ThisData['fleet_amount'] = '0'; - } - else - { - $ThisData['fleet_array'] = "'{$ThisData['fleet_array']}'"; - } - if(empty($ThisData['fleet_mess'])) - { - $ThisData['fleet_mess'] = '0'; - } - if(empty($ThisData['fleet_resource_metal'])) - { - $ThisData['fleet_resource_metal'] = '0'; - } - if(empty($ThisData['fleet_resource_crystal'])) - { - $ThisData['fleet_resource_crystal'] = '0'; - } - if(empty($ThisData['fleet_resource_deuterium'])) - { - $ThisData['fleet_resource_deuterium'] = '0'; - } - $TempArray[] = "({$ThisID}, {$ThisData['fleet_amount']}, {$ThisData['fleet_array']}, {$ThisData['fleet_mess']}, {$ThisData['fleet_resource_metal']}, {$ThisData['fleet_resource_crystal']}, {$ThisData['fleet_resource_deuterium']})"; - } - $TempArray = implode(',', $TempArray); - $Query_UpdateFleets = ''; - $Query_UpdateFleets .= "INSERT INTO {{table}} (`fleet_id`, `fleet_amount`, `fleet_array`, `fleet_mess`, `fleet_resource_metal`, `fleet_resource_crystal`, `fleet_resource_deuterium`) "; - $Query_UpdateFleets .= "VALUES {$TempArray} "; - $Query_UpdateFleets .= "ON DUPLICATE KEY UPDATE "; - $Query_UpdateFleets .= "`fleet_amount` = IF(VALUES(`fleet_amount`) = 0, `fleet_amount`, VALUES(`fleet_amount`)), "; - $Query_UpdateFleets .= "`fleet_array` = IF(VALUES(`fleet_array`) = '', `fleet_array`, VALUES(`fleet_array`)), "; - $Query_UpdateFleets .= "`fleet_mess` = IF(VALUES(`fleet_mess`) = 0, `fleet_mess`, VALUES(`fleet_mess`)), "; - $Query_UpdateFleets .= "`fleet_resource_metal` = `fleet_resource_metal` + VALUES(`fleet_resource_metal`), "; - $Query_UpdateFleets .= "`fleet_resource_crystal` = `fleet_resource_crystal` + VALUES(`fleet_resource_crystal`), "; - $Query_UpdateFleets .= "`fleet_resource_deuterium` = `fleet_resource_deuterium` + VALUES(`fleet_resource_deuterium`); -- FlyingFleetHandler.php [#21]"; - doquery($Query_UpdateFleets, 'fleets'); - } - // --- - - if(!isset($FleetHandlerReturn['ThisMoonDestroyed'])) - { - if(!empty($_FleetCache['planets'][$planet['id']])) - { - $planet = $_FleetCache['planets'][$planet['id']]; - } - else - { - $planet = doquery("SELECT * FROM {{table}} WHERE `id` = {$planet['id']}; -- FlyingFleetHandler.php [#22]", 'planets', true); - } - } - if(isset($_GalaxyRow['galaxy_id']) && $_GalaxyRow['galaxy_id'] > 0 AND !empty($_FleetCache['galaxy'][$_GalaxyRow['galaxy_id']])) - { - $_GalaxyRow['metal'] = $_FleetCache['galaxy'][$_GalaxyRow['galaxy_id']]['metal']; - $_GalaxyRow['crystal'] = $_FleetCache['galaxy'][$_GalaxyRow['galaxy_id']]['crystal']; - } - - if(!empty($Updater_FleetArchive)) - { - $Qry_Updater_FleetArchive = "INSERT INTO {{table}} VALUES "; - foreach($Updater_FleetArchive as $FleetID => $Data) - { - $Qry_Updater_FleetArchive_Row = "({$FleetID}, "; - foreach($Data as &$DataVal) - { - if($DataVal === null) - { - $DataVal = '"!noupd!"'; - } - elseif($DataVal === 0) - { - $DataVal = '0'; - } - elseif($DataVal === '') - { - $DataVal = '""'; - } - elseif($DataVal === true) - { - $DataVal = 'true'; - } - elseif($DataVal === false) - { - $DataVal = 'false'; - } - elseif(substr($DataVal, 0, 1) == '!') - { - $DataVal = preg_replace('/^\!/', '', $DataVal); - } - } - $Qry_Updater_FleetArchive_Row .= implode(', ', $Data); - $Qry_Updater_FleetArchive_Row .= ')'; - $Qry_Updater_FleetArchive_Array[] = $Qry_Updater_FleetArchive_Row; - } - $Qry_Updater_FleetArchive .= implode(', ', $Qry_Updater_FleetArchive_Array); - $Qry_Updater_FleetArchive .= " ON DUPLICATE KEY UPDATE "; - foreach($FleetArchive_Fields as $FieldName) - { - $Qry_Updater_FleetArchive_Array2[] = "`{$FieldName}` = IF((VALUES(`{$FieldName}`) = \"!noupd!\"), `{$FieldName}`, IF(SUBSTRING(VALUES(`{$FieldName}`), 1, 1) = '+', CONCAT(`{$FieldName}`, SUBSTRING(VALUES(`{$FieldName}`), 2)), VALUES(`{$FieldName}`)))"; - } - $Qry_Updater_FleetArchive .= implode(', ', $Qry_Updater_FleetArchive_Array2); - $Qry_Updater_FleetArchive .= "; -- FlyingFleetHandler.php [#23]"; - doquery($Qry_Updater_FleetArchive, 'fleet_archive'); - } - - if(!empty($UserStatsData)) - { - $QryUsersStats = ''; - $QryUsersStats .= "INSERT INTO {{table}} (`A_UserID`, `ustat_raids_won`, `ustat_raids_draw`, `ustat_raids_lost`, `ustat_raids_acs_won`, `ustat_raids_inAlly`, `ustat_raids_missileAttack`, `ustat_moons_destroyed`, `ustat_moons_created`, `ustat_other_expeditions_count`, {$CreateAchievementKeys}) VALUES "; - foreach($UserStatsData as $UserID => $Data) - { - if($UserID <= 0) - { - continue; - } - foreach($Data as &$Value) - { - if($Value == '') - { - $Value = '""'; - } - elseif($Value === 0) - { - $Value = '0'; - } - } - $QryUsersStatsA[] = "({$UserID}, ".implode(', ', $Data).")"; - } - $QryUsersStats .= implode(', ', $QryUsersStatsA); - $QryUsersStats .= " ON DUPLICATE KEY UPDATE "; - $QryUsersStats .= "`ustat_raids_won` = `ustat_raids_won` + VALUES(`ustat_raids_won`), "; - $QryUsersStats .= "`ustat_raids_draw` = `ustat_raids_draw` + VALUES(`ustat_raids_draw`), "; - $QryUsersStats .= "`ustat_raids_lost` = `ustat_raids_lost` + VALUES(`ustat_raids_lost`), "; - $QryUsersStats .= "`ustat_raids_acs_won` = `ustat_raids_acs_won` + VALUES(`ustat_raids_acs_won`), "; - $QryUsersStats .= "`ustat_raids_inAlly` = `ustat_raids_inAlly` + VALUES(`ustat_raids_inAlly`), "; - $QryUsersStats .= "`ustat_raids_missileAttack` = `ustat_raids_missileAttack` + VALUES(`ustat_raids_missileAttack`), "; - $QryUsersStats .= "`ustat_moons_destroyed` = `ustat_moons_destroyed` + VALUES(`ustat_moons_destroyed`), "; - $QryUsersStats .= "`ustat_moons_created` = `ustat_moons_created` + VALUES(`ustat_moons_created`), "; - $QryUsersStats .= "`ustat_other_expeditions_count` = `ustat_other_expeditions_count` + VALUES(`ustat_other_expeditions_count`)"; - if(!empty($UserStatsUpQuery)) - { - $QryUsersStats .= ", ".implode(', ', $UserStatsUpQuery); - } - $QryUsersStats .= '; -- FlyingFleetHandler.php [#24]'; - doquery($QryUsersStats, 'achievements_stats'); - } - - if(!empty($ACS2Delete)) - { - doquery("DELETE FROM {{table}} WHERE `id` IN (".implode(', ', $ACS2Delete)."); -- FlyingFleetHandler.php [#25]", 'acs'); - } - if(!empty($Fleets2Delete)) - { - doquery("DELETE FROM {{table}} WHERE `fleet_id` IN (".implode(', ', $Fleets2Delete)."); -- FlyingFleetHandler.php [#26]", 'fleets'); - } - doquery('UNLOCK TABLES; -- FlyingFleetHandler.php [#27]', ''); - - if(!empty($_Cache['Messages'])) - { - SendSimpleMultipleMessages($_Cache['Messages']); - $_Cache['Messages'] = array(); - } - } - - if(!empty($_BenchTool)){ $_BenchTool->simpleCountStop(); } - - if(!isset($FleetHandlerReturn)) - { - $FleetHandlerReturn = array(); - } - return $FleetHandlerReturn; - } -} - -?> \ No newline at end of file +simpleCountStart(false, 'telemetry__f0'); } + + $UserStatsPattern = array + ( + 'raids_won' => '0', + 'raids_draw' => '0', + 'raids_lost' => '0', + 'raids_acs_won' => '0', + 'raids_inAlly' => '0', + 'raids_missileAttack' => '0', + 'moons_destroyed' => '0', + 'moons_created' => '0', + 'other_expeditions_count' => '0', + ); + + $FleetArchive_Fields = array + ( + 'Owner', 'Mission', 'Mission_Changed', 'Array', 'Array_Changes', 'Time_Send', 'Time_Start', 'Time_Stay', + 'Time_End', 'Time_ACSAdd', 'Start_ID', 'Start_Galaxy', 'Start_System', 'Start_Planet', 'Start_Type', + 'Start_Type_Changed', 'Start_ID_Changed', 'Start_Res_Metal', 'Start_Res_Crystal', 'Start_Res_Deuterium', + 'End_ID', 'End_ID_Galaxy', 'End_Galaxy', 'End_System', 'End_Planet', 'End_Type', 'End_Type_Changed', + 'End_ID_Changed', 'End_Res_Metal', 'End_Res_Crystal', 'End_Res_Deuterium', 'End_Owner', 'End_Owner_IdleHours', + 'Calculated_Mission', 'Calculated_Mission_Time', 'Calculated_ComeBack', 'Calculated_ComeBack_Time', 'Destroyed', + 'Destroyed_Reason', 'TurnedBack', 'TurnedBack_Time', 'TurnedBack_EndTime', 'ACSID', 'ReportID', 'DefenderReportIDs', + 'Info_HadSameIP_Ever', 'Info_HadSameIP_Ever_Filtred', 'Info_HadSameIP_OnSend', 'Info_HasLostShips', 'Info_UsedTeleport' + ); + foreach($FleetArchive_Fields as $Key => $Value) + { + $FleetArchive_Fields[$Key] = 'Fleet_'.$Value; + $FleetArchive_Pattern[$FleetArchive_Fields[$Key]] = null; + } + + foreach($_Vars_ElementCategories['fleet'] as $ElementID) + { + $ThisKey1 = 'destroyed_'.$ElementID; + $CreateAchievementKeys[] = "`{$ThisKey1}`"; + $UserStatsPattern[$ThisKey1] = '0'; + $UserStatsUpQuery[] = "`{$ThisKey1}` = `{$ThisKey1}` + VALUES(`{$ThisKey1}`)"; + + $ThisKey2 = 'lost_'.$ElementID; + $CreateAchievementKeys[] = "`{$ThisKey2}`"; + $UserStatsPattern[$ThisKey2] = '0'; + $UserStatsUpQuery[] = "`{$ThisKey2}` = `{$ThisKey2}` + VALUES(`{$ThisKey2}`)"; + } + foreach($_Vars_ElementCategories['defense'] as $ElementID) + { + if($ElementID >= 500) + { + // Exclude missiles + break; + } + $ThisKey1 = 'destroyed_'.$ElementID; + $CreateAchievementKeys[] = "`{$ThisKey1}`"; + $UserStatsPattern[$ThisKey1] = '0'; + $UserStatsUpQuery[] = "`{$ThisKey1}` = `{$ThisKey1}` + VALUES(`{$ThisKey1}`)"; + + $ThisKey2 = 'lost_'.$ElementID; + $CreateAchievementKeys[] = "`{$ThisKey2}`"; + $UserStatsPattern[$ThisKey2] = '0'; + $UserStatsUpQuery[] = "`{$ThisKey2}` = `{$ThisKey2}` + VALUES(`{$ThisKey2}`)"; + } + $CreateAchievementKeys = implode(', ', $CreateAchievementKeys); + $UserStatsData = false; + + // --- Get all "not own" Fleets, which can interact with own Target + $InsertGalaxyIDs = array(); + $InsertGalaxyPos = array(); + $AdditionalIDs = array(); + $NotOwnFleetsGetter_FleetEndIDs = array(); + + if(!empty($IncludeFleetsFromEndIDs)) + { + $NotOwnFleetsGetter_FleetEndIDs = array_merge($NotOwnFleetsGetter_FleetEndIDs, $IncludeFleetsFromEndIDs); + } + + // Get all not own ACS MainFleets (we participate in that ACS) + $Query_GetACS = ''; + $Query_GetACS .= "SELECT `main_fleet_id`, `end_target_id` FROM {{table}} "; + $Query_GetACS .= "WHERE `owner_id` != {$planet['id_owner']} AND `user_joined` LIKE '%|{$planet['id_owner']}|%'; -- FlyingFleetHandler.php [#01]"; + $Result_GetACS = doquery($Query_GetACS, 'acs'); + if(mysql_num_rows($Result_GetACS) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_GetACS)) + { + if($FetchData['end_target_id'] == $planet['id']) + { + continue; + } + else + { + $AdditionalIDs[] = $FetchData['main_fleet_id']; + } + } + } + + // Select all my Recycling & Colonizing Fleets to check if other fleets do not fly to this position too + $Query_MyGalaxyFleets = ''; + $Query_MyGalaxyFleets .= "SELECT `fleet_mission`, `fleet_end_id_galaxy`, `fleet_end_galaxy`, `fleet_end_system`, `fleet_end_planet` FROM {{table}} "; + $Query_MyGalaxyFleets .= "WHERE `fleet_mission` IN (7, 8) AND `fleet_owner` = {$planet['id_owner']}; -- FlyingFleetHandler.php [#02]"; + $Result_MyGalaxyFleets = doquery($Query_MyGalaxyFleets, 'fleets'); + if(mysql_num_rows($Result_MyGalaxyFleets) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_MyGalaxyFleets)) + { + if($FetchData['fleet_mission'] == 7) + { + // Colonization + $ThisArray = array + ( + 'g' => $FetchData['fleet_end_galaxy'], + 's' => $FetchData['fleet_end_system'], + 'p' => $FetchData['fleet_end_planet'] + ); + if(!in_array($ThisArray, $InsertGalaxyPos)) + { + $InsertGalaxyPos[] = $ThisArray; + } + } + else if($FetchData['fleet_mission'] == 8) + { + // Debris recycling + if(!in_array($FetchData['fleet_end_id_galaxy'], $InsertGalaxyIDs)) + { + $InsertGalaxyIDs[] = $FetchData['fleet_end_id_galaxy']; + } + } + } + } + + // Get all EndIDs from my fleets or ACS flights which I have joined + $Query_GetMyFleets = ''; + $Query_GetMyFleets .= "SELECT `fleet_end_id` FROM {{table}} WHERE ( "; + $Query_GetMyFleets .= "`fleet_owner` = {$planet['id_owner']} "; + if(!empty($AdditionalIDs)) + { + // We need to add position from all ACS flights we participate in + $ImplodeAddIDS = implode(',', $AdditionalIDs); + $Query_GetMyFleets .= "OR `fleet_id` IN ({$ImplodeAddIDS}) "; + } + $Query_GetMyFleets .= ") AND `fleet_end_id` > 0 AND `fleet_mission` IN (1, 6, 7, 9, 10) "; + $Query_GetMyFleets .= "AND (`fleet_start_time` <= UNIX_TIMESTAMP() OR `fleet_end_time` <= UNIX_TIMESTAMP()); -- FlyingFleetHandler.php [#03]"; + $Result_GetMyFleets = doquery($Query_GetMyFleets, 'fleets'); + if(mysql_num_rows($Result_GetMyFleets) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_GetMyFleets)) + { + if(!in_array($FetchData['fleet_end_id'], $NotOwnFleetsGetter_FleetEndIDs)) + { + $NotOwnFleetsGetter_FleetEndIDs[] = $FetchData['fleet_end_id']; + } + } + } + + if(!empty($NotOwnFleetsGetter_FleetEndIDs) OR !empty($InsertGalaxyIDs) OR !empty($InsertGalaxyPos)) + { + // Get All non-mine Fleets (FleetIDs) + if(!empty($NotOwnFleetsGetter_FleetEndIDs)) + { + $NotOwnFleetsGetter_FleetEndIDs = implode(',', $NotOwnFleetsGetter_FleetEndIDs); + $QryPreCounterWhere[] = "(`fleet_start_id` IN ({$NotOwnFleetsGetter_FleetEndIDs}) OR `fleet_end_id` IN ({$NotOwnFleetsGetter_FleetEndIDs}))"; + } + if(!empty($InsertGalaxyIDs)) + { + $InsertGalaxyIDs = implode(',', $InsertGalaxyIDs); + $QryPreCounterWhere[] = "`fleet_end_id_galaxy` IN ({$InsertGalaxyIDs})"; + } + if(!empty($InsertGalaxyPos)) + { + foreach($InsertGalaxyPos as $ThisPos) + { + $TempPos[] = "(`fleet_end_galaxy` = {$ThisPos['g']} AND `fleet_end_system` = {$ThisPos['s']} AND `fleet_end_planet` = {$ThisPos['p']})"; + } + $TempPos = implode(' OR ', $TempPos); + $QryPreCounterWhere[] = "(`fleet_mission` = 7 AND ({$TempPos}))"; + } + $Query_GetNotOwnFleets = ''; + $Query_GetNotOwnFleets .= "SELECT `fleet_id` FROM {{table}} "; + $Query_GetNotOwnFleets .= "WHERE ( ".implode(' OR ', $QryPreCounterWhere)." ) "; + $Query_GetNotOwnFleets .= "AND `fleet_owner` != {$planet['id_owner']} "; + $Query_GetNotOwnFleets .= "; -- FlyingFleetHandler.php [#04]"; + $Result_GetNotOwnFleets = doquery($Query_GetNotOwnFleets, 'fleets'); + if(mysql_num_rows($Result_GetNotOwnFleets) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_GetNotOwnFleets)) + { + if(!in_array($FetchData['fleet_id'], $AdditionalIDs)) + { + $AdditionalIDs[] = $FetchData['fleet_id']; + } + } + } + } + + // ------------------------------------------------------------------------------------- + // --- Main Fleet Getter Query --------------------------------------------------------- + // ------------------------------------------------------------------------------------- + $Fields[] = "{{table}}.*"; + $Fields[] = "`usr`.`username`, `usr`.`ally_id`, `usr`.`tech_espionage`"; + $Fields[] = "`usr`.`morale_level`, `usr`.`morale_points`, `usr`.`morale_droptime`, `usr`.`morale_lastupdate`"; + $Fields[] = "`usr`.`tech_weapons`, `usr`.`tech_armour`, `usr`.`tech_shielding`, `usr`.`tech_laser`, `usr`.`tech_ion`, `usr`.`tech_plasma`"; + $Fields[] = "`usr`.`tech_antimatter`, `usr`.`tech_disintegration`, `usr`.`tech_graviton`"; + $Fields[] = "`ally`.`ally_tag`"; + $Fields[] = "`fleets_count`"; + $Fields[] = "{{prefix}}acs.`id` AS `acs_id`, {{prefix}}acs.`fleets_id`"; + $Fields[] = "`planet1`.`name` AS `attacking_planet_name`, `planet1`.`id_owner` AS `attacking_planet_owner`"; + $Fields[] = "`planet2`.`name` AS `endtarget_planet_name`, `planet2`.`id_owner` AS `endtarget_planet_owner`"; + $Fields = implode(', ', $Fields); + + $Query_GetAllFleets = ''; + $Query_GetAllFleets .= "SELECT {$Fields} FROM {{table}} "; + $Query_GetAllFleets .= "LEFT JOIN {{prefix}}users AS `usr` ON `usr`.`id` = {{table}}.fleet_owner "; + $Query_GetAllFleets .= "LEFT JOIN {{prefix}}alliance AS `ally` ON `usr`.`ally_id` = `ally`.`id` "; + $Query_GetAllFleets .= "LEFT JOIN {{prefix}}acs ON {{prefix}}acs.main_fleet_id = {{table}}.fleet_id "; + $Query_GetAllFleets .= "LEFT JOIN {{prefix}}planets AS `planet1` ON `planet1`.`id` = `fleet_start_id` "; + $Query_GetAllFleets .= "LEFT JOIN {{prefix}}planets AS `planet2` ON `planet2`.`id` = `fleet_end_id` "; + $Query_GetAllFleets .= "WHERE "; + $Query_GetAllFleets .= "( `fleet_start_time` <= UNIX_TIMESTAMP() OR `fleet_end_time` <= UNIX_TIMESTAMP() ) AND "; + $Query_GetAllFleets .= "( `fleet_start_id` = {$planet['id']} OR `fleet_end_id` = {$planet['id']} "; + if(!empty($AdditionalIDs)) + { + $Query_GetAllFleets .= "OR `fleet_id` IN (".implode(',', $AdditionalIDs).") "; + } + $Query_GetAllFleets .= "OR `fleet_owner` = {$planet['id_owner']} OR `fleet_target_owner` = {$planet['id_owner']} ); -- FlyingFleetHandler.php [#05]"; + $Result_GetAllFleets = doquery($Query_GetAllFleets, 'fleets'); + + if(!empty($_BenchTool)){ $_BenchTool->simpleCountStop(); } + + if(mysql_num_rows($Result_GetAllFleets) > 0) + { + if(!empty($_BenchTool)){ $_BenchTool->simpleCountStart(false, 'telemetry__f1'); } + + include('MissionCheckCalculation.php'); + $FleetCalcTimestamp = time(); + $RowNo = 0; + $PrepareData = array(); + + while($ThisFleet = mysql_fetch_assoc($Result_GetAllFleets)) + { + $PrepareReturn = MissionCheckCalculation($ThisFleet, $FleetCalcTimestamp); + foreach($PrepareReturn as $Key => $Value) + { + if($Key == 'timeSort') + { + $_FleetCache['fleetRowStatus'][$ThisFleet['fleet_id']]['calcCount'] = 0; + foreach($Value as $Key2 => $Value2) + { + $FleetTimes[$Key2] = array('rowNo' => $RowNo, 'type' => $Value2); + $_FleetCache['fleetRowStatus'][$ThisFleet['fleet_id']]['calcCount'] += 1; + } + } + else if($Key == 'acsFleets') + { + foreach($Value as $Key2 => $Value2) + { + $PrepareData[$Key][$Key2] = $Value2; + } + } + else if($Key == 'taskData') + { + foreach($Value as $Value2) + { + if(empty($PrepareData[$Key]) OR !in_array($Value2, $PrepareData[$Key])) + { + $PrepareData[$Key][] = $Value2; + } + } + } + else + { + if(empty($PrepareData[$Key]) OR !in_array($Value, $PrepareData[$Key])) + { + $PrepareData[$Key][] = $Value; + } + } + } + $RowNo += 1; + } + if(!empty($FleetTimes)) + { + ksort($FleetTimes, SORT_STRING); + include('RestoreFleetToPlanet.php'); + + $QueryData_LockTables = array + ( + 'fleet_archive' => null, + 'fleets' => 'get_ids', + 'acs' => null, + 'battle_reports' => null, + 'errors' => null, + 'fleets' => null, + 'planets' => null, + 'galaxy' => null, + 'users*' => null, + 'users' => 'users', + 'alliance' => 'ally', + 'achievements_stats' => null, + 'user_developmentlog' => null + ); + foreach($QueryData_LockTables as $LockTables_Key => $LockTables_Value) + { + $LockTables_Key = str_replace('*', '', $LockTables_Key); + if($LockTables_Value === null) + { + $QueryData_LockTablesJoin[] = "`{{prefix}}{$LockTables_Key}` WRITE"; + } + else + { + $QueryData_LockTablesJoin[] = "`{{prefix}}{$LockTables_Key}` AS `{$LockTables_Value}` WRITE"; + } + } + $QueryData_LockTablesJoin = implode(', ', $QueryData_LockTablesJoin); + $Query_LockTables = "LOCK TABLE {$QueryData_LockTablesJoin}; -- FlyingFleetHandler.php [#06]"; + doquery($Query_LockTables, ''); + + // --- Prepare $_FleetCache --- + if(!empty($PrepareData['users'])) + { + global $_User; + if(in_array($_User['id'], $PrepareData['users'])) + { + $Temp1 = array_keys($PrepareData['users'], $_User['id']); + unset($PrepareData['users'][$Temp1[0]]); + $_FleetCache['users'][$_User['id']] = $_User; + if($_User['techQueue_EndTime'] > 0) + { + $PrepareData['planets'][] = $_User['techQueue_Planet']; + } + if($_User['ally_id'] > 0) + { + $Query_GetMyAllyTag = "SELECT `ally_tag` FROM {{table}} AS `ally` WHERE `id` = {$_User['ally_id']} LIMIT 1; -- FlyingFleetHandler.php [#07]"; + $Result_GetMyAllyTag = doquery($Query_GetMyAllyTag, 'alliance', true); + $_FleetCache['users'][$_User['id']]['ally_tag'] = $Result_GetMyAllyTag['ally_tag']; + } + } + if(!empty($PrepareData['users'])) + { + $Temp1 = implode(',', $PrepareData['users']); + $Temp2 = count($PrepareData['users']); + $Query_PrepUsers = ''; + $Query_PrepUsers .= "SELECT `users`.*, `ally`.`ally_tag` FROM {{table}} AS `users` "; + $Query_PrepUsers .= "LEFT JOIN `{{prefix}}alliance` AS `ally` ON `users`.`ally_id` = `ally`.`id` "; + $Query_PrepUsers .= "WHERE `users`.`id` IN ({$Temp1}) LIMIT {$Temp2}; -- FlyingFleetHandler.php [#08]"; + $Result_PrepUsers = doquery($Query_PrepUsers, 'users'); + while($FetchData = mysql_fetch_assoc($Result_PrepUsers)) + { + $_FleetCache['users'][$FetchData['id']] = $FetchData; + if($FetchData['techQueue_EndTime'] > 0) + { + $PrepareData['planets'][] = $FetchData['techQueue_Planet']; + } + } + } + } + if(!empty($PrepareData['addPlanets'])) + { + $Temp1 = implode(',', $PrepareData['addPlanets']); + $Temp2 = count($PrepareData['addPlanets']); + $Query_PrepAddPlanets = "SELECT `id_planet`, `id_moon` FROM {{table}} WHERE `id_moon` IN ({$Temp1}) LIMIT {$Temp2}; -- FlyingFleetHandler.php [#09]"; + $Result_PrepAddPlanets = doquery($Query_PrepAddPlanets, 'galaxy'); + while($FetchData = mysql_fetch_assoc($Result_PrepAddPlanets)) + { + $_FleetCache['moonPlanets'][$FetchData['id_moon']] = $FetchData['id_planet']; + $PrepareData['planets'][] = $FetchData['id_planet']; + $PrepareData['defFleets'][] = $FetchData['id_planet']; + } + } + if(!empty($PrepareData['planets'])) + { + if(in_array($planet['id'], $PrepareData['planets'])) + { + $Temp1 = array_keys($PrepareData['planets'], $planet['id']); + unset($PrepareData['planets'][$Temp1[0]]); + $_FleetCache['planets'][$planet['id']] = $planet; + } + if(!empty($PrepareData['planets'])) + { + $Temp1 = implode(',', $PrepareData['planets']); + $Temp2 = count($PrepareData['planets']); + $Query_PrepPlanets = "SELECT * FROM {{table}} WHERE `id` IN ({$Temp1}) LIMIT {$Temp2}; -- FlyingFleetHandler.php [#10]"; + $Result_PrepPlanets = doquery($Query_PrepPlanets, 'planets'); + while($FetchData = mysql_fetch_assoc($Result_PrepPlanets)) + { + $_FleetCache['planets'][$FetchData['id']] = $FetchData; + } + } + } + if(!empty($PrepareData['defFleets'])) + { + $Temp1 = implode(',', $PrepareData['defFleets']); + $Query_PrepDefFleets = ''; + $Query_PrepDefFleets .= "SELECT `fleet_id`, `fleet_owner`, `fleet_array`, `fleet_end_id`, `username`, `ally_tag`, "; + $Query_PrepDefFleets .= "`morale_level`, `morale_droptime`, `morale_lastupdate`, "; + $Query_PrepDefFleets .= "`tech_weapons`, `tech_armour`, `tech_shielding`, `tech_laser`, `tech_ion`, `tech_plasma`, `tech_antimatter`, "; + $Query_PrepDefFleets .= "`tech_disintegration`, `tech_graviton`, `fleet_start_galaxy`, `fleet_start_system`, `fleet_start_planet` "; + $Query_PrepDefFleets .= "FROM {{table}} "; + $Query_PrepDefFleets .= "LEFT JOIN {{prefix}}users AS `users` ON `users`.`id` = `fleet_owner` "; + $Query_PrepDefFleets .= "LEFT JOIN {{prefix}}alliance AS `ally` ON `users`.`ally_id` = `ally`.`id` "; + $Query_PrepDefFleets .= "WHERE "; + $Query_PrepDefFleets .= "`fleet_end_id` IN ({$Temp1}) AND "; + $Query_PrepDefFleets .= "`fleet_mission` = 5 AND "; + $Query_PrepDefFleets .= "`fleet_start_time` <= UNIX_TIMESTAMP() AND "; + $Query_PrepDefFleets .= "`fleet_end_stay` > UNIX_TIMESTAMP(); -- FlyingFleetHandler.php [#11]"; + $Result_PrepDefFleets = doquery($Query_PrepDefFleets, 'fleets'); + while($FetchData = mysql_fetch_assoc($Result_PrepDefFleets)) + { + $_FleetCache['defFleets'][$FetchData['fleet_end_id']][$FetchData['fleet_id']] = $FetchData; + } + } + if(!empty($PrepareData['acsFleets'])) + { + $Temp1 = array(); + $Temp3 = array(); + foreach($PrepareData['acsFleets'] as $ACSFleetID => $Fleets) + { + foreach($Fleets as $FleetID) + { + $Temp1[] = $FleetID; + $Temp3[$FleetID] = $ACSFleetID; + } + } + $Temp2 = count($Temp1); + $Temp1 = implode(',', $Temp1); + $Query_PrepACSFleets = ''; + $Query_PrepACSFleets .= "SELECT `fleet_id`, `fleet_owner`, `fleet_array`, `username`, `ally_id`, `ally_tag`, "; + $Query_PrepACSFleets .= "`morale_level`, `morale_points`, `morale_droptime`, `morale_lastupdate`, "; + $Query_PrepACSFleets .= "`fleet_start_galaxy`, `fleet_start_system`, `fleet_start_planet`, `fleet_resource_metal`, `fleet_resource_crystal`, `fleet_resource_deuterium`, "; + $Query_PrepACSFleets .= "`tech_weapons`, `tech_armour`, `tech_shielding`, `tech_laser`, `tech_ion`, `tech_plasma`, `tech_antimatter`, `tech_disintegration`, `tech_graviton` "; + $Query_PrepACSFleets .= "FROM {{table}} "; + $Query_PrepACSFleets .= "LEFT JOIN {{prefix}}users as `users` ON `users`.`id` = `fleet_owner` "; + $Query_PrepACSFleets .= "LEFT JOIN {{prefix}}alliance AS `ally` ON `users`.`ally_id` = `ally`.`id` "; + $Query_PrepACSFleets .= "WHERE `fleet_id` IN ({$Temp1}) LIMIT {$Temp2}; -- FlyingFleetHandler.php [#12]"; + $Result_PrepACSFleets = doquery($Query_PrepACSFleets, 'fleets'); + while($FetchData = mysql_fetch_assoc($Result_PrepACSFleets)) + { + $_FleetCache['acsFleets'][$Temp3[$FetchData['fleet_id']]][] = $FetchData; + $PrepareData['taskData'][] = $FetchData['fleet_owner']; + } + } + if(!empty($PrepareData['taskData'])) + { + global $_User; + $Temp1 = array(); + foreach($PrepareData['taskData'] as $UserID) + { + if($UserID == $_User['id']) + { + $_FleetCache['userTasks'][$UserID] = $_User['tasks_done']; + } + elseif(!empty($PrepareData['users']) AND in_array($UserID, $PrepareData['users'])) + { + $_FleetCache['userTasks'][$UserID] = $_FleetCache['users'][$UserID]['tasks_done']; + } + else + { + $Temp1[] = $UserID; + } + } + if(!empty($Temp1)) + { + $Temp2 = count($Temp1); + $Temp1 = implode(',', $Temp1); + $Query_PrepUserTasks = ''; + $Query_PrepUserTasks .= "SELECT `id`, `tasks_done` FROM {{table}} "; + $Query_PrepUserTasks .= "WHERE `id` IN ({$Temp1}) LIMIT {$Temp2}; -- FlyingFleetHandler.php [#13]"; + $Result_PrepUserTasks = doquery($Query_PrepUserTasks, 'users'); + while($FetchData = mysql_fetch_assoc($Result_PrepUserTasks)) + { + $_FleetCache['userTasks'][$FetchData['id']] = $FetchData['tasks_done']; + } + } + } + if(!empty($PrepareData['galaxy'])) + { + if(in_array($_GalaxyRow['galaxy_id'], $PrepareData['galaxy'])) + { + $Temp1 = array_keys($PrepareData['galaxy'], $_GalaxyRow['galaxy_id']); + unset($PrepareData['galaxy'][$Temp1[0]]); + $_FleetCache['galaxy'][$_GalaxyRow['galaxy_id']] = $_GalaxyRow; + $_FleetCache['galaxyMap']['byPlanet'][$_GalaxyRow['id_planet']] = $_GalaxyRow['galaxy_id']; + if($_GalaxyRow['id_moon'] > 0) + { + $_FleetCache['galaxyMap']['byMoon'][$_GalaxyRow['id_moon']] = $_GalaxyRow['galaxy_id']; + } + } + if(!empty($PrepareData['galaxy'])) + { + $Temp1 = implode(',', $PrepareData['galaxy']); + $Temp2 = count($PrepareData['galaxy']); + $Query_PrepGalaxy = ''; + $Query_PrepGalaxy .= "SELECT `galaxy_id`, `id_planet`, `id_moon`, `metal`, `crystal` FROM {{table}} "; + $Query_PrepGalaxy .= "WHERE `galaxy_id` IN ({$Temp1}) LIMIT {$Temp2}; -- FlyingFleetHandler.php [#14]"; + $Result_PrepGalaxy = doquery($Query_PrepGalaxy, 'galaxy'); + while($FetchData = mysql_fetch_assoc($Result_PrepGalaxy)) + { + $_FleetCache['galaxy'][$FetchData['galaxy_id']] = $FetchData; + $_FleetCache['galaxyMap']['byPlanet'][$FetchData['id_planet']] = $FetchData['galaxy_id']; + if($FetchData['id_moon'] > 0) + { + $_FleetCache['galaxyMap']['byMoon'][$FetchData['id_moon']] = $FetchData['galaxy_id']; + } + } + } + } + // --- + $Fleets2Delete = array(); + $ACS2Delete = array(); + foreach($FleetTimes as $CalculationData) + { + // Investigate if mysql_data_seek should be replaced by HashMap of Fleets (for O(1) access to FleetRow instead of O(n)) + // May cause bad impact on memory usage + mysql_data_seek($Result_GetAllFleets, $CalculationData['rowNo']); + $CurrentFleet = mysql_fetch_assoc($Result_GetAllFleets); + $CurrentFleet['calcType'] = $CalculationData['type']; + + if(!empty($ChangeCoordinatesForFleets)) + { + $FoundKey = array_search($CurrentFleet['fleet_start_id'], $ChangeCoordinatesForFleets); + if($FoundKey > 0) + { + $ExplodeFoundKey = explode('<|>', $FoundKey); + $CurrentFleet['fleet_start_id'] = $ExplodeFoundKey[0]; + $CurrentFleet['attacking_planet_name'] = $ExplodeFoundKey[1]; + $CurrentFleet['fleet_start_type'] = 1; + } + else + { + $FoundKey = array_search($CurrentFleet['fleet_end_id'], $ChangeCoordinatesForFleets); + if($FoundKey > 0) + { + $ExplodeFoundKey = explode('<|>', $FoundKey); + $CurrentFleet['fleet_end_id'] = $ExplodeFoundKey[0]; + $CurrentFleet['endtarget_planet_name'] = $ExplodeFoundKey[1]; + $CurrentFleet['fleet_end_type'] = 1; + if($CurrentFleet['fleet_mission'] == 9) + { + $CurrentFleet['fleet_mission'] = 1; + } + } + } + } + + $MissionReturn = false; + switch($CurrentFleet['fleet_mission']) + { + case 1: + { + if($CurrentFleet['fleets_count'] > 0) + { + // Mission : Group Attack + if(!isset($Inc_MissionGroupAttack)) + { + $Inc_MissionGroupAttack = true; + include('MissionCaseGroupAttack.php'); + } + if(!isset($Inc_Function_CreateOneMoonRecord)) + { + $Inc_Function_CreateOneMoonRecord = true; + include('CreateOneMoonRecord.php'); + } + $MissionReturn = MissionCaseGroupAttack($CurrentFleet, $_FleetCache); + if(!empty($MissionReturn['DeleteACS'])) + { + $ACS2Delete[] = $MissionReturn['DeleteACS']; + } + } + else + { + // Mission : Attack + if(!isset($Inc_MissionAttack)) + { + $Inc_MissionAttack = true; + include('MissionCaseAttack.php'); + } + if(!isset($Inc_Function_CreateOneMoonRecord)) + { + $Inc_Function_CreateOneMoonRecord = true; + include('CreateOneMoonRecord.php'); + } + $MissionReturn = MissionCaseAttack($CurrentFleet, $_FleetCache); + if($CurrentFleet['acs_id'] > 0) + { + $ACS2Delete[] = $CurrentFleet['acs_id']; + } + } + break; + } + case 2: + { + // Mission : Attack in Group (Joined fleet) + // Make ReturnUpdate only if main fleet (GroupAttack Leader) was calculated + if($CurrentFleet['calcType'] == 3) + { + if(!isset($Inc_MissionAttack)) + { + $Inc_MissionAttack = true; + include('MissionCaseAttack.php'); + } + $MissionReturn = MissionCaseAttack($CurrentFleet, $_FleetCache); + } + break; + } + case 3: + { + // Mission: Transport + if(!isset($Inc_MissionTransport)) + { + $Inc_MissionTransport = true; + include('MissionCaseTransport.php'); + } + if($CurrentFleet['calcType'] == 1 && !isset($Inc_Function_StoreGoodsToPlanet)) + { + $Inc_Function_StoreGoodsToPlanet = true; + include('StoreGoodsToPlanet.php'); + } + $MissionReturn = MissionCaseTransport($CurrentFleet, $_FleetCache); + break; + } + case 4: + { + // Mission: Stay + if(!isset($Inc_MissionStay)) + { + $Inc_MissionStay = true; + include('MissionCaseStay.php'); + } + $MissionReturn = MissionCaseStay($CurrentFleet, $_FleetCache); + break; + } + case 5: + { + // Mission: Stay and Defend (for allys) + if(!isset($Inc_MissionStayAlly)) + { + $Inc_MissionStayAlly = true; + include('MissionCaseStayAlly.php'); + } + $MissionReturn = MissionCaseStayAlly($CurrentFleet, $_FleetCache); + break; + } + case 6: + { + // Mission: Spy + if(!isset($Inc_MissionSpy)) + { + $Inc_MissionSpy = true; + include('MissionCaseSpy.php'); + } + $MissionReturn = MissionCaseSpy($CurrentFleet, $_FleetCache); + break; + } + case 7: + { + // Mission: Colonisation + if(!isset($Inc_MissionColonisation)) + { + $Inc_MissionColonisation = true; + include('MissionCaseColonisation.php'); + include('CreateOnePlanetRecord.php'); + } + $MissionReturn = MissionCaseColonisation($CurrentFleet, $_FleetCache); + break; + } + case 8: + { + // Mission: Recycling + if(!isset($Inc_MissionRecycling)) + { + $Inc_MissionRecycling = true; + include('MissionCaseRecycling.php'); + } + $MissionReturn = MissionCaseRecycling($CurrentFleet, $_FleetCache); + break; + } + case 9: + { + // Mission: Moon destruction + if(!isset($Inc_MissionDestruction)) + { + $Inc_MissionDestruction = true; + include('MissionCaseDestruction.php'); + } + if(!isset($Inc_Function_CreateOneMoonRecord)) + { + $Inc_Function_CreateOneMoonRecord = true; + include('CreateOneMoonRecord.php'); + } + $MissionReturn = MissionCaseDestruction($CurrentFleet, $_FleetCache); + if(isset($MissionReturn['MoonDestroyed']) && $MissionReturn['MoonDestroyed'] === true) + { + if($CurrentFleet['fleet_end_id'] == $planet['id']) + { + $FleetHandlerReturn['ThisMoonDestroyed'] = true; + } + } + break; + } + case 10: + { + // Mission: Interplanetar Attack + if(!isset($Inc_MissionMIP)) + { + $Inc_MissionMIP = true; + include('MissionCaseMIP.php'); + } + $MissionReturn = MissionCaseMIP($CurrentFleet, $_FleetCache); + break; + } + case 15: + { + // Mission: Expedition + if(!isset($Inc_MissionExpedition)) + { + $Inc_MissionExpedition = true; + include('MissionCaseExpedition.php'); + } + $MissionReturn = MissionCaseExpedition($CurrentFleet); + break; + } + default: + { + // Bad mission number!!! + $Fleets2Delete[] = $CurrentFleet['fleet_id']; + break; + } + } + + if(!empty($MissionReturn['FleetsToDelete'])) + { + foreach($MissionReturn['FleetsToDelete'] as $ThisID) + { + if(!in_array($ThisID, $Fleets2Delete)) + { + $Fleets2Delete[] = $ThisID; + } + } + } + + if(!empty($MissionReturn['FleetArchive'])) + { + foreach($MissionReturn['FleetArchive'] as $FleetID => $ArchiveData) + { + $ThisResult = array_merge($FleetArchive_Pattern, $ArchiveData); + if(!isset($Updater_FleetArchive[$FleetID])) + { + $Updater_FleetArchive[$FleetID] = $ThisResult; + } + else + { + $Pointer = &$Updater_FleetArchive[$FleetID]; + foreach($ThisResult as $Key => $Value) + { + if($Value !== null) + { + if($Pointer[$Key] !== null) + { + if(substr($Pointer[$Key], 0, 1) != '!') + { + if(substr($Value, 0, 2) == '"+') + { + $Value = rtrim($Pointer[$Key], '"').str_replace('"+', '', $Value); + } + $Pointer[$Key] = $Value; + } + } + else + { + $Pointer[$Key] = $Value; + } + } + } + } + } + } + } + + // $_FleetCache Handler + if(!empty($_FleetCache['updatePlanets'])) + { + foreach($_FleetCache['updatePlanets'] as $ThisID => $ThisData) + { + if($ThisData === true) + { + $Results['planets'][] = &$_FleetCache['planets'][$ThisID]; + } + } + $Results['users'] = &$_FleetCache['users']; + HandlePlanetUpdate_MultiUpdate($Results, array(), true, true); + $Results = null; + } + if(!empty($_FleetCache['addToPlanets']['data'])) + { + $TempArray = array(); + $TempArray3 = array(); + $TempArray4 = array(); + foreach($_FleetCache['addToPlanets']['data'] as $ThisID => $ThisData) + { + $TempArray2 = array(); + foreach($_FleetCache['addToPlanets']['fields'] as $ThisField) + { + $TempArray2[] = (empty($ThisData[$ThisField]) ? '0' : $ThisData[$ThisField]); + } + $TempArray2 = implode(', ', $TempArray2); + $TempArray[] = "({$ThisID}, {$TempArray2})"; + } + foreach($_FleetCache['addToPlanets']['fields'] as $ThisField) + { + $TempArray3[] = "`{$ThisField}`"; + $TempArray4[] = "`{$ThisField}` = `{$ThisField}` + VALUES(`{$ThisField}`)"; + } + $TempArray = implode(', ', $TempArray); + $TempArray3 = implode(', ', $TempArray3); + $TempArray4 = implode(', ', $TempArray4); + $Query_AddToPlanets = ''; + $Query_AddToPlanets .= "INSERT INTO {{table}} (`id`, {$TempArray3}) VALUES {$TempArray}"; + $Query_AddToPlanets .= " ON DUPLICATE KEY UPDATE {$TempArray4}; -- FlyingFleetHandler.php [#15]"; + doquery($Query_AddToPlanets, 'planets'); + } + if(!empty($_FleetCache['galaxy']) AND $_FleetCache['updated']['galaxy'] === true) + { + $TempArray = array(); + foreach($_FleetCache['galaxy'] as $ThisID => $ThisData) + { + if($ThisData['updated'] === true) + { + $TempArray[] = "({$ThisID}, {$ThisData['metal']}, {$ThisData['crystal']})"; + } + } + if(!empty($TempArray)) + { + $Query_UpdCachedGalaxy = ''; + $Query_UpdCachedGalaxy .= "INSERT INTO {{table}} (`galaxy_id`, `metal`, `crystal`) VALUES "; + $Query_UpdCachedGalaxy .= implode(', ', $TempArray); + $Query_UpdCachedGalaxy .= " ON DUPLICATE KEY UPDATE "; + $Query_UpdCachedGalaxy .= "`metal` = VALUES(`metal`), "; + $Query_UpdCachedGalaxy .= "`crystal` = VALUES(`crystal`); -- FlyingFleetHandler.php [#16]"; + doquery($Query_UpdCachedGalaxy, 'galaxy'); + } + } + if(!empty($_FleetCache['deleteMoons'])) + { + $Temp2 = count($_FleetCache['deleteMoons']); + $Temp1 = implode(',', $_FleetCache['deleteMoons']); + $Query_DeleteMoons = "DELETE FROM {{table}} WHERE `id` IN ({$Temp1}) LIMIT {$Temp2}; -- FlyingFleetHandler.php [#17]"; + doquery($Query_DeleteMoons, 'planets'); + } + if(!empty($_FleetCache['moonGalaxyUpdate'])) + { + $Temp2 = count($_FleetCache['moonGalaxyUpdate']); + $Temp1 = implode(',', $_FleetCache['moonGalaxyUpdate']); + $Query_UpdMoonGalaxy = "UPDATE {{table}} SET `id_moon` = 0 WHERE `id_planet` IN ({$Temp1}) LIMIT {$Temp2}; -- FlyingFleetHandler.php [#18]"; + doquery($Query_UpdMoonGalaxy, 'galaxy'); + } + if(!empty($_FleetCache['moonUserUpdate'])) + { + $TempArray = array(); + foreach($_FleetCache['moonUserUpdate'] as $ThisUser => $ThisID) + { + $TempArray[] = "({$ThisUser}, {$ThisID})"; + } + $TempArray = implode(',', $TempArray); + $Query_UpdMoonUser = ''; + $Query_UpdMoonUser .= "INSERT INTO {{table}} (`id`, `current_planet`) VALUES {$TempArray} "; + $Query_UpdMoonUser .= "ON DUPLICATE KEY UPDATE `current_planet` = VALUES(`current_planet`); -- FlyingFleetHandler.php [#19]"; + doquery($Query_UpdMoonUser, 'users'); + } + if(!empty($_FleetCache['MoraleCache'])) + { + $TempArray = array(); + foreach($_FleetCache['MoraleCache'] as $ThisUserID => $ThisData) + { + $TempArray[] = "({$ThisUserID}, {$ThisData['level']}, {$ThisData['droptime']}, {$ThisData['lastupdate']})"; + } + $TempArray = implode(',', $TempArray); + $Query_UpdUserMorale = ''; + $Query_UpdUserMorale .= "INSERT INTO {{table}} (`id`, `morale_level`, `morale_droptime`, `morale_lastupdate`) VALUES {$TempArray} "; + $Query_UpdUserMorale .= "ON DUPLICATE KEY UPDATE "; + $Query_UpdUserMorale .= "`morale_level` = VALUES(`morale_level`), "; + $Query_UpdUserMorale .= "`morale_droptime` = VALUES(`morale_droptime`), "; + $Query_UpdUserMorale .= "`morale_lastupdate` = VALUES(`morale_lastupdate`); -- FlyingFleetHandler.php [#20]"; + doquery($Query_UpdUserMorale, 'users'); + } + + if(!empty($_FleetCache['updateFleets'])) + { + $TempArray = array(); + foreach($_FleetCache['updateFleets'] as $ThisID => $ThisData) + { + if(empty($ThisData['fleet_array'])) + { + $ThisData['fleet_array'] = "''"; + $ThisData['fleet_amount'] = '0'; + } + else + { + $ThisData['fleet_array'] = "'{$ThisData['fleet_array']}'"; + } + if(empty($ThisData['fleet_mess'])) + { + $ThisData['fleet_mess'] = '0'; + } + if(empty($ThisData['fleet_resource_metal'])) + { + $ThisData['fleet_resource_metal'] = '0'; + } + if(empty($ThisData['fleet_resource_crystal'])) + { + $ThisData['fleet_resource_crystal'] = '0'; + } + if(empty($ThisData['fleet_resource_deuterium'])) + { + $ThisData['fleet_resource_deuterium'] = '0'; + } + $TempArray[] = "({$ThisID}, {$ThisData['fleet_amount']}, {$ThisData['fleet_array']}, {$ThisData['fleet_mess']}, {$ThisData['fleet_resource_metal']}, {$ThisData['fleet_resource_crystal']}, {$ThisData['fleet_resource_deuterium']})"; + } + $TempArray = implode(',', $TempArray); + $Query_UpdateFleets = ''; + $Query_UpdateFleets .= "INSERT INTO {{table}} (`fleet_id`, `fleet_amount`, `fleet_array`, `fleet_mess`, `fleet_resource_metal`, `fleet_resource_crystal`, `fleet_resource_deuterium`) "; + $Query_UpdateFleets .= "VALUES {$TempArray} "; + $Query_UpdateFleets .= "ON DUPLICATE KEY UPDATE "; + $Query_UpdateFleets .= "`fleet_amount` = IF(VALUES(`fleet_amount`) = 0, `fleet_amount`, VALUES(`fleet_amount`)), "; + $Query_UpdateFleets .= "`fleet_array` = IF(VALUES(`fleet_array`) = '', `fleet_array`, VALUES(`fleet_array`)), "; + $Query_UpdateFleets .= "`fleet_mess` = IF(VALUES(`fleet_mess`) = 0, `fleet_mess`, VALUES(`fleet_mess`)), "; + $Query_UpdateFleets .= "`fleet_resource_metal` = `fleet_resource_metal` + VALUES(`fleet_resource_metal`), "; + $Query_UpdateFleets .= "`fleet_resource_crystal` = `fleet_resource_crystal` + VALUES(`fleet_resource_crystal`), "; + $Query_UpdateFleets .= "`fleet_resource_deuterium` = `fleet_resource_deuterium` + VALUES(`fleet_resource_deuterium`); -- FlyingFleetHandler.php [#21]"; + doquery($Query_UpdateFleets, 'fleets'); + } + // --- + + if(!isset($FleetHandlerReturn['ThisMoonDestroyed'])) + { + if(!empty($_FleetCache['planets'][$planet['id']])) + { + $planet = $_FleetCache['planets'][$planet['id']]; + } + else + { + $planet = doquery("SELECT * FROM {{table}} WHERE `id` = {$planet['id']}; -- FlyingFleetHandler.php [#22]", 'planets', true); + } + } + if(isset($_GalaxyRow['galaxy_id']) && $_GalaxyRow['galaxy_id'] > 0 AND !empty($_FleetCache['galaxy'][$_GalaxyRow['galaxy_id']])) + { + $_GalaxyRow['metal'] = $_FleetCache['galaxy'][$_GalaxyRow['galaxy_id']]['metal']; + $_GalaxyRow['crystal'] = $_FleetCache['galaxy'][$_GalaxyRow['galaxy_id']]['crystal']; + } + + if(!empty($Updater_FleetArchive)) + { + $Qry_Updater_FleetArchive = "INSERT INTO {{table}} VALUES "; + foreach($Updater_FleetArchive as $FleetID => $Data) + { + $Qry_Updater_FleetArchive_Row = "({$FleetID}, "; + foreach($Data as &$DataVal) + { + if($DataVal === null) + { + $DataVal = '"!noupd!"'; + } + elseif($DataVal === 0) + { + $DataVal = '0'; + } + elseif($DataVal === '') + { + $DataVal = '""'; + } + elseif($DataVal === true) + { + $DataVal = 'true'; + } + elseif($DataVal === false) + { + $DataVal = 'false'; + } + elseif(substr($DataVal, 0, 1) == '!') + { + $DataVal = preg_replace('/^\!/', '', $DataVal); + } + } + $Qry_Updater_FleetArchive_Row .= implode(', ', $Data); + $Qry_Updater_FleetArchive_Row .= ')'; + $Qry_Updater_FleetArchive_Array[] = $Qry_Updater_FleetArchive_Row; + } + $Qry_Updater_FleetArchive .= implode(', ', $Qry_Updater_FleetArchive_Array); + $Qry_Updater_FleetArchive .= " ON DUPLICATE KEY UPDATE "; + foreach($FleetArchive_Fields as $FieldName) + { + $Qry_Updater_FleetArchive_Array2[] = "`{$FieldName}` = IF((VALUES(`{$FieldName}`) = \"!noupd!\"), `{$FieldName}`, IF(SUBSTRING(VALUES(`{$FieldName}`), 1, 1) = '+', CONCAT(`{$FieldName}`, SUBSTRING(VALUES(`{$FieldName}`), 2)), VALUES(`{$FieldName}`)))"; + } + $Qry_Updater_FleetArchive .= implode(', ', $Qry_Updater_FleetArchive_Array2); + $Qry_Updater_FleetArchive .= "; -- FlyingFleetHandler.php [#23]"; + doquery($Qry_Updater_FleetArchive, 'fleet_archive'); + } + + if(!empty($UserStatsData)) + { + $QryUsersStats = ''; + $QryUsersStats .= "INSERT INTO {{table}} (`A_UserID`, `ustat_raids_won`, `ustat_raids_draw`, `ustat_raids_lost`, `ustat_raids_acs_won`, `ustat_raids_inAlly`, `ustat_raids_missileAttack`, `ustat_moons_destroyed`, `ustat_moons_created`, `ustat_other_expeditions_count`, {$CreateAchievementKeys}) VALUES "; + foreach($UserStatsData as $UserID => $Data) + { + if($UserID <= 0) + { + continue; + } + foreach($Data as &$Value) + { + if($Value == '') + { + $Value = '""'; + } + elseif($Value === 0) + { + $Value = '0'; + } + } + $QryUsersStatsA[] = "({$UserID}, ".implode(', ', $Data).")"; + } + $QryUsersStats .= implode(', ', $QryUsersStatsA); + $QryUsersStats .= " ON DUPLICATE KEY UPDATE "; + $QryUsersStats .= "`ustat_raids_won` = `ustat_raids_won` + VALUES(`ustat_raids_won`), "; + $QryUsersStats .= "`ustat_raids_draw` = `ustat_raids_draw` + VALUES(`ustat_raids_draw`), "; + $QryUsersStats .= "`ustat_raids_lost` = `ustat_raids_lost` + VALUES(`ustat_raids_lost`), "; + $QryUsersStats .= "`ustat_raids_acs_won` = `ustat_raids_acs_won` + VALUES(`ustat_raids_acs_won`), "; + $QryUsersStats .= "`ustat_raids_inAlly` = `ustat_raids_inAlly` + VALUES(`ustat_raids_inAlly`), "; + $QryUsersStats .= "`ustat_raids_missileAttack` = `ustat_raids_missileAttack` + VALUES(`ustat_raids_missileAttack`), "; + $QryUsersStats .= "`ustat_moons_destroyed` = `ustat_moons_destroyed` + VALUES(`ustat_moons_destroyed`), "; + $QryUsersStats .= "`ustat_moons_created` = `ustat_moons_created` + VALUES(`ustat_moons_created`), "; + $QryUsersStats .= "`ustat_other_expeditions_count` = `ustat_other_expeditions_count` + VALUES(`ustat_other_expeditions_count`)"; + if(!empty($UserStatsUpQuery)) + { + $QryUsersStats .= ", ".implode(', ', $UserStatsUpQuery); + } + $QryUsersStats .= '; -- FlyingFleetHandler.php [#24]'; + doquery($QryUsersStats, 'achievements_stats'); + } + + if(!empty($ACS2Delete)) + { + doquery("DELETE FROM {{table}} WHERE `id` IN (".implode(', ', $ACS2Delete)."); -- FlyingFleetHandler.php [#25]", 'acs'); + } + if(!empty($Fleets2Delete)) + { + doquery("DELETE FROM {{table}} WHERE `fleet_id` IN (".implode(', ', $Fleets2Delete)."); -- FlyingFleetHandler.php [#26]", 'fleets'); + } + doquery('UNLOCK TABLES; -- FlyingFleetHandler.php [#27]', ''); + + if(!empty($_Cache['Messages'])) + { + SendSimpleMultipleMessages($_Cache['Messages']); + $_Cache['Messages'] = array(); + } + } + + if(!empty($_BenchTool)){ $_BenchTool->simpleCountStop(); } + + if(!isset($FleetHandlerReturn)) + { + $FleetHandlerReturn = array(); + } + return $FleetHandlerReturn; + } +} + +?> diff --git a/includes/functions/GalaxyLegendPopup.php b/includes/functions/GalaxyLegendPopup.php index 256a7d306..91e9b8377 100644 --- a/includes/functions/GalaxyLegendPopup.php +++ b/includes/functions/GalaxyLegendPopup.php @@ -1,33 +1,33 @@ - $_Lang['Legend'], - 'User_NonActivatedText' => $_Lang['User_NonActivatedText'], - 'User_NonActivated' => $_Lang['User_NonActivated'], - 'FleetBlockadeUser' => $_Lang['FleetBlockadeUser'], - 'Fleet_Blockade_Protected' => $_Lang['Fleet_Blockade_Protected'], - 'Strong_player' => $_Lang['Strong_player'], - 'strong_player_shortcut' => $_Lang['strong_player_shortcut'], - 'Weak_player' => $_Lang['Weak_player'], - 'weak_player_shortcut' => $_Lang['weak_player_shortcut'], - 'New_player' => sprintf($_Lang['New_player'], prettyNumber($_GameConfig['Protection_NewPlayerTime'] / 3600)), - 'new_player_shortcut' => $_Lang['new_player_shortcut'], - 'Way_vacation' => $_Lang['Way_vacation'], - 'vacation_shortcut' => $_Lang['vacation_shortcut'], - 'Pendent_user' => $_Lang['Pendent_user'], - 'banned_shortcut' => $_Lang['banned_shortcut'], - 'Inactive_7_days' => $_Lang['Inactive_7_days'], - 'inactif_7_shortcut' => $_Lang['inactif_7_shortcut'], - 'Inactive_28_days' => $_Lang['Inactive_28_days'], - 'inactif_28_shortcut' => $_Lang['inactif_28_shortcut'], - ); - return parsetemplate($TPL, $Parse); -} - -?> \ No newline at end of file + $_Lang['Legend'], + 'User_NonActivatedText' => $_Lang['User_NonActivatedText'], + 'User_NonActivated' => $_Lang['User_NonActivated'], + 'FleetBlockadeUser' => $_Lang['FleetBlockadeUser'], + 'Fleet_Blockade_Protected' => $_Lang['Fleet_Blockade_Protected'], + 'Strong_player' => $_Lang['Strong_player'], + 'strong_player_shortcut' => $_Lang['strong_player_shortcut'], + 'Weak_player' => $_Lang['Weak_player'], + 'weak_player_shortcut' => $_Lang['weak_player_shortcut'], + 'New_player' => sprintf($_Lang['New_player'], prettyNumber($_GameConfig['Protection_NewPlayerTime'] / 3600)), + 'new_player_shortcut' => $_Lang['new_player_shortcut'], + 'Way_vacation' => $_Lang['Way_vacation'], + 'vacation_shortcut' => $_Lang['vacation_shortcut'], + 'Pendent_user' => $_Lang['Pendent_user'], + 'banned_shortcut' => $_Lang['banned_shortcut'], + 'Inactive_7_days' => $_Lang['Inactive_7_days'], + 'inactif_7_shortcut' => $_Lang['inactif_7_shortcut'], + 'Inactive_28_days' => $_Lang['Inactive_28_days'], + 'inactif_28_shortcut' => $_Lang['inactif_28_shortcut'], + ); + return parsetemplate($TPL, $Parse); +} + +?> diff --git a/includes/functions/GalaxyRowActions.php b/includes/functions/GalaxyRowActions.php index 162a3244e..bba3cffe6 100644 --- a/includes/functions/GalaxyRowActions.php +++ b/includes/functions/GalaxyRowActions.php @@ -1,87 +1,87 @@ - 0 && $GalaxyRowPlayer['id'] != $_User['id']) - { - $HiddenOptions = $OptionsCount = 4; - - $Parse = array - ( - 'Hide_Spy' => ' hide', - 'Hide_Msg' => ' hide', - 'Hide_Buddy' => ' hide', - 'Hide_Rocket' => ' hide', - 'Galaxy' => $Galaxy, - 'System' => $System, - 'Planet' => $Planet, - 'SkinPath' => $_SkinPath, - 'UserID' => $GalaxyRowPlayer['id'], - 'Current' => $_User['current_planet'], - ); - - if($_User['settings_mis'] == 1) - { - if($CurrentMIP > 0) - { - if($GalaxyRowPlanet['galaxy'] == $CurrentGalaxy) - { - $MiRange = GetMissileRange(); - $SystemLimitMin = $CurrentSystem - $MiRange; - if($SystemLimitMin < 1) - { - $SystemLimitMin = 1; - } - $SystemLimitMax = $CurrentSystem + $MiRange; - if($System <= $SystemLimitMax AND $System >= $SystemLimitMin) - { - --$HiddenOptions; - $Parse['Hide_Rocket'] = ''; - } - } - } - } - if($_User['settings_esp'] == 1) - { - --$HiddenOptions; - $Parse['Hide_Spy'] = ''; - } - if($_User['settings_wri'] == 1 AND $GalaxyRowPlanet['id_owner'] > 0) - { - --$HiddenOptions; - $Parse['Hide_Msg'] = ''; - } - if($_User['settings_bud'] == 1 AND $GalaxyRowPlanet['id_owner'] > 0) - { - if(!in_array($GalaxyRowPlayer['id'], $MyBuddies)) - { - --$HiddenOptions; - $Parse['Hide_Buddy'] = ''; - } - } - - if($OptionsCount == $HiddenOptions) - { - $Result = ' '; - } - else - { - $Result = parsetemplate($TPL, $Parse); - } - } - else - { - $Result = ' '; - } - - return $Result; -} - -?> \ No newline at end of file + 0 && $GalaxyRowPlayer['id'] != $_User['id']) + { + $HiddenOptions = $OptionsCount = 4; + + $Parse = array + ( + 'Hide_Spy' => ' hide', + 'Hide_Msg' => ' hide', + 'Hide_Buddy' => ' hide', + 'Hide_Rocket' => ' hide', + 'Galaxy' => $Galaxy, + 'System' => $System, + 'Planet' => $Planet, + 'SkinPath' => $_SkinPath, + 'UserID' => $GalaxyRowPlayer['id'], + 'Current' => $_User['current_planet'], + ); + + if($_User['settings_mis'] == 1) + { + if($CurrentMIP > 0) + { + if($GalaxyRowPlanet['galaxy'] == $CurrentGalaxy) + { + $MiRange = GetMissileRange(); + $SystemLimitMin = $CurrentSystem - $MiRange; + if($SystemLimitMin < 1) + { + $SystemLimitMin = 1; + } + $SystemLimitMax = $CurrentSystem + $MiRange; + if($System <= $SystemLimitMax AND $System >= $SystemLimitMin) + { + --$HiddenOptions; + $Parse['Hide_Rocket'] = ''; + } + } + } + } + if($_User['settings_esp'] == 1) + { + --$HiddenOptions; + $Parse['Hide_Spy'] = ''; + } + if($_User['settings_wri'] == 1 AND $GalaxyRowPlanet['id_owner'] > 0) + { + --$HiddenOptions; + $Parse['Hide_Msg'] = ''; + } + if($_User['settings_bud'] == 1 AND $GalaxyRowPlanet['id_owner'] > 0) + { + if(!in_array($GalaxyRowPlayer['id'], $MyBuddies)) + { + --$HiddenOptions; + $Parse['Hide_Buddy'] = ''; + } + } + + if($OptionsCount == $HiddenOptions) + { + $Result = ' '; + } + else + { + $Result = parsetemplate($TPL, $Parse); + } + } + else + { + $Result = ' '; + } + + return $Result; +} + +?> diff --git a/includes/functions/GalaxyRowAlly.php b/includes/functions/GalaxyRowAlly.php index ecbb9ac74..c058bd43a 100644 --- a/includes/functions/GalaxyRowAlly.php +++ b/includes/functions/GalaxyRowAlly.php @@ -1,48 +1,48 @@ - 0) - { - if(!empty($GalaxyRowUser['ally_web']) AND ($GalaxyRowUser['ally_web_reveal'] == 1 OR $GalaxyRowUser['ally_id'] == $_User['ally_id'])) - { - $AllyWeb = $GalaxyRowUser['ally_web']; - } - - $Parse = array - ( - 'AllyID' => $GalaxyRowUser['ally_id'], - 'AllyClass' => ($GalaxyRowUser['ally_id'] == $_User['ally_id'] ? 'lime' : (isset($MyAllyPacts[$GalaxyRowUser['ally_id']]) && $MyAllyPacts[$GalaxyRowUser['ally_id']] > 0 ? 'skyblue' : '')), - 'Lang_Ally' => $_Lang['Alliance'], - 'AllyName' => $GalaxyRowUser['ally_name'], - 'Lang_MemberCount' => $_Lang['gl_allymembers'], - 'AllyMembers' => prettyNumber($GalaxyRowUser['ally_members']), - 'Lang_Internal' => $_Lang['gl_ally_internal'], - 'AllyPosition' => (string) ($GalaxyRowUser['ally_total_rank'] + 0), - 'AllyPositionPretty' => (string) ($GalaxyRowUser['ally_total_rank'] + 0), - 'Lang_Stats' => $_Lang['gl_stats'], - 'AllyWeb' => (isset($AllyWeb) ? $AllyWeb : ''), - 'Lang_Web' => $_Lang['gl_ally_web'], - 'Hide_AllyWeb' => ($GalaxyRowUser['ally_web_reveal'] != 1 ? ' class=hide' : ''), - 'AllyTag' => $GalaxyRowUser['ally_tag'], - ); - - $Result = parsetemplate($TPL, $Parse); - } - else - { - $Result = ' '; - } - - return $Result; -} - -?> \ No newline at end of file + 0) + { + if(!empty($GalaxyRowUser['ally_web']) AND ($GalaxyRowUser['ally_web_reveal'] == 1 OR $GalaxyRowUser['ally_id'] == $_User['ally_id'])) + { + $AllyWeb = $GalaxyRowUser['ally_web']; + } + + $Parse = array + ( + 'AllyID' => $GalaxyRowUser['ally_id'], + 'AllyClass' => ($GalaxyRowUser['ally_id'] == $_User['ally_id'] ? 'lime' : (isset($MyAllyPacts[$GalaxyRowUser['ally_id']]) && $MyAllyPacts[$GalaxyRowUser['ally_id']] > 0 ? 'skyblue' : '')), + 'Lang_Ally' => $_Lang['Alliance'], + 'AllyName' => $GalaxyRowUser['ally_name'], + 'Lang_MemberCount' => $_Lang['gl_allymembers'], + 'AllyMembers' => prettyNumber($GalaxyRowUser['ally_members']), + 'Lang_Internal' => $_Lang['gl_ally_internal'], + 'AllyPosition' => (string) ($GalaxyRowUser['ally_total_rank'] + 0), + 'AllyPositionPretty' => (string) ($GalaxyRowUser['ally_total_rank'] + 0), + 'Lang_Stats' => $_Lang['gl_stats'], + 'AllyWeb' => (isset($AllyWeb) ? $AllyWeb : ''), + 'Lang_Web' => $_Lang['gl_ally_web'], + 'Hide_AllyWeb' => ($GalaxyRowUser['ally_web_reveal'] != 1 ? ' class=hide' : ''), + 'AllyTag' => $GalaxyRowUser['ally_tag'], + ); + + $Result = parsetemplate($TPL, $Parse); + } + else + { + $Result = ' '; + } + + return $Result; +} + +?> diff --git a/includes/functions/GalaxyRowDebris.php b/includes/functions/GalaxyRowDebris.php index 7b1c603ff..f2042bb46 100644 --- a/includes/functions/GalaxyRowDebris.php +++ b/includes/functions/GalaxyRowDebris.php @@ -1,72 +1,72 @@ - '; - if($GalaxyRow) - { - $TotalDebris = $GalaxyRow['metal'] + $GalaxyRow['crystal']; - if($TotalDebris > 0) - { - $RecNeeded = ceil($TotalDebris / $_Vars_Prices[209]['capacity']); - if($RecNeeded < $CurrentRC) - { - $RecSended = $RecNeeded; - } - else if($RecNeeded >= $CurrentRC) - { - $RecSended = $CurrentRC; - } - else - { - $RecSended = $RecyclerCount; - } - - $BackgroundColor = null; - if($TotalDebris >= 10000000) - { - $BackgroundColor = 'bgBig'; - } - else if($TotalDebris >= 1000000) - { - $BackgroundColor = 'bgMed'; - } - else if($TotalDebris >= 100000) - { - $BackgroundColor = 'bgSmall'; - } - - $Parse = array - ( - 'Lang_Debris' => $_Lang['Debris'], - 'Galaxy' => $Galaxy, - 'System' => $System, - 'Planet' => $Planet, - 'PlanetType' => $PlanetType, - 'SkinPath' => $_SkinPath, - 'Lang_Resource' => $_Lang['gl_ressource'], - 'Lang_Metal' => $_Lang['Metal'], - 'Metal' => prettyNumber($GalaxyRow['metal']), - 'Lang_Crystal' => $_Lang['Crystal'], - 'Crystal' => prettyNumber($GalaxyRow['crystal']), - 'Lang_Actions' => $_Lang['Actions'], - 'Lang_Mission' => $_Lang['type_mission'][8], - 'BackgroundColor' => $BackgroundColor, - ); - - $Result = parsetemplate($TPL, $Parse); - } - } - - return $Result; -} - -?> \ No newline at end of file + '; + if($GalaxyRow) + { + $TotalDebris = $GalaxyRow['metal'] + $GalaxyRow['crystal']; + if($TotalDebris > 0) + { + $RecNeeded = ceil($TotalDebris / $_Vars_Prices[209]['capacity']); + if($RecNeeded < $CurrentRC) + { + $RecSended = $RecNeeded; + } + else if($RecNeeded >= $CurrentRC) + { + $RecSended = $CurrentRC; + } + else + { + $RecSended = $RecyclerCount; + } + + $BackgroundColor = null; + if($TotalDebris >= 10000000) + { + $BackgroundColor = 'bgBig'; + } + else if($TotalDebris >= 1000000) + { + $BackgroundColor = 'bgMed'; + } + else if($TotalDebris >= 100000) + { + $BackgroundColor = 'bgSmall'; + } + + $Parse = array + ( + 'Lang_Debris' => $_Lang['Debris'], + 'Galaxy' => $Galaxy, + 'System' => $System, + 'Planet' => $Planet, + 'PlanetType' => $PlanetType, + 'SkinPath' => $_SkinPath, + 'Lang_Resource' => $_Lang['gl_ressource'], + 'Lang_Metal' => $_Lang['Metal'], + 'Metal' => prettyNumber($GalaxyRow['metal']), + 'Lang_Crystal' => $_Lang['Crystal'], + 'Crystal' => prettyNumber($GalaxyRow['crystal']), + 'Lang_Actions' => $_Lang['Actions'], + 'Lang_Mission' => $_Lang['type_mission'][8], + 'BackgroundColor' => $BackgroundColor, + ); + + $Result = parsetemplate($TPL, $Parse); + } + } + + return $Result; +} + +?> diff --git a/includes/functions/GalaxyRowMoon.php b/includes/functions/GalaxyRowMoon.php index 22c85804c..14fc79ca8 100644 --- a/includes/functions/GalaxyRowMoon.php +++ b/includes/functions/GalaxyRowMoon.php @@ -1,81 +1,81 @@ - 0) - { - $MoonCount += 1; - - if($GalaxyRowUser['id'] != $_User['id']) - { - $Links[] = array('prio' => 1, 'txt' => "{$_Lang['type_mission'][6]}"); - $Links[] = array('prio' => 2, 'txt' => '', 'html' => ' '); - $Links[] = array('prio' => 3, 'txt' => "{$_Lang['type_mission'][1]}"); - if($GalaxyRowUser['id'] > 0) - { - if(($GalaxyRowUser['ally_id'] == $_User['ally_id'] AND $_User['ally_id'] > 0) OR in_array($GalaxyRowUser['id'], $MyBuddies) OR (isset($MyAllyPacts[$GalaxyRowUser['ally_id']]) && $MyAllyPacts[$GalaxyRowUser['ally_id']] >= 3)) - { - $Links[] = array('prio' => 4, 'txt' => "{$_Lang['type_mission'][5]}"); - } - } - if($CanDestroy) - { - $Links[] = array('prio' => 5, 'txt' => "{$_Lang['type_mission'][9]}"); - } - } - else - { - $Links[] = array('prio' => 6, 'txt' => "{$_Lang['type_mission'][4]}"); - } - $Links[] = array('prio' => 7, 'txt' => "{$_Lang['type_mission'][3]}"); - - foreach($Links as $Index => $Data) - { - $PriorityArray[$Index] = $Data['prio']; - } - array_multisort($PriorityArray, SORT_ASC, $Links); - - $Parse = array - ( - 'Lang_Moon' => $_Lang['Moon'], - 'MoonName' => $GalaxyRowPlanet['name'], - 'Galaxy' => $Galaxy, - 'System' => $System, - 'Planet' => $Planet, - 'SkinPath' => $_SkinPath, - 'Lang_Diameter' => $_Lang['diameter'], - 'Diameter' => prettyNumber($GalaxyRowPlanet['diameter']), - 'Diameter_Units' => $_Lang['diameter_units'], - 'RowCount' => (count($Links) + 2), - 'Links' => '' - ); - foreach($Links as $Index => $Data) - { - if(!empty($Data['html'])) - { - $Parse['Links'] .= "{$Data['html']}"; - } - else - { - $Parse['Links'] .= "{$Data['txt']}"; - } - } - - $Result = parsetemplate($TPL, $Parse); - } - else - { - $Result = ' '; - } - - return $Result; -} - -?> \ No newline at end of file + 0) + { + $MoonCount += 1; + + if($GalaxyRowUser['id'] != $_User['id']) + { + $Links[] = array('prio' => 1, 'txt' => "{$_Lang['type_mission'][6]}"); + $Links[] = array('prio' => 2, 'txt' => '', 'html' => ' '); + $Links[] = array('prio' => 3, 'txt' => "{$_Lang['type_mission'][1]}"); + if($GalaxyRowUser['id'] > 0) + { + if(($GalaxyRowUser['ally_id'] == $_User['ally_id'] AND $_User['ally_id'] > 0) OR in_array($GalaxyRowUser['id'], $MyBuddies) OR (isset($MyAllyPacts[$GalaxyRowUser['ally_id']]) && $MyAllyPacts[$GalaxyRowUser['ally_id']] >= 3)) + { + $Links[] = array('prio' => 4, 'txt' => "{$_Lang['type_mission'][5]}"); + } + } + if($CanDestroy) + { + $Links[] = array('prio' => 5, 'txt' => "{$_Lang['type_mission'][9]}"); + } + } + else + { + $Links[] = array('prio' => 6, 'txt' => "{$_Lang['type_mission'][4]}"); + } + $Links[] = array('prio' => 7, 'txt' => "{$_Lang['type_mission'][3]}"); + + foreach($Links as $Index => $Data) + { + $PriorityArray[$Index] = $Data['prio']; + } + array_multisort($PriorityArray, SORT_ASC, $Links); + + $Parse = array + ( + 'Lang_Moon' => $_Lang['Moon'], + 'MoonName' => $GalaxyRowPlanet['name'], + 'Galaxy' => $Galaxy, + 'System' => $System, + 'Planet' => $Planet, + 'SkinPath' => $_SkinPath, + 'Lang_Diameter' => $_Lang['diameter'], + 'Diameter' => prettyNumber($GalaxyRowPlanet['diameter']), + 'Diameter_Units' => $_Lang['diameter_units'], + 'RowCount' => (count($Links) + 2), + 'Links' => '' + ); + foreach($Links as $Index => $Data) + { + if(!empty($Data['html'])) + { + $Parse['Links'] .= "{$Data['html']}"; + } + else + { + $Parse['Links'] .= "{$Data['txt']}"; + } + } + + $Result = parsetemplate($TPL, $Parse); + } + else + { + $Result = ' '; + } + + return $Result; +} + +?> diff --git a/includes/functions/GalaxyRowPlanet.php b/includes/functions/GalaxyRowPlanet.php index b91b4f86a..51ce04723 100644 --- a/includes/functions/GalaxyRowPlanet.php +++ b/includes/functions/GalaxyRowPlanet.php @@ -1,126 +1,126 @@ - 0) - { - if($SensonPhalanxLevel > 0) - { - if($GalaxyRowUser['id'] != $_User['id']) - { - if($GalaxyRowPlanet['galaxy'] == $CurrentGalaxy) - { - $PhRange = GetPhalanxRange($SensonPhalanxLevel); - $SystemLimitMin = $CurrentSystem - $PhRange; - if($SystemLimitMin < 1) - { - $SystemLimitMin = 1; - } - $SystemLimitMax = $CurrentSystem + $PhRange; - if($System <= $SystemLimitMax AND $System >= $SystemLimitMin) - { - $Links[] = array('prio' => 3, 'txt' => "{$_Lang['gl_phalanx']}"); - } - } - } - } - - if($CurrentMIP > 0) - { - if($GalaxyRowUser['id'] != $_User['id']) - { - if($GalaxyRowPlanet['galaxy'] == $CurrentGalaxy) - { - $MiRange = GetMissileRange(); - $SystemLimitMin = $CurrentSystem - $MiRange; - if($SystemLimitMin < 1) - { - $SystemLimitMin = 1; - } - $SystemLimitMax = $CurrentSystem + $MiRange; - if($System <= $SystemLimitMax AND $System >= $SystemLimitMin) - { - $Links[] = array('prio' => 9, 'txt' => "{$_Lang['type_mission'][10]}"); - } - } - } - } - - if($GalaxyRowUser['id'] != $_User['id']) - { - $Links[] = array('prio' => 1, 'txt' => "{$_Lang['type_mission'][6]}"); - $Links[] = array('prio' => 2, 'txt' => '', 'html' => ' '); - $Links[] = array('prio' => 4, 'txt' => "{$_Lang['type_mission'][1]}"); - if($GalaxyRowPlanet['id_owner'] > 0) - { - if(($GalaxyRowUser['ally_id'] == $_User['ally_id'] AND $_User['ally_id'] > 0) OR in_array($GalaxyRowUser['id'], $MyBuddies) OR (isset($MyAllyPacts[$GalaxyRowUser['ally_id']]) && $MyAllyPacts[$GalaxyRowUser['ally_id']] >= 3)) - { - $Links[] = array('prio' => 5, 'txt' => "{$_Lang['type_mission'][5]}"); - } - } - } - else - { - $Links[] = array('prio' => 6, 'txt' => "{$_Lang['type_mission'][4]}"); - if(isPro() AND $_User['current_planet'] != $GalaxyRowPlanet['id']) - { - $Links[] = array('prio' => 8, 'txt' => "{$_Lang['type_mission_quickres']}"); - } - } - - $Links[] = array('prio' => 7, 'txt' => "{$_Lang['type_mission'][3]}"); - - foreach($Links as $Index => $Data) - { - $PriorityArray[$Index] = $Data['prio']; - } - array_multisort($PriorityArray, SORT_ASC, $Links); - - $Parse = array - ( - 'Lang_Planet' => $_Lang['gl_planet'], - 'PlanetName' => $GalaxyRowPlanet['name'], - 'Galaxy' => $Galaxy, - 'System' => $System, - 'Planet' => $Planet, - 'SkinPath' => $_SkinPath, - 'PlanetImg' => $GalaxyRowPlanet['image'], - 'RowCount' => count($Links), - 'FirstLink' => $Links[0]['txt'], - 'OtherLinks' => '' - ); - - foreach($Links as $Index => $Data) - { - if($Index == 0) - { - continue; - } - if(!empty($Data['html'])) - { - $Parse['OtherLinks'] .= "{$Data['html']}"; - } - else - { - $Parse['OtherLinks'] .= "{$Data['txt']}"; - } - } - - $Result = parsetemplate($TPL, $Parse); - } - else - { - $Result = ' '; - } - - return $Result; -} - -?> \ No newline at end of file + 0) + { + if($SensonPhalanxLevel > 0) + { + if($GalaxyRowUser['id'] != $_User['id']) + { + if($GalaxyRowPlanet['galaxy'] == $CurrentGalaxy) + { + $PhRange = GetPhalanxRange($SensonPhalanxLevel); + $SystemLimitMin = $CurrentSystem - $PhRange; + if($SystemLimitMin < 1) + { + $SystemLimitMin = 1; + } + $SystemLimitMax = $CurrentSystem + $PhRange; + if($System <= $SystemLimitMax AND $System >= $SystemLimitMin) + { + $Links[] = array('prio' => 3, 'txt' => "{$_Lang['gl_phalanx']}"); + } + } + } + } + + if($CurrentMIP > 0) + { + if($GalaxyRowUser['id'] != $_User['id']) + { + if($GalaxyRowPlanet['galaxy'] == $CurrentGalaxy) + { + $MiRange = GetMissileRange(); + $SystemLimitMin = $CurrentSystem - $MiRange; + if($SystemLimitMin < 1) + { + $SystemLimitMin = 1; + } + $SystemLimitMax = $CurrentSystem + $MiRange; + if($System <= $SystemLimitMax AND $System >= $SystemLimitMin) + { + $Links[] = array('prio' => 9, 'txt' => "{$_Lang['type_mission'][10]}"); + } + } + } + } + + if($GalaxyRowUser['id'] != $_User['id']) + { + $Links[] = array('prio' => 1, 'txt' => "{$_Lang['type_mission'][6]}"); + $Links[] = array('prio' => 2, 'txt' => '', 'html' => ' '); + $Links[] = array('prio' => 4, 'txt' => "{$_Lang['type_mission'][1]}"); + if($GalaxyRowPlanet['id_owner'] > 0) + { + if(($GalaxyRowUser['ally_id'] == $_User['ally_id'] AND $_User['ally_id'] > 0) OR in_array($GalaxyRowUser['id'], $MyBuddies) OR (isset($MyAllyPacts[$GalaxyRowUser['ally_id']]) && $MyAllyPacts[$GalaxyRowUser['ally_id']] >= 3)) + { + $Links[] = array('prio' => 5, 'txt' => "{$_Lang['type_mission'][5]}"); + } + } + } + else + { + $Links[] = array('prio' => 6, 'txt' => "{$_Lang['type_mission'][4]}"); + if(isPro() AND $_User['current_planet'] != $GalaxyRowPlanet['id']) + { + $Links[] = array('prio' => 8, 'txt' => "{$_Lang['type_mission_quickres']}"); + } + } + + $Links[] = array('prio' => 7, 'txt' => "{$_Lang['type_mission'][3]}"); + + foreach($Links as $Index => $Data) + { + $PriorityArray[$Index] = $Data['prio']; + } + array_multisort($PriorityArray, SORT_ASC, $Links); + + $Parse = array + ( + 'Lang_Planet' => $_Lang['gl_planet'], + 'PlanetName' => $GalaxyRowPlanet['name'], + 'Galaxy' => $Galaxy, + 'System' => $System, + 'Planet' => $Planet, + 'SkinPath' => $_SkinPath, + 'PlanetImg' => $GalaxyRowPlanet['image'], + 'RowCount' => count($Links), + 'FirstLink' => $Links[0]['txt'], + 'OtherLinks' => '' + ); + + foreach($Links as $Index => $Data) + { + if($Index == 0) + { + continue; + } + if(!empty($Data['html'])) + { + $Parse['OtherLinks'] .= "{$Data['html']}"; + } + else + { + $Parse['OtherLinks'] .= "{$Data['txt']}"; + } + } + + $Result = parsetemplate($TPL, $Parse); + } + else + { + $Result = ' '; + } + + return $Result; +} + +?> diff --git a/includes/functions/GalaxyRowPlanetName.php b/includes/functions/GalaxyRowPlanetName.php index 31091d962..b2fcacad8 100644 --- a/includes/functions/GalaxyRowPlanetName.php +++ b/includes/functions/GalaxyRowPlanetName.php @@ -1,103 +1,103 @@ - 0) - { - $Now = $Time; - $Activity = ''; - $NameColor = ''; - if($TPLPlanet === false) - { - $TPLPlanet = gettemplate('galaxy_row_planetname'); - } - - if($GalaxyRowUser['id'] == $_User['id']) - { - $NameColor = 'skyblue'; - } - else - { - if($GalaxyRowPlanet['id_owner'] > 0) - { - if($GalaxyRowUser['ally_id'] == $_User['ally_id'] AND $_User['ally_id'] > 0) - { - $NameColor = 'lime'; - } - elseif(in_array($GalaxyRowUser['id'], $MyBuddies)) - { - $NameColor = 'green'; - } - } - else - { - $NameColor = 'red'; - $GalaxyRowPlanet['name'] = $_Lang['gl_destroyedplanet']; - } - $UpdateDiff = $Now - $GalaxyRowPlanet['last_update']; - if($UpdateDiff < 3600) - { - if($UpdateDiff < TIME_ONLINE) - { - $Activity = '*'; - } - else - { - $Activity = pretty_time_hour($UpdateDiff, true); - } - $Activity = "({$Activity})"; - } - } - if($GalaxyRow['hide_planet'] == 1) - { - $NameColor = 'orange'; - } - - $Parse = array('NameColor' => $NameColor, 'PlanetName' => $GalaxyRowPlanet['name'], 'Activity' => $Activity); - if($GalaxyRowUser['id'] != $_User['id']) - { - $Parse['AddHref'] = "href=\"fleet.php?galaxy={$Galaxy}&system={$System}&planet={$Planet}&planettype={$PlanetType}&target_mission=1\""; - $Parse['AddTitle'] = "title=\"{$_Lang['gl_attack']}\""; - - if($GalaxyRowPlanet['galaxy'] == $CurrentGalaxy AND $SensonPhalanxLevel > 0) - { - $PhRange = GetPhalanxRange($SensonPhalanxLevel); - $SystemLimitMin = $CurrentSystem - $PhRange; - if($SystemLimitMin < 1) - { - $SystemLimitMin = 1; - } - $SystemLimitMax = $CurrentSystem + $PhRange; - if($System <= $SystemLimitMax AND $System >= $SystemLimitMin) - { - $Parse['AddHref'] = 'href="#"'; - $Parse['AddOnClick'] = "onclick=\"return Phalanx({$Galaxy}, {$System}, {$Planet}, {$PlanetType});\""; - $Parse['AddTitle'] = "title=\"{$_Lang['gl_phalanx']}\""; - } - } - } - else - { - $Parse['AddHref'] = "href=\"fleet.php?galaxy={$Galaxy}&system={$System}&planet={$Planet}&planettype={$PlanetType}&target_mission=3\""; - $Parse['AddTitle'] = "title=\"{$_Lang['gl_transport']}\""; - } - - $Result = parsetemplate($TPLPlanet, $Parse); - } - else - { - if($TPLEmpty === false) - { - $TPLEmpty = gettemplate('galaxy_row_planetempty'); - } - - $Result = parsetemplate($TPLEmpty, array('Galaxy' => $Galaxy, 'System' => $System, 'Planet' => $Planet, 'MissionText' => $_Lang['type_mission'][7])); - } - - return $Result; -} - -?> \ No newline at end of file + 0) + { + $Now = $Time; + $Activity = ''; + $NameColor = ''; + if($TPLPlanet === false) + { + $TPLPlanet = gettemplate('galaxy_row_planetname'); + } + + if($GalaxyRowUser['id'] == $_User['id']) + { + $NameColor = 'skyblue'; + } + else + { + if($GalaxyRowPlanet['id_owner'] > 0) + { + if($GalaxyRowUser['ally_id'] == $_User['ally_id'] AND $_User['ally_id'] > 0) + { + $NameColor = 'lime'; + } + elseif(in_array($GalaxyRowUser['id'], $MyBuddies)) + { + $NameColor = 'green'; + } + } + else + { + $NameColor = 'red'; + $GalaxyRowPlanet['name'] = $_Lang['gl_destroyedplanet']; + } + $UpdateDiff = $Now - $GalaxyRowPlanet['last_update']; + if($UpdateDiff < 3600) + { + if($UpdateDiff < TIME_ONLINE) + { + $Activity = '*'; + } + else + { + $Activity = pretty_time_hour($UpdateDiff, true); + } + $Activity = "({$Activity})"; + } + } + if($GalaxyRow['hide_planet'] == 1) + { + $NameColor = 'orange'; + } + + $Parse = array('NameColor' => $NameColor, 'PlanetName' => $GalaxyRowPlanet['name'], 'Activity' => $Activity); + if($GalaxyRowUser['id'] != $_User['id']) + { + $Parse['AddHref'] = "href=\"fleet.php?galaxy={$Galaxy}&system={$System}&planet={$Planet}&planettype={$PlanetType}&target_mission=1\""; + $Parse['AddTitle'] = "title=\"{$_Lang['gl_attack']}\""; + + if($GalaxyRowPlanet['galaxy'] == $CurrentGalaxy AND $SensonPhalanxLevel > 0) + { + $PhRange = GetPhalanxRange($SensonPhalanxLevel); + $SystemLimitMin = $CurrentSystem - $PhRange; + if($SystemLimitMin < 1) + { + $SystemLimitMin = 1; + } + $SystemLimitMax = $CurrentSystem + $PhRange; + if($System <= $SystemLimitMax AND $System >= $SystemLimitMin) + { + $Parse['AddHref'] = 'href="#"'; + $Parse['AddOnClick'] = "onclick=\"return Phalanx({$Galaxy}, {$System}, {$Planet}, {$PlanetType});\""; + $Parse['AddTitle'] = "title=\"{$_Lang['gl_phalanx']}\""; + } + } + } + else + { + $Parse['AddHref'] = "href=\"fleet.php?galaxy={$Galaxy}&system={$System}&planet={$Planet}&planettype={$PlanetType}&target_mission=3\""; + $Parse['AddTitle'] = "title=\"{$_Lang['gl_transport']}\""; + } + + $Result = parsetemplate($TPLPlanet, $Parse); + } + else + { + if($TPLEmpty === false) + { + $TPLEmpty = gettemplate('galaxy_row_planetempty'); + } + + $Result = parsetemplate($TPLEmpty, array('Galaxy' => $Galaxy, 'System' => $System, 'Planet' => $Planet, 'MissionText' => $_Lang['type_mission'][7])); + } + + return $Result; +} + +?> diff --git a/includes/functions/GalaxyRowPos.php b/includes/functions/GalaxyRowPos.php index b3ddb4c49..ae4686edc 100644 --- a/includes/functions/GalaxyRowPos.php +++ b/includes/functions/GalaxyRowPos.php @@ -1,22 +1,22 @@ - $Galaxy, - 'System' => $System, - 'Planet' => $Planet, - ); - - return parsetemplate($TPL, $Parse); -} - -?> \ No newline at end of file + $Galaxy, + 'System' => $System, + 'Planet' => $Planet, + ); + + return parsetemplate($TPL, $Parse); +} + +?> diff --git a/includes/functions/GalaxyRowUser.php b/includes/functions/GalaxyRowUser.php index 5887512dc..309e321cb 100644 --- a/includes/functions/GalaxyRowUser.php +++ b/includes/functions/GalaxyRowUser.php @@ -1,220 +1,220 @@ - 0) - { - $NoobProt = $_GameConfig['noobprotection']; - $NoobTime = $_GameConfig['noobprotectiontime']; - $NoobMulti = $_GameConfig['noobprotectionmulti']; - $noNoobProtect = $_GameConfig['no_noob_protect']; - $noIdleProtect = $_GameConfig['no_idle_protect']; - $Protections['idleTime'] = $_GameConfig['no_idle_protect'] * TIME_DAY; - - $UserPoints['total_points'] = $_User['total_points']; - $UserPoints['total_rank'] = $_User['total_rank']; - $User2Points['total_points'] = $GalaxyRowUser['total_points']; - $User2Points['total_rank'] = $GalaxyRowUser['total_rank']; - - if($GalaxyRowUser['is_banned'] == 1 OR isOnVacation($GalaxyRowUser)) - { - if(isOnVacation($GalaxyRowUser)) - { - $Status[] = array('class' => 'vacation', 'sign' => $_Lang['vacation_shortcut']); - $NameClasses[] = array('class' => 'vacation', 'importance' => 90); - } - if($GalaxyRowUser['is_banned'] == 1) - { - $Status[] = array('class' => 'banned', 'sign' => $_Lang['banned_shortcut']); - $NameClasses[] = array('class' => 'red', 'importance' => 100); - } - } - else if(!empty($GalaxyRowUser['activation_code'])) - { - $Status[] = array('class' => 'nonactivated', 'sign' => $_Lang['User_NonActivated']); - $NameClasses[] = array('class' => 'nonactivated', 'importance' => 50); - } - else if($GalaxyRowUser['first_login'] == 0 OR $GalaxyRowUser['NoobProtection_EndTime'] > $Time) - { - $Status[] = array('class' => 'newplayer', 'sign' => ''.$_Lang['new_player_shortcut'].''); - $NameClasses[] = array('class' => 'newplayer', 'importance' => 60); - } - else if($GalaxyRowUser['onlinetime'] < ($Time - (TIME_DAY * 7))) - { - $Status[] = array('class' => 'inactive', 'sign' => $_Lang['inactif_7_shortcut']); - $NameClasses[] = array('class' => 'inactive', 'importance' => 40); - if($GalaxyRowUser['onlinetime'] < ($Time - (TIME_DAY * 28))) - { - $Status[] = array('class' => 'longinactive', 'sign' => $_Lang['inactif_28_shortcut']); - $NameClasses[] = array('class' => 'longinactive', 'importance' => 41); - } - } - else if($NoobProt) - { - if($GalaxyRowUser['id'] != $_User['id']) - { - if($GalaxyRowUser['onlinetime'] >= ($Time - (TIME_DAY * $noIdleProtect))) - { - if($User2Points['total_points'] < ($NoobTime * 1000)) - { - $Status[] = array('class' => 'noob', 'sign' => $_Lang['weak_player_shortcut']); - $NameClasses[] = array('class' => 'noob', 'importance' => 50); - } - else - { - if($UserPoints['total_points'] < ($noNoobProtect * 1000) OR $User2Points['total_points'] < ($noNoobProtect * 1000)) - { - if(($UserPoints['total_points'] > ($User2Points['total_points'] * $NoobMulti))) - { - $Status[] = array('class' => 'noob', 'sign' => $_Lang['weak_player_shortcut']); - $NameClasses[] = array('class' => 'noob', 'importance' => 50); - } - elseif(($UserPoints['total_points'] * $NoobMulti) < $User2Points['total_points']) - { - $Status[] = array('class' => 'strong', 'sign' => $_Lang['strong_player_shortcut']); - $NameClasses[] = array('class' => 'strong', 'importance' => 50); - } - } - } - } - } - } - // Smart Fleet Blockade indicator - if($SFBStatus['BlockMissions'] == '0') - { - $AllMissionsBlocked = true; - } - - if($SFBStatus['ID'] > 0 AND - ( - ($AllMissionsBlocked !== true AND $GalaxyRowUser['onlinetime'] > ($Time - $Protections['idleTime']) AND $GalaxyRowUser['onlinetime'] < $SFBStatus['StartTime']) - OR - ($AllMissionsBlocked === true AND $GalaxyRowUser['onlinetime'] > ($Time - $Protections['idleTime']) AND $GalaxyRowUser['onlinetime'] < $SFBStatus['EndTime']) - )) - { - $Status[] = array('class' => 'orange', 'sign' => $_Lang['Fleet_Blockade_Protected']); - } - if($GalaxyRowUser['avatar'] != '') - { - $Avatar = ""; - } - else - { - $Avatar = ' '; - } - if(CheckAuth('supportadmin', AUTHCHECK_NORMAL, $GalaxyRowUser)) - { - $Status[] = array('class' => 'lime', 'sign' => "{$_Lang['User_isAdmin']}"); - } - - if($User2Points['total_rank'] > 0) - { - $UserStatPosition = $User2Points['total_rank']; - $UserStatPositionTH = prettyNumber($User2Points['total_rank']); - } - else - { - $UserStatPosition = '0'; - $UserStatPositionTH = ' '; - } - - if(!empty($NameClasses)) - { - foreach($NameClasses as $Data) - { - $NameClassesImportance[] = $Data['importance']; - } - array_multisort($NameClasses, SORT_DESC, $NameClassesImportance); - } - if(!empty($Status)) - { - foreach($Status as $Data) - { - $Statuses[] = "{$Data['sign']}"; - } - } - - if(MORALE_ENABLED AND $GalaxyRowUser['id'] != $_User['id']) - { - $Parse = array - ( - 'Lang_MoralePoints' => $_Lang['gl_moralepoints'], - 'Lang_MoralePoints_Units' => $_Lang['gl_moralepoints_units'], - 'MoralePoints' => prettyNumber($GalaxyRowUser['morale_points']) - ); - - $MoraleBox = parsetemplate($TPL_MoraleBox, $Parse); - } - - $Parse = array - ( - 'Avatar' => $Avatar, - 'UserID' => $GalaxyRowUser['id'], - 'Lang_User' => $_Lang['gl_username'], - 'Username' => $GalaxyRowUser['username'], - 'NameClass' => (isset($NameClasses) ? $NameClasses[0]['class'] : ''), - 'AddOldUsername' => ($GalaxyRowUser['old_username_expire'] > $Time ? ' (?)' : ''), - 'Lang_Profile' => $_Lang['gl_showprofile'], - 'Lang_Message' => $_Lang['gl_sendmess'], - 'Lang_Buddy' => $_Lang['gl_buddyreq'], - 'Lang_AllyInvite' => $_Lang['gl_allyinvite'], - 'StatStart' => $UserStatPosition, - 'Lang_Stats' => $_Lang['gl_stats'], - 'Position' => prettyNumber($UserStatPosition), - 'PositionTH' => $UserStatPositionTH, - 'Add_hiFntClass' => ($UserStatPositionTH == ' ' ? 'class="hiFnt"' : ''), - 'Statuses' => (!empty($Statuses) ? '('.implode(' ', $Statuses).')' : ''), - 'Hide_Message' => ' class=hide', - 'Hide_Buddy' => ' class=hide', - 'Hide_InviteToAlly' => ' class=hide', - 'Insert_MoraleBox' => (isset($MoraleBox) ? $MoraleBox : '') - ); - if($GalaxyRowUser['id'] != $_User['id']) - { - $Parse['Hide_Message'] = ''; - if(!in_array($GalaxyRowUser['id'], $MyBuddies)) - { - $Parse['Hide_Buddy'] = ''; - } - if($_User['ally_id'] > 0 AND $GalaxyRowUser['ally_id'] <= 0) - { - $Parse['Hide_InviteToAlly'] = ''; - } - } - - $Result = parsetemplate($TPL, $Parse); - } - else - { - if($_User['settings_Galaxy_ShowUserAvatars'] == 1) - { - $Result = '   '; - } - else - { - $Result = '  '; - } - } - - return $Result; -} - -?> \ No newline at end of file + 0) + { + $NoobProt = $_GameConfig['noobprotection']; + $NoobTime = $_GameConfig['noobprotectiontime']; + $NoobMulti = $_GameConfig['noobprotectionmulti']; + $noNoobProtect = $_GameConfig['no_noob_protect']; + $noIdleProtect = $_GameConfig['no_idle_protect']; + $Protections['idleTime'] = $_GameConfig['no_idle_protect'] * TIME_DAY; + + $UserPoints['total_points'] = $_User['total_points']; + $UserPoints['total_rank'] = $_User['total_rank']; + $User2Points['total_points'] = $GalaxyRowUser['total_points']; + $User2Points['total_rank'] = $GalaxyRowUser['total_rank']; + + if($GalaxyRowUser['is_banned'] == 1 OR isOnVacation($GalaxyRowUser)) + { + if(isOnVacation($GalaxyRowUser)) + { + $Status[] = array('class' => 'vacation', 'sign' => $_Lang['vacation_shortcut']); + $NameClasses[] = array('class' => 'vacation', 'importance' => 90); + } + if($GalaxyRowUser['is_banned'] == 1) + { + $Status[] = array('class' => 'banned', 'sign' => $_Lang['banned_shortcut']); + $NameClasses[] = array('class' => 'red', 'importance' => 100); + } + } + else if(!empty($GalaxyRowUser['activation_code'])) + { + $Status[] = array('class' => 'nonactivated', 'sign' => $_Lang['User_NonActivated']); + $NameClasses[] = array('class' => 'nonactivated', 'importance' => 50); + } + else if($GalaxyRowUser['first_login'] == 0 OR $GalaxyRowUser['NoobProtection_EndTime'] > $Time) + { + $Status[] = array('class' => 'newplayer', 'sign' => ''.$_Lang['new_player_shortcut'].''); + $NameClasses[] = array('class' => 'newplayer', 'importance' => 60); + } + else if($GalaxyRowUser['onlinetime'] < ($Time - (TIME_DAY * 7))) + { + $Status[] = array('class' => 'inactive', 'sign' => $_Lang['inactif_7_shortcut']); + $NameClasses[] = array('class' => 'inactive', 'importance' => 40); + if($GalaxyRowUser['onlinetime'] < ($Time - (TIME_DAY * 28))) + { + $Status[] = array('class' => 'longinactive', 'sign' => $_Lang['inactif_28_shortcut']); + $NameClasses[] = array('class' => 'longinactive', 'importance' => 41); + } + } + else if($NoobProt) + { + if($GalaxyRowUser['id'] != $_User['id']) + { + if($GalaxyRowUser['onlinetime'] >= ($Time - (TIME_DAY * $noIdleProtect))) + { + if($User2Points['total_points'] < ($NoobTime * 1000)) + { + $Status[] = array('class' => 'noob', 'sign' => $_Lang['weak_player_shortcut']); + $NameClasses[] = array('class' => 'noob', 'importance' => 50); + } + else + { + if($UserPoints['total_points'] < ($noNoobProtect * 1000) OR $User2Points['total_points'] < ($noNoobProtect * 1000)) + { + if(($UserPoints['total_points'] > ($User2Points['total_points'] * $NoobMulti))) + { + $Status[] = array('class' => 'noob', 'sign' => $_Lang['weak_player_shortcut']); + $NameClasses[] = array('class' => 'noob', 'importance' => 50); + } + elseif(($UserPoints['total_points'] * $NoobMulti) < $User2Points['total_points']) + { + $Status[] = array('class' => 'strong', 'sign' => $_Lang['strong_player_shortcut']); + $NameClasses[] = array('class' => 'strong', 'importance' => 50); + } + } + } + } + } + } + // Smart Fleet Blockade indicator + if($SFBStatus['BlockMissions'] == '0') + { + $AllMissionsBlocked = true; + } + + if($SFBStatus['ID'] > 0 AND + ( + ($AllMissionsBlocked !== true AND $GalaxyRowUser['onlinetime'] > ($Time - $Protections['idleTime']) AND $GalaxyRowUser['onlinetime'] < $SFBStatus['StartTime']) + OR + ($AllMissionsBlocked === true AND $GalaxyRowUser['onlinetime'] > ($Time - $Protections['idleTime']) AND $GalaxyRowUser['onlinetime'] < $SFBStatus['EndTime']) + )) + { + $Status[] = array('class' => 'orange', 'sign' => $_Lang['Fleet_Blockade_Protected']); + } + if($GalaxyRowUser['avatar'] != '') + { + $Avatar = ""; + } + else + { + $Avatar = ' '; + } + if(CheckAuth('supportadmin', AUTHCHECK_NORMAL, $GalaxyRowUser)) + { + $Status[] = array('class' => 'lime', 'sign' => "{$_Lang['User_isAdmin']}"); + } + + if($User2Points['total_rank'] > 0) + { + $UserStatPosition = $User2Points['total_rank']; + $UserStatPositionTH = prettyNumber($User2Points['total_rank']); + } + else + { + $UserStatPosition = '0'; + $UserStatPositionTH = ' '; + } + + if(!empty($NameClasses)) + { + foreach($NameClasses as $Data) + { + $NameClassesImportance[] = $Data['importance']; + } + array_multisort($NameClasses, SORT_DESC, $NameClassesImportance); + } + if(!empty($Status)) + { + foreach($Status as $Data) + { + $Statuses[] = "{$Data['sign']}"; + } + } + + if(MORALE_ENABLED AND $GalaxyRowUser['id'] != $_User['id']) + { + $Parse = array + ( + 'Lang_MoralePoints' => $_Lang['gl_moralepoints'], + 'Lang_MoralePoints_Units' => $_Lang['gl_moralepoints_units'], + 'MoralePoints' => prettyNumber($GalaxyRowUser['morale_points']) + ); + + $MoraleBox = parsetemplate($TPL_MoraleBox, $Parse); + } + + $Parse = array + ( + 'Avatar' => $Avatar, + 'UserID' => $GalaxyRowUser['id'], + 'Lang_User' => $_Lang['gl_username'], + 'Username' => $GalaxyRowUser['username'], + 'NameClass' => (isset($NameClasses) ? $NameClasses[0]['class'] : ''), + 'AddOldUsername' => ($GalaxyRowUser['old_username_expire'] > $Time ? ' (?)' : ''), + 'Lang_Profile' => $_Lang['gl_showprofile'], + 'Lang_Message' => $_Lang['gl_sendmess'], + 'Lang_Buddy' => $_Lang['gl_buddyreq'], + 'Lang_AllyInvite' => $_Lang['gl_allyinvite'], + 'StatStart' => $UserStatPosition, + 'Lang_Stats' => $_Lang['gl_stats'], + 'Position' => prettyNumber($UserStatPosition), + 'PositionTH' => $UserStatPositionTH, + 'Add_hiFntClass' => ($UserStatPositionTH == ' ' ? 'class="hiFnt"' : ''), + 'Statuses' => (!empty($Statuses) ? '('.implode(' ', $Statuses).')' : ''), + 'Hide_Message' => ' class=hide', + 'Hide_Buddy' => ' class=hide', + 'Hide_InviteToAlly' => ' class=hide', + 'Insert_MoraleBox' => (isset($MoraleBox) ? $MoraleBox : '') + ); + if($GalaxyRowUser['id'] != $_User['id']) + { + $Parse['Hide_Message'] = ''; + if(!in_array($GalaxyRowUser['id'], $MyBuddies)) + { + $Parse['Hide_Buddy'] = ''; + } + if($_User['ally_id'] > 0 AND $GalaxyRowUser['ally_id'] <= 0) + { + $Parse['Hide_InviteToAlly'] = ''; + } + } + + $Result = parsetemplate($TPL, $Parse); + } + else + { + if($_User['settings_Galaxy_ShowUserAvatars'] == 1) + { + $Result = '   '; + } + else + { + $Result = '  '; + } + } + + return $Result; +} + +?> diff --git a/includes/functions/GetBuildingPrice.php b/includes/functions/GetBuildingPrice.php index 32e74ebad..939a05c56 100644 --- a/includes/functions/GetBuildingPrice.php +++ b/includes/functions/GetBuildingPrice.php @@ -1,66 +1,66 @@ - 0) - { - if($Incremental) - { - $cost[$ResType] = floor($_Vars_Prices[$ElementID][$ResType] * pow($_Vars_Prices[$ElementID]['factor'], $level)); - } - else - { - $cost[$ResType] = floor($_Vars_Prices[$ElementID][$ResType]); - } - - if($ForDestroy == true) - { - $cost[$ResType] = floor($cost[$ResType] / 2); - } - } - else - { - $cost[$ResType] = 0; - } - } - if($GetPremiumData) - { - global $_Vars_PremiumBuildingPrices; - if(isset($_Vars_PremiumBuildingPrices[$ElementID]) && $_Vars_PremiumBuildingPrices[$ElementID] > 0) - { - $cost['darkEnergy'] = $_Vars_PremiumBuildingPrices[$ElementID]; - } - } - - return $cost; -} - -?> \ No newline at end of file + 0) + { + if($Incremental) + { + $cost[$ResType] = floor($_Vars_Prices[$ElementID][$ResType] * pow($_Vars_Prices[$ElementID]['factor'], $level)); + } + else + { + $cost[$ResType] = floor($_Vars_Prices[$ElementID][$ResType]); + } + + if($ForDestroy == true) + { + $cost[$ResType] = floor($cost[$ResType] / 2); + } + } + else + { + $cost[$ResType] = 0; + } + } + if($GetPremiumData) + { + global $_Vars_PremiumBuildingPrices; + if(isset($_Vars_PremiumBuildingPrices[$ElementID]) && $_Vars_PremiumBuildingPrices[$ElementID] > 0) + { + $cost['darkEnergy'] = $_Vars_PremiumBuildingPrices[$ElementID]; + } + } + + return $cost; +} + +?> diff --git a/includes/functions/GetBuildingTime.php b/includes/functions/GetBuildingTime.php index 8b7f42bf9..6cb852fd3 100644 --- a/includes/functions/GetBuildingTime.php +++ b/includes/functions/GetBuildingTime.php @@ -1,81 +1,81 @@ -= 1) - { - $lablevel = 0; - $empire = doquery("SELECT `{$_Vars_GameElements[31]}` FROM {{table}} WHERE `id_owner` = {$TheUser['id']} AND `{$_Vars_GameElements[31]}` > 0 ORDER BY `{$_Vars_GameElements[31]}` DESC LIMIT ".($intergal_lab + 1).";", 'planets'); - if(mysql_num_rows($empire) > 1) - { - while($colony = mysql_fetch_assoc($empire)) - { - $lablevel += $colony[$_Vars_GameElements[31]]; - } - } - else - { - $lablevel = $ThePlanet[$_Vars_GameElements[31]]; - } - } - $timeBase = $cost_crystal + $cost_metal; - $time = ($timeBase / $_GameConfig['game_speed']) / (($lablevel + 1) * 2); - $time = floor($time * 60 * 60 * (($TheUser['technocrat_time'] > time()) ? 0.8 : 1)); - } - else if(in_array($ElementID, $_Vars_ElementCategories['defense'])) - { - $timeBase = $_Vars_Prices[$ElementID]['metal'] + $_Vars_Prices[$ElementID]['crystal']; - $time = ($timeBase / $_GameConfig['game_speed']) * (1 / ($ThePlanet[$_Vars_GameElements['21']] + 1)) * pow(1 / 2, $ThePlanet[$_Vars_GameElements['15']]); - $time = floor($time * 60 * 60); - } - else if(in_array($ElementID, $_Vars_ElementCategories['fleet'])) - { - $timeBase = $_Vars_Prices[$ElementID]['metal'] + $_Vars_Prices[$ElementID]['crystal']; - $time = ($timeBase / $_GameConfig['game_speed']) * (1 / ($ThePlanet[$_Vars_GameElements['21']] + 1)) * pow(1 / 2, $ThePlanet[$_Vars_GameElements['15']]); - $time = floor($time * 60 * 60); - } - - if($time < 0) - { - $time = 0; - } - - return $time; -} - -?> \ No newline at end of file += 1) + { + $lablevel = 0; + $empire = doquery("SELECT `{$_Vars_GameElements[31]}` FROM {{table}} WHERE `id_owner` = {$TheUser['id']} AND `{$_Vars_GameElements[31]}` > 0 ORDER BY `{$_Vars_GameElements[31]}` DESC LIMIT ".($intergal_lab + 1).";", 'planets'); + if(mysql_num_rows($empire) > 1) + { + while($colony = mysql_fetch_assoc($empire)) + { + $lablevel += $colony[$_Vars_GameElements[31]]; + } + } + else + { + $lablevel = $ThePlanet[$_Vars_GameElements[31]]; + } + } + $timeBase = $cost_crystal + $cost_metal; + $time = ($timeBase / $_GameConfig['game_speed']) / (($lablevel + 1) * 2); + $time = floor($time * 60 * 60 * (($TheUser['technocrat_time'] > time()) ? 0.8 : 1)); + } + else if(in_array($ElementID, $_Vars_ElementCategories['defense'])) + { + $timeBase = $_Vars_Prices[$ElementID]['metal'] + $_Vars_Prices[$ElementID]['crystal']; + $time = ($timeBase / $_GameConfig['game_speed']) * (1 / ($ThePlanet[$_Vars_GameElements['21']] + 1)) * pow(1 / 2, $ThePlanet[$_Vars_GameElements['15']]); + $time = floor($time * 60 * 60); + } + else if(in_array($ElementID, $_Vars_ElementCategories['fleet'])) + { + $timeBase = $_Vars_Prices[$ElementID]['metal'] + $_Vars_Prices[$ElementID]['crystal']; + $time = ($timeBase / $_GameConfig['game_speed']) * (1 / ($ThePlanet[$_Vars_GameElements['21']] + 1)) * pow(1 / 2, $ThePlanet[$_Vars_GameElements['15']]); + $time = floor($time * 60 * 60); + } + + if($time < 0) + { + $time = 0; + } + + return $time; +} + +?> diff --git a/includes/functions/GetElementPrice.php b/includes/functions/GetElementPrice.php index e033fda66..f851af009 100644 --- a/includes/functions/GetElementPrice.php +++ b/includes/functions/GetElementPrice.php @@ -1,62 +1,62 @@ - $_Lang["Metal"], - 'crystal' => $_Lang["Crystal"], - 'deuterium' => $_Lang["Deuterium"], - 'energy_max' => $_Lang["Energy"] - ); - - $text = $_Lang['Requires'] . ": "; - foreach($array as $ResType => $ResTitle) - { - if(isset($_Vars_Prices[$ElementID][$ResType]) && $_Vars_Prices[$ElementID][$ResType] != 0) - { - $text .= $ResTitle . ": "; - if($userfactor) - { - $cost = floor($_Vars_Prices[$ElementID][$ResType] * pow($_Vars_Prices[$ElementID]['factor'], $level)); - } - else - { - $cost = floor($_Vars_Prices[$ElementID][$ResType]); - } - if($cost > $ThePlanet[$ResType]) - { - $text .= " "; - $text .= "".prettyNumber($cost)." "; - } - else - { - $text .= " ".prettyNumber($cost)." "; - } - } - } - return $text; -} - -?> \ No newline at end of file + $_Lang["Metal"], + 'crystal' => $_Lang["Crystal"], + 'deuterium' => $_Lang["Deuterium"], + 'energy_max' => $_Lang["Energy"] + ); + + $text = $_Lang['Requires'] . ": "; + foreach($array as $ResType => $ResTitle) + { + if(isset($_Vars_Prices[$ElementID][$ResType]) && $_Vars_Prices[$ElementID][$ResType] != 0) + { + $text .= $ResTitle . ": "; + if($userfactor) + { + $cost = floor($_Vars_Prices[$ElementID][$ResType] * pow($_Vars_Prices[$ElementID]['factor'], $level)); + } + else + { + $cost = floor($_Vars_Prices[$ElementID][$ResType]); + } + if($cost > $ThePlanet[$ResType]) + { + $text .= " "; + $text .= "".prettyNumber($cost)." "; + } + else + { + $text .= " ".prettyNumber($cost)." "; + } + } + } + return $text; +} + +?> diff --git a/includes/functions/GetElementRessources.php b/includes/functions/GetElementRessources.php index 9b5c6a1b1..96e97cf41 100644 --- a/includes/functions/GetElementRessources.php +++ b/includes/functions/GetElementRessources.php @@ -1,14 +1,14 @@ - \ No newline at end of file + diff --git a/includes/functions/GetElementTechReq.php b/includes/functions/GetElementTechReq.php index b7f4361e2..818cb780e 100644 --- a/includes/functions/GetElementTechReq.php +++ b/includes/functions/GetElementTechReq.php @@ -1,94 +1,94 @@ - $RequiredLevel) - { - if(in_array($RequiredElementID, $_Vars_ElementCategories['tech'])) - { - $TempArray = array - ( - $RequiredLevel, - (isset($TheUser[$_Vars_GameElements[$RequiredElementID]]) ? $TheUser[$_Vars_GameElements[$RequiredElementID]] : 0) - ); - - if($RequiredLevel == 0 || (isset($TheUser[$_Vars_GameElements[$RequiredElementID]]) && $TheUser[$_Vars_GameElements[$RequiredElementID]] >= $RequiredLevel)) - { - $RequiredDone[$RequiredElementID] = $TempArray; - } - else - { - $Required[$RequiredElementID] = $TempArray; - } - } - else - { - $TempArray = array - ( - $RequiredLevel, - (isset($ThePlanet[$_Vars_GameElements[$RequiredElementID]]) ? $ThePlanet[$_Vars_GameElements[$RequiredElementID]] : 0) - ); - - if($RequiredLevel == 0 || (isset($ThePlanet[$_Vars_GameElements[$RequiredElementID]]) && $ThePlanet[$_Vars_GameElements[$RequiredElementID]] >= $RequiredLevel)) - { - $RequiredDone[$RequiredElementID] = $TempArray; - } - else - { - $Required[$RequiredElementID] = $TempArray; - } - } - } - } - - if(!empty($Required)) - { - if(!empty($RequiredDone)) - { - foreach($RequiredDone as $Key => $Data) - { - $Required[$Key] = $Data; - } - asort($Required); - } - if(empty($TPL)) - { - $TPL['main'] = gettemplate('_function_getelementtechreq_main'); - $TPL['divs'] = gettemplate('_function_getelementtechreq_divs'); - } - - if(!isset($_Lang['Insert_TechReqDivs'])) - { - $_Lang['Insert_TechReqDivs'] = ''; - } - foreach($Required as $ElementID => $Data) - { - if($Data[1] >= $Data[0]) - { - $Color = 'lime'; - } - else - { - $Color = 'red'; - } - $_Lang['Insert_TechReqDivs'] .= parsetemplate($TPL['divs'], array('ID' => $ElementID, 'Name' => $_Lang['tech'][$ElementID], 'skinpath' => $_SkinPath, 'Color' => $Color, 'CLevel' => $Data[1], 'NLevel' => $Data[0])); - } - if($OnlyDivs) - { - $ToReturn = $_Lang['Insert_TechReqDivs']; - $_Lang['Insert_TechReqDivs'] = ''; - return $ToReturn; - } - - $Return = parsetemplate($TPL['main'], $_Lang); - $_Lang['Insert_TechReqDivs'] = ''; - } - return $Return; -} - -?> \ No newline at end of file + $RequiredLevel) + { + if(in_array($RequiredElementID, $_Vars_ElementCategories['tech'])) + { + $TempArray = array + ( + $RequiredLevel, + (isset($TheUser[$_Vars_GameElements[$RequiredElementID]]) ? $TheUser[$_Vars_GameElements[$RequiredElementID]] : 0) + ); + + if($RequiredLevel == 0 || (isset($TheUser[$_Vars_GameElements[$RequiredElementID]]) && $TheUser[$_Vars_GameElements[$RequiredElementID]] >= $RequiredLevel)) + { + $RequiredDone[$RequiredElementID] = $TempArray; + } + else + { + $Required[$RequiredElementID] = $TempArray; + } + } + else + { + $TempArray = array + ( + $RequiredLevel, + (isset($ThePlanet[$_Vars_GameElements[$RequiredElementID]]) ? $ThePlanet[$_Vars_GameElements[$RequiredElementID]] : 0) + ); + + if($RequiredLevel == 0 || (isset($ThePlanet[$_Vars_GameElements[$RequiredElementID]]) && $ThePlanet[$_Vars_GameElements[$RequiredElementID]] >= $RequiredLevel)) + { + $RequiredDone[$RequiredElementID] = $TempArray; + } + else + { + $Required[$RequiredElementID] = $TempArray; + } + } + } + } + + if(!empty($Required)) + { + if(!empty($RequiredDone)) + { + foreach($RequiredDone as $Key => $Data) + { + $Required[$Key] = $Data; + } + asort($Required); + } + if(empty($TPL)) + { + $TPL['main'] = gettemplate('_function_getelementtechreq_main'); + $TPL['divs'] = gettemplate('_function_getelementtechreq_divs'); + } + + if(!isset($_Lang['Insert_TechReqDivs'])) + { + $_Lang['Insert_TechReqDivs'] = ''; + } + foreach($Required as $ElementID => $Data) + { + if($Data[1] >= $Data[0]) + { + $Color = 'lime'; + } + else + { + $Color = 'red'; + } + $_Lang['Insert_TechReqDivs'] .= parsetemplate($TPL['divs'], array('ID' => $ElementID, 'Name' => $_Lang['tech'][$ElementID], 'skinpath' => $_SkinPath, 'Color' => $Color, 'CLevel' => $Data[1], 'NLevel' => $Data[0])); + } + if($OnlyDivs) + { + $ToReturn = $_Lang['Insert_TechReqDivs']; + $_Lang['Insert_TechReqDivs'] = ''; + return $ToReturn; + } + + $Return = parsetemplate($TPL['main'], $_Lang); + $_Lang['Insert_TechReqDivs'] = ''; + } + return $Return; +} + +?> diff --git a/includes/functions/GetMaxConstructibleElements.php b/includes/functions/GetMaxConstructibleElements.php index 192c2a4f1..79b692b7e 100644 --- a/includes/functions/GetMaxConstructibleElements.php +++ b/includes/functions/GetMaxConstructibleElements.php @@ -1,55 +1,55 @@ - $Buildable) - { - $MaxElements = $Buildable; - } - - if($_Vars_Prices[$Element]['deuterium'] != 0) - { - $ResType_3_Needed = $_Vars_Prices[$Element]['deuterium']; - $Buildable = floor($Ressources["deuterium"] / $ResType_3_Needed); - } - if(!isset($MaxElements)) - { - $MaxElements = $Buildable; - } - else if($MaxElements > $Buildable) - { - $MaxElements = $Buildable; - } - - if($_Vars_Prices[$Element]['energy'] != 0) - { - $ResType_4_Needed = $_Vars_Prices[$Element]['energy']; - $Buildable = floor($Ressources["energy_max"] / $ResType_4_Needed); - } - if($Buildable < 1) - { - $MaxElements = 0; - } - - return $MaxElements; -} - -?> \ No newline at end of file + $Buildable) + { + $MaxElements = $Buildable; + } + + if($_Vars_Prices[$Element]['deuterium'] != 0) + { + $ResType_3_Needed = $_Vars_Prices[$Element]['deuterium']; + $Buildable = floor($Ressources["deuterium"] / $ResType_3_Needed); + } + if(!isset($MaxElements)) + { + $MaxElements = $Buildable; + } + else if($MaxElements > $Buildable) + { + $MaxElements = $Buildable; + } + + if($_Vars_Prices[$Element]['energy'] != 0) + { + $ResType_4_Needed = $_Vars_Prices[$Element]['energy']; + $Buildable = floor($Ressources["energy_max"] / $ResType_4_Needed); + } + if($Buildable < 1) + { + $MaxElements = 0; + } + + return $MaxElements; +} + +?> diff --git a/includes/functions/GetMissileRange.php b/includes/functions/GetMissileRange.php index e6f1634f8..2dd331e9e 100644 --- a/includes/functions/GetMissileRange.php +++ b/includes/functions/GetMissileRange.php @@ -1,30 +1,30 @@ - 0) - { - $MissileRange = ($Level * 5) - 1; - } - else - { - $MissileRange = 0; - } - - return $MissileRange; -} - -?> \ No newline at end of file + 0) + { + $MissileRange = ($Level * 5) - 1; + } + else + { + $MissileRange = 0; + } + + return $MissileRange; +} + +?> diff --git a/includes/functions/GetPhalanxRange.php b/includes/functions/GetPhalanxRange.php index c2da8d8df..838e8ee33 100644 --- a/includes/functions/GetPhalanxRange.php +++ b/includes/functions/GetPhalanxRange.php @@ -1,8 +1,8 @@ - \ No newline at end of file + diff --git a/includes/functions/GetRestPrice.php b/includes/functions/GetRestPrice.php index 2cea0d6a0..0f1c39116 100644 --- a/includes/functions/GetRestPrice.php +++ b/includes/functions/GetRestPrice.php @@ -1,63 +1,63 @@ - $_Lang["Metal"], - 'crystal' => $_Lang["Crystal"], - 'deuterium' => $_Lang["Deuterium"], - 'energy_max' => $_Lang["Energy"] - ); - - $text = "
    {$_Lang['Rest_ress']}: "; - foreach($array as $ResType => $ResTitle) - { - if(isset($_Vars_Prices[$ElementID][$ResType]) && $_Vars_Prices[$ElementID][$ResType] != 0) - { - $text .= $ResTitle . ": "; - if($userfactor) - { - $cost = floor($_Vars_Prices[$ElementID][$ResType] * pow($_Vars_Prices[$ElementID]['factor'], $level)); - } - else - { - $cost = floor($_Vars_Prices[$ElementID][$ResType]); - } - if($cost > $ThePlanet[$ResType]) - { - $text .= "". prettyNumber($ThePlanet[$ResType] - $cost) ." "; - } - else - { - $text .= "". prettyNumber($ThePlanet[$ResType] - $cost) ." "; - } - } - } - $text .= ""; - - return $text; -} - -?> \ No newline at end of file + $_Lang["Metal"], + 'crystal' => $_Lang["Crystal"], + 'deuterium' => $_Lang["Deuterium"], + 'energy_max' => $_Lang["Energy"] + ); + + $text = "
    {$_Lang['Rest_ress']}: "; + foreach($array as $ResType => $ResTitle) + { + if(isset($_Vars_Prices[$ElementID][$ResType]) && $_Vars_Prices[$ElementID][$ResType] != 0) + { + $text .= $ResTitle . ": "; + if($userfactor) + { + $cost = floor($_Vars_Prices[$ElementID][$ResType] * pow($_Vars_Prices[$ElementID]['factor'], $level)); + } + else + { + $cost = floor($_Vars_Prices[$ElementID][$ResType]); + } + if($cost > $ThePlanet[$ResType]) + { + $text .= "". prettyNumber($ThePlanet[$ResType] - $cost) ." "; + } + else + { + $text .= "". prettyNumber($ThePlanet[$ResType] - $cost) ." "; + } + } + } + $text .= ""; + + return $text; +} + +?> diff --git a/includes/functions/HandleFullUserUpdate.php b/includes/functions/HandleFullUserUpdate.php index 9e16383ec..8e6a397ce 100644 --- a/includes/functions/HandleFullUserUpdate.php +++ b/includes/functions/HandleFullUserUpdate.php @@ -1,66 +1,66 @@ - 0 && $TheUser['techQueue_Planet'] != $ThePlanet['id']) - { - if(empty($TheLabPlanet)) - { - $TheLabPlanet = doquery("SELECT * FROM {{table}} WHERE `id` = {$TheUser['techQueue_Planet']} LIMIT 1;", 'planets', true); - } - if($ThePlanetFullUpdate === true) - { - $NeedUpdate[$ThePlanet['id']] = HandlePlanetUpdate($ThePlanet, $TheUser, $CurrentTime, true); - } - else - { - $NeedUpdate[$ThePlanet['id']] = HandlePlanetQueue($ThePlanet, $TheUser, $CurrentTime, true); - } - $NeedUpdate[$TheLabPlanet['id']] = HandlePlanetQueue($TheLabPlanet, $TheUser, $CurrentTime, true); - if($ForMultiUpdate === true) - { - return $NeedUpdate; - } - else - { - $UpdateArray = array(); - foreach($NeedUpdate as $PlanetID => $Value) - { - if($Value === true) - { - if($ThePlanet['id'] == $PlanetID) - { - $UpdateArray[] = $ThePlanet; - } - elseif($TheLabPlanet['id'] == $PlanetID) - { - $UpdateArray[] = $TheLabPlanet; - } - } - } - HandlePlanetUpdate_MultiUpdate(array('planets' => $UpdateArray), $TheUser); - } - } - else - { - if($ThePlanetFullUpdate === true) - { - $NeedUpdate[$ThePlanet['id']] = HandlePlanetUpdate($ThePlanet, $TheUser, $CurrentTime, $ForMultiUpdate); - } - else - { - $NeedUpdate[$ThePlanet['id']] = HandlePlanetQueue($ThePlanet, $TheUser, $CurrentTime, $ForMultiUpdate); - } - if($ForMultiUpdate === true) - { - return $NeedUpdate; - } - } -} - -?> \ No newline at end of file + 0 && $TheUser['techQueue_Planet'] != $ThePlanet['id']) + { + if(empty($TheLabPlanet)) + { + $TheLabPlanet = doquery("SELECT * FROM {{table}} WHERE `id` = {$TheUser['techQueue_Planet']} LIMIT 1;", 'planets', true); + } + if($ThePlanetFullUpdate === true) + { + $NeedUpdate[$ThePlanet['id']] = HandlePlanetUpdate($ThePlanet, $TheUser, $CurrentTime, true); + } + else + { + $NeedUpdate[$ThePlanet['id']] = HandlePlanetQueue($ThePlanet, $TheUser, $CurrentTime, true); + } + $NeedUpdate[$TheLabPlanet['id']] = HandlePlanetQueue($TheLabPlanet, $TheUser, $CurrentTime, true); + if($ForMultiUpdate === true) + { + return $NeedUpdate; + } + else + { + $UpdateArray = array(); + foreach($NeedUpdate as $PlanetID => $Value) + { + if($Value === true) + { + if($ThePlanet['id'] == $PlanetID) + { + $UpdateArray[] = $ThePlanet; + } + elseif($TheLabPlanet['id'] == $PlanetID) + { + $UpdateArray[] = $TheLabPlanet; + } + } + } + HandlePlanetUpdate_MultiUpdate(array('planets' => $UpdateArray), $TheUser); + } + } + else + { + if($ThePlanetFullUpdate === true) + { + $NeedUpdate[$ThePlanet['id']] = HandlePlanetUpdate($ThePlanet, $TheUser, $CurrentTime, $ForMultiUpdate); + } + else + { + $NeedUpdate[$ThePlanet['id']] = HandlePlanetQueue($ThePlanet, $TheUser, $CurrentTime, $ForMultiUpdate); + } + if($ForMultiUpdate === true) + { + return $NeedUpdate; + } + } +} + +?> diff --git a/includes/functions/HandlePlanetQueue.php b/includes/functions/HandlePlanetQueue.php index 18bcef57b..7b6c7a172 100644 --- a/includes/functions/HandlePlanetQueue.php +++ b/includes/functions/HandlePlanetQueue.php @@ -1,110 +1,110 @@ - $Count) - { - $HPQ_PlanetUpdatedFields[] = $_Vars_GameElements[$KeyID]; - } - } - $NeedQueueListRebuild = HandlePlanetQueue_StructuresSetNext($ThePlanet, $TheUser, $QueueList[$IDX]['endtime']); - } - } - elseif($QueueList[$IDX]['type'] === 2) - { - // Queue Type is: Technology on ThePlanet - $NeedUpdate = true; - if(HandlePlanetQueue_OnTechnologyEnd($ThePlanet, $TheUser, $QueueList[$IDX]['endtime'])) - { - $LastPlanetUpdate = $ThePlanet['last_update']; - PlanetResourceUpdate($TheUser, $ThePlanet, $QueueList[$IDX]['endtime'], true); - $NeedQueueListRebuild = HandlePlanetQueue_TechnologySetNext($ThePlanet, $TheUser, $QueueList[$IDX]['endtime']); - } - } - - if($NeedQueueListRebuild !== true) - { - unset($QueueList[$IDX]); - $IDX += 1; - } - else - { - $QueueList = HandlePlanetQueue_CreateQueueList($CurrentTime, $ThePlanet); - $IDX = 0; - } - } - - if($ForMultiUpdate === true) - { - if($NeedUpdate === true) - { - return true; - } - } - else - { - if($NeedUpdate === true) - { - $HPQ_PlanetUpdatedFields = array_unique($HPQ_PlanetUpdatedFields); - foreach($HPQ_PlanetUpdatedFields as $Value) - { - $Query_Update_Arr[] = "`{$Value}` = '{$ThePlanet[$Value]}'"; - } - $Query_Update = "UPDATE {{table}} SET ".implode(', ', $Query_Update_Arr)." WHERE `id` = {$ThePlanet['id']} LIMIT 1;"; - doquery($Query_Update, 'planets'); - $HPQ_PlanetUpdatedFields = array(); - } - if(!empty($HPQ_UserUpdatedFields)) - { - $HPQ_UserUpdatedFields = array_unique($HPQ_UserUpdatedFields); - $UpdateFields = array(); - foreach($HPQ_UserUpdatedFields as $Value) - { - $UpdateFields[] = "`{$Value}` = '{$TheUser[$Value]}'"; - } - $Query_Update = "UPDATE {{table}} SET ".implode(', ', $UpdateFields)." WHERE `id` = {$TheUser['id']};"; - doquery($Query_Update, 'users'); - $HPQ_UserUpdatedFields = array(); - } - } -} - -?> \ No newline at end of file + $Count) + { + $HPQ_PlanetUpdatedFields[] = $_Vars_GameElements[$KeyID]; + } + } + $NeedQueueListRebuild = HandlePlanetQueue_StructuresSetNext($ThePlanet, $TheUser, $QueueList[$IDX]['endtime']); + } + } + elseif($QueueList[$IDX]['type'] === 2) + { + // Queue Type is: Technology on ThePlanet + $NeedUpdate = true; + if(HandlePlanetQueue_OnTechnologyEnd($ThePlanet, $TheUser, $QueueList[$IDX]['endtime'])) + { + $LastPlanetUpdate = $ThePlanet['last_update']; + PlanetResourceUpdate($TheUser, $ThePlanet, $QueueList[$IDX]['endtime'], true); + $NeedQueueListRebuild = HandlePlanetQueue_TechnologySetNext($ThePlanet, $TheUser, $QueueList[$IDX]['endtime']); + } + } + + if($NeedQueueListRebuild !== true) + { + unset($QueueList[$IDX]); + $IDX += 1; + } + else + { + $QueueList = HandlePlanetQueue_CreateQueueList($CurrentTime, $ThePlanet); + $IDX = 0; + } + } + + if($ForMultiUpdate === true) + { + if($NeedUpdate === true) + { + return true; + } + } + else + { + if($NeedUpdate === true) + { + $HPQ_PlanetUpdatedFields = array_unique($HPQ_PlanetUpdatedFields); + foreach($HPQ_PlanetUpdatedFields as $Value) + { + $Query_Update_Arr[] = "`{$Value}` = '{$ThePlanet[$Value]}'"; + } + $Query_Update = "UPDATE {{table}} SET ".implode(', ', $Query_Update_Arr)." WHERE `id` = {$ThePlanet['id']} LIMIT 1;"; + doquery($Query_Update, 'planets'); + $HPQ_PlanetUpdatedFields = array(); + } + if(!empty($HPQ_UserUpdatedFields)) + { + $HPQ_UserUpdatedFields = array_unique($HPQ_UserUpdatedFields); + $UpdateFields = array(); + foreach($HPQ_UserUpdatedFields as $Value) + { + $UpdateFields[] = "`{$Value}` = '{$TheUser[$Value]}'"; + } + $Query_Update = "UPDATE {{table}} SET ".implode(', ', $UpdateFields)." WHERE `id` = {$TheUser['id']};"; + doquery($Query_Update, 'users'); + $HPQ_UserUpdatedFields = array(); + } + } +} + +?> diff --git a/includes/functions/HandlePlanetQueue_CreateQueueList.php b/includes/functions/HandlePlanetQueue_CreateQueueList.php index fda7585c9..04573a98a 100644 --- a/includes/functions/HandlePlanetQueue_CreateQueueList.php +++ b/includes/functions/HandlePlanetQueue_CreateQueueList.php @@ -1,60 +1,60 @@ - 1, 'endtime' => $ElementData[3]); - $QueueListID += 1; - } - } - } - } - if(!empty($ThePlanet['techQueue']) AND $ThePlanet['techQueue_firstEndTime'] <= $CurrentTime) - { - $ExplodeQueue = explode(';', $ThePlanet['techQueue']); - foreach($ExplodeQueue as $ElementData) - { - if(!empty($ElementData)) - { - $ElementData = explode(',', $ElementData); - if($ElementData[3] <= $CurrentTime) - { - $KeyString = $ElementData[3].str_pad($QueueListID, 4, '0', STR_PAD_LEFT); - $QueueList[$KeyString] = array('type' => 2, 'endtime' => $ElementData[3]); - $QueueListID += 1; - } - } - } - } - - if(!empty($QueueList)) - { - ksort($QueueList); - foreach($QueueList as $QueueData) - { - $TempList[] = $QueueData; - } - $QueueList = $TempList; - } - else - { - $QueueList = array(); - } - - return $QueueList; -} - -?> \ No newline at end of file + 1, 'endtime' => $ElementData[3]); + $QueueListID += 1; + } + } + } + } + if(!empty($ThePlanet['techQueue']) AND $ThePlanet['techQueue_firstEndTime'] <= $CurrentTime) + { + $ExplodeQueue = explode(';', $ThePlanet['techQueue']); + foreach($ExplodeQueue as $ElementData) + { + if(!empty($ElementData)) + { + $ElementData = explode(',', $ElementData); + if($ElementData[3] <= $CurrentTime) + { + $KeyString = $ElementData[3].str_pad($QueueListID, 4, '0', STR_PAD_LEFT); + $QueueList[$KeyString] = array('type' => 2, 'endtime' => $ElementData[3]); + $QueueListID += 1; + } + } + } + } + + if(!empty($QueueList)) + { + ksort($QueueList); + foreach($QueueList as $QueueData) + { + $TempList[] = $QueueData; + } + $QueueList = $TempList; + } + else + { + $QueueList = array(); + } + + return $QueueList; +} + +?> diff --git a/includes/functions/HandlePlanetQueue_OnStructureBuildEnd.php b/includes/functions/HandlePlanetQueue_OnStructureBuildEnd.php index 121a94b59..352425e67 100644 --- a/includes/functions/HandlePlanetQueue_OnStructureBuildEnd.php +++ b/includes/functions/HandlePlanetQueue_OnStructureBuildEnd.php @@ -1,236 +1,236 @@ - $ThePlanet['id'], 'Date' => $BuildEndTime, 'Place' => 3, 'Code' => $SetCode, 'ElementID' => $ElementID); - - // Trigger Tasks Check - if(empty($TheUser['tasks_done_parsed'])) - { - global $GlobalParsedTasks; - Tasks_CheckUservar($TheUser); - $GlobalParsedTasks[$TheUser['id']]['tasks_done_parsed'] = $TheUser['tasks_done_parsed']; - } - if(!$ForDestroy) - { - if($ElementID == 33) - { - Tasks_TriggerTask($TheUser, 'REACH_TERRAFORMING_LEVEL', array - ( - 'mainCheck' => function($JobArray) use ($ThePlanet) - { - if(CalculateMaxPlanetFields($ThePlanet) < $JobArray['fields']) - { - return true; - } - } - )); - } - if(in_array($ElementID, $_Vars_ElementCategories['prod'])) - { - Tasks_TriggerTask($TheUser, 'REACH_EXTRACTION_LEVEL', array - ( - 'preCheck' => function($JobArray) use ($ElementID) - { - return ($JobArray['buildingID'] != $ElementID); - }, - 'mainCheck' => function($JobArray) use ($ThePlanet, $ElementID) - { - global $_Vars_ResProduction, $_GameConfig, $_Vars_GameElements; - - $BuildTemp = $ThePlanet['temp_max']; - $BuildLevelFactor = 10; - $BuildLevel = $ThePlanet[$_Vars_GameElements[$ElementID]]; - $ThisExtraction = floor(eval($_Vars_ResProduction[$ElementID]['formule'][$JobArray['resource']]) * $_GameConfig['resource_multiplier'] * 1); - - if($ThisExtraction < $JobArray['level']) - { - return true; - } - } - )); - Tasks_TriggerTask($TheUser, 'REACH_TOTAL_EXTRACTION_LEVEL', array - ( - 'preCheck' => function($JobArray) use ($ElementID) - { - return ($JobArray['buildingID'] != $ElementID); - }, - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThePlanet, $TheUser, $ElementID) - { - global $_Vars_ResProduction, $_GameConfig, $_Vars_GameElements; - - $BuildTemp = $ThePlanet['temp_max']; - $BuildLevelFactor = 10; - $BuildLevel = $ThePlanet[$_Vars_GameElements[$ElementID]] - 1; - $PreviousExtraction = floor(eval($_Vars_ResProduction[$ElementID]['formule'][$JobArray['resource']]) * $_GameConfig['resource_multiplier'] * 1); - $BuildLevel = $ThePlanet[$_Vars_GameElements[$ElementID]]; - $ThisExtraction = floor(eval($_Vars_ResProduction[$ElementID]['formule'][$JobArray['resource']]) * $_GameConfig['resource_multiplier'] * 1); - $Difference = $ThisExtraction - $PreviousExtraction; - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $TheUser, $Difference); - } - )); - } - Tasks_TriggerTask($TheUser, 'CONSTRUCTION_END', array - ( - 'preCheck' => function($JobArray) use ($ElementID) - { - return ($JobArray['elementID'] != $ElementID); - }, - 'mainCheck' => function($JobArray) use ($ThePlanet, $_Vars_GameElements) - { - if($ThePlanet[$_Vars_GameElements[$JobArray['elementID']]] < $JobArray['level']) - { - return true; - } - } - )); - Tasks_TriggerTask($TheUser, 'MULTIPLE_CONSTRUCTION_END', array - ( - 'preCheck' => function($JobArray) use ($ElementID) - { - return ($JobArray['elementID'] != $ElementID); - }, - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($TheUser, $ThePlanet, $_Vars_GameElements) - { - if($ThePlanet[$_Vars_GameElements[$JobArray['elementID']]] != $JobArray['level']) - { - return true; - } - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $TheUser, 1); - } - )); - } - else - { - // Prevent building and destroying to make mission - if(in_array($ElementID, $_Vars_ElementCategories['prod'])) - { - Tasks_TriggerTask($TheUser, 'REACH_TOTAL_EXTRACTION_LEVEL', array - ( - 'preCheck' => function($JobArray) use ($ElementID) - { - return ($JobArray['buildingID'] != $ElementID); - }, - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThePlanet, $TheUser, $ElementID) - { - global $_Vars_ResProduction, $_GameConfig, $_Vars_GameElements, $UserTasksUpdate; - - $BuildTemp = $ThePlanet['temp_max']; - $BuildLevelFactor = 10; - $BuildLevel = $ThePlanet[$_Vars_GameElements[$ElementID]] + 1; - $PreviousExtraction = floor(eval($_Vars_ResProduction[$ElementID]['formule'][$JobArray['resource']]) * $_GameConfig['resource_multiplier'] * 1); - $BuildLevel = $ThePlanet[$_Vars_GameElements[$ElementID]]; - $ThisExtraction = floor(eval($_Vars_ResProduction[$ElementID]['formule'][$JobArray['resource']]) * $_GameConfig['resource_multiplier'] * 1); - $Difference = $PreviousExtraction - $ThisExtraction; - - if(!empty($UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID])) - { - $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID]; - } - if($TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] <= 0) - { - return true; - } - $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] -= $Difference; - $UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; - return true; - } - )); - } - Tasks_TriggerTask($TheUser, 'MULTIPLE_CONSTRUCTION_END', array - ( - 'preCheck' => function($JobArray) use ($ElementID) - { - return ($JobArray['elementID'] != $ElementID); - }, - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($TheUser, $ThePlanet, $_Vars_GameElements) - { - global $UserTasksUpdate; - if(!empty($UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID])) - { - $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID]; - } - if($TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] <= 0) - { - return true; - } - if(($ThePlanet[$_Vars_GameElements[$JobArray['elementID']]] + 1) != $JobArray['level']) - { - return true; - } - $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] -= 1; - $UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; - return true; - } - )); - } - - $HPQ_PlanetUpdatedFields[] = 'buildQueue_firstEndTime'; - $HPQ_PlanetUpdatedFields[] = 'buildQueue'; - $ThePlanet['buildQueue_firstEndTime'] = '0'; - if($QueueLength > 0) - { - $ThePlanet['buildQueue'] = implode(';', $Queue); - return true; - } - else - { - $ThePlanet['buildQueue'] = '0'; - } - } - } - return false; -} - -?> \ No newline at end of file + $ThePlanet['id'], 'Date' => $BuildEndTime, 'Place' => 3, 'Code' => $SetCode, 'ElementID' => $ElementID); + + // Trigger Tasks Check + if(empty($TheUser['tasks_done_parsed'])) + { + global $GlobalParsedTasks; + Tasks_CheckUservar($TheUser); + $GlobalParsedTasks[$TheUser['id']]['tasks_done_parsed'] = $TheUser['tasks_done_parsed']; + } + if(!$ForDestroy) + { + if($ElementID == 33) + { + Tasks_TriggerTask($TheUser, 'REACH_TERRAFORMING_LEVEL', array + ( + 'mainCheck' => function($JobArray) use ($ThePlanet) + { + if(CalculateMaxPlanetFields($ThePlanet) < $JobArray['fields']) + { + return true; + } + } + )); + } + if(in_array($ElementID, $_Vars_ElementCategories['prod'])) + { + Tasks_TriggerTask($TheUser, 'REACH_EXTRACTION_LEVEL', array + ( + 'preCheck' => function($JobArray) use ($ElementID) + { + return ($JobArray['buildingID'] != $ElementID); + }, + 'mainCheck' => function($JobArray) use ($ThePlanet, $ElementID) + { + global $_Vars_ResProduction, $_GameConfig, $_Vars_GameElements; + + $BuildTemp = $ThePlanet['temp_max']; + $BuildLevelFactor = 10; + $BuildLevel = $ThePlanet[$_Vars_GameElements[$ElementID]]; + $ThisExtraction = floor(eval($_Vars_ResProduction[$ElementID]['formule'][$JobArray['resource']]) * $_GameConfig['resource_multiplier'] * 1); + + if($ThisExtraction < $JobArray['level']) + { + return true; + } + } + )); + Tasks_TriggerTask($TheUser, 'REACH_TOTAL_EXTRACTION_LEVEL', array + ( + 'preCheck' => function($JobArray) use ($ElementID) + { + return ($JobArray['buildingID'] != $ElementID); + }, + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThePlanet, $TheUser, $ElementID) + { + global $_Vars_ResProduction, $_GameConfig, $_Vars_GameElements; + + $BuildTemp = $ThePlanet['temp_max']; + $BuildLevelFactor = 10; + $BuildLevel = $ThePlanet[$_Vars_GameElements[$ElementID]] - 1; + $PreviousExtraction = floor(eval($_Vars_ResProduction[$ElementID]['formule'][$JobArray['resource']]) * $_GameConfig['resource_multiplier'] * 1); + $BuildLevel = $ThePlanet[$_Vars_GameElements[$ElementID]]; + $ThisExtraction = floor(eval($_Vars_ResProduction[$ElementID]['formule'][$JobArray['resource']]) * $_GameConfig['resource_multiplier'] * 1); + $Difference = $ThisExtraction - $PreviousExtraction; + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $TheUser, $Difference); + } + )); + } + Tasks_TriggerTask($TheUser, 'CONSTRUCTION_END', array + ( + 'preCheck' => function($JobArray) use ($ElementID) + { + return ($JobArray['elementID'] != $ElementID); + }, + 'mainCheck' => function($JobArray) use ($ThePlanet, $_Vars_GameElements) + { + if($ThePlanet[$_Vars_GameElements[$JobArray['elementID']]] < $JobArray['level']) + { + return true; + } + } + )); + Tasks_TriggerTask($TheUser, 'MULTIPLE_CONSTRUCTION_END', array + ( + 'preCheck' => function($JobArray) use ($ElementID) + { + return ($JobArray['elementID'] != $ElementID); + }, + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($TheUser, $ThePlanet, $_Vars_GameElements) + { + if($ThePlanet[$_Vars_GameElements[$JobArray['elementID']]] != $JobArray['level']) + { + return true; + } + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $TheUser, 1); + } + )); + } + else + { + // Prevent building and destroying to make mission + if(in_array($ElementID, $_Vars_ElementCategories['prod'])) + { + Tasks_TriggerTask($TheUser, 'REACH_TOTAL_EXTRACTION_LEVEL', array + ( + 'preCheck' => function($JobArray) use ($ElementID) + { + return ($JobArray['buildingID'] != $ElementID); + }, + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThePlanet, $TheUser, $ElementID) + { + global $_Vars_ResProduction, $_GameConfig, $_Vars_GameElements, $UserTasksUpdate; + + $BuildTemp = $ThePlanet['temp_max']; + $BuildLevelFactor = 10; + $BuildLevel = $ThePlanet[$_Vars_GameElements[$ElementID]] + 1; + $PreviousExtraction = floor(eval($_Vars_ResProduction[$ElementID]['formule'][$JobArray['resource']]) * $_GameConfig['resource_multiplier'] * 1); + $BuildLevel = $ThePlanet[$_Vars_GameElements[$ElementID]]; + $ThisExtraction = floor(eval($_Vars_ResProduction[$ElementID]['formule'][$JobArray['resource']]) * $_GameConfig['resource_multiplier'] * 1); + $Difference = $PreviousExtraction - $ThisExtraction; + + if(!empty($UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID])) + { + $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID]; + } + if($TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] <= 0) + { + return true; + } + $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] -= $Difference; + $UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; + return true; + } + )); + } + Tasks_TriggerTask($TheUser, 'MULTIPLE_CONSTRUCTION_END', array + ( + 'preCheck' => function($JobArray) use ($ElementID) + { + return ($JobArray['elementID'] != $ElementID); + }, + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($TheUser, $ThePlanet, $_Vars_GameElements) + { + global $UserTasksUpdate; + if(!empty($UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID])) + { + $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID]; + } + if($TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] <= 0) + { + return true; + } + if(($ThePlanet[$_Vars_GameElements[$JobArray['elementID']]] + 1) != $JobArray['level']) + { + return true; + } + $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] -= 1; + $UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; + return true; + } + )); + } + + $HPQ_PlanetUpdatedFields[] = 'buildQueue_firstEndTime'; + $HPQ_PlanetUpdatedFields[] = 'buildQueue'; + $ThePlanet['buildQueue_firstEndTime'] = '0'; + if($QueueLength > 0) + { + $ThePlanet['buildQueue'] = implode(';', $Queue); + return true; + } + else + { + $ThePlanet['buildQueue'] = '0'; + } + } + } + return false; +} + +?> diff --git a/includes/functions/HandlePlanetQueue_OnTechnologyEnd.php b/includes/functions/HandlePlanetQueue_OnTechnologyEnd.php index 1048c75d4..5cefb3df0 100644 --- a/includes/functions/HandlePlanetQueue_OnTechnologyEnd.php +++ b/includes/functions/HandlePlanetQueue_OnTechnologyEnd.php @@ -1,76 +1,76 @@ - '0', 'Date' => $BuildEndTime, 'Place' => 5, 'Code' => '0', 'ElementID' => $ElementID); - - // Trigger Tasks Check - if(empty($TheUser['tasks_done_parsed'])) - { - global $GlobalParsedTasks; - Tasks_CheckUservar($TheUser); - $GlobalParsedTasks[$TheUser['id']]['tasks_done_parsed'] = $TheUser['tasks_done_parsed']; - } - Tasks_TriggerTask($TheUser, 'RESEARCH_END', array - ( - 'mainCheck' => function($JobArray) use ($TheUser, $_Vars_GameElements) - { - if($TheUser[$_Vars_GameElements[$JobArray['elementID']]] < $JobArray['level']) - { - return true; - } - } - )); - Tasks_TriggerTask($TheUser, 'REACH_TECHPOINTS_LEVEL', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThePlanet, $TheUser, $ElementID) - { - global $_Vars_GameElements, $_GameConfig; - $TheUser[$_Vars_GameElements[$ElementID]] -= 1; - $ThisPoints = GetBuildingPrice($TheUser, $ThePlanet, $ElementID); - $ThisPoints = ($ThisPoints['metal'] + $ThisPoints['crystal'] + $ThisPoints['deuterium']) / $_GameConfig['stat_settings']; - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $TheUser, $ThisPoints); - } - )); - - $HPQ_PlanetUpdatedFields[] = 'techQueue_firstEndTime'; - $HPQ_PlanetUpdatedFields[] = 'techQueue'; - $ThePlanet['techQueue_firstEndTime'] = '0'; - if($QueueLength > 0) - { - $ThePlanet['techQueue'] = implode(';', $Queue); - return true; - } - else - { - $ThePlanet['techQueue'] = '0'; - } - } - } - return false; -} - -?> \ No newline at end of file + '0', 'Date' => $BuildEndTime, 'Place' => 5, 'Code' => '0', 'ElementID' => $ElementID); + + // Trigger Tasks Check + if(empty($TheUser['tasks_done_parsed'])) + { + global $GlobalParsedTasks; + Tasks_CheckUservar($TheUser); + $GlobalParsedTasks[$TheUser['id']]['tasks_done_parsed'] = $TheUser['tasks_done_parsed']; + } + Tasks_TriggerTask($TheUser, 'RESEARCH_END', array + ( + 'mainCheck' => function($JobArray) use ($TheUser, $_Vars_GameElements) + { + if($TheUser[$_Vars_GameElements[$JobArray['elementID']]] < $JobArray['level']) + { + return true; + } + } + )); + Tasks_TriggerTask($TheUser, 'REACH_TECHPOINTS_LEVEL', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThePlanet, $TheUser, $ElementID) + { + global $_Vars_GameElements, $_GameConfig; + $TheUser[$_Vars_GameElements[$ElementID]] -= 1; + $ThisPoints = GetBuildingPrice($TheUser, $ThePlanet, $ElementID); + $ThisPoints = ($ThisPoints['metal'] + $ThisPoints['crystal'] + $ThisPoints['deuterium']) / $_GameConfig['stat_settings']; + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $TheUser, $ThisPoints); + } + )); + + $HPQ_PlanetUpdatedFields[] = 'techQueue_firstEndTime'; + $HPQ_PlanetUpdatedFields[] = 'techQueue'; + $ThePlanet['techQueue_firstEndTime'] = '0'; + if($QueueLength > 0) + { + $ThePlanet['techQueue'] = implode(';', $Queue); + return true; + } + else + { + $ThePlanet['techQueue'] = '0'; + } + } + } + return false; +} + +?> diff --git a/includes/functions/HandlePlanetQueue_StructuresSetNext.php b/includes/functions/HandlePlanetQueue_StructuresSetNext.php index 9e625509b..a91eb68a9 100644 --- a/includes/functions/HandlePlanetQueue_StructuresSetNext.php +++ b/includes/functions/HandlePlanetQueue_StructuresSetNext.php @@ -1,280 +1,280 @@ - $_Vars_MaxElementLevel[$ElementID]) - { - $BlockBuilding = true; - $BlockReason = 5; - } - else if(isset($_Vars_PremiumBuildings[$ElementID]) && $_Vars_PremiumBuildings[$ElementID] == 1 && isset($_Vars_PremiumBuildingPrices[$ElementID]) && $_Vars_PremiumBuildingPrices[$ElementID] > 0 AND $TheUser['darkEnergy'] < $_Vars_PremiumBuildingPrices[$ElementID]) - { - $BlockBuilding = true; - $BlockReason = 6; - } - else if($ElementID == 31 AND $TheUser['techQueue_Planet'] > 0 AND $TheUser['techQueue_EndTime'] > 0 AND $_GameConfig['BuildLabWhileRun'] != 1) - { - $BlockBuilding = true; - $BlockReason = 7; - } - } - else - { - $BlockBuilding = true; - $BlockReason = 4; - } - } - else - { - $BlockBuilding = true; - $BlockReason = 3; - } - } - } - else - { - $BlockBuilding = true; - $BlockReason = 0; - } - - if($BlockBuilding === false) - { - $RemoveRes = GetBuildingPrice($TheUser, $ThePlanet, $ElementID, true, $ForDestroy); - $ThePlanet['metal'] -= $RemoveRes['metal']; - $ThePlanet['crystal'] -= $RemoveRes['crystal']; - $ThePlanet['deuterium'] -= $RemoveRes['deuterium']; - if(isset($_Vars_PremiumBuildings[$ElementID]) && $_Vars_PremiumBuildings[$ElementID] == 1 && isset($_Vars_PremiumBuildingPrices[$ElementID]) && $_Vars_PremiumBuildingPrices[$ElementID] > 0) - { - $NeedUpdateUser = true; - $TheUser['darkEnergy'] -= $_Vars_PremiumBuildingPrices[$ElementID]; - $HPQ_UserUpdatedFields[] = 'darkEnergy'; - $HFUU_UsersToUpdate[$TheUser['id']] = true; - } - $ThePlanet['buildQueue_firstEndTime'] = $ElementEndTime; - - if($ForDestroy === true) - { - $SetCode = 2; - } - else - { - $SetCode = 1; - } - $UserDev_Log[] = array('PlanetID' => $ThePlanet['id'], 'Date' => $CurrentTime, 'Place' => 1, 'Code' => $SetCode, 'ElementID' => $ElementID); - - break; - } - else - { - $Message = false; - $ElementName = $_Lang['tech'][$ElementID]; - - if($BlockReason === 0) - { - // No Resources - $Needed = GetBuildingPrice($TheUser, $ThePlanet, $ElementID, true, $ForDestroy); - $Message['msg_id'] = '082'; - $Message['args'] = array - ( - $ElementName, $ElementLevel, (($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name'], - prettyNumber($ThePlanet['metal']), prettyNumber($ThePlanet['crystal']), prettyNumber($ThePlanet['deuterium']), - ($Needed['metal'] > $ThePlanet['metal'] ? 'red' : 'lime'), prettyNumber($Needed['metal']), - ($Needed['crystal'] > $ThePlanet['crystal'] ? 'red' : 'lime'), prettyNumber($Needed['crystal']), - ($Needed['deuterium'] > $ThePlanet['deuterium'] ? 'red' : 'lime'), prettyNumber($Needed['deuterium']) - ); - } - elseif($BlockReason === 1) - { - // Destroy 0 level - $Message['msg_id'] = '001'; - $Message['args'] = array($ElementName); - } - elseif($BlockReason === 2) - { - // Undestroyable - $Message['msg_id'] = '004'; - $Message['args'] = array($ElementName); - } - elseif($BlockReason === 3) - { - // No Technology - $Message['msg_id'] = '070'; - $Message['args'] = array($ElementName, (($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name'], $ElementID); - } - elseif($BlockReason === 4) - { - // No Free Fields - $Message['msg_id'] = '037'; - $Message['args'] = array((($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name'], $ElementName); - } - elseif($BlockReason === 5) - { - // Max level reached - $Message['msg_id'] = '083'; - $Message['args'] = array((($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name'], $ElementName); - } - elseif($BlockReason === 6) - { - // No enough DarkEnergy - $Message['msg_id'] = '003'; - $Message['args'] = array($ElementName, $_Vars_PremiumBuildingPrices[$ElementID], $TheUser['darkEnergy']); - } - elseif($BlockReason === 7) - { - // Lab in ResearchMode - $Message['msg_id'] = '084'; - $Message['args'] = array($ElementName, (($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name']); - } - else - { - // Unknown reason - $Message['msg_id'] = '081'; - $Message['args'] = array($ElementName, (($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name']); - } - $Message = json_encode($Message); - if(empty($SentMessages) OR !in_array($Message, $SentMessages)) - { - $SentMessages[] = $Message; - Cache_Message($TheUser['id'], 0, $CurrentTime, 50, '001', '001', $Message); - } - - // Now rebuild Queue - unset($Queue[$i]); - $NeedQueueRebuild = true; - $RemovedTime = $ElementTime; - if(($i + 1) < $QueueLength) - { - $TempPlanet = $ThePlanet; - foreach($Queue as &$Data) - { - if(empty($Data)) - { - continue; - } - $Data = explode(',', $Data); - $TempTime = GetBuildingTime($TheUser, $TempPlanet, $Data[0]); - if($Data[4] == 'build') - { - $TempPlanet[$_Vars_GameElements[$Data[0]]] += 1; - } - else - { - $TempTime /= 2; - $TempPlanet[$_Vars_GameElements[$Data[0]]] -= 1; - } - $RemovedTime += ($Data[2] - $TempTime); - $Data[1] = $TempPlanet[$_Vars_GameElements[$Data[0]]]; - $Data[2] = $TempTime; - $Data[3] -= $RemovedTime; - $Data = implode(',', $Data); - } - } - $Return = true; - } - } - - if(isset($NeedQueueRebuild)) - { - foreach($Queue as $QueueRow) - { - if(!empty($QueueRow)) - { - $Temp[] = $QueueRow; - } - } - if(!empty($Temp)) - { - $ThePlanet['buildQueue'] = implode(';', $Temp); - } - else - { - $ThePlanet['buildQueue'] = ''; - $ThePlanet['buildQueue_firstEndTime'] = '0'; - } - } - } - - if($RunStandAlone === true) - { - $Return = false; - if(isset($NeedUpdate)) - { - $Query_Update = ''; - $Query_Update .= "UPDATE {{table}} SET "; - $Query_Update .= "`metal` = '{$ThePlanet['metal']}', `crystal` = '{$ThePlanet['crystal']}', `deuterium` = '{$ThePlanet['deuterium']}', "; - $Query_Update .= "`buildQueue` = '{$ThePlanet['buildQueue']}', `buildQueue_firstEndTime` = '{$ThePlanet['buildQueue_firstEndTime']}' "; - $Query_Update .= "WHERE `id` = {$ThePlanet['id']};"; - doquery($Query_Update, 'planets'); - - $Return = true; - } - if(isset($NeedUpdateUser)) - { - doquery("UPDATE {{table}} SET `darkEnergy` = '{$TheUser['darkEnergy']}' WHERE `id` = {$TheUser['id']};", 'users'); - } - } - - return $Return; -} - -?> \ No newline at end of file + $_Vars_MaxElementLevel[$ElementID]) + { + $BlockBuilding = true; + $BlockReason = 5; + } + else if(isset($_Vars_PremiumBuildings[$ElementID]) && $_Vars_PremiumBuildings[$ElementID] == 1 && isset($_Vars_PremiumBuildingPrices[$ElementID]) && $_Vars_PremiumBuildingPrices[$ElementID] > 0 AND $TheUser['darkEnergy'] < $_Vars_PremiumBuildingPrices[$ElementID]) + { + $BlockBuilding = true; + $BlockReason = 6; + } + else if($ElementID == 31 AND $TheUser['techQueue_Planet'] > 0 AND $TheUser['techQueue_EndTime'] > 0 AND $_GameConfig['BuildLabWhileRun'] != 1) + { + $BlockBuilding = true; + $BlockReason = 7; + } + } + else + { + $BlockBuilding = true; + $BlockReason = 4; + } + } + else + { + $BlockBuilding = true; + $BlockReason = 3; + } + } + } + else + { + $BlockBuilding = true; + $BlockReason = 0; + } + + if($BlockBuilding === false) + { + $RemoveRes = GetBuildingPrice($TheUser, $ThePlanet, $ElementID, true, $ForDestroy); + $ThePlanet['metal'] -= $RemoveRes['metal']; + $ThePlanet['crystal'] -= $RemoveRes['crystal']; + $ThePlanet['deuterium'] -= $RemoveRes['deuterium']; + if(isset($_Vars_PremiumBuildings[$ElementID]) && $_Vars_PremiumBuildings[$ElementID] == 1 && isset($_Vars_PremiumBuildingPrices[$ElementID]) && $_Vars_PremiumBuildingPrices[$ElementID] > 0) + { + $NeedUpdateUser = true; + $TheUser['darkEnergy'] -= $_Vars_PremiumBuildingPrices[$ElementID]; + $HPQ_UserUpdatedFields[] = 'darkEnergy'; + $HFUU_UsersToUpdate[$TheUser['id']] = true; + } + $ThePlanet['buildQueue_firstEndTime'] = $ElementEndTime; + + if($ForDestroy === true) + { + $SetCode = 2; + } + else + { + $SetCode = 1; + } + $UserDev_Log[] = array('PlanetID' => $ThePlanet['id'], 'Date' => $CurrentTime, 'Place' => 1, 'Code' => $SetCode, 'ElementID' => $ElementID); + + break; + } + else + { + $Message = false; + $ElementName = $_Lang['tech'][$ElementID]; + + if($BlockReason === 0) + { + // No Resources + $Needed = GetBuildingPrice($TheUser, $ThePlanet, $ElementID, true, $ForDestroy); + $Message['msg_id'] = '082'; + $Message['args'] = array + ( + $ElementName, $ElementLevel, (($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name'], + prettyNumber($ThePlanet['metal']), prettyNumber($ThePlanet['crystal']), prettyNumber($ThePlanet['deuterium']), + ($Needed['metal'] > $ThePlanet['metal'] ? 'red' : 'lime'), prettyNumber($Needed['metal']), + ($Needed['crystal'] > $ThePlanet['crystal'] ? 'red' : 'lime'), prettyNumber($Needed['crystal']), + ($Needed['deuterium'] > $ThePlanet['deuterium'] ? 'red' : 'lime'), prettyNumber($Needed['deuterium']) + ); + } + elseif($BlockReason === 1) + { + // Destroy 0 level + $Message['msg_id'] = '001'; + $Message['args'] = array($ElementName); + } + elseif($BlockReason === 2) + { + // Undestroyable + $Message['msg_id'] = '004'; + $Message['args'] = array($ElementName); + } + elseif($BlockReason === 3) + { + // No Technology + $Message['msg_id'] = '070'; + $Message['args'] = array($ElementName, (($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name'], $ElementID); + } + elseif($BlockReason === 4) + { + // No Free Fields + $Message['msg_id'] = '037'; + $Message['args'] = array((($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name'], $ElementName); + } + elseif($BlockReason === 5) + { + // Max level reached + $Message['msg_id'] = '083'; + $Message['args'] = array((($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name'], $ElementName); + } + elseif($BlockReason === 6) + { + // No enough DarkEnergy + $Message['msg_id'] = '003'; + $Message['args'] = array($ElementName, $_Vars_PremiumBuildingPrices[$ElementID], $TheUser['darkEnergy']); + } + elseif($BlockReason === 7) + { + // Lab in ResearchMode + $Message['msg_id'] = '084'; + $Message['args'] = array($ElementName, (($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name']); + } + else + { + // Unknown reason + $Message['msg_id'] = '081'; + $Message['args'] = array($ElementName, (($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name']); + } + $Message = json_encode($Message); + if(empty($SentMessages) OR !in_array($Message, $SentMessages)) + { + $SentMessages[] = $Message; + Cache_Message($TheUser['id'], 0, $CurrentTime, 50, '001', '001', $Message); + } + + // Now rebuild Queue + unset($Queue[$i]); + $NeedQueueRebuild = true; + $RemovedTime = $ElementTime; + if(($i + 1) < $QueueLength) + { + $TempPlanet = $ThePlanet; + foreach($Queue as &$Data) + { + if(empty($Data)) + { + continue; + } + $Data = explode(',', $Data); + $TempTime = GetBuildingTime($TheUser, $TempPlanet, $Data[0]); + if($Data[4] == 'build') + { + $TempPlanet[$_Vars_GameElements[$Data[0]]] += 1; + } + else + { + $TempTime /= 2; + $TempPlanet[$_Vars_GameElements[$Data[0]]] -= 1; + } + $RemovedTime += ($Data[2] - $TempTime); + $Data[1] = $TempPlanet[$_Vars_GameElements[$Data[0]]]; + $Data[2] = $TempTime; + $Data[3] -= $RemovedTime; + $Data = implode(',', $Data); + } + } + $Return = true; + } + } + + if(isset($NeedQueueRebuild)) + { + foreach($Queue as $QueueRow) + { + if(!empty($QueueRow)) + { + $Temp[] = $QueueRow; + } + } + if(!empty($Temp)) + { + $ThePlanet['buildQueue'] = implode(';', $Temp); + } + else + { + $ThePlanet['buildQueue'] = ''; + $ThePlanet['buildQueue_firstEndTime'] = '0'; + } + } + } + + if($RunStandAlone === true) + { + $Return = false; + if(isset($NeedUpdate)) + { + $Query_Update = ''; + $Query_Update .= "UPDATE {{table}} SET "; + $Query_Update .= "`metal` = '{$ThePlanet['metal']}', `crystal` = '{$ThePlanet['crystal']}', `deuterium` = '{$ThePlanet['deuterium']}', "; + $Query_Update .= "`buildQueue` = '{$ThePlanet['buildQueue']}', `buildQueue_firstEndTime` = '{$ThePlanet['buildQueue_firstEndTime']}' "; + $Query_Update .= "WHERE `id` = {$ThePlanet['id']};"; + doquery($Query_Update, 'planets'); + + $Return = true; + } + if(isset($NeedUpdateUser)) + { + doquery("UPDATE {{table}} SET `darkEnergy` = '{$TheUser['darkEnergy']}' WHERE `id` = {$TheUser['id']};", 'users'); + } + } + + return $Return; +} + +?> diff --git a/includes/functions/HandlePlanetQueue_TechnologySetNext.php b/includes/functions/HandlePlanetQueue_TechnologySetNext.php index c1f0ccb61..147ddcf7c 100644 --- a/includes/functions/HandlePlanetQueue_TechnologySetNext.php +++ b/includes/functions/HandlePlanetQueue_TechnologySetNext.php @@ -1,213 +1,213 @@ - $_Vars_MaxElementLevel[$ElementID]) - { - $BlockResearch = true; - $BlockReason = 1; - } - else if(isset($_Vars_PremiumBuildings[$ElementID]) && $_Vars_PremiumBuildings[$ElementID] == 1 && isset($_Vars_PremiumBuildingPrices[$ElementID]) AND $TheUser['darkEnergy'] < $_Vars_PremiumBuildingPrices[$ElementID]) - { - $BlockResearch = true; - $BlockReason = 2; - } - } - else - { - $BlockResearch = true; - $BlockReason = 3; - } - } - else - { - $BlockResearch = true; - $BlockReason = 0; - } - - if($BlockResearch === false) - { - $NeedUpdate = true; - $NeedUpdateUser = true; - - $RemoveRes = GetBuildingPrice($TheUser, $ThePlanet, $ElementID); - $ThePlanet['metal'] -= $RemoveRes['metal']; - $ThePlanet['crystal'] -= $RemoveRes['crystal']; - $ThePlanet['deuterium'] -= $RemoveRes['deuterium']; - if(isset($_Vars_PremiumBuildings[$ElementID]) && $_Vars_PremiumBuildings[$ElementID] == 1 && isset($_Vars_PremiumBuildingPrices[$ElementID])) - { - $TheUser['darkEnergy'] -= $_Vars_PremiumBuildingPrices[$ElementID]; - $HPQ_UserUpdatedFields[] = 'darkEnergy'; - } - $ThePlanet['techQueue'] = implode(';', $Queue); - $ThePlanet['techQueue_firstEndTime'] = $ElementEndTime; - $TheUser['techQueue_Planet'] = $ThePlanet['id']; - $TheUser['techQueue_EndTime'] = $ElementEndTime; - - $UserDev_Log[] = array('PlanetID' => $ThePlanet['id'], 'Date' => $CurrentTime, 'Place' => 4, 'Code' => 1, 'ElementID' => $ElementID); - - break; - } - else - { - $Message = false; - $ElementName = $_Lang['tech'][$ElementID]; - - if($BlockReason === 0) - { - // No Resources - $Needed = GetBuildingPrice($TheUser, $ThePlanet, $ElementID); - $Message['msg_id'] = '085'; - $Message['args'] = array - ( - $ElementName, $ElementLevel, (($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name'], - prettyNumber($ThePlanet['metal']), prettyNumber($ThePlanet['crystal']), prettyNumber($ThePlanet['deuterium']), - ($Needed['metal'] > $ThePlanet['metal'] ? 'red' : 'lime'), prettyNumber($Needed['metal']), - ($Needed['crystal'] > $ThePlanet['crystal'] ? 'red' : 'lime'), prettyNumber($Needed['crystal']), - ($Needed['deuterium'] > $ThePlanet['deuterium'] ? 'red' : 'lime'), prettyNumber($Needed['deuterium']) - ); - } - elseif($BlockReason === 1) - { - // Max level reached - $Message['msg_id'] = '086'; - $Message['args'] = array($ElementName); - } - elseif($BlockReason === 2) - { - // No enough DarkEnergy - $Message['msg_id'] = '087'; - $Message['args'] = array($ElementName); - } - elseif($BlockReason === 3) - { - // No Technology - $Message['msg_id'] = '088'; - $Message['args'] = array($ElementName, (($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name'], $ElementID); - } - else - { - // Unknown reason - $Message['msg_id'] = '089'; - $Message['args'] = array($ElementName, (($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name']); - } - $Message = json_encode($Message); - if(empty($SentMessages) OR !in_array($Message, $SentMessages)) - { - $SentMessages[] = $Message; - Cache_Message($TheUser['id'], 0, $CurrentTime, 50, '001', '001', $Message); - } - - // Now rebuild Queue - unset($Queue[$i]); - $NeedQueueRebuild = true; - $RemovedTime = $ElementTime; - if(($i + 1) < $QueueLength) - { - $TempUser = $TheUser; - foreach($Queue as &$Data) - { - if(empty($Data)) - { - continue; - } - $Data = explode(',', $Data); - $TempTime = GetBuildingTime($TempUser, $ThePlanet, $Data[0]); - $TempUser[$_Vars_GameElements[$Data[0]]] += 1; - $RemovedTime += ($Data[2] - $TempTime); - $Data[1] = $TempUser[$_Vars_GameElements[$Data[0]]]; - $Data[2] = $TempTime; - $Data[3] -= $RemovedTime; - $Data = implode(',', $Data); - } - } - $Return = true; - } - } - - if($NeedQueueRebuild === true) - { - foreach($Queue as $QueueRow) - { - if(!empty($QueueRow)) - { - $Temp[] = $QueueRow; - } - } - if(!empty($Temp)) - { - $ThePlanet['techQueue'] = implode(';', $Queue); - $ThePlanet['techQueue_firstEndTime'] = $ElementEndTime; - $TheUser['techQueue_Planet'] = $ThePlanet['id']; - $TheUser['techQueue_EndTime'] = $ElementEndTime; - } - else - { - $ThePlanet['techQueue'] = ''; - $ThePlanet['techQueue_firstEndTime'] = '0'; - $TheUser['techQueue_Planet'] = '0'; - $TheUser['techQueue_EndTime'] = '0'; - } - } - } - - if($RunStandAlone === true) - { - $Return = false; - if($NeedUpdate === true) - { - $Query_Update = ''; - $Query_Update .= "UPDATE {{table}} SET "; - $Query_Update .= "`metal` = '{$ThePlanet['metal']}', `crystal` = '{$ThePlanet['crystal']}', `deuterium` = '{$ThePlanet['deuterium']}', "; - $Query_Update .= "`techQueue` = '{$ThePlanet['techQueue']}', `techQueue_firstEndTime` = '{$ThePlanet['techQueue_firstEndTime']}' "; - $Query_Update .= "WHERE `id` = {$ThePlanet['id']};"; - doquery($Query_Update, 'planets'); - - $Return = true; - } - if($NeedUpdateUser === true) - { - doquery("UPDATE {{table}} SET `techQueue_EndTime` = '{$TheUser['techQueue_EndTime']}', `techQueue_Planet` = '{$TheUser['techQueue_Planet']}', `darkEnergy` = '{$TheUser['darkEnergy']}' WHERE `id` = {$TheUser['id']};", 'users'); - } - } - - return $Return; -} - -?> \ No newline at end of file + $_Vars_MaxElementLevel[$ElementID]) + { + $BlockResearch = true; + $BlockReason = 1; + } + else if(isset($_Vars_PremiumBuildings[$ElementID]) && $_Vars_PremiumBuildings[$ElementID] == 1 && isset($_Vars_PremiumBuildingPrices[$ElementID]) AND $TheUser['darkEnergy'] < $_Vars_PremiumBuildingPrices[$ElementID]) + { + $BlockResearch = true; + $BlockReason = 2; + } + } + else + { + $BlockResearch = true; + $BlockReason = 3; + } + } + else + { + $BlockResearch = true; + $BlockReason = 0; + } + + if($BlockResearch === false) + { + $NeedUpdate = true; + $NeedUpdateUser = true; + + $RemoveRes = GetBuildingPrice($TheUser, $ThePlanet, $ElementID); + $ThePlanet['metal'] -= $RemoveRes['metal']; + $ThePlanet['crystal'] -= $RemoveRes['crystal']; + $ThePlanet['deuterium'] -= $RemoveRes['deuterium']; + if(isset($_Vars_PremiumBuildings[$ElementID]) && $_Vars_PremiumBuildings[$ElementID] == 1 && isset($_Vars_PremiumBuildingPrices[$ElementID])) + { + $TheUser['darkEnergy'] -= $_Vars_PremiumBuildingPrices[$ElementID]; + $HPQ_UserUpdatedFields[] = 'darkEnergy'; + } + $ThePlanet['techQueue'] = implode(';', $Queue); + $ThePlanet['techQueue_firstEndTime'] = $ElementEndTime; + $TheUser['techQueue_Planet'] = $ThePlanet['id']; + $TheUser['techQueue_EndTime'] = $ElementEndTime; + + $UserDev_Log[] = array('PlanetID' => $ThePlanet['id'], 'Date' => $CurrentTime, 'Place' => 4, 'Code' => 1, 'ElementID' => $ElementID); + + break; + } + else + { + $Message = false; + $ElementName = $_Lang['tech'][$ElementID]; + + if($BlockReason === 0) + { + // No Resources + $Needed = GetBuildingPrice($TheUser, $ThePlanet, $ElementID); + $Message['msg_id'] = '085'; + $Message['args'] = array + ( + $ElementName, $ElementLevel, (($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name'], + prettyNumber($ThePlanet['metal']), prettyNumber($ThePlanet['crystal']), prettyNumber($ThePlanet['deuterium']), + ($Needed['metal'] > $ThePlanet['metal'] ? 'red' : 'lime'), prettyNumber($Needed['metal']), + ($Needed['crystal'] > $ThePlanet['crystal'] ? 'red' : 'lime'), prettyNumber($Needed['crystal']), + ($Needed['deuterium'] > $ThePlanet['deuterium'] ? 'red' : 'lime'), prettyNumber($Needed['deuterium']) + ); + } + elseif($BlockReason === 1) + { + // Max level reached + $Message['msg_id'] = '086'; + $Message['args'] = array($ElementName); + } + elseif($BlockReason === 2) + { + // No enough DarkEnergy + $Message['msg_id'] = '087'; + $Message['args'] = array($ElementName); + } + elseif($BlockReason === 3) + { + // No Technology + $Message['msg_id'] = '088'; + $Message['args'] = array($ElementName, (($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name'], $ElementID); + } + else + { + // Unknown reason + $Message['msg_id'] = '089'; + $Message['args'] = array($ElementName, (($ThePlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']), $ThePlanet['name']); + } + $Message = json_encode($Message); + if(empty($SentMessages) OR !in_array($Message, $SentMessages)) + { + $SentMessages[] = $Message; + Cache_Message($TheUser['id'], 0, $CurrentTime, 50, '001', '001', $Message); + } + + // Now rebuild Queue + unset($Queue[$i]); + $NeedQueueRebuild = true; + $RemovedTime = $ElementTime; + if(($i + 1) < $QueueLength) + { + $TempUser = $TheUser; + foreach($Queue as &$Data) + { + if(empty($Data)) + { + continue; + } + $Data = explode(',', $Data); + $TempTime = GetBuildingTime($TempUser, $ThePlanet, $Data[0]); + $TempUser[$_Vars_GameElements[$Data[0]]] += 1; + $RemovedTime += ($Data[2] - $TempTime); + $Data[1] = $TempUser[$_Vars_GameElements[$Data[0]]]; + $Data[2] = $TempTime; + $Data[3] -= $RemovedTime; + $Data = implode(',', $Data); + } + } + $Return = true; + } + } + + if($NeedQueueRebuild === true) + { + foreach($Queue as $QueueRow) + { + if(!empty($QueueRow)) + { + $Temp[] = $QueueRow; + } + } + if(!empty($Temp)) + { + $ThePlanet['techQueue'] = implode(';', $Queue); + $ThePlanet['techQueue_firstEndTime'] = $ElementEndTime; + $TheUser['techQueue_Planet'] = $ThePlanet['id']; + $TheUser['techQueue_EndTime'] = $ElementEndTime; + } + else + { + $ThePlanet['techQueue'] = ''; + $ThePlanet['techQueue_firstEndTime'] = '0'; + $TheUser['techQueue_Planet'] = '0'; + $TheUser['techQueue_EndTime'] = '0'; + } + } + } + + if($RunStandAlone === true) + { + $Return = false; + if($NeedUpdate === true) + { + $Query_Update = ''; + $Query_Update .= "UPDATE {{table}} SET "; + $Query_Update .= "`metal` = '{$ThePlanet['metal']}', `crystal` = '{$ThePlanet['crystal']}', `deuterium` = '{$ThePlanet['deuterium']}', "; + $Query_Update .= "`techQueue` = '{$ThePlanet['techQueue']}', `techQueue_firstEndTime` = '{$ThePlanet['techQueue_firstEndTime']}' "; + $Query_Update .= "WHERE `id` = {$ThePlanet['id']};"; + doquery($Query_Update, 'planets'); + + $Return = true; + } + if($NeedUpdateUser === true) + { + doquery("UPDATE {{table}} SET `techQueue_EndTime` = '{$TheUser['techQueue_EndTime']}', `techQueue_Planet` = '{$TheUser['techQueue_Planet']}', `darkEnergy` = '{$TheUser['darkEnergy']}' WHERE `id` = {$TheUser['id']};", 'users'); + } + } + + return $Return; +} + +?> diff --git a/includes/functions/HandlePlanetUpdate.php b/includes/functions/HandlePlanetUpdate.php index 90f89f00e..e43285a11 100644 --- a/includes/functions/HandlePlanetUpdate.php +++ b/includes/functions/HandlePlanetUpdate.php @@ -1,66 +1,66 @@ - $Count) - { - $HPQ_PlanetUpdatedFields[] = $_Vars_GameElements[$KeyID]; - } - } - - if($ForMultiUpdate === true) - { - if($NeedPlanetUpdate === true) - { - return true; - } - } - else - { - if(!empty($HPQ_PlanetUpdatedFields)) - { - $HPQ_PlanetUpdatedFields = array_unique($HPQ_PlanetUpdatedFields); - foreach($HPQ_PlanetUpdatedFields as $Value) - { - $Query_Update_Arr[] = "`{$Value}` = '{$ThePlanet[$Value]}'"; - } - $Query_Update = "UPDATE {{table}} SET ".implode(', ', $Query_Update_Arr)." WHERE `id` = {$ThePlanet['id']} LIMIT 1;"; - doquery($Query_Update, 'planets'); - $HPQ_PlanetUpdatedFields = array(); - } - if(!empty($HPQ_UserUpdatedFields)) - { - $HPQ_UserUpdatedFields = array_unique($HPQ_UserUpdatedFields); - $UpdateFields = array(); - foreach($HPQ_UserUpdatedFields as $Value) - { - $UpdateFields[] = "`{$Value}` = '{$TheUser[$Value]}'"; - } - $Query_Update = "UPDATE {{table}} SET ".implode(', ', $UpdateFields)." WHERE `id` = {$TheUser['id']};"; - doquery($Query_Update, 'users'); - $HPQ_UserUpdatedFields = array(); - } - } -} - -?> \ No newline at end of file + $Count) + { + $HPQ_PlanetUpdatedFields[] = $_Vars_GameElements[$KeyID]; + } + } + + if($ForMultiUpdate === true) + { + if($NeedPlanetUpdate === true) + { + return true; + } + } + else + { + if(!empty($HPQ_PlanetUpdatedFields)) + { + $HPQ_PlanetUpdatedFields = array_unique($HPQ_PlanetUpdatedFields); + foreach($HPQ_PlanetUpdatedFields as $Value) + { + $Query_Update_Arr[] = "`{$Value}` = '{$ThePlanet[$Value]}'"; + } + $Query_Update = "UPDATE {{table}} SET ".implode(', ', $Query_Update_Arr)." WHERE `id` = {$ThePlanet['id']} LIMIT 1;"; + doquery($Query_Update, 'planets'); + $HPQ_PlanetUpdatedFields = array(); + } + if(!empty($HPQ_UserUpdatedFields)) + { + $HPQ_UserUpdatedFields = array_unique($HPQ_UserUpdatedFields); + $UpdateFields = array(); + foreach($HPQ_UserUpdatedFields as $Value) + { + $UpdateFields[] = "`{$Value}` = '{$TheUser[$Value]}'"; + } + $Query_Update = "UPDATE {{table}} SET ".implode(', ', $UpdateFields)." WHERE `id` = {$TheUser['id']};"; + doquery($Query_Update, 'users'); + $HPQ_UserUpdatedFields = array(); + } + } +} + +?> diff --git a/includes/functions/HandlePlanetUpdate_MultiUpdate.php b/includes/functions/HandlePlanetUpdate_MultiUpdate.php index bbb714a1d..a758567d9 100644 --- a/includes/functions/HandlePlanetUpdate_MultiUpdate.php +++ b/includes/functions/HandlePlanetUpdate_MultiUpdate.php @@ -1,114 +1,114 @@ - \ No newline at end of file + diff --git a/includes/functions/HandleShipyardQueue.php b/includes/functions/HandleShipyardQueue.php index 21a140ea7..c4bfaf947 100644 --- a/includes/functions/HandleShipyardQueue.php +++ b/includes/functions/HandleShipyardQueue.php @@ -1,164 +1,164 @@ -= 0) - { - $AllBuilded = $Count; - } - else - { - $AllBuilded = 0; - } - } - if($AllBuilded > $Count) - { - $AllBuilded = $Count; - } - elseif($AllBuilded < 0) - { - $AllBuilded = 0; - } - $AllBuildedTime = $AllBuilded * $BuildTime; - $LeftToBuild = $Count - $AllBuilded; - if($AllBuilded > 0) - { - $ThePlanet['shipyardQueue_additionalWorkTime'] -= $AllBuildedTime; - $WorkTime -= $AllBuildedTime; - if(!isset($Builded[$ElementID])) - { - $Builded[$ElementID] = 0; - } - $Builded[$ElementID] += $AllBuilded; - $ThePlanet[$_Vars_GameElements[$ElementID]] += $AllBuilded; - if($LeftToBuild == 0) - { - continue; - } - else - { - $ThePlanet['shipyardQueue'] .= "{$ElementID},{$LeftToBuild};"; - $WorkTime = -1; - continue; - } - } - else - { - $ThePlanet['shipyardQueue'] .= "{$ElementID},{$LeftToBuild};"; - $WorkTime = -1; - } - } - - if(!empty($Builded)) - { - global $UserDev_Log, $UserTasksUpdate, $_Vars_TasksData; - $Temp = Array2String($Builded); - $UserDev_Log[] = array('UserID' => $TheUser['id'], 'PlanetID' => $ThePlanet['id'], 'Date' => $EndTime, 'Place' => 8, 'Code' => '1', 'ElementID' => '0', 'AdditionalData' => $Temp); - foreach($Builded as $Key => $Value) - { - $BuildedIDs[] = $Key; - } - - // Trigger Tasks Check - if(empty($TheUser['tasks_done_parsed'])) - { - global $GlobalParsedTasks; - Tasks_CheckUservar($TheUser); - $GlobalParsedTasks[$TheUser['id']]['tasks_done_parsed'] = $TheUser['tasks_done_parsed']; - } - Tasks_TriggerTask($TheUser, 'CONSTRUCT_SHIPS_OR_DEFENSE', array - ( - 'preCheck' => function($JobArray) use ($BuildedIDs) - { - return !in_array($JobArray['elementID'], $BuildedIDs); - }, - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($TheUser, $Builded) - { - global $UserTasksUpdate; - if(isset($UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID]) && !empty($UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID])) - { - $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID]; - } - - if(!isset($TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID])) - { - $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = 0; - } - $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] += $Builded[$JobArray['elementID']]; - if($TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] < $JobArray['count']) - { - $UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; - return true; - } - } - )); - foreach($Builded as $ThisID => $ThisCount) - { - Tasks_TriggerTask($TheUser, 'CONSTRUCT_SHIPS_OR_DEFENSE_MULTIID', array - ( - 'preCheck' => function($JobArray) use ($ThisID) - { - return !in_array($ThisID, $JobArray['elementIDs']); - }, - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($TheUser, $ThisCount) - { - global $UserTasksUpdate; - if(!empty($UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID])) - { - $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID]; - } - if(!isset($TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID])) - { - $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = 0; - } - $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] += $ThisCount; - if($TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] < $JobArray['count']) - { - $UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; - return true; - } - } - )); - } - } - } - else - { - $ThePlanet['shipyardQueue_additionalWorkTime'] = 0; - } - - return $Builded; -} - -?> \ No newline at end of file += 0) + { + $AllBuilded = $Count; + } + else + { + $AllBuilded = 0; + } + } + if($AllBuilded > $Count) + { + $AllBuilded = $Count; + } + elseif($AllBuilded < 0) + { + $AllBuilded = 0; + } + $AllBuildedTime = $AllBuilded * $BuildTime; + $LeftToBuild = $Count - $AllBuilded; + if($AllBuilded > 0) + { + $ThePlanet['shipyardQueue_additionalWorkTime'] -= $AllBuildedTime; + $WorkTime -= $AllBuildedTime; + if(!isset($Builded[$ElementID])) + { + $Builded[$ElementID] = 0; + } + $Builded[$ElementID] += $AllBuilded; + $ThePlanet[$_Vars_GameElements[$ElementID]] += $AllBuilded; + if($LeftToBuild == 0) + { + continue; + } + else + { + $ThePlanet['shipyardQueue'] .= "{$ElementID},{$LeftToBuild};"; + $WorkTime = -1; + continue; + } + } + else + { + $ThePlanet['shipyardQueue'] .= "{$ElementID},{$LeftToBuild};"; + $WorkTime = -1; + } + } + + if(!empty($Builded)) + { + global $UserDev_Log, $UserTasksUpdate, $_Vars_TasksData; + $Temp = Array2String($Builded); + $UserDev_Log[] = array('UserID' => $TheUser['id'], 'PlanetID' => $ThePlanet['id'], 'Date' => $EndTime, 'Place' => 8, 'Code' => '1', 'ElementID' => '0', 'AdditionalData' => $Temp); + foreach($Builded as $Key => $Value) + { + $BuildedIDs[] = $Key; + } + + // Trigger Tasks Check + if(empty($TheUser['tasks_done_parsed'])) + { + global $GlobalParsedTasks; + Tasks_CheckUservar($TheUser); + $GlobalParsedTasks[$TheUser['id']]['tasks_done_parsed'] = $TheUser['tasks_done_parsed']; + } + Tasks_TriggerTask($TheUser, 'CONSTRUCT_SHIPS_OR_DEFENSE', array + ( + 'preCheck' => function($JobArray) use ($BuildedIDs) + { + return !in_array($JobArray['elementID'], $BuildedIDs); + }, + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($TheUser, $Builded) + { + global $UserTasksUpdate; + if(isset($UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID]) && !empty($UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID])) + { + $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID]; + } + + if(!isset($TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID])) + { + $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = 0; + } + $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] += $Builded[$JobArray['elementID']]; + if($TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] < $JobArray['count']) + { + $UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; + return true; + } + } + )); + foreach($Builded as $ThisID => $ThisCount) + { + Tasks_TriggerTask($TheUser, 'CONSTRUCT_SHIPS_OR_DEFENSE_MULTIID', array + ( + 'preCheck' => function($JobArray) use ($ThisID) + { + return !in_array($ThisID, $JobArray['elementIDs']); + }, + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($TheUser, $ThisCount) + { + global $UserTasksUpdate; + if(!empty($UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID])) + { + $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID]; + } + if(!isset($TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID])) + { + $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = 0; + } + $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] += $ThisCount; + if($TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] < $JobArray['count']) + { + $UserTasksUpdate[$TheUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $TheUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; + return true; + } + } + )); + } + } + } + else + { + $ThePlanet['shipyardQueue_additionalWorkTime'] = 0; + } + + return $Builded; +} + +?> diff --git a/includes/functions/IPandUA_Logger.php b/includes/functions/IPandUA_Logger.php index 53f6ddab4..4ab043571 100644 --- a/includes/functions/IPandUA_Logger.php +++ b/includes/functions/IPandUA_Logger.php @@ -1,86 +1,86 @@ - 0) - { - if($Failed === true) - { - $Query_InsertLog_Array[] = "`FailCount` = `FailCount` + 1"; - } - $Query_InsertLog = ''; - $Query_InsertLog .= "UPDATE {{table}} SET "; - $Query_InsertLog_Array[] = "`Times` = CONCAT(`Times`, ',{$TextServerStamp}')"; - $Query_InsertLog_Array[] = "`Count` = `Count` + 1"; - $Query_InsertLog_Array[] = "`LastTime` = {$ServerStamp}"; - $Query_InsertLog .= implode(', ', $Query_InsertLog_Array); - $Query_InsertLog .= " WHERE `ID` = {$SelectEnterLog['ID']};"; - } - else - { - if($Failed === true) - { - $Query_InsertLog_Array[] = "`FailCount` = 1"; - } - $Query_InsertLog = ''; - $Query_InsertLog .= "INSERT INTO {{table}} SET "; - $Query_InsertLog_Array[] = "`User_ID` = {$TheUser['id']}"; - $Query_InsertLog_Array[] = "`IP_ID` = {$UsedIP_ID}"; - $Query_InsertLog_Array[] = "`UA_ID` = {$UsedUA_ID}"; - $Query_InsertLog_Array[] = "`Times` = '{$TextServerStamp}'"; - $Query_InsertLog_Array[] = "`Count` = `Count`"; - $Query_InsertLog_Array[] = "`LastTime` = {$ServerStamp}"; - $Query_InsertLog .= implode(', ', $Query_InsertLog_Array); - $Query_InsertLog .= ';'; - } - doquery($Query_InsertLog, 'user_enterlog'); -} - -?> \ No newline at end of file + 0) + { + if($Failed === true) + { + $Query_InsertLog_Array[] = "`FailCount` = `FailCount` + 1"; + } + $Query_InsertLog = ''; + $Query_InsertLog .= "UPDATE {{table}} SET "; + $Query_InsertLog_Array[] = "`Times` = CONCAT(`Times`, ',{$TextServerStamp}')"; + $Query_InsertLog_Array[] = "`Count` = `Count` + 1"; + $Query_InsertLog_Array[] = "`LastTime` = {$ServerStamp}"; + $Query_InsertLog .= implode(', ', $Query_InsertLog_Array); + $Query_InsertLog .= " WHERE `ID` = {$SelectEnterLog['ID']};"; + } + else + { + if($Failed === true) + { + $Query_InsertLog_Array[] = "`FailCount` = 1"; + } + $Query_InsertLog = ''; + $Query_InsertLog .= "INSERT INTO {{table}} SET "; + $Query_InsertLog_Array[] = "`User_ID` = {$TheUser['id']}"; + $Query_InsertLog_Array[] = "`IP_ID` = {$UsedIP_ID}"; + $Query_InsertLog_Array[] = "`UA_ID` = {$UsedUA_ID}"; + $Query_InsertLog_Array[] = "`Times` = '{$TextServerStamp}'"; + $Query_InsertLog_Array[] = "`Count` = `Count`"; + $Query_InsertLog_Array[] = "`LastTime` = {$ServerStamp}"; + $Query_InsertLog .= implode(', ', $Query_InsertLog_Array); + $Query_InsertLog .= ';'; + } + doquery($Query_InsertLog, 'user_enterlog'); +} + +?> diff --git a/includes/functions/InsertBuildListScript.php b/includes/functions/InsertBuildListScript.php index 3c9f41da0..fcea31775 100644 --- a/includes/functions/InsertBuildListScript.php +++ b/includes/functions/InsertBuildListScript.php @@ -1,58 +1,58 @@ -\n"; - $BuildListScript .= "\n"; - $BuildListScript .= "\n"; - - return $BuildListScript; -} - -?> \ No newline at end of file +\n"; + $BuildListScript .= "\n"; + $BuildListScript .= "\n"; + + return $BuildListScript; +} + +?> diff --git a/includes/functions/InsertGalaxyScripts.php b/includes/functions/InsertGalaxyScripts.php index d7ec091db..042bdbe78 100644 --- a/includes/functions/InsertGalaxyScripts.php +++ b/includes/functions/InsertGalaxyScripts.php @@ -1,19 +1,19 @@ - $Value) - { - if(strstr($Key, 'ajax_send_') !== false) - { - $Code = str_replace('ajax_send_', '', $Key); - $Lang['Insert_ReponseCodes'] .= "RespCodes['{$Code}'] = '{$Value}';\n"; - } - } - - return parsetemplate($TPL, $Lang); -} - -?> \ No newline at end of file + $Value) + { + if(strstr($Key, 'ajax_send_') !== false) + { + $Code = str_replace('ajax_send_', '', $Key); + $Lang['Insert_ReponseCodes'] .= "RespCodes['{$Code}'] = '{$Value}';\n"; + } + } + + return parsetemplate($TPL, $Lang); +} + +?> diff --git a/includes/functions/InsertJavaScriptChronoApplet.php b/includes/functions/InsertJavaScriptChronoApplet.php index 009babbfe..9c12d1275 100644 --- a/includes/functions/InsertJavaScriptChronoApplet.php +++ b/includes/functions/InsertJavaScriptChronoApplet.php @@ -1,51 +1,51 @@ - $_EnginePath, 'ServerTimestamp' => time(), 'Lang_day1' => $_Lang['Chrono_Day1'], 'Lang_dayM' => $_Lang['Chrono_DayM']))); - $TPL_Instance = gettemplate('_JSTimer_instance'); - $Created = true; - if($Type === false) - { - return true; - } - } - - $ReverseChrono = ''; - $InsertCallback = ''; - - if($FixedTime) - { - $InsertTime = $Value; - } - else - { - $InsertTime = time() + $Value; - } - if($Reverse !== false) - { - $ReverseChrono = ', true'; - } - - if($CallbackFunction !== false) - { - if($Reverse === false) - { - $ReverseChrono = ', false'; - } - $InsertCallback = ', '.$CallbackFunction; - } - - return parsetemplate($TPL_Instance, array - ( - 'Type' => $Type, 'Ref' => $Ref, 'InsertTime' => $InsertTime, 'ReverseChrono' => $ReverseChrono, 'InsertCallback' => $InsertCallback, - )); -} - -?> \ No newline at end of file + $_EnginePath, 'ServerTimestamp' => time(), 'Lang_day1' => $_Lang['Chrono_Day1'], 'Lang_dayM' => $_Lang['Chrono_DayM']))); + $TPL_Instance = gettemplate('_JSTimer_instance'); + $Created = true; + if($Type === false) + { + return true; + } + } + + $ReverseChrono = ''; + $InsertCallback = ''; + + if($FixedTime) + { + $InsertTime = $Value; + } + else + { + $InsertTime = time() + $Value; + } + if($Reverse !== false) + { + $ReverseChrono = ', true'; + } + + if($CallbackFunction !== false) + { + if($Reverse === false) + { + $ReverseChrono = ', false'; + } + $InsertCallback = ', '.$CallbackFunction; + } + + return parsetemplate($TPL_Instance, array + ( + 'Type' => $Type, 'Ref' => $Ref, 'InsertTime' => $InsertTime, 'ReverseChrono' => $ReverseChrono, 'InsertCallback' => $InsertCallback, + )); +} + +?> diff --git a/includes/functions/IsElementBuyable.php b/includes/functions/IsElementBuyable.php index 80492c7bf..65a3d011f 100644 --- a/includes/functions/IsElementBuyable.php +++ b/includes/functions/IsElementBuyable.php @@ -1,74 +1,74 @@ - 0) - { - if($Incremental) - { - $cost[$ResType] = floor($_Vars_Prices[$ElementID][$ResType] * pow($_Vars_Prices[$ElementID]['factor'], $level)); - } - else - { - $cost[$ResType] = floor($_Vars_Prices[$ElementID][$ResType]); - } - - if($ForDestroy) - { - $cost[$ResType] = floor($cost[$ResType] / 2); - } - - if($cost[$ResType] > $ThePlanet[$ResType]) - { - return false; - } - } - } - - if($GetPremiumData) - { - global $_Vars_PremiumBuildingPrices; - if(isset($_Vars_PremiumBuildingPrices[$ElementID]) && $_Vars_PremiumBuildingPrices[$ElementID] > $TheUser['darkEnergy']) - { - return false; - } - } - - return true; -} - -?> \ No newline at end of file + 0) + { + if($Incremental) + { + $cost[$ResType] = floor($_Vars_Prices[$ElementID][$ResType] * pow($_Vars_Prices[$ElementID]['factor'], $level)); + } + else + { + $cost[$ResType] = floor($_Vars_Prices[$ElementID][$ResType]); + } + + if($ForDestroy) + { + $cost[$ResType] = floor($cost[$ResType] / 2); + } + + if($cost[$ResType] > $ThePlanet[$ResType]) + { + return false; + } + } + } + + if($GetPremiumData) + { + global $_Vars_PremiumBuildingPrices; + if(isset($_Vars_PremiumBuildingPrices[$ElementID]) && $_Vars_PremiumBuildingPrices[$ElementID] > $TheUser['darkEnergy']) + { + return false; + } + } + + return true; +} + +?> diff --git a/includes/functions/IsTechnologieAccessible.php b/includes/functions/IsTechnologieAccessible.php index 12fdcb33c..89f5ec125 100644 --- a/includes/functions/IsTechnologieAccessible.php +++ b/includes/functions/IsTechnologieAccessible.php @@ -1,31 +1,31 @@ - $RequiredLevel) - { - if(in_array($RequiredElementID, $_Vars_ElementCategories['tech'])) - { - if(!($RequiredLevel == 0 || (isset($TheUser[$_Vars_GameElements[$RequiredElementID]]) && $TheUser[$_Vars_GameElements[$RequiredElementID]] >= $RequiredLevel))) - { - return false; - } - } - else - { - if(!($RequiredLevel == 0 || (isset($ThePlanet[$_Vars_GameElements[$RequiredElementID]]) && $ThePlanet[$_Vars_GameElements[$RequiredElementID]] >= $RequiredLevel))) - { - return false; - } - } - } - } - - return true; -} - -?> \ No newline at end of file + $RequiredLevel) + { + if(in_array($RequiredElementID, $_Vars_ElementCategories['tech'])) + { + if(!($RequiredLevel == 0 || (isset($TheUser[$_Vars_GameElements[$RequiredElementID]]) && $TheUser[$_Vars_GameElements[$RequiredElementID]] >= $RequiredLevel))) + { + return false; + } + } + else + { + if(!($RequiredLevel == 0 || (isset($ThePlanet[$_Vars_GameElements[$RequiredElementID]]) && $ThePlanet[$_Vars_GameElements[$RequiredElementID]] >= $RequiredLevel))) + { + return false; + } + } + } + } + + return true; +} + +?> diff --git a/includes/functions/LaboratoryPage.php b/includes/functions/LaboratoryPage.php index a26a5c3f9..867ac8b1f 100644 --- a/includes/functions/LaboratoryPage.php +++ b/includes/functions/LaboratoryPage.php @@ -1,620 +1,620 @@ - 'dPart')); - $TPL['list_disabled'] = parsetemplate($TPL['list_disabled'], array('AddOpacity' => '')); - $TPL['queue_topinfo'] = gettemplate('buildings_compact_queue_topinfo'); - $TPL['queue_planetlink'] = gettemplate('buildings_compact_queue_planetlink'); - $TPL['infobox_body'] = gettemplate('buildings_compact_infobox_body_lab'); - $TPL['infobox_levelmodif'] = gettemplate('buildings_compact_infobox_levelmodif'); - $TPL['infobox_req_res'] = gettemplate('buildings_compact_infobox_req_res'); - $TPL['infobox_req_desttable'] = gettemplate('buildings_compact_infobox_req_desttable'); - $TPL['infobox_req_destres'] = gettemplate('buildings_compact_infobox_req_destres'); - $TPL['infobox_additionalnfo'] = gettemplate('buildings_compact_infobox_additionalnfo'); - $TPL['infobox_req_selector_single'] = gettemplate('buildings_compact_infobox_req_selector_single'); - $TPL['infobox_req_selector_dual'] = gettemplate('buildings_compact_infobox_req_selector_dual'); - - if($CurrentPlanet[$_Vars_GameElements[31]] > 0) - { - $HasLab = true; - } - else - { - $HasLab = false; - } - - // Get OtherPlanets with Lab - $OtherLabs_ConnectedLabs = 0; - $OtherLabs_ConnectedLabsLevel = 0; - $OtherLabs_TotalLabsLevel = 0; - $OtherLabs_LabsCount = 0; - - $LabInQueue_CheckID = 0; - - $Query_GetOtherLabs = ''; - $Query_GetOtherLabs .= "SELECT `id`, `buildQueue`, `{$_Vars_GameElements[31]}` FROM {{table}} "; - $Query_GetOtherLabs .= "WHERE `id_owner` = {$CurrentUser['id']} AND `planet_type` = 1;"; - $Result_GetOtherLabs = doquery($Query_GetOtherLabs, 'planets'); - if(mysql_num_rows($Result_GetOtherLabs) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_GetOtherLabs)) - { - if(!empty($FetchData['buildQueue'])) - { - if(substr($FetchData['buildQueue'], 0, 3) == '31,' OR strstr($FetchData['buildQueue'], ';31,') !== false) - { - $LabInQueue_CheckID = $FetchData['id']; - } - } - if($FetchData[$_Vars_GameElements[31]] > 0) - { - $OtherLabs_Levels[] = $FetchData[$_Vars_GameElements[31]]; - } - } - if(!empty($OtherLabs_Levels)) - { - rsort($OtherLabs_Levels); - $OtherLabs_ConnectedLabsCount = 1 + $CurrentUser[$_Vars_GameElements[123]]; - foreach($OtherLabs_Levels as $ThisLabLevel) - { - if($OtherLabs_ConnectedLabs < $OtherLabs_ConnectedLabsCount) - { - $OtherLabs_ConnectedLabsLevel += $ThisLabLevel; - $OtherLabs_ConnectedLabs += 1; - } - $OtherLabs_TotalLabsLevel += $ThisLabLevel; - } - $OtherLabs_LabsCount = count($OtherLabs_Levels); - } - } - - // Check if Lab is in BuildQueue - $LabInQueue = false; - if($_GameConfig['BuildLabWhileRun'] != 1 AND $LabInQueue_CheckID > 0) - { - include($_EnginePath.'/includes/functions/CheckLabInQueue.php'); - - $LabInQueue_CheckPlanet = doquery("SELECT * FROM {{table}} WHERE `id` = {$LabInQueue_CheckID} LIMIT 1;", 'planets', true); - - $Results['planets'] = array(); - // Update Planet - Building Queue - $CheckLab = CheckLabInQueue($LabInQueue_CheckPlanet); - if($CheckLab !== false) - { - if($CheckLab <= $Now) - { - if(HandlePlanetQueue($LabInQueue_CheckPlanet, $CurrentUser, $Now, true) === true) - { - $Results['planets'][] = $LabInQueue_CheckPlanet; - } - } - else - { - $LabInQueueAt[] = parsetemplate($TPL['queue_planetlink'], array - ( - 'PlanetID' => $LabInQueue_CheckPlanet['id'], - 'PlanetName' => $LabInQueue_CheckPlanet['name'], - 'PlanetCoords' => "{$LabInQueue_CheckPlanet['galaxy']}:{$LabInQueue_CheckPlanet['system']}:{$LabInQueue_CheckPlanet['planet']}" - )); - $LabInQueue = true; - } - } - HandlePlanetUpdate_MultiUpdate($Results, $CurrentUser); - } - - PlanetResourceUpdate($CurrentUser, $CurrentPlanet, $Now); - - if(is_array($ThePlanet)) - { - $ResearchPlanet = &$ThePlanet; - } - else - { - $ResearchPlanet = &$CurrentPlanet; - } - - // Execute Commands - if(!isOnVacation($CurrentUser)) - { - if(isset($_GET['cmd'])) - { - if($LabInQueue === false) - { - $TheCommand = $_GET['cmd']; - $TechID = isset($_GET['tech']) ? intval($_GET['tech']) : 0; - $QueueElementID = (isset($_GET['el']) ? intval($_GET['el']) : 0); - - if((in_array($TechID, $_Vars_ElementCategories['tech']) AND $TheCommand == 'search') OR ($TheCommand == 'cancel' AND $QueueElementID >= 0)) - { - // Parse Commands - if($TheCommand == 'cancel') - { - // User requested cancel Action - include($_EnginePath.'includes/functions/TechQueue_Remove.php'); - $ShowElementID = TechQueue_Remove($ResearchPlanet, $CurrentUser, $QueueElementID, $Now); - if($ShowElementID !== false AND $CurrentUser['techQueue_Planet'] == '0') - { - $UpdateUser = &$CurrentUser; - } - else - { - $UpdateUser = false; - } - $CommandDone = true; - } - else if($TheCommand == 'search') - { - // User requested do the research - include($_EnginePath.'includes/functions/TechQueue_Add.php'); - TechQueue_Add($ResearchPlanet, $CurrentUser, $TechID); - $ShowElementID = $TechID; - $CommandDone = true; - } - - if($CommandDone === true) - { - if(HandlePlanetQueue_TechnologySetNext($ResearchPlanet, $CurrentUser, $Now, true) === false) - { - include($_EnginePath.'includes/functions/PostResearchSaveChanges.php'); - PostResearchSaveChanges($ResearchPlanet, ($ResearchPlanet['id'] == $CurrentPlanet['id'] ? true : false), isset($UpdateUser) ? $UpdateUser : false); - } - } - } - } - } - } - - if($InResearch === true && $ResearchPlanet['id'] != $CurrentPlanet['id']) - { - $ResearchInThisLab = false; - } - else - { - $ResearchInThisLab = true; - } - // End of - Execute Commands - - // Parse Queue - $CurrentQueue = (isset($ResearchPlanet['techQueue']) ? $ResearchPlanet['techQueue'] : false); - if(!empty($CurrentQueue)) - { - $LockResources['metal'] = 0; - $LockResources['crystal'] = 0; - $LockResources['deuterium'] = 0; - - $CurrentQueue = explode(';', $CurrentQueue); - $QueueIndex = 0; - foreach($CurrentQueue as $QueueID => $QueueData) - { - $QueueData = explode(',', $QueueData); - $BuildEndTime = $QueueData[3]; - if($BuildEndTime >= $Now) - { - $ListID = $QueueIndex; - $ElementID = $QueueData[0]; - $ElementLevel = $QueueData[1]; - $ElementBuildtime = $BuildEndTime - $Now; - $ElementName = $_Lang['tech'][$ElementID]; - if($QueueIndex == 0) - { - include($_EnginePath.'/includes/functions/InsertJavaScriptChronoApplet.php'); - - $QueueParser[] = array - ( - 'ChronoAppletScript' => InsertJavaScriptChronoApplet('QueueFirstTimer', '', $BuildEndTime, true, false, 'function() { $(\"#QueueCancel\").html(\"'.$_Lang['Queue_Cancel_Go'].'\").attr(\"href\", \"buildings.php?mode=research\").removeClass(\"cancelQueue\").addClass(\"lime\"); SetTimer = \"'.$_Lang['completed'].'\"; window.setTimeout(\'document.location.href=\"buildings.php?mode=research\";\', 1000); }'), - 'EndTimer' => pretty_time($ElementBuildtime, true), - 'SkinPath' => $_SkinPath, - 'ElementID' => $ElementID, - 'Name' => $ElementName, - 'LevelText' => $_Lang['level'], - 'Level' => $ElementLevel, - 'PlanetID' => $ResearchPlanet['id'], - 'PlanetImg' => $ResearchPlanet['image'], - 'Queue_ResearchOn' => $_Lang['Queue_ResearchOn'], - 'PlanetLabColor' => ($ResearchInThisLab ? 'lime' : 'orange'), - 'PlanetName' => $ResearchPlanet['name'], - 'PlanetCoords' => "{$ResearchPlanet['galaxy']}:{$ResearchPlanet['system']}:{$ResearchPlanet['planet']}", - 'EndText' => $_Lang['Queue_EndTime'], - 'EndDate' => date('d/m | H:i:s', $BuildEndTime), - 'EndTitleBeg' => $_Lang['Queue_EndTitleBeg'], - 'EndTitleHour' => $_Lang['Queue_EndTitleHour'], - 'EndDateExpand' => prettyDate('d m Y', $BuildEndTime, 1), - 'EndTimeExpand' => date('H:i:s', $BuildEndTime), - 'PremBlock' => (isset($_Vars_PremiumBuildings[$ElementID]) && $_Vars_PremiumBuildings[$ElementID] == 1 ? 'premblock' : ''), - 'CancelText' => (isset($_Vars_PremiumBuildings[$ElementID]) && $_Vars_PremiumBuildings[$ElementID] == 1 ? $_Lang['Queue_Cancel_CantCancel'] : $_Lang['Queue_Cancel_Research']) - ); - } - else - { - $QueueParser[] = array - ( - 'ElementNo' => $ListID + 1, - 'ElementID' => $ElementID, - 'Name' => $ElementName, - 'LevelText' => $_Lang['level'], - 'Level' => $ElementLevel, - 'EndDate' => date('d/m H:i:s', $BuildEndTime), - 'EndTitleBeg' => $_Lang['Queue_EndTitleBeg'], - 'EndTitleHour' => $_Lang['Queue_EndTitleHour'], - 'EndDateExpand' => prettyDate('d m Y', $BuildEndTime, 1), - 'EndTimeExpand' => date('H:i:s', $BuildEndTime), - 'InfoBox_BuildTime' => $_Lang['InfoBox_ResearchTime'], - 'BuildTime' => pretty_time($BuildEndTime - $PreviousBuildEndTime), - 'ListID' => $ListID, - 'RemoveText' => $_Lang['Queue_Cancel_Remove'] - ); - - $GetResourcesToLock = GetBuildingPrice($CurrentUser, $CurrentPlanet, $ElementID, true, false); - $LockResources['metal'] += $GetResourcesToLock['metal']; - $LockResources['crystal'] += $GetResourcesToLock['crystal']; - $LockResources['deuterium'] += $GetResourcesToLock['deuterium']; - } - - if(!isset($LevelModifiers[$ElementID])) - { - $LevelModifiers[$ElementID] = 0; - } - $LevelModifiers[$ElementID] -= 1; - $CurrentUser[$_Vars_GameElements[$ElementID]] += 1; - - $QueueIndex += 1; - } - $PreviousBuildEndTime = $BuildEndTime; - } - $CurrentPlanet['metal'] -= (isset($LockResources['metal']) ? $LockResources['metal'] : 0); - $CurrentPlanet['crystal'] -= (isset($LockResources['crystal']) ? $LockResources['crystal'] : 0); - $CurrentPlanet['deuterium'] -= (isset($LockResources['deuterium']) ? $LockResources['deuterium'] : 0); - - $Queue['lenght'] = $QueueIndex; - if(!empty($QueueParser)) - { - foreach($QueueParser as $QueueID => $QueueData) - { - if($QueueID == 0) - { - $ThisTPL = gettemplate('buildings_compact_queue_firstel_lab'); - } - else if($QueueID == 1) - { - $ThisTPL = gettemplate('buildings_compact_queue_nextel_lab'); - } - $Parse['Create_Queue'] .= parsetemplate($ThisTPL, $QueueData); - } - } - } - else - { - $Queue['lenght'] = 0; - $Parse['Create_Queue'] = parsetemplate($TPL['queue_topinfo'], array('InfoText' => $_Lang['Queue_Empty'])); - } - if($LabInQueue === false) - { - if($Queue['lenght'] < ((isPro($CurrentUser)) ? MAX_TECH_QUEUE_LENGTH_PRO : MAX_TECH_QUEUE_LENGTH)) - { - $CanAddToQueue = true; - } - else - { - $CanAddToQueue = false; - $Parse['Create_Queue'] = parsetemplate($TPL['queue_topinfo'], array('InfoColor' => 'red', 'InfoText' => $_Lang['Queue_Full'])).$Parse['Create_Queue']; - } - } - else - { - $CanAddToQueue = false; - $Parse['Create_Queue'] = parsetemplate($TPL['queue_topinfo'], array('InfoColor' => 'red', 'InfoText' => sprintf($_Lang['Queue_LabInQueue'], implode('
    ', $LabInQueueAt)))); - } - // End of - Parse Queue - - $ResImages = array - ( - 'metal' => 'metall', - 'crystal' => 'kristall', - 'deuterium' => 'deuterium', - 'energy_max' => 'energie', - 'darkEnergy' => 'darkenergy' - ); - $ResLangs = array - ( - 'metal' => $_Lang['Metal'], - 'crystal' => $_Lang['Crystal'], - 'deuterium' => $_Lang['Deuterium'], - 'energy_max' => $_Lang['Energy'], - 'darkEnergy' => $_Lang['DarkEnergy'] - ); - - $ElementParserDefault = array - ( - 'SkinPath' => $_SkinPath, - 'InfoBox_Level' => $_Lang['InfoBox_Level'], - 'InfoBox_Build' => $_Lang['InfoBox_DoResearch'], - 'InfoBox_RequirementsFor' => $_Lang['InfoBox_RequirementsFor'], - 'InfoBox_ResRequirements' => $_Lang['InfoBox_ResRequirements'], - 'InfoBox_TechRequirements' => $_Lang['InfoBox_TechRequirements'], - 'InfoBox_Requirements_Res' => $_Lang['InfoBox_Requirements_Res'], - 'InfoBox_Requirements_Tech' => $_Lang['InfoBox_Requirements_Tech'], - 'InfoBox_BuildTime' => $_Lang['InfoBox_ResearchTime'], - 'InfoBox_ShowTechReq' => $_Lang['InfoBox_ShowTechReq'], - 'InfoBox_ShowResReq' => $_Lang['InfoBox_ShowResReq'], - 'ElementPriceDiv' => '' - ); - - foreach($_Vars_ElementCategories['tech'] as $ElementID) - { - $ElementParser = $ElementParserDefault; - - $CurrentLevel = $CurrentUser[$_Vars_GameElements[$ElementID]]; - $NextLevel = $CurrentUser[$_Vars_GameElements[$ElementID]] + 1; - $MaxLevelReached = false; - $TechLevelOK = false; - $HasResources = true; - - $HideButton_Build = false; - $HideButton_QuickBuild = false; - - $ElementParser['HideBuildWarn'] = 'hide'; - $ElementParser['ElementName'] = $_Lang['tech'][$ElementID]; - $ElementParser['ElementID'] = $ElementID; - $ElementParser['ElementLevel'] = prettyNumber($CurrentUser[$_Vars_GameElements[$ElementID]]); - $ElementParser['ElementRealLevel'] = prettyNumber($CurrentUser[$_Vars_GameElements[$ElementID]] + (isset($LevelModifiers[$ElementID]) ? $LevelModifiers[$ElementID] : 0)); - $ElementParser['BuildLevel'] = prettyNumber($CurrentUser[$_Vars_GameElements[$ElementID]] + 1); - $ElementParser['Desc'] = $_Lang['res']['descriptions'][$ElementID]; - $ElementParser['BuildButtonColor'] = 'buildDo_Green'; - - if(isset($LevelModifiers[$ElementID])) - { - $ElementParser['levelmodif']['modColor'] = 'lime'; - $ElementParser['levelmodif']['modText'] = '+'.prettyNumber($LevelModifiers[$ElementID] * (-1)); - $ElementParser['LevelModifier'] = parsetemplate($TPL['infobox_levelmodif'], $ElementParser['levelmodif']); - $ElementParser['ElementLevelModif'] = parsetemplate($TPL['list_levelmodif'], $ElementParser['levelmodif']); - unset($ElementParser['levelmodif']); - } - - if(!(isset($_Vars_MaxElementLevel[$ElementID]) && $_Vars_MaxElementLevel[$ElementID] > 0 && $NextLevel > $_Vars_MaxElementLevel[$ElementID])) - { - $ElementParser['ElementPrice'] = GetBuildingPrice($CurrentUser, $CurrentPlanet, $ElementID, true, false, true); - foreach($ElementParser['ElementPrice'] as $Key => $Value) - { - if($Value > 0) - { - $ResColor = ''; - $ResMinusColor = ''; - $MinusValue = ' '; - - if($Key != 'darkEnergy') - { - $UseVar = &$CurrentPlanet; - } - else - { - $UseVar = &$CurrentUser; - } - if($UseVar[$Key] < $Value) - { - $ResMinusColor = 'red'; - $MinusValue = '('.prettyNumber($UseVar[$Key] - $Value).')'; - if($Queue['lenght'] > 0) - { - $ResColor = 'orange'; - } - else - { - $ResColor = 'red'; - } - } - - $ElementParser['ElementPrices'] = array - ( - 'SkinPath' => $_SkinPath, - 'ResName' => $Key, - 'ResImg' => $ResImages[$Key], - 'ResColor' => $ResColor, - 'Value' => prettyNumber($Value), - 'ResMinusColor' => $ResMinusColor, - 'MinusValue' => $MinusValue - ); - $ElementParser['ElementPriceDiv'] .= parsetemplate($TPL['infobox_req_res'], $ElementParser['ElementPrices']); - } - } - $ElementParser['BuildTime'] = pretty_time(GetBuildingTime($CurrentUser, $CurrentPlanet, $ElementID)); - } - else - { - $MaxLevelReached = true; - $ElementParser['HideBuildInfo'] = 'hide'; - $ElementParser['HideBuildWarn'] = ''; - $HideButton_Build = true; - $ElementParser['BuildWarn_Color'] = 'red'; - $ElementParser['BuildWarn_Text'] = $_Lang['ListBox_Disallow_MaxLevelReached']; - } - if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $ElementID)) - { - $TechLevelOK = true; - $ElementParser['ElementRequirementsHeadline'] = $TPL['infobox_req_selector_single']; - } - else - { - $ElementParser['ElementRequirementsHeadline'] = $TPL['infobox_req_selector_dual']; - $ElementParser['ElementTechDiv'] = GetElementTechReq($CurrentUser, $CurrentPlanet, $ElementID, true); - $ElementParser['HideResReqDiv'] = 'hide'; - } - if(IsElementBuyable($CurrentUser, $CurrentPlanet, $ElementID, true, false, true) === false) - { - $HasResources = false; - if($Queue['lenght'] == 0) - { - $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; - $HideButton_QuickBuild = true; - } - else - { - $ElementParser['BuildButtonColor'] = 'buildDo_Orange'; - } - } - - $BlockReason = array(); - - if($MaxLevelReached) - { - $BlockReason[] = $_Lang['ListBox_Disallow_MaxLevelReached']; - } - else if(!$HasResources) - { - $BlockReason[] = $_Lang['ListBox_Disallow_NoResources']; - } - if(!$TechLevelOK) - { - $BlockReason[] = $_Lang['ListBox_Disallow_NoTech']; - $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; - $HideButton_QuickBuild = true; - } - if($CanAddToQueue === false) - { - $BlockReason[] = $_Lang['ListBox_Disallow_QueueIsFull']; - $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; - $HideButton_QuickBuild = true; - } - if($HasLab === false) - { - $BlockReason[] = $_Lang['ListBox_Disallow_NoLab']; - $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; - $HideButton_QuickBuild = true; - } - if($ResearchInThisLab === false) - { - $BlockReason[] = $_Lang['ListBox_Disallow_NotThisLab']; - $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; - $HideButton_QuickBuild = true; - } - if($LabInQueue === true) - { - $BlockReason[] = $_Lang['ListBox_Disallow_LabInQueue']; - $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; - $HideButton_QuickBuild = true; - } - if(isOnVacation($CurrentUser)) - { - $BlockReason[] = $_Lang['ListBox_Disallow_VacationMode']; - $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; - $HideButton_QuickBuild = true; - } - - if(!empty($BlockReason)) - { - if($ElementParser['BuildButtonColor'] == 'buildDo_Orange') - { - $ElementParser['ElementDisabled'] = $TPL['list_partdisabled']; - } - else - { - $ElementParser['ElementDisabled'] = $TPL['list_disabled']; - } - $ElementParser['ElementDisableReason'] = end($BlockReason); - } - - if($HideButton_Build) - { - $ElementParser['HideBuildButton'] = 'hide'; - } - if($HideButton_Build OR $HideButton_QuickBuild) - { - $ElementParser['HideQuickBuildButton'] = 'hide'; - } - - if(!empty($ElementParser['AdditionalNfo'])) - { - $ElementParser['AdditionalNfo'] = implode('', $ElementParser['AdditionalNfo']); - } - $ElementParser['ElementRequirementsHeadline'] = parsetemplate($ElementParser['ElementRequirementsHeadline'], $ElementParser); - $StructuresList[] = parsetemplate($TPL['list_element'], $ElementParser); - $InfoBoxes[] = parsetemplate($TPL['infobox_body'], $ElementParser); - } - - if(!empty($LevelModifiers)) - { - foreach($LevelModifiers as $ElementID => $Modifier) - { - $CurrentUser[$_Vars_GameElements[$ElementID]] += $Modifier; - } - } - $CurrentPlanet['metal'] += (isset($LockResources['metal']) ? $LockResources['metal'] : 0); - $CurrentPlanet['crystal'] += (isset($LockResources['crystal']) ? $LockResources['crystal'] : 0); - $CurrentPlanet['deuterium'] += (isset($LockResources['deuterium']) ? $LockResources['deuterium'] : 0); - - // Create List - $ThisRowIndex = 0; - $InRowCount = 0; - foreach($StructuresList as $ParsedData) - { - if($InRowCount == $ElementsPerRow) - { - $ParsedRows[($ThisRowIndex + 1)] = $TPL['list_breakrow']; - $ThisRowIndex += 2; - $InRowCount = 0; - } - - if(!isset($StructureRows[$ThisRowIndex]['Elements'])) - { - $StructureRows[$ThisRowIndex]['Elements'] = ''; - } - $StructureRows[$ThisRowIndex]['Elements'] .= $ParsedData; - $InRowCount += 1; - } - if($InRowCount < $ElementsPerRow) - { - $StructureRows[$ThisRowIndex]['Elements'] .= str_repeat($TPL['list_hidden'], ($ElementsPerRow - $InRowCount)); - } - foreach($StructureRows as $Index => $Data) - { - $ParsedRows[$Index] = parsetemplate($TPL['list_row'], $Data); - } - ksort($ParsedRows, SORT_ASC); - $Parse['Create_StructuresList'] = implode('', $ParsedRows); - $Parse['Create_ElementsInfoBoxes'] = implode('', $InfoBoxes); - if($ShowElementID > 0) - { - $Parse['Create_ShowElementOnStartup'] = $ShowElementID; - } - // End of - Parse all available technologies - - $Parse['Insert_SkinPath'] = $_SkinPath; - $Parse['Insert_PlanetImg'] = $CurrentPlanet['image']; - $Parse['Insert_PlanetType'] = $_Lang['PlanetType_'.$CurrentPlanet['planet_type']]; - $Parse['Insert_PlanetName'] = $CurrentPlanet['name']; - $Parse['Insert_PlanetPos_Galaxy'] = $CurrentPlanet['galaxy']; - $Parse['Insert_PlanetPos_System'] = $CurrentPlanet['system']; - $Parse['Insert_PlanetPos_Planet'] = $CurrentPlanet['planet']; - $Parse['Insert_Overview_LabLevel'] = $CurrentPlanet[$_Vars_GameElements[31]]; - $Parse['Insert_Overview_LabsConnected'] = prettyNumber($OtherLabs_ConnectedLabs); - $Parse['Insert_Overview_TotalLabsCount'] = prettyNumber($OtherLabs_LabsCount); - $Parse['Insert_Overview_LabPower'] = prettyNumber($OtherLabs_ConnectedLabsLevel); - $Parse['Insert_Overview_LabPowerTotal'] = prettyNumber($OtherLabs_TotalLabsLevel); - - $Page = parsetemplate(gettemplate('buildings_compact_body_lab'), $Parse); - - display($Page, $_Lang['Research']); -} - -?> \ No newline at end of file + 'dPart')); + $TPL['list_disabled'] = parsetemplate($TPL['list_disabled'], array('AddOpacity' => '')); + $TPL['queue_topinfo'] = gettemplate('buildings_compact_queue_topinfo'); + $TPL['queue_planetlink'] = gettemplate('buildings_compact_queue_planetlink'); + $TPL['infobox_body'] = gettemplate('buildings_compact_infobox_body_lab'); + $TPL['infobox_levelmodif'] = gettemplate('buildings_compact_infobox_levelmodif'); + $TPL['infobox_req_res'] = gettemplate('buildings_compact_infobox_req_res'); + $TPL['infobox_req_desttable'] = gettemplate('buildings_compact_infobox_req_desttable'); + $TPL['infobox_req_destres'] = gettemplate('buildings_compact_infobox_req_destres'); + $TPL['infobox_additionalnfo'] = gettemplate('buildings_compact_infobox_additionalnfo'); + $TPL['infobox_req_selector_single'] = gettemplate('buildings_compact_infobox_req_selector_single'); + $TPL['infobox_req_selector_dual'] = gettemplate('buildings_compact_infobox_req_selector_dual'); + + if($CurrentPlanet[$_Vars_GameElements[31]] > 0) + { + $HasLab = true; + } + else + { + $HasLab = false; + } + + // Get OtherPlanets with Lab + $OtherLabs_ConnectedLabs = 0; + $OtherLabs_ConnectedLabsLevel = 0; + $OtherLabs_TotalLabsLevel = 0; + $OtherLabs_LabsCount = 0; + + $LabInQueue_CheckID = 0; + + $Query_GetOtherLabs = ''; + $Query_GetOtherLabs .= "SELECT `id`, `buildQueue`, `{$_Vars_GameElements[31]}` FROM {{table}} "; + $Query_GetOtherLabs .= "WHERE `id_owner` = {$CurrentUser['id']} AND `planet_type` = 1;"; + $Result_GetOtherLabs = doquery($Query_GetOtherLabs, 'planets'); + if(mysql_num_rows($Result_GetOtherLabs) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_GetOtherLabs)) + { + if(!empty($FetchData['buildQueue'])) + { + if(substr($FetchData['buildQueue'], 0, 3) == '31,' OR strstr($FetchData['buildQueue'], ';31,') !== false) + { + $LabInQueue_CheckID = $FetchData['id']; + } + } + if($FetchData[$_Vars_GameElements[31]] > 0) + { + $OtherLabs_Levels[] = $FetchData[$_Vars_GameElements[31]]; + } + } + if(!empty($OtherLabs_Levels)) + { + rsort($OtherLabs_Levels); + $OtherLabs_ConnectedLabsCount = 1 + $CurrentUser[$_Vars_GameElements[123]]; + foreach($OtherLabs_Levels as $ThisLabLevel) + { + if($OtherLabs_ConnectedLabs < $OtherLabs_ConnectedLabsCount) + { + $OtherLabs_ConnectedLabsLevel += $ThisLabLevel; + $OtherLabs_ConnectedLabs += 1; + } + $OtherLabs_TotalLabsLevel += $ThisLabLevel; + } + $OtherLabs_LabsCount = count($OtherLabs_Levels); + } + } + + // Check if Lab is in BuildQueue + $LabInQueue = false; + if($_GameConfig['BuildLabWhileRun'] != 1 AND $LabInQueue_CheckID > 0) + { + include($_EnginePath.'/includes/functions/CheckLabInQueue.php'); + + $LabInQueue_CheckPlanet = doquery("SELECT * FROM {{table}} WHERE `id` = {$LabInQueue_CheckID} LIMIT 1;", 'planets', true); + + $Results['planets'] = array(); + // Update Planet - Building Queue + $CheckLab = CheckLabInQueue($LabInQueue_CheckPlanet); + if($CheckLab !== false) + { + if($CheckLab <= $Now) + { + if(HandlePlanetQueue($LabInQueue_CheckPlanet, $CurrentUser, $Now, true) === true) + { + $Results['planets'][] = $LabInQueue_CheckPlanet; + } + } + else + { + $LabInQueueAt[] = parsetemplate($TPL['queue_planetlink'], array + ( + 'PlanetID' => $LabInQueue_CheckPlanet['id'], + 'PlanetName' => $LabInQueue_CheckPlanet['name'], + 'PlanetCoords' => "{$LabInQueue_CheckPlanet['galaxy']}:{$LabInQueue_CheckPlanet['system']}:{$LabInQueue_CheckPlanet['planet']}" + )); + $LabInQueue = true; + } + } + HandlePlanetUpdate_MultiUpdate($Results, $CurrentUser); + } + + PlanetResourceUpdate($CurrentUser, $CurrentPlanet, $Now); + + if(is_array($ThePlanet)) + { + $ResearchPlanet = &$ThePlanet; + } + else + { + $ResearchPlanet = &$CurrentPlanet; + } + + // Execute Commands + if(!isOnVacation($CurrentUser)) + { + if(isset($_GET['cmd'])) + { + if($LabInQueue === false) + { + $TheCommand = $_GET['cmd']; + $TechID = isset($_GET['tech']) ? intval($_GET['tech']) : 0; + $QueueElementID = (isset($_GET['el']) ? intval($_GET['el']) : 0); + + if((in_array($TechID, $_Vars_ElementCategories['tech']) AND $TheCommand == 'search') OR ($TheCommand == 'cancel' AND $QueueElementID >= 0)) + { + // Parse Commands + if($TheCommand == 'cancel') + { + // User requested cancel Action + include($_EnginePath.'includes/functions/TechQueue_Remove.php'); + $ShowElementID = TechQueue_Remove($ResearchPlanet, $CurrentUser, $QueueElementID, $Now); + if($ShowElementID !== false AND $CurrentUser['techQueue_Planet'] == '0') + { + $UpdateUser = &$CurrentUser; + } + else + { + $UpdateUser = false; + } + $CommandDone = true; + } + else if($TheCommand == 'search') + { + // User requested do the research + include($_EnginePath.'includes/functions/TechQueue_Add.php'); + TechQueue_Add($ResearchPlanet, $CurrentUser, $TechID); + $ShowElementID = $TechID; + $CommandDone = true; + } + + if($CommandDone === true) + { + if(HandlePlanetQueue_TechnologySetNext($ResearchPlanet, $CurrentUser, $Now, true) === false) + { + include($_EnginePath.'includes/functions/PostResearchSaveChanges.php'); + PostResearchSaveChanges($ResearchPlanet, ($ResearchPlanet['id'] == $CurrentPlanet['id'] ? true : false), isset($UpdateUser) ? $UpdateUser : false); + } + } + } + } + } + } + + if($InResearch === true && $ResearchPlanet['id'] != $CurrentPlanet['id']) + { + $ResearchInThisLab = false; + } + else + { + $ResearchInThisLab = true; + } + // End of - Execute Commands + + // Parse Queue + $CurrentQueue = (isset($ResearchPlanet['techQueue']) ? $ResearchPlanet['techQueue'] : false); + if(!empty($CurrentQueue)) + { + $LockResources['metal'] = 0; + $LockResources['crystal'] = 0; + $LockResources['deuterium'] = 0; + + $CurrentQueue = explode(';', $CurrentQueue); + $QueueIndex = 0; + foreach($CurrentQueue as $QueueID => $QueueData) + { + $QueueData = explode(',', $QueueData); + $BuildEndTime = $QueueData[3]; + if($BuildEndTime >= $Now) + { + $ListID = $QueueIndex; + $ElementID = $QueueData[0]; + $ElementLevel = $QueueData[1]; + $ElementBuildtime = $BuildEndTime - $Now; + $ElementName = $_Lang['tech'][$ElementID]; + if($QueueIndex == 0) + { + include($_EnginePath.'/includes/functions/InsertJavaScriptChronoApplet.php'); + + $QueueParser[] = array + ( + 'ChronoAppletScript' => InsertJavaScriptChronoApplet('QueueFirstTimer', '', $BuildEndTime, true, false, 'function() { $(\"#QueueCancel\").html(\"'.$_Lang['Queue_Cancel_Go'].'\").attr(\"href\", \"buildings.php?mode=research\").removeClass(\"cancelQueue\").addClass(\"lime\"); SetTimer = \"'.$_Lang['completed'].'\"; window.setTimeout(\'document.location.href=\"buildings.php?mode=research\";\', 1000); }'), + 'EndTimer' => pretty_time($ElementBuildtime, true), + 'SkinPath' => $_SkinPath, + 'ElementID' => $ElementID, + 'Name' => $ElementName, + 'LevelText' => $_Lang['level'], + 'Level' => $ElementLevel, + 'PlanetID' => $ResearchPlanet['id'], + 'PlanetImg' => $ResearchPlanet['image'], + 'Queue_ResearchOn' => $_Lang['Queue_ResearchOn'], + 'PlanetLabColor' => ($ResearchInThisLab ? 'lime' : 'orange'), + 'PlanetName' => $ResearchPlanet['name'], + 'PlanetCoords' => "{$ResearchPlanet['galaxy']}:{$ResearchPlanet['system']}:{$ResearchPlanet['planet']}", + 'EndText' => $_Lang['Queue_EndTime'], + 'EndDate' => date('d/m | H:i:s', $BuildEndTime), + 'EndTitleBeg' => $_Lang['Queue_EndTitleBeg'], + 'EndTitleHour' => $_Lang['Queue_EndTitleHour'], + 'EndDateExpand' => prettyDate('d m Y', $BuildEndTime, 1), + 'EndTimeExpand' => date('H:i:s', $BuildEndTime), + 'PremBlock' => (isset($_Vars_PremiumBuildings[$ElementID]) && $_Vars_PremiumBuildings[$ElementID] == 1 ? 'premblock' : ''), + 'CancelText' => (isset($_Vars_PremiumBuildings[$ElementID]) && $_Vars_PremiumBuildings[$ElementID] == 1 ? $_Lang['Queue_Cancel_CantCancel'] : $_Lang['Queue_Cancel_Research']) + ); + } + else + { + $QueueParser[] = array + ( + 'ElementNo' => $ListID + 1, + 'ElementID' => $ElementID, + 'Name' => $ElementName, + 'LevelText' => $_Lang['level'], + 'Level' => $ElementLevel, + 'EndDate' => date('d/m H:i:s', $BuildEndTime), + 'EndTitleBeg' => $_Lang['Queue_EndTitleBeg'], + 'EndTitleHour' => $_Lang['Queue_EndTitleHour'], + 'EndDateExpand' => prettyDate('d m Y', $BuildEndTime, 1), + 'EndTimeExpand' => date('H:i:s', $BuildEndTime), + 'InfoBox_BuildTime' => $_Lang['InfoBox_ResearchTime'], + 'BuildTime' => pretty_time($BuildEndTime - $PreviousBuildEndTime), + 'ListID' => $ListID, + 'RemoveText' => $_Lang['Queue_Cancel_Remove'] + ); + + $GetResourcesToLock = GetBuildingPrice($CurrentUser, $CurrentPlanet, $ElementID, true, false); + $LockResources['metal'] += $GetResourcesToLock['metal']; + $LockResources['crystal'] += $GetResourcesToLock['crystal']; + $LockResources['deuterium'] += $GetResourcesToLock['deuterium']; + } + + if(!isset($LevelModifiers[$ElementID])) + { + $LevelModifiers[$ElementID] = 0; + } + $LevelModifiers[$ElementID] -= 1; + $CurrentUser[$_Vars_GameElements[$ElementID]] += 1; + + $QueueIndex += 1; + } + $PreviousBuildEndTime = $BuildEndTime; + } + $CurrentPlanet['metal'] -= (isset($LockResources['metal']) ? $LockResources['metal'] : 0); + $CurrentPlanet['crystal'] -= (isset($LockResources['crystal']) ? $LockResources['crystal'] : 0); + $CurrentPlanet['deuterium'] -= (isset($LockResources['deuterium']) ? $LockResources['deuterium'] : 0); + + $Queue['lenght'] = $QueueIndex; + if(!empty($QueueParser)) + { + foreach($QueueParser as $QueueID => $QueueData) + { + if($QueueID == 0) + { + $ThisTPL = gettemplate('buildings_compact_queue_firstel_lab'); + } + else if($QueueID == 1) + { + $ThisTPL = gettemplate('buildings_compact_queue_nextel_lab'); + } + $Parse['Create_Queue'] .= parsetemplate($ThisTPL, $QueueData); + } + } + } + else + { + $Queue['lenght'] = 0; + $Parse['Create_Queue'] = parsetemplate($TPL['queue_topinfo'], array('InfoText' => $_Lang['Queue_Empty'])); + } + if($LabInQueue === false) + { + if($Queue['lenght'] < ((isPro($CurrentUser)) ? MAX_TECH_QUEUE_LENGTH_PRO : MAX_TECH_QUEUE_LENGTH)) + { + $CanAddToQueue = true; + } + else + { + $CanAddToQueue = false; + $Parse['Create_Queue'] = parsetemplate($TPL['queue_topinfo'], array('InfoColor' => 'red', 'InfoText' => $_Lang['Queue_Full'])).$Parse['Create_Queue']; + } + } + else + { + $CanAddToQueue = false; + $Parse['Create_Queue'] = parsetemplate($TPL['queue_topinfo'], array('InfoColor' => 'red', 'InfoText' => sprintf($_Lang['Queue_LabInQueue'], implode('
    ', $LabInQueueAt)))); + } + // End of - Parse Queue + + $ResImages = array + ( + 'metal' => 'metall', + 'crystal' => 'kristall', + 'deuterium' => 'deuterium', + 'energy_max' => 'energie', + 'darkEnergy' => 'darkenergy' + ); + $ResLangs = array + ( + 'metal' => $_Lang['Metal'], + 'crystal' => $_Lang['Crystal'], + 'deuterium' => $_Lang['Deuterium'], + 'energy_max' => $_Lang['Energy'], + 'darkEnergy' => $_Lang['DarkEnergy'] + ); + + $ElementParserDefault = array + ( + 'SkinPath' => $_SkinPath, + 'InfoBox_Level' => $_Lang['InfoBox_Level'], + 'InfoBox_Build' => $_Lang['InfoBox_DoResearch'], + 'InfoBox_RequirementsFor' => $_Lang['InfoBox_RequirementsFor'], + 'InfoBox_ResRequirements' => $_Lang['InfoBox_ResRequirements'], + 'InfoBox_TechRequirements' => $_Lang['InfoBox_TechRequirements'], + 'InfoBox_Requirements_Res' => $_Lang['InfoBox_Requirements_Res'], + 'InfoBox_Requirements_Tech' => $_Lang['InfoBox_Requirements_Tech'], + 'InfoBox_BuildTime' => $_Lang['InfoBox_ResearchTime'], + 'InfoBox_ShowTechReq' => $_Lang['InfoBox_ShowTechReq'], + 'InfoBox_ShowResReq' => $_Lang['InfoBox_ShowResReq'], + 'ElementPriceDiv' => '' + ); + + foreach($_Vars_ElementCategories['tech'] as $ElementID) + { + $ElementParser = $ElementParserDefault; + + $CurrentLevel = $CurrentUser[$_Vars_GameElements[$ElementID]]; + $NextLevel = $CurrentUser[$_Vars_GameElements[$ElementID]] + 1; + $MaxLevelReached = false; + $TechLevelOK = false; + $HasResources = true; + + $HideButton_Build = false; + $HideButton_QuickBuild = false; + + $ElementParser['HideBuildWarn'] = 'hide'; + $ElementParser['ElementName'] = $_Lang['tech'][$ElementID]; + $ElementParser['ElementID'] = $ElementID; + $ElementParser['ElementLevel'] = prettyNumber($CurrentUser[$_Vars_GameElements[$ElementID]]); + $ElementParser['ElementRealLevel'] = prettyNumber($CurrentUser[$_Vars_GameElements[$ElementID]] + (isset($LevelModifiers[$ElementID]) ? $LevelModifiers[$ElementID] : 0)); + $ElementParser['BuildLevel'] = prettyNumber($CurrentUser[$_Vars_GameElements[$ElementID]] + 1); + $ElementParser['Desc'] = $_Lang['res']['descriptions'][$ElementID]; + $ElementParser['BuildButtonColor'] = 'buildDo_Green'; + + if(isset($LevelModifiers[$ElementID])) + { + $ElementParser['levelmodif']['modColor'] = 'lime'; + $ElementParser['levelmodif']['modText'] = '+'.prettyNumber($LevelModifiers[$ElementID] * (-1)); + $ElementParser['LevelModifier'] = parsetemplate($TPL['infobox_levelmodif'], $ElementParser['levelmodif']); + $ElementParser['ElementLevelModif'] = parsetemplate($TPL['list_levelmodif'], $ElementParser['levelmodif']); + unset($ElementParser['levelmodif']); + } + + if(!(isset($_Vars_MaxElementLevel[$ElementID]) && $_Vars_MaxElementLevel[$ElementID] > 0 && $NextLevel > $_Vars_MaxElementLevel[$ElementID])) + { + $ElementParser['ElementPrice'] = GetBuildingPrice($CurrentUser, $CurrentPlanet, $ElementID, true, false, true); + foreach($ElementParser['ElementPrice'] as $Key => $Value) + { + if($Value > 0) + { + $ResColor = ''; + $ResMinusColor = ''; + $MinusValue = ' '; + + if($Key != 'darkEnergy') + { + $UseVar = &$CurrentPlanet; + } + else + { + $UseVar = &$CurrentUser; + } + if($UseVar[$Key] < $Value) + { + $ResMinusColor = 'red'; + $MinusValue = '('.prettyNumber($UseVar[$Key] - $Value).')'; + if($Queue['lenght'] > 0) + { + $ResColor = 'orange'; + } + else + { + $ResColor = 'red'; + } + } + + $ElementParser['ElementPrices'] = array + ( + 'SkinPath' => $_SkinPath, + 'ResName' => $Key, + 'ResImg' => $ResImages[$Key], + 'ResColor' => $ResColor, + 'Value' => prettyNumber($Value), + 'ResMinusColor' => $ResMinusColor, + 'MinusValue' => $MinusValue + ); + $ElementParser['ElementPriceDiv'] .= parsetemplate($TPL['infobox_req_res'], $ElementParser['ElementPrices']); + } + } + $ElementParser['BuildTime'] = pretty_time(GetBuildingTime($CurrentUser, $CurrentPlanet, $ElementID)); + } + else + { + $MaxLevelReached = true; + $ElementParser['HideBuildInfo'] = 'hide'; + $ElementParser['HideBuildWarn'] = ''; + $HideButton_Build = true; + $ElementParser['BuildWarn_Color'] = 'red'; + $ElementParser['BuildWarn_Text'] = $_Lang['ListBox_Disallow_MaxLevelReached']; + } + if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $ElementID)) + { + $TechLevelOK = true; + $ElementParser['ElementRequirementsHeadline'] = $TPL['infobox_req_selector_single']; + } + else + { + $ElementParser['ElementRequirementsHeadline'] = $TPL['infobox_req_selector_dual']; + $ElementParser['ElementTechDiv'] = GetElementTechReq($CurrentUser, $CurrentPlanet, $ElementID, true); + $ElementParser['HideResReqDiv'] = 'hide'; + } + if(IsElementBuyable($CurrentUser, $CurrentPlanet, $ElementID, true, false, true) === false) + { + $HasResources = false; + if($Queue['lenght'] == 0) + { + $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; + $HideButton_QuickBuild = true; + } + else + { + $ElementParser['BuildButtonColor'] = 'buildDo_Orange'; + } + } + + $BlockReason = array(); + + if($MaxLevelReached) + { + $BlockReason[] = $_Lang['ListBox_Disallow_MaxLevelReached']; + } + else if(!$HasResources) + { + $BlockReason[] = $_Lang['ListBox_Disallow_NoResources']; + } + if(!$TechLevelOK) + { + $BlockReason[] = $_Lang['ListBox_Disallow_NoTech']; + $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; + $HideButton_QuickBuild = true; + } + if($CanAddToQueue === false) + { + $BlockReason[] = $_Lang['ListBox_Disallow_QueueIsFull']; + $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; + $HideButton_QuickBuild = true; + } + if($HasLab === false) + { + $BlockReason[] = $_Lang['ListBox_Disallow_NoLab']; + $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; + $HideButton_QuickBuild = true; + } + if($ResearchInThisLab === false) + { + $BlockReason[] = $_Lang['ListBox_Disallow_NotThisLab']; + $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; + $HideButton_QuickBuild = true; + } + if($LabInQueue === true) + { + $BlockReason[] = $_Lang['ListBox_Disallow_LabInQueue']; + $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; + $HideButton_QuickBuild = true; + } + if(isOnVacation($CurrentUser)) + { + $BlockReason[] = $_Lang['ListBox_Disallow_VacationMode']; + $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; + $HideButton_QuickBuild = true; + } + + if(!empty($BlockReason)) + { + if($ElementParser['BuildButtonColor'] == 'buildDo_Orange') + { + $ElementParser['ElementDisabled'] = $TPL['list_partdisabled']; + } + else + { + $ElementParser['ElementDisabled'] = $TPL['list_disabled']; + } + $ElementParser['ElementDisableReason'] = end($BlockReason); + } + + if($HideButton_Build) + { + $ElementParser['HideBuildButton'] = 'hide'; + } + if($HideButton_Build OR $HideButton_QuickBuild) + { + $ElementParser['HideQuickBuildButton'] = 'hide'; + } + + if(!empty($ElementParser['AdditionalNfo'])) + { + $ElementParser['AdditionalNfo'] = implode('', $ElementParser['AdditionalNfo']); + } + $ElementParser['ElementRequirementsHeadline'] = parsetemplate($ElementParser['ElementRequirementsHeadline'], $ElementParser); + $StructuresList[] = parsetemplate($TPL['list_element'], $ElementParser); + $InfoBoxes[] = parsetemplate($TPL['infobox_body'], $ElementParser); + } + + if(!empty($LevelModifiers)) + { + foreach($LevelModifiers as $ElementID => $Modifier) + { + $CurrentUser[$_Vars_GameElements[$ElementID]] += $Modifier; + } + } + $CurrentPlanet['metal'] += (isset($LockResources['metal']) ? $LockResources['metal'] : 0); + $CurrentPlanet['crystal'] += (isset($LockResources['crystal']) ? $LockResources['crystal'] : 0); + $CurrentPlanet['deuterium'] += (isset($LockResources['deuterium']) ? $LockResources['deuterium'] : 0); + + // Create List + $ThisRowIndex = 0; + $InRowCount = 0; + foreach($StructuresList as $ParsedData) + { + if($InRowCount == $ElementsPerRow) + { + $ParsedRows[($ThisRowIndex + 1)] = $TPL['list_breakrow']; + $ThisRowIndex += 2; + $InRowCount = 0; + } + + if(!isset($StructureRows[$ThisRowIndex]['Elements'])) + { + $StructureRows[$ThisRowIndex]['Elements'] = ''; + } + $StructureRows[$ThisRowIndex]['Elements'] .= $ParsedData; + $InRowCount += 1; + } + if($InRowCount < $ElementsPerRow) + { + $StructureRows[$ThisRowIndex]['Elements'] .= str_repeat($TPL['list_hidden'], ($ElementsPerRow - $InRowCount)); + } + foreach($StructureRows as $Index => $Data) + { + $ParsedRows[$Index] = parsetemplate($TPL['list_row'], $Data); + } + ksort($ParsedRows, SORT_ASC); + $Parse['Create_StructuresList'] = implode('', $ParsedRows); + $Parse['Create_ElementsInfoBoxes'] = implode('', $InfoBoxes); + if($ShowElementID > 0) + { + $Parse['Create_ShowElementOnStartup'] = $ShowElementID; + } + // End of - Parse all available technologies + + $Parse['Insert_SkinPath'] = $_SkinPath; + $Parse['Insert_PlanetImg'] = $CurrentPlanet['image']; + $Parse['Insert_PlanetType'] = $_Lang['PlanetType_'.$CurrentPlanet['planet_type']]; + $Parse['Insert_PlanetName'] = $CurrentPlanet['name']; + $Parse['Insert_PlanetPos_Galaxy'] = $CurrentPlanet['galaxy']; + $Parse['Insert_PlanetPos_System'] = $CurrentPlanet['system']; + $Parse['Insert_PlanetPos_Planet'] = $CurrentPlanet['planet']; + $Parse['Insert_Overview_LabLevel'] = $CurrentPlanet[$_Vars_GameElements[31]]; + $Parse['Insert_Overview_LabsConnected'] = prettyNumber($OtherLabs_ConnectedLabs); + $Parse['Insert_Overview_TotalLabsCount'] = prettyNumber($OtherLabs_LabsCount); + $Parse['Insert_Overview_LabPower'] = prettyNumber($OtherLabs_ConnectedLabsLevel); + $Parse['Insert_Overview_LabPowerTotal'] = prettyNumber($OtherLabs_TotalLabsLevel); + + $Page = parsetemplate(gettemplate('buildings_compact_body_lab'), $Parse); + + display($Page, $_Lang['Research']); +} + +?> diff --git a/includes/functions/MakeGraphs.php b/includes/functions/MakeGraphs.php index 8768a8574..ae69b6d66 100644 --- a/includes/functions/MakeGraphs.php +++ b/includes/functions/MakeGraphs.php @@ -1,256 +1,256 @@ - $Data) - { - if(empty($Data)) - { - unset($Scores[$Index]); - } - } - if(empty($Scores)) - { - return false; - } - - require($_EnginePath.'class/Smarty/Smarty.class.php'); - $smarty = new Smarty; - $smarty->template_dir = $_EnginePath.TEMPLATE_DIR.TEMPLATE_NAME.'/'; - $smarty->compile_dir = $_EnginePath.'/tmp/Smarty/Compile/'; - $smarty->cache_dir = $_EnginePath.'/tmp/Smarty/Cache/'; - - $graphs = array(); - $cx = new Context($Modes); - - foreach($Scores as $Index => $Data) - { - foreach($Data as $SubIndex => $Data2) - { - if($SubIndex === 'data') - { - $GraphData[$Index] = $Data2; - unset($Scores[$Index][$SubIndex]); - break; - } - } - } - - $SingleGraphTPL = gettemplate('Graphs_SingleGraph'); - foreach($Scores as $Index => $Data) - { - $GraphName = 'Graph_'.(string)($Index + 1); - - $filter = RunFilter::FromGET($cx, $Data); - $gb = new GraphBuilder($cx, $filter); - - $graphs[$GraphName] = array('name' => $GraphName, 'graph' => $gb, 'graphdata' => $GraphData[$Index]); - - $ReturnGraphs[] = parsetemplate($SingleGraphTPL, array('GraphName' => $GraphName)); - } - - if($Dimensions['x'] <= 0) - { - $Dimensions['x'] = 500; - } - if($Dimensions['y'] <= 0) - { - $Dimensions['y'] = 300; - } - $smarty->assign('RootPaht', $_EnginePath); - $smarty->assign('cx', $cx); - $smarty->assign('graphs', $graphs); - $smarty->assign('width', $Dimensions['x']); - $smarty->assign('height', $Dimensions['y']); - if($OwnTooltipCode) - { - $smarty->assign('OwnTooltipCode', $OwnTooltipCode); - } - - return array('includes' => $smarty->fetch('Graphs_Body.tpl'), 'graphs' => $ReturnGraphs, 'legend' => $smarty->fetch('Graphs_Legend.tpl')); -} - -class Context -{ - var $vendors; - var $modes; - - function Context($Modes) - { - $Vendors = array(array('id' => 1, 'name' => '', 'vendor' => '', 'browser' => '')); - foreach($Vendors as $Index => $Data) - { - $this->vendorMap_[$Data['id']] = count($this->vendors); - $this->vendors[] = $Data; - } - - foreach($Modes as $Index => $Data) - { - $this->modeMap_[$Data['id']] = count($this->modes); - $Data['vendor'] = $this->vendorMap_[$Data['vendor_id']]; - $Data['used'] = false; - $this->modes[] = $Data; - } - } - - function UpdateContext($Modes) - { - foreach($Modes as $Index => $Data) - { - $this->modeMap_[$Data['id']] = count($this->modes); - $Data['vendor'] = $this->vendorMap_[$Data['vendor_id']]; - $Data['used'] = false; - $this->modes[] = $Data; - } - } - - function markModeUsed($mode_id) - { - $mode = $this->modeFromDB($mode_id); - $this->modes[$mode]['used'] = true; - } - - function modeFromDB($mode_id) - { - return $this->modeMap_[$mode_id]; - } -} - -class RunFilter -{ - var $AllScores; - var $run_points; - var $runs; - var $runmap; - var $modemap; - var $series; - - function RunFilter($cx, $AllScores) - { - $this->AllScores = $AllScores; - - $this->runs = $this->findRuns(); - - // Get the list of run IDs for this graph. - $HasRuns = false; - $this->runmap = array(); - $RunMapID = 0; - foreach($this->runs as $Index => $Data) - { - $HasRuns = true; - $Data['stamp'] = substr($Data['stamp'], 0, 30); - if(empty($StampsIDs[$Data['stamp']]) && (!isset($StampsIDs[$Data['stamp']]) || $StampsIDs[$Data['stamp']] !== 0)) - { - $StampsIDs[$Data['stamp']] = $RunMapID; - $RunMapID += 1; - } - $this->runmap[$Data['id']] = $StampsIDs[$Data['stamp']]; - } - $this->run_points = array_flip($StampsIDs); - foreach($this->run_points as &$ThisVal) - { - $ThisVal = substr($ThisVal, 0, 10); - } - $ModesInTable = array(); - - foreach($this->AllScores as $Data) - { - $mode_id = $Data['mode_id']; - $ThisMode = $cx->modeFromDB($mode_id); - if(!in_array($ThisMode, $ModesInTable)) - { - $this->modemap[$mode_id] = count($this->series); - $this->series[] = array('mode' => $cx->modeFromDB($mode_id)); - $cx->markModeUsed($mode_id); - $ModesInTable[] = $ThisMode; - } - } - } - - function findSeriesOfMode($mode_id) - { - return $this->modemap[$mode_id]; - } - - function findRuns() - { - $TempScores = $this->AllScores; - if(empty($TempScores)) - { - return array(); - } - foreach($TempScores as $Index => $Data) - { - $TempStamps[$Index] = $Data['stamp']; - } - array_multisort($TempScores, SORT_DESC, $TempStamps); - - foreach($TempScores as $Data) - { - $rows[] = array('id' => $Data['run_id'], 'stamp' => $Data['stamp']); - } - return array_reverse($rows); - } - - function findRun($run_id) - { - return $this->runmap[$run_id]; - } - - static function FromGET($cx, $AllScores) - { - return new RunFilter($cx, $AllScores); - } -} - -class GraphBuilder -{ - var $AllScores; - var $series; - var $runs; - var $run_points; - - function GraphBuilder(&$cx, &$filter) - { - $this->AllScores = $filter->AllScores; - $this->runs = $filter->runs; - $this->run_points = $filter->run_points; - $this->series = $filter->series; - - foreach($this->AllScores as $Index => $Data) - { - $run_id = $Data['run_id']; - $mode_id = $Data['mode_id']; - $mode = $filter->findSeriesOfMode($mode_id); - $run = $filter->findRun($run_id); - $this->series[$mode]['scores'][$run] = $Data['score']; - } - } -} - -?> \ No newline at end of file + $Data) + { + if(empty($Data)) + { + unset($Scores[$Index]); + } + } + if(empty($Scores)) + { + return false; + } + + require($_EnginePath.'class/Smarty/Smarty.class.php'); + $smarty = new Smarty; + $smarty->template_dir = $_EnginePath.TEMPLATE_DIR.TEMPLATE_NAME.'/'; + $smarty->compile_dir = $_EnginePath.'/tmp/Smarty/Compile/'; + $smarty->cache_dir = $_EnginePath.'/tmp/Smarty/Cache/'; + + $graphs = array(); + $cx = new Context($Modes); + + foreach($Scores as $Index => $Data) + { + foreach($Data as $SubIndex => $Data2) + { + if($SubIndex === 'data') + { + $GraphData[$Index] = $Data2; + unset($Scores[$Index][$SubIndex]); + break; + } + } + } + + $SingleGraphTPL = gettemplate('Graphs_SingleGraph'); + foreach($Scores as $Index => $Data) + { + $GraphName = 'Graph_'.(string)($Index + 1); + + $filter = RunFilter::FromGET($cx, $Data); + $gb = new GraphBuilder($cx, $filter); + + $graphs[$GraphName] = array('name' => $GraphName, 'graph' => $gb, 'graphdata' => $GraphData[$Index]); + + $ReturnGraphs[] = parsetemplate($SingleGraphTPL, array('GraphName' => $GraphName)); + } + + if($Dimensions['x'] <= 0) + { + $Dimensions['x'] = 500; + } + if($Dimensions['y'] <= 0) + { + $Dimensions['y'] = 300; + } + $smarty->assign('RootPaht', $_EnginePath); + $smarty->assign('cx', $cx); + $smarty->assign('graphs', $graphs); + $smarty->assign('width', $Dimensions['x']); + $smarty->assign('height', $Dimensions['y']); + if($OwnTooltipCode) + { + $smarty->assign('OwnTooltipCode', $OwnTooltipCode); + } + + return array('includes' => $smarty->fetch('Graphs_Body.tpl'), 'graphs' => $ReturnGraphs, 'legend' => $smarty->fetch('Graphs_Legend.tpl')); +} + +class Context +{ + var $vendors; + var $modes; + + function Context($Modes) + { + $Vendors = array(array('id' => 1, 'name' => '', 'vendor' => '', 'browser' => '')); + foreach($Vendors as $Index => $Data) + { + $this->vendorMap_[$Data['id']] = count($this->vendors); + $this->vendors[] = $Data; + } + + foreach($Modes as $Index => $Data) + { + $this->modeMap_[$Data['id']] = count($this->modes); + $Data['vendor'] = $this->vendorMap_[$Data['vendor_id']]; + $Data['used'] = false; + $this->modes[] = $Data; + } + } + + function UpdateContext($Modes) + { + foreach($Modes as $Index => $Data) + { + $this->modeMap_[$Data['id']] = count($this->modes); + $Data['vendor'] = $this->vendorMap_[$Data['vendor_id']]; + $Data['used'] = false; + $this->modes[] = $Data; + } + } + + function markModeUsed($mode_id) + { + $mode = $this->modeFromDB($mode_id); + $this->modes[$mode]['used'] = true; + } + + function modeFromDB($mode_id) + { + return $this->modeMap_[$mode_id]; + } +} + +class RunFilter +{ + var $AllScores; + var $run_points; + var $runs; + var $runmap; + var $modemap; + var $series; + + function RunFilter($cx, $AllScores) + { + $this->AllScores = $AllScores; + + $this->runs = $this->findRuns(); + + // Get the list of run IDs for this graph. + $HasRuns = false; + $this->runmap = array(); + $RunMapID = 0; + foreach($this->runs as $Index => $Data) + { + $HasRuns = true; + $Data['stamp'] = substr($Data['stamp'], 0, 30); + if(empty($StampsIDs[$Data['stamp']]) && (!isset($StampsIDs[$Data['stamp']]) || $StampsIDs[$Data['stamp']] !== 0)) + { + $StampsIDs[$Data['stamp']] = $RunMapID; + $RunMapID += 1; + } + $this->runmap[$Data['id']] = $StampsIDs[$Data['stamp']]; + } + $this->run_points = array_flip($StampsIDs); + foreach($this->run_points as &$ThisVal) + { + $ThisVal = substr($ThisVal, 0, 10); + } + $ModesInTable = array(); + + foreach($this->AllScores as $Data) + { + $mode_id = $Data['mode_id']; + $ThisMode = $cx->modeFromDB($mode_id); + if(!in_array($ThisMode, $ModesInTable)) + { + $this->modemap[$mode_id] = count($this->series); + $this->series[] = array('mode' => $cx->modeFromDB($mode_id)); + $cx->markModeUsed($mode_id); + $ModesInTable[] = $ThisMode; + } + } + } + + function findSeriesOfMode($mode_id) + { + return $this->modemap[$mode_id]; + } + + function findRuns() + { + $TempScores = $this->AllScores; + if(empty($TempScores)) + { + return array(); + } + foreach($TempScores as $Index => $Data) + { + $TempStamps[$Index] = $Data['stamp']; + } + array_multisort($TempScores, SORT_DESC, $TempStamps); + + foreach($TempScores as $Data) + { + $rows[] = array('id' => $Data['run_id'], 'stamp' => $Data['stamp']); + } + return array_reverse($rows); + } + + function findRun($run_id) + { + return $this->runmap[$run_id]; + } + + static function FromGET($cx, $AllScores) + { + return new RunFilter($cx, $AllScores); + } +} + +class GraphBuilder +{ + var $AllScores; + var $series; + var $runs; + var $run_points; + + function GraphBuilder(&$cx, &$filter) + { + $this->AllScores = $filter->AllScores; + $this->runs = $filter->runs; + $this->run_points = $filter->run_points; + $this->series = $filter->series; + + foreach($this->AllScores as $Index => $Data) + { + $run_id = $Data['run_id']; + $mode_id = $Data['mode_id']; + $mode = $filter->findSeriesOfMode($mode_id); + $run = $filter->findRun($run_id); + $this->series[$mode]['scores'][$run] = $Data['score']; + } + } +} + +?> diff --git a/includes/functions/MissionCaseAttack.php b/includes/functions/MissionCaseAttack.php index 9b4a9319f..4b25ebbe9 100644 --- a/includes/functions/MissionCaseAttack.php +++ b/includes/functions/MissionCaseAttack.php @@ -1,1549 +1,1549 @@ - 0 ? false : true); - $TargetPlanet = &$_FleetCache['planets'][$FleetRow['fleet_end_id']]; - $TargetUser = &$_FleetCache['users'][$FleetRow['fleet_target_owner']]; - $IsAllyFight = (($FleetRow['ally_id'] == 0 OR ($FleetRow['ally_id'] != $TargetUser['ally_id'])) ? false : true); - - // Update planet before attack begins - $UpdateResult = HandleFullUserUpdate($TargetUser, $TargetPlanet, $_FleetCache['planets'][$TargetUser['techQueue_Planet']], $FleetRow['fleet_start_time'], true, true); - if(!empty($UpdateResult)) - { - foreach($UpdateResult as $PlanetID => $Value) - { - if($Value === true) - { - $_FleetCache['updatePlanets'][$PlanetID] = true; - } - } - } - - $TargetUserID = $TargetPlanet['id_owner']; - $TargetPlanetGetName = $TargetPlanet['name']; - $TargetPlanetID = $TargetPlanet['id']; - - if(!$IsAbandoned) - { - $IdleHours = floor(($FleetRow['fleet_start_time'] - $TargetUser['onlinetime']) / 3600); - if($IdleHours > 0) - { - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Owner_IdleHours'] = $IdleHours; - } - } - - // Create data arrays for attacker and main defender - $CurrentUserID = $FleetRow['fleet_owner']; - $DefendersIDs[] = $TargetUser['id']; - $AttackersIDs[] = $FleetRow['fleet_owner']; - $AttackingFleets = array(); - $DefendingFleets = array(); - - $DefendingTechs[0] = array - ( - 109 => $TargetUser['tech_weapons'], - 110 => $TargetUser['tech_armour'], - 111 => $TargetUser['tech_shielding'], - 120 => $TargetUser['tech_laser'], - 121 => $TargetUser['tech_ion'], - 122 => $TargetUser['tech_plasma'], - 125 => $TargetUser['tech_antimatter'], - 126 => $TargetUser['tech_disintegration'], - 199 => $TargetUser['tech_graviton'] - ); - $DefendersData[0] = array - ( - 'id' => $TargetUser['id'], - 'username' => $TargetUser['username'], - 'techs' => Array2String($DefendingTechs[0]), - 'pos' => "{$FleetRow['fleet_end_galaxy']}:{$FleetRow['fleet_end_system']}:{$FleetRow['fleet_end_planet']}" - ); - if(!empty($TargetUser['ally_tag'])) - { - $DefendersData[0]['ally'] = $TargetUser['ally_tag']; - } - - $AttackingTechs[0] = array - ( - 109 => $FleetRow['tech_weapons'], - 110 => $FleetRow['tech_armour'], - 111 => $FleetRow['tech_shielding'], - 120 => $FleetRow['tech_laser'], - 121 => $FleetRow['tech_ion'], - 122 => $FleetRow['tech_plasma'], - 125 => $FleetRow['tech_antimatter'], - 126 => $FleetRow['tech_disintegration'], - 199 => $FleetRow['tech_graviton'] - ); - $AttackersData[0] = array - ( - 'id' => $FleetRow['fleet_owner'], - 'username' => $FleetRow['username'], - 'techs' => Array2String($AttackingTechs[0]), - 'pos' => "{$FleetRow['fleet_start_galaxy']}:{$FleetRow['fleet_start_system']}:{$FleetRow['fleet_start_planet']}" - ); - if(!empty($FleetRow['ally_tag'])) - { - $AttackersData[0]['ally'] = $FleetRow['ally_tag']; - } - - // MoraleSystem Init - if(MORALE_ENABLED) - { - if(!empty($_FleetCache['MoraleCache'][$FleetRow['fleet_owner']])) - { - $FleetRow['morale_level'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['level']; - $FleetRow['morale_droptime'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['droptime']; - $FleetRow['morale_lastupdate'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['lastupdate']; - } - Morale_ReCalculate($FleetRow, $FleetRow['fleet_start_time']); - $AttackersData[0]['morale'] = $FleetRow['morale_level']; - $AttackersData[0]['moralePoints'] = $FleetRow['morale_points']; - - // Bonuses - if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETPOWERUP1) - { - $AttackingTechs[0]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; - } - if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETSHIELDUP1) - { - $AttackingTechs[0]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; - } - if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETSDADDITION) - { - $AttackingTechs[0]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; - } - // Penalties - if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN1) - { - $AttackingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; - } - if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN2) - { - $AttackingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; - } - if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) - { - $AttackingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; - } - if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) - { - $AttackingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; - } - if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSDDOWN) - { - $AttackingTechs[0]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; - } - - if(!$IsAbandoned) - { - if(!empty($_FleetCache['MoraleCache'][$TargetUser['id']])) - { - $TargetUser['morale_level'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['level']; - $TargetUser['morale_droptime'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['droptime']; - $TargetUser['morale_lastupdate'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['lastupdate']; - } - Morale_ReCalculate($TargetUser, $FleetRow['fleet_start_time']); - $DefendersData[0]['morale'] = $TargetUser['morale_level']; - $DefendersData[0]['moralePoints'] = $TargetUser['morale_points']; - - // Bonuses - if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETPOWERUP1) - { - $DefendingTechs[0]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; - } - if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETSHIELDUP1) - { - $DefendingTechs[0]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; - } - if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETSDADDITION) - { - $DefendingTechs[0]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; - } - // Penalties - if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN1) - { - $DefendingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; - } - if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN2) - { - $DefendingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; - } - if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) - { - $DefendingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; - } - if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) - { - $DefendingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; - } - if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSDDOWN) - { - $DefendingTechs[0]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; - } - } - } - - // Select All Defending Fleets on the Orbit from $_FleetCache - if(!empty($_FleetCache['defFleets'][$FleetRow['fleet_end_id']])) - { - $i = 1; - foreach($_FleetCache['defFleets'][$FleetRow['fleet_end_id']] as $FleetData) - { - if($_FleetCache['fleetRowStatus'][$FleetData['fleet_id']]['isDestroyed'] !== true) - { - $DefendingFleets[$i] = String2Array($FleetData['fleet_array']); - $DefendingFleetID[$i] = $FleetData['fleet_id']; - $DefendingTechs[$i] = array - ( - 109 => $FleetData['tech_weapons'], - 110 => $FleetData['tech_armour'], - 111 => $FleetData['tech_shielding'], - 120 => $FleetData['tech_laser'], - 121 => $FleetData['tech_ion'], - 122 => $FleetData['tech_plasma'], - 125 => $FleetData['tech_antimatter'], - 126 => $FleetData['tech_disintegration'], - 199 => $FleetData['tech_graviton'] - ); - $DefendersData[$i] = array - ( - 'id' => $FleetData['fleet_owner'], - 'username' => $FleetData['username'], - 'techs' => Array2String($DefendingTechs[$i]), - 'pos' => "{$FleetData['fleet_start_galaxy']}:{$FleetData['fleet_start_system']}:{$FleetData['fleet_start_planet']}" - ); - if(!empty($FleetData['ally_tag'])) - { - $DefendersData[$i]['ally'] = $FleetData['ally_tag']; - } - if(!in_array($FleetData['fleet_owner'], $DefendersIDs)) - { - $DefendersIDs[] = $FleetData['fleet_owner']; - } - $DefendingFleetOwners[$FleetData['fleet_id']] = $FleetData['fleet_owner']; - - if(MORALE_ENABLED) - { - if(empty($_TempCache['MoraleCache'][$FleetData['fleet_owner']])) - { - if(!empty($_FleetCache['MoraleCache'][$FleetData['fleet_owner']])) - { - $FleetData['morale_level'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['level']; - $FleetData['morale_droptime'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['droptime']; - $FleetData['morale_lastupdate'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['lastupdate']; - } - Morale_ReCalculate($FleetData, $FleetRow['fleet_start_time']); - $DefendersData[$i]['morale'] = $FleetData['morale_level']; - $DefendersData[$i]['moralePoints'] = $FleetData['morale_points']; - - $_TempCache['MoraleCache'][$FleetData['fleet_owner']] = array - ( - 'level' => $FleetData['morale_level'], - 'points' => $FleetData['morale_points'] - ); - } - else - { - $DefendersData[$i]['morale'] = $_TempCache['MoraleCache'][$FleetData['fleet_owner']]['level']; - $DefendersData[$i]['moralePoints'] = $_TempCache['MoraleCache'][$FleetData['fleet_owner']]['points']; - } - - // Bonuses - if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETPOWERUP1) - { - $DefendingTechs[$i]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; - } - if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETSHIELDUP1) - { - $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; - } - if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETSDADDITION) - { - $DefendingTechs[$i]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; - } - // Penalties - if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN1) - { - $DefendingTechs[$i]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; - } - if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN2) - { - $DefendingTechs[$i]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; - } - if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) - { - $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; - } - if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) - { - $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; - } - if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSDDOWN) - { - $DefendingTechs[$i]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; - } - } - - $i += 1; - } - } - } - - foreach($AttackersIDs as $ID) - { - if(empty($UserStatsData[$ID])) - { - $UserStatsData[$ID] = $UserStatsPattern; - } - } - foreach($DefendersIDs as $ID) - { - if(empty($UserStatsData[$ID])) - { - $UserStatsData[$ID] = $UserStatsPattern; - } - } - - // Create main defender fleet array - foreach($_Vars_ElementCategories['fleet'] as $ElementID) - { - if($TargetPlanet[$_Vars_GameElements[$ElementID]] > 0) - { - $DefendingFleets[0][$ElementID] = $TargetPlanet[$_Vars_GameElements[$ElementID]]; - } - } - foreach($_Vars_ElementCategories['defense'] as $ElementID) - { - if(in_array($ElementID, $_Vars_ElementCategories['rockets'])) - { - continue; - } - if($TargetPlanet[$_Vars_GameElements[$ElementID]] > 0) - { - $DefendingFleets[0][$ElementID] = $TargetPlanet[$_Vars_GameElements[$ElementID]]; - } - } - - // Create attacker fleet array - $AttackingFleets[0] = String2Array($FleetRow['fleet_array']); - - $StartTime = microtime(true); - - // Now start Combat calculations - $Combat = Combat($AttackingFleets, $DefendingFleets, $AttackingTechs, $DefendingTechs); - - // Get the calculations time - $EndTime = microtime(true); - $totaltime = sprintf('%0.6f', $EndTime - $StartTime); - - $RealDebrisMetalAtk = 0; - $RealDebrisCrystalAtk = 0; - $RealDebrisDeuteriumAtk = 0; - $RealDebrisMetalDef = 0; - $RealDebrisCrystalDef = 0; - $RealDebrisDeuteriumDef = 0; - $TotalMoonChance = 0; - $TotalLostMetal = 0; - $TotalLostCrystal = 0; - $DebrisMetalDef = 0; - $DebrisCrystalDef = 0; - - $MoonHasBeenCreated = false; - - $RoundsData = $Combat['rounds']; - $Result = $Combat['result']; - $AtkShips = $Combat['AttackerShips']; - $DefShips = $Combat['DefenderShips']; - $AtkLost = $Combat['AtkLose']; - $DefLost = $Combat['DefLose']; - $DefSysLost = $Combat['DefSysLost']; - $ShotDown = $Combat['ShotDown']; - - $FleetStorage = 0; - // Parse result data - attacker fleet - if(!empty($AtkShips[0])) - { - $QryUpdateFleets[0]['id'] = $FleetRow['fleet_id']; - foreach($AtkShips[0] as $ID => $Count) - { - $QryUpdateFleets[0]['mess'] = '1'; - if($Count > 0) - { - if(!isset($QryUpdateFleets[0]['count'])) - { - $QryUpdateFleets[0]['count'] = 0; - } - $QryUpdateFleets[0]['array'][] = "{$ID},{$Count}"; - $QryUpdateFleets[0]['count'] += $Count; - } - if($Result === COMBAT_ATK && (!isset($_Vars_Prices[$ID]['cantPillage']) || $_Vars_Prices[$ID]['cantPillage'] !== true)) - { - $FleetStorage += $_Vars_Prices[$ID]['capacity'] * $Count; - } - - if($Count < $AttackingFleets[0][$ID]) - { - $UserDev_UpFl[$FleetRow['fleet_id']][] = $ID.','.($AttackingFleets[0][$ID] - $Count); - } - } - - foreach($AttackingFleets[0] as $ID => $Count) - { - $Difference = $Count; - if(isset($AtkShips[0][$ID])) - { - $Difference -= $AtkShips[0][$ID]; - } - if($Difference > 0) - { - $QryUpdateFleets[0]['array_lost'][] = "{$ID},{$Difference}"; - } - } - if(!empty($QryUpdateFleets[0]['array_lost'])) - { - $QryUpdateFleets[0]['array_lost'] = implode(';', $QryUpdateFleets[0]['array_lost']); - } - - if($Result === COMBAT_ATK) - { - $FleetStorage -= $FleetRow['fleet_resource_metal']; - $FleetStorage -= $FleetRow['fleet_resource_crystal']; - $FleetStorage -= $FleetRow['fleet_resource_deuterium']; - - if($FleetStorage > 0) - { - $ResourceSteal_Factor = (COMBAT_RESOURCESTEAL_PERCENT / 100); - if(MORALE_ENABLED) - { - if(!$IsAbandoned AND $TargetUser['morale_level'] <= MORALE_PENALTY_RESOURCELOSE) - { - $ResourceSteal_NewFactor[] = MORALE_PENALTY_RESOURCELOSE_STEALPERCENT; - } - if($FleetRow['morale_level'] >= MORALE_BONUS_SOLOIDLERSTEAL AND $IdleHours >= (7 * 24)) - { - $ResourceSteal_NewFactor[] = MORALE_BONUS_SOLOIDLERSTEAL_STEALPERCENT; - } - if($FleetRow['morale_level'] <= MORALE_PENALTY_STEAL) - { - $ResourceSteal_NewFactor[] = MORALE_PENALTY_STEAL_STEALPERCENT; - } - else if($FleetRow['morale_level'] <= MORALE_PENALTY_IDLERSTEAL AND $IdleHours >= (7 * 24)) - { - $ResourceSteal_NewFactor[] = MORALE_PENALTY_IDLERSTEAL_STEALPERCENT; - } - - if(!empty($ResourceSteal_NewFactor)) - { - $ResourceSteal_Factor = (array_sum($ResourceSteal_NewFactor) / count($ResourceSteal_NewFactor)) / 100; - } - } - - $StolenMet = 0; - $StolenCry = 0; - $StolenDeu = 0; - - $AllowTakeMoreMet = 0; - $AllowTakeMoreCry = 0; - $AllowTakeMoreDeu = 0; - - $MaxMetSteal = $TargetPlanet['metal'] * $ResourceSteal_Factor; - $MaxCrySteal = $TargetPlanet['crystal'] * $ResourceSteal_Factor; - $MaxDeuSteal = $TargetPlanet['deuterium'] * $ResourceSteal_Factor; - - $StoragePerResource = $FleetStorage / 3; - - // First - calculate, if any resource will leave free storage - if($MaxMetSteal < $StoragePerResource) - { - $AllowTakeMore = ($StoragePerResource - $MaxMetSteal) / 2; - $AllowTakeMoreCry += $AllowTakeMore; - $AllowTakeMoreDeu += $AllowTakeMore; - $GiveAwayMet = true; - } - - if($MaxCrySteal < ($StoragePerResource + $AllowTakeMoreCry)) - { - $AllowTakeMore = (($StoragePerResource + $AllowTakeMoreCry) - $MaxCrySteal) / 2; - if($GiveAwayMet == false) - { - $AllowTakeMoreMet += $AllowTakeMore; - $AllowTakeMoreDeu += $AllowTakeMore; - } - else - { - $AllowTakeMoreDeu += $AllowTakeMore * 2; - } - $GiveAwayCry = true; - } - - if($MaxDeuSteal < ($StoragePerResource + $AllowTakeMoreDeu)) - { - $AllowTakeMore = (($StoragePerResource + $AllowTakeMoreDeu) - $MaxDeuSteal) / 2; - if($GiveAwayCry == false) - { - $AllowTakeMoreMet += $AllowTakeMore; - $AllowTakeMoreCry += $AllowTakeMore; - } - else - { - $AllowTakeMoreMet += $AllowTakeMore * 2; - } - } - - // Second - calculate stolen resources - if($MaxMetSteal > ($StoragePerResource + $AllowTakeMoreMet)) - { - $StolenMet = $StoragePerResource + $AllowTakeMoreMet; - } - else - { - $StolenMet = $MaxMetSteal; - } - if($MaxCrySteal > ($StoragePerResource + $AllowTakeMoreCry)) - { - $StolenCry = $StoragePerResource + $AllowTakeMoreCry; - } - else - { - $StolenCry = $MaxCrySteal; - } - if($MaxDeuSteal > ($StoragePerResource + $AllowTakeMoreDeu)) - { - $StolenDeu = $StoragePerResource + $AllowTakeMoreDeu; - } - else - { - $StolenDeu = $MaxDeuSteal; - } - - $StolenMet = floor($StolenMet); - $StolenCry = floor($StolenCry); - $StolenDeu = floor($StolenDeu); - if($StolenMet > 0) - { - $UserDev_UpFl[$FleetRow['fleet_id']][] = 'M,'.$StolenMet; - $TriggerTasksCheck['BATTLE_COLLECT_METAL'] = $StolenMet; - } - if($StolenCry > 0) - { - $UserDev_UpFl[$FleetRow['fleet_id']][] = 'C,'.$StolenCry; - $TriggerTasksCheck['BATTLE_COLLECT_CRYSTAL'] = $StolenCry; - } - if($StolenDeu > 0) - { - $UserDev_UpFl[$FleetRow['fleet_id']][] = 'D,'.$StolenDeu; - $TriggerTasksCheck['BATTLE_COLLECT_DEUTERIUM'] = $StolenDeu; - } - - $QryUpdateFleets[0]['metal'] = $StolenMet; - $QryUpdateFleets[0]['crystal'] = $StolenCry; - $QryUpdateFleets[0]['deuterium'] = $StolenDeu; - - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Metal'] = $StolenMet; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Crystal'] = $StolenCry; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Deuterium'] = $StolenDeu; - } - } - } - else - { - $DeleteFleet[] = $FleetRow['fleet_id']; - foreach($AttackingFleets[0] as $ShipID => $ShipCount) - { - $UserDev_UpFl[$FleetRow['fleet_id']][] = $ShipID.','.$ShipCount; - } - - $fleetHasBeenDeleted = true; - } - - // Parse result data - Defenders - $i = 1; - if(!empty($DefendingFleets)) - { - foreach($DefendingFleets as $User => $Ships) - { - if($User == 0) - { - $DefSysLostIDs = array_keys($DefSysLost); - $DefSysLostIDs[] = -1; - - foreach($Ships as $ID => $Count) - { - if(in_array($ID, $DefSysLostIDs)) - { - $Count = $DefShips[0][$ID]; - $Chance = mt_rand(60, 80 + (($TargetUser['engineer_time'] >= $FleetRow['fleet_start_time']) ? 20 : 0)); - $Fluctuation = mt_rand(-15, 15); - if($Fluctuation > 0) - { - $Fluctuation = 0; - } - $Rebuilt[$ID] = round($DefSysLost[$ID] * (($Chance + $Fluctuation) / 100)); - $Count += $Rebuilt[$ID]; - if($DefendingFleets[0][$ID] < $Count) - { - $Count = $DefendingFleets[0][$ID]; - } - unset($DefSysLost[$ID]); - } - else - { - $Count = $DefShips[0][$ID]; - } - if($Count == 0) - { - $Count = '0'; - } - $TargetPlanet[$_Vars_GameElements[$ID]] = $Count; - if($Count < $DefendingFleets[0][$ID]) - { - $UserDev_UpPl[] = $ID.','.($DefendingFleets[0][$ID] - $Count); - $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; - $HPQ_PlanetUpdatedFields[] = $_Vars_GameElements[$ID]; - } - } - } - else - { - $QryUpdateFleets[$i]['id'] = $DefendingFleetID[$User]; - if(!empty($DefShips[$User])) - { - foreach($Ships as $ID => $Count) - { - $ThisCount = 0; - if(!empty($DefShips[$User][$ID])) - { - $OldCount = $Count; - $Count = $DefShips[$User][$ID]; - $ThisCount = $Count; - if($Count > 0) - { - if(!isset($QryUpdateFleets[$i]['count'])) - { - $QryUpdateFleets[$i]['count'] = 0; - } - $QryUpdateFleets[$i]['array'][] = "{$ID},{$Count}"; - $QryUpdateFleets[$i]['count'] += $Count; - } - $Difference = $OldCount - $Count; - if($Difference > 0) - { - $QryUpdateFleets[$i]['array_lost'][] = "{$ID},{$Difference}"; - } - } - - if($ThisCount < $DefendingFleets[$User][$ID]) - { - $UserDev_UpFl[$DefendingFleetID[$User]][] = $ID.','.($DefendingFleets[$User][$ID] - $ThisCount); - } - } - - if(!empty($QryUpdateFleets[$i]['array_lost'])) - { - $QryUpdateFleets[$i]['array_lost'] = implode(';', $QryUpdateFleets[$i]['array_lost']); - } - } - else - { - $DeleteFleet[] = $DefendingFleetID[$User]; - foreach($DefendingFleets[$User] as $ShipID => $ShipCount) - { - $UserDev_UpFl[$DefendingFleetID[$User]][] = "{$ShipID},{$ShipCount}"; - } - } - } - $i += 1; - } - } - - if($StolenMet > 0) - { - $TargetPlanet['metal'] -= $StolenMet; - $UserDev_UpPl[] = 'M,'.$StolenMet; - $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; - } - if($StolenCry > 0) - { - $TargetPlanet['crystal'] -= $StolenCry; - $UserDev_UpPl[] = 'C,'.$StolenCry; - $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; - } - if($StolenDeu > 0) - { - $TargetPlanet['deuterium'] -= $StolenDeu; - $UserDev_UpPl[] = 'D,'.$StolenDeu; - $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; - } - - // Update all fleets (if necessary) - if(!empty($QryUpdateFleets)) - { - foreach($QryUpdateFleets as $Data) - { - if(!empty($Data)) - { - if($Data['metal'] <= 0) - { - $Data['metal'] = '0'; - } - if($Data['crystal'] <= 0) - { - $Data['crystal'] = '0'; - } - if($Data['deuterium'] <= 0) - { - $Data['deuterium'] = '0'; - } - - if(!empty($Data['array'])) - { - $Data['array'] = implode(';', $Data['array']); - if(!empty($Data['array_lost'])) - { - if(strlen($Data['array']) > strlen($Data['array_lost'])) - { - $Return['FleetArchive'][$Data['id']]['Fleet_Array_Changes'] = "\"+D;{$Data['array_lost']}|\""; - } - else - { - $Return['FleetArchive'][$Data['id']]['Fleet_Array_Changes'] = "\"+L;{$Data['array']}|\""; - } - $Return['FleetArchive'][$Data['id']]['Fleet_Info_HasLostShips'] = '!true'; - } - if($Data['id'] != $FleetRow['fleet_id']) - { - $_FleetCache['defFleets'][$FleetRow['fleet_end_id']][$Data['id']]['fleet_array'] = $Data['array']; - } - } - - if($Data['id'] == $FleetRow['fleet_id'] AND $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['calcCount'] == 2) - { - // Update $_FleetCache, instead of sending additional Query to Update FleetState - // This fleet will be restored in this Calculation, so don't waste our time - $CachePointer = &$_FleetCache['fleetRowUpdate'][$Data['id']]; - $CachePointer['fleet_array'] = $Data['array']; - $CachePointer['fleet_resource_metal'] = $FleetRow['fleet_resource_metal'] + $Data['metal']; - $CachePointer['fleet_resource_crystal'] = $FleetRow['fleet_resource_crystal'] + $Data['crystal']; - $CachePointer['fleet_resource_deuterium'] = $FleetRow['fleet_resource_deuterium'] + $Data['deuterium']; - } - else - { - // Create UpdateFleet record for $_FleetCache - $CachePointer = &$_FleetCache['updateFleets'][$Data['id']]; - $CachePointer['fleet_array'] = $Data['array']; - $CachePointer['fleet_amount'] = $Data['count']; - $CachePointer['fleet_mess'] = $Data['mess']; - if(!isset($CachePointer['fleet_resource_metal'])) - { - $CachePointer['fleet_resource_metal'] = 0; - } - if(!isset($CachePointer['fleet_resource_crystal'])) - { - $CachePointer['fleet_resource_crystal'] = 0; - } - if(!isset($CachePointer['fleet_resource_deuterium'])) - { - $CachePointer['fleet_resource_deuterium'] = 0; - } - $CachePointer['fleet_resource_metal'] += $Data['metal']; - $CachePointer['fleet_resource_crystal'] += $Data['crystal']; - $CachePointer['fleet_resource_deuterium'] += $Data['deuterium']; - } - } - } - } - - if(!empty($UserDev_UpFl)) - { - foreach($UserDev_UpFl as $FleetID => $DevArray) - { - if($FleetID == $FleetRow['fleet_id']) - { - $SetCode = '2'; - $FleetUserID = $FleetRow['fleet_owner']; - } - else - { - $SetCode = '3'; - $FleetUserID = $DefendingFleetOwners[$FleetID]; - } - $UserDev_Log[] = array('UserID' => $FleetUserID, 'PlanetID' => '0', 'Date' => $FleetRow['fleet_start_time'], 'Place' => 12, 'Code' => $SetCode, 'ElementID' => $FleetID, 'AdditionalData' => implode(';', $DevArray)); - } - } - - // Calculate Debris & Looses - Init - $DebrisFactor_Fleet = $_GameConfig['Fleet_Cdr'] / 100; - $DebrisFactor_Defense = $_GameConfig['Defs_Cdr'] / 100; - - // Calculate looses - attacker - if(!empty($AtkLost)) - { - $DebrisMetalAtk = 0; - $DebrisCrystalAtk = 0; - foreach($AtkLost as $ID => $Count) - { - if(in_array($ID, $_Vars_ElementCategories['fleet'])) - { - if($DebrisFactor_Fleet > 0) - { - $DebrisMetalAtk += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Fleet); - $DebrisCrystalAtk += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Fleet); - } - $RealDebrisMetalAtk += floor($_Vars_Prices[$ID]['metal'] * $Count); - $RealDebrisCrystalAtk += floor($_Vars_Prices[$ID]['crystal'] * $Count); - $RealDebrisDeuteriumAtk += floor($_Vars_Prices[$ID]['deuterium'] * $Count); - } - } - $TotalLostMetal = $DebrisMetalAtk; - $TotalLostCrystal = $DebrisCrystalAtk; - } - // Calculate looses - defender - if(!empty($DefLost)) - { - foreach($DefLost as $ID => $Count) - { - if(in_array($ID, $_Vars_ElementCategories['fleet'])) - { - if($DebrisFactor_Fleet > 0) - { - $DebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Fleet); - $DebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Fleet); - } - } - elseif(in_array($ID, $_Vars_ElementCategories['defense'])) - { - if($DebrisFactor_Defense > 0) - { - $DebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Defense); - $DebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Defense); - } - } - $RealDebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count); - $RealDebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count); - $RealDebrisDeuteriumDef += floor($_Vars_Prices[$ID]['deuterium'] * $Count); - } - $TotalLostMetal += $DebrisMetalDef; - $TotalLostCrystal += $DebrisCrystalDef; - } - - // Delete fleets (if necessary) - if(!empty($DeleteFleet)) - { - foreach($DeleteFleet as $FleetID) - { - $_FleetCache['fleetRowStatus'][$FleetID]['isDestroyed'] = true; - if(!empty($_FleetCache['updateFleets'][$FleetID])) - { - unset($_FleetCache['updateFleets'][$FleetID]); - } - $Return['FleetsToDelete'][] = $FleetID; - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed'] = true; - $Return['FleetArchive'][$FleetID]['Fleet_Info_HasLostShips'] = true; - if($FleetID == $FleetRow['fleet_id']) - { - if($Result === COMBAT_DEF AND ($RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef) <= 0) - { - if(count($RoundsData) == 2) - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 1; - } - else - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 11; - } - } - else - { - if(count($RoundsData) == 2) - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 12; - } - else - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 2; - } - } - } - else - { - unset($_FleetCache['defFleets'][$FleetRow['fleet_end_id']][$FleetID]); - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 3; - } - } - } - - if($Result === COMBAT_DRAW AND (($RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef) <= 0)) - { - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed_Reason'] = 4; - } - - // Create debris field on the orbit - if($TotalLostMetal > 0 || $TotalLostCrystal > 0) - { - if($TotalLostCrystal == 0) - { - $TotalLostCrystal = '0'; - } - if($TotalLostMetal == 0) - { - $TotalLostMetal = '0'; - } - if($TargetPlanet['planet_type'] == 1) - { - $Query_UpdateGalaxy_SearchField = 'id_planet'; - $CacheKey = 'byPlanet'; - } - else - { - $Query_UpdateGalaxy_SearchField = 'id_moon'; - $CacheKey = 'byMoon'; - } - - if(isset($_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]) && $_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']] > 0) - { - if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['metal'])) - { - $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['metal'] = 0; - } - if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'])) - { - $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'] = 0; - } - - $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['metal'] += $TotalLostMetal; - $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'] += $TotalLostCrystal; - $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['updated'] = true; - $_FleetCache['updated']['galaxy'] = true; - } - else - { - $Query_UpdateGalaxy = ''; - $Query_UpdateGalaxy .= "UPDATE {{table}} SET `metal` = `metal` + {$TotalLostMetal}, `crystal` = `crystal` + {$TotalLostCrystal} "; - $Query_UpdateGalaxy .= "WHERE `{$Query_UpdateGalaxy_SearchField}` = {$FleetRow['fleet_end_id']} LIMIT 1; "; - $Query_UpdateGalaxy .= "-- MISSION ATTACK [Q02][FID: {$FleetRow['fleet_id']}]"; - doquery($Query_UpdateGalaxy, 'galaxy'); - } - } - - // Check if Moon has been created - $FleetDebris = $TotalLostCrystal + $TotalLostMetal; - - $MoonChance = floor($FleetDebris / COMBAT_MOONPERCENT_RESOURCES); - if($MoonChance > 20) - { - $TotalMoonChance = $MoonChance; - $MoonChance = 20; - } - if($MoonChance < 1) - { - $UserChance = 0; - } - elseif($MoonChance >= 1) - { - $UserChance = mt_rand(1, 100); - } - - if(($UserChance > 0) AND ($UserChance <= $MoonChance)) - { - if($TargetPlanet['planet_type'] == 1) - { - $CreatedMoonID = CreateOneMoonRecord($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetUserID, '', $MoonChance); - if($CreatedMoonID !== false) - { - $TriggerTasksCheck['CREATE_MOON'] = true; - $MoonHasBeenCreated = true; - - $UserDev_UpPl[] = "L,{$CreatedMoonID}"; - - // Update User Stats - foreach($AttackersIDs as $UserID) - { - $UserStatsData[$UserID]['moons_created'] += 1; - } - } - else - { - $MoonHasBeenCreated = false; - } - } - else - { - $MoonHasBeenCreated = false; - } - } - elseif($UserChance = 0 or $UserChance > $MoonChance) - { - $MoonHasBeenCreated = false; - } - - // Create DevLog Record (PlanetDefender's) - if(!empty($UserDev_UpPl) AND !$IsAbandoned) - { - $UserDev_Log[] = array('UserID' => $TargetUserID, 'PlanetID' => $TargetPlanetID, 'Date' => $FleetRow['fleet_start_time'], 'Place' => 12, 'Code' => '1', 'ElementID' => '0', 'AdditionalData' => implode(';', $UserDev_UpPl)); - } - - // Morale System - if(MORALE_ENABLED AND !$IsAbandoned AND !$IsAllyFight AND $IdleHours < (7 * 24)) - { - $Morale_Factor = $FleetRow['morale_points'] / $TargetUser['morale_points']; - if($Morale_Factor < 1) - { - $Morale_Factor = pow($Morale_Factor, -1); - $Morale_AttackerStronger = false; - } - else - { - $Morale_AttackerStronger = true; - } - - if($Morale_Factor > MORALE_MINIMALFACTOR) - { - if($Morale_AttackerStronger) - { - $Morale_Update_Attacker_Type = MORALE_NEGATIVE; - if($Result === COMBAT_DEF OR $Result === COMBAT_DRAW) - { - $Morale_Update_Defender = true; - } - } - else - { - $Morale_Update_Attacker_Type = MORALE_POSITIVE; - } - - $Morale_Updated = Morale_AddMorale($FleetRow, $Morale_Update_Attacker_Type, $Morale_Factor, 1, 1, $FleetRow['fleet_start_time']); - if($Morale_Updated) - { - $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['level'] = $FleetRow['morale_level']; - $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['droptime'] = $FleetRow['morale_droptime']; - $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['lastupdate'] = $FleetRow['morale_lastupdate']; - - $ReportData['morale'][$FleetRow['fleet_owner']] = array - ( - 'usertype' => 'atk', - 'type' => $Morale_Update_Attacker_Type, - 'factor' => $Morale_Factor, - 'level' => $FleetRow['morale_level'] - ); - } - - if($Morale_Update_Defender === true) - { - if($Result === COMBAT_DRAW) - { - $Morale_LevelFactor = 1/2; - $Morale_TimeFactor = 1/2; - } - else - { - $Morale_LevelFactor = 1; - $Morale_TimeFactor = 1; - } - - $Morale_Updated = Morale_AddMorale($TargetUser, MORALE_POSITIVE, $Morale_Factor, $Morale_LevelFactor, $Morale_TimeFactor, $FleetRow['fleet_start_time']); - if($Morale_Updated) - { - $_FleetCache['MoraleCache'][$TargetUser['id']]['level'] = $TargetUser['morale_level']; - $_FleetCache['MoraleCache'][$TargetUser['id']]['droptime'] = $TargetUser['morale_droptime']; - $_FleetCache['MoraleCache'][$TargetUser['id']]['lastupdate'] = $TargetUser['morale_lastupdate']; - - $ReportData['morale'][$TargetUser['id']] = array - ( - 'usertype' => 'def', - 'type' => MORALE_POSITIVE, - 'factor' => $Morale_Factor, - 'level' => $TargetUser['morale_level'] - ); - } - } - } - } - - // CREATE BATTLE REPORT - $ReportData['init']['usr']['atk'] = $AttackersData; - $ReportData['init']['usr']['def'] = $DefendersData; - $ReportData['init']['time'] = $totaltime; - $ReportData['init']['date'] = $FleetRow['fleet_start_time']; - - $ReportData['init']['result'] = $Result; - $ReportData['init']['met'] = $StolenMet; - $ReportData['init']['cry'] = $StolenCry; - $ReportData['init']['deu'] = $StolenDeu; - $ReportData['init']['deb_met'] = $TotalLostMetal; - $ReportData['init']['deb_cry'] = $TotalLostCrystal; - $ReportData['init']['moon_chance'] = $MoonChance; - $ReportData['init']['moon_created'] = $MoonHasBeenCreated; - $ReportData['init']['total_moon_chance'] = $TotalMoonChance; - $ReportData['init']['moon_destroyed'] = false; - $ReportData['init']['moon_des_chance'] = 0; - $ReportData['init']['fleet_destroyed'] = false; - $ReportData['init']['fleet_des_chance'] = 0; - $ReportData['init']['planet_name'] = $TargetPlanetGetName; - $ReportData['init']['onMoon'] = ($FleetRow['fleet_end_type'] == 3 ? true : false); - $ReportData['init']['atk_lost'] = $RealDebrisMetalAtk + $RealDebrisCrystalAtk + $RealDebrisDeuteriumAtk; - $ReportData['init']['def_lost'] = $RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef; - - foreach($RoundsData as $RoundKey => $RoundData) - { - foreach($RoundData as $MainKey => $RoundData2) - { - if(!empty($RoundData2['ships'])) - { - foreach($RoundData2['ships'] as $UserKey => $UserData) - { - $RoundsData[$RoundKey][$MainKey]['ships'][$UserKey] = Array2String($UserData); - } - } - } - } - $ReportData['rounds'] = $RoundsData; - - if(count($RoundsData) <= 2 AND $Result === COMBAT_DEF) - { - $DisallowAttackers = true; - } - else - { - $DisallowAttackers = false; - } - - $CreatedReport = CreateBattleReport($ReportData, array('atk' => $AttackersIDs, 'def' => $DefendersIDs), $DisallowAttackers); - $ReportID = $CreatedReport['ID']; - $ReportHasHLinkRelative = 'battlereport.php?hash='.$CreatedReport['Hash']; - $ReportHasHLinkReal = GAMEURL.$ReportHasHLinkRelative; - - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_ReportID'] = $ReportID; - if(!empty($DefendingFleetID)) - { - foreach($DefendingFleetID as $FleetID) - { - $Return['FleetArchive'][$FleetID]['Fleet_DefenderReportIDs'] = "\"+,{$ReportID}\""; - } - } - - // Update battle stats & set Battle Report colors - if(!$IsAllyFight) - { - if($Result === COMBAT_ATK) - { - foreach($AttackersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_won'] += 1; - } - foreach($DefendersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_lost'] += 1; - } - $ReportColor = 'green'; - $ReportColor2 = 'red'; - } - elseif($Result === COMBAT_DRAW) - { - foreach($AttackersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_draw'] += 1; - } - foreach($DefendersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_draw'] += 1; - } - $ReportColor = 'orange'; - $ReportColor2 = 'orange'; - } - elseif($Result === COMBAT_DEF) - { - foreach($AttackersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_lost'] += 1; - } - foreach($DefendersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_won'] += 1; - } - $ReportColor = 'red'; - $ReportColor2 = 'green'; - } - - // Update User Destroyed & Lost Stats - if(!empty($ShotDown)) - { - foreach($ShotDown as $ThisType => $ThisData) - { - foreach($ThisData as $ThisType2 => $ThisData2) - { - if($ThisType2 == 'd') - { - $ThisKey = 'destroyed_'; - } - else - { - $ThisKey = 'lost_'; - } - foreach($ThisData2 as $UserID => $DestShips) - { - if($UserID == 0) - { - if($ThisType == 'atk') - { - $ThisUserID = $FleetRow['fleet_owner']; - } - else - { - $ThisUserID = $TargetUser['id']; - } - } - else - { - if($ThisType == 'atk') - { - $ThisUserID = $AttackingFleetOwners[$AttackingFleetID[$UserID]]; - } - else - { - $ThisUserID = $DefendingFleetOwners[$DefendingFleetID[$UserID]]; - } - } - foreach($DestShips as $ShipID => $ShipCount) - { - $UserStatsData[$ThisUserID][$ThisKey.$ShipID] += $ShipCount; - } - } - } - } - } - - if(!empty($ShotDown)) - { - if(!empty($ShotDown['atk']['d'][0])) - { - if(!isset($TriggerTasksCheck['BATTLE_DESTROY_MILITARYUNITS'])) - { - $TriggerTasksCheck['BATTLE_DESTROY_MILITARYUNITS'] = 0; - } - if(!isset($TriggerTasksCheck['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'])) - { - $TriggerTasksCheck['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'] = 0; - } - foreach($ShotDown['atk']['d'][0] as $ShipID => $ShipCount) - { - $TriggerTasksCheck['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'] += (($_Vars_Prices[$ShipID]['metal'] + $_Vars_Prices[$ShipID]['crystal'] + $_Vars_Prices[$ShipID]['deuterium']) * $ShipCount); - if(in_array($ShipID, $_Vars_ElementCategories['units']['military'])) - { - $TriggerTasksCheck['BATTLE_DESTROY_MILITARYUNITS'] += $ShipCount; - } - } - } - } - - if($Result === COMBAT_ATK) - { - $TriggerTasksCheck['BATTLE_WIN'] = true; - $TriggerTasksCheck['BATTLE_WINORDRAW_SOLO_TOTALLIMIT'] = true; - $TriggerTasksCheck['BATTLE_WINORDRAW_SOLO_LIMIT'] = true; - $TriggerTasksCheck['BATTLE_WINORDRAW_LIMIT'] = true; - } - elseif($Result === COMBAT_DRAW) - { - $TriggerTasksCheck['BATTLE_WINORDRAW_SOLO_TOTALLIMIT'] = true; - $TriggerTasksCheck['BATTLE_WINORDRAW_SOLO_LIMIT'] = true; - $TriggerTasksCheck['BATTLE_WINORDRAW_LIMIT'] = true; - } - elseif($Result === COMBAT_DEF) - { - $TriggerTasksCheck['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'] = 0; - } - } - else - { - if($MoonHasBeenCreated) - { - $TriggerTasksCheck['CREATE_MOON_FRIENDLY'] = true; - } - unset($TriggerTasksCheck['BATTLE_COLLECT_METAL']); - unset($TriggerTasksCheck['BATTLE_COLLECT_CRYSTAL']); - unset($TriggerTasksCheck['BATTLE_COLLECT_DEUTERIUM']); - - foreach($AttackersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_inAlly'] += 1; - } - foreach($DefendersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_inAlly'] += 1; - } - if($Result === COMBAT_ATK) - { - $ReportColor = 'green'; - $ReportColor2 = 'red'; - } - elseif($Result === COMBAT_DRAW) - { - $ReportColor = 'orange'; - $ReportColor2 = 'orange'; - } - elseif($Result === COMBAT_DEF) - { - $ReportColor = 'red'; - $ReportColor2 = 'green'; - } - } - - $TargetTypeMsg = $_Lang['BR_Target_'.$FleetRow['fleet_end_type']]; - $Message['msg_id'] = '071'; - $Message['args'] = array - ( - $ReportID, $ReportColor, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetTypeMsg, - prettyNumber($RealDebrisMetalAtk + $RealDebrisCrystalAtk + $RealDebrisDeuteriumAtk), - prettyNumber($RealDebrisCrystalDef + $RealDebrisMetalDef + $RealDebrisDeuteriumDef), - prettyNumber($StolenMet), prettyNumber($StolenCry), prettyNumber($StolenDeu), - prettyNumber(isset($TotalLostMetal) ? $TotalLostMetal : 0), prettyNumber(isset($TotalLostCrystal) ? $TotalLostCrystal : 0), - $ReportHasHLinkRelative, $ReportHasHLinkReal - ); - $Message = json_encode($Message); - Cache_Message($CurrentUserID, 0, $FleetRow['fleet_start_time'], 3, '003', '012', $Message); - - if(!$IsAbandoned) - { - $Message = false; - $Message['msg_id'] = '074'; - if(!empty($Rebuilt) AND (array)$Rebuilt === $Rebuilt) - { - foreach($Rebuilt as $SysID => $Count) - { - $RebuildReport[] = ''.$_Lang['tech'][$SysID].' - '.$Count; - } - $RebuildReport = implode('
    ', $RebuildReport); - } - else - { - if(!isset($DefSysLostIDs) || count($DefSysLostIDs) == 1) - { - $RebuildReport = $_Lang['no_loses_in_defence']; - } - else - { - $RebuildReport = $_Lang['nothing_have_been_rebuilt']; - } - } - $Message['args'] = array($ReportID, $ReportColor2, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetTypeMsg, $RebuildReport, $ReportHasHLinkRelative, $ReportHasHLinkReal); - $Message = json_encode($Message); - Cache_Message($TargetUserID, 0, $FleetRow['fleet_start_time'], 3, '003', '012', $Message); - } - - if(count($DefendersIDs) > 1) - { - $Message = false; - $Message['msg_id'] = '075'; - $Message['args'] = array($ReportID, $ReportColor2, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetTypeMsg, $ReportHasHLinkRelative, $ReportHasHLinkReal); - $Message = json_encode($Message); - unset($DefendersIDs[0]); - Cache_Message($DefendersIDs, 0, $FleetRow['fleet_start_time'], 3, '003', '017', $Message); - } - - if(!empty($TriggerTasksCheck)) - { - global $GlobalParsedTasks, $_User; - - if($_User['id'] == $FleetRow['fleet_owner']) - { - $ThisTaskUser = $_User; - } - else - { - if(empty($GlobalParsedTasks[$FleetRow['fleet_owner']]['tasks_done_parsed'])) - { - $GetUserTasksDone['tasks_done'] = $_FleetCache['userTasks'][$FleetRow['fleet_owner']]; - Tasks_CheckUservar($GetUserTasksDone); - $GlobalParsedTasks[$FleetRow['fleet_owner']] = $GetUserTasksDone; - } - $ThisTaskUser = $GlobalParsedTasks[$FleetRow['fleet_owner']]; - $ThisTaskUser['id'] = $FleetRow['fleet_owner']; - } - - if(isset($TriggerTasksCheck['BATTLE_WIN'])) - { - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WIN', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - if(isset($TriggerTasksCheck['BATTLE_WINORDRAW_SOLO_TOTALLIMIT']) && $TotalMoonChance > 0) - { - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WINORDRAW_SOLO_TOTALLIMIT', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TotalMoonChance) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TotalMoonChance); - } - )); - } - if(isset($TriggerTasksCheck['BATTLE_WINORDRAW_SOLO_LIMIT']) || isset($TriggerTasksCheck['BATTLE_WINORDRAW_LIMIT'])) - { - $Debris_Total_Def = ($DebrisMetalDef + $DebrisCrystalDef) / COMBAT_MOONPERCENT_RESOURCES; - if(isset($TriggerTasksCheck['BATTLE_WINORDRAW_SOLO_LIMIT'])) - { - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WINORDRAW_SOLO_LIMIT', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $Debris_Total_Def) - { - if($JobArray['minimalEnemyPercentLimit'] > $Debris_Total_Def) - { - return true; - } - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - if(isset($TriggerTasksCheck['BATTLE_WINORDRAW_LIMIT'])) - { - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WINORDRAW_LIMIT', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $Debris_Total_Def) - { - if($JobArray['minimalEnemyPercentLimit'] > $Debris_Total_Def) - { - return true; - } - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - } - if(isset($TriggerTasksCheck['BATTLE_COLLECT_METAL']) && $TriggerTasksCheck['BATTLE_COLLECT_METAL'] > 0) - { - $TaskTemp = $TriggerTasksCheck['BATTLE_COLLECT_METAL']; - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_METAL', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); - } - )); - } - if(isset($TriggerTasksCheck['BATTLE_COLLECT_CRYSTAL']) && $TriggerTasksCheck['BATTLE_COLLECT_CRYSTAL'] > 0) - { - $TaskTemp = $TriggerTasksCheck['BATTLE_COLLECT_CRYSTAL']; - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_CRYSTAL', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); - } - )); - } - if(isset($TriggerTasksCheck['BATTLE_COLLECT_DEUTERIUM']) && $TriggerTasksCheck['BATTLE_COLLECT_DEUTERIUM'] > 0) - { - $TaskTemp = $TriggerTasksCheck['BATTLE_COLLECT_DEUTERIUM']; - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_DEUTERIUM', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); - } - )); - } - if(isset($TriggerTasksCheck['CREATE_MOON'])) - { - Tasks_TriggerTask($ThisTaskUser, 'CREATE_MOON', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - if(isset($TriggerTasksCheck['CREATE_MOON_FRIENDLY'])) - { - Tasks_TriggerTask($ThisTaskUser, 'CREATE_MOON_FRIENDLY', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - if(isset($TriggerTasksCheck['BATTLE_DESTROY_MILITARYUNITS']) && $TriggerTasksCheck['BATTLE_DESTROY_MILITARYUNITS'] > 0) - { - $TaskTemp = $TriggerTasksCheck['BATTLE_DESTROY_MILITARYUNITS']; - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_DESTROY_MILITARYUNITS', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); - } - )); - } - if(isset($TriggerTasksCheck['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO']) && $TriggerTasksCheck['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'] > 0) - { - $TaskTemp2 = 0; - foreach($AttackingFleets[0] as $ShipID => $ShipCount) - { - $TaskTemp2 += (($_Vars_Prices[$ShipID]['metal'] + $_Vars_Prices[$ShipID]['crystal'] + $_Vars_Prices[$ShipID]['deuterium']) * $ShipCount); - } - $TaskTemp = $TriggerTasksCheck['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO']; - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp, $TaskTemp2) - { - if($JobArray['minimalEnemyCost'] > $TaskTemp) - { - return true; - } - if($TaskTemp2 > ($TaskTemp * $JobArray['maximalOwnValue'])) - { - return true; - } - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - } - } - - if($FleetRow['calcType'] == 3 && (!isset($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed']) || $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] !== true)) - { - if(!empty($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']])) - { - foreach($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']] as $Key => $Value) - { - $FleetRow[$Key] = $Value; - } - } - $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack'] = true; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack_Time'] = $Now; - RestoreFleetToPlanet($FleetRow, true, $_FleetCache); - } - - return $Return; -} - -?> \ No newline at end of file + 0 ? false : true); + $TargetPlanet = &$_FleetCache['planets'][$FleetRow['fleet_end_id']]; + $TargetUser = &$_FleetCache['users'][$FleetRow['fleet_target_owner']]; + $IsAllyFight = (($FleetRow['ally_id'] == 0 OR ($FleetRow['ally_id'] != $TargetUser['ally_id'])) ? false : true); + + // Update planet before attack begins + $UpdateResult = HandleFullUserUpdate($TargetUser, $TargetPlanet, $_FleetCache['planets'][$TargetUser['techQueue_Planet']], $FleetRow['fleet_start_time'], true, true); + if(!empty($UpdateResult)) + { + foreach($UpdateResult as $PlanetID => $Value) + { + if($Value === true) + { + $_FleetCache['updatePlanets'][$PlanetID] = true; + } + } + } + + $TargetUserID = $TargetPlanet['id_owner']; + $TargetPlanetGetName = $TargetPlanet['name']; + $TargetPlanetID = $TargetPlanet['id']; + + if(!$IsAbandoned) + { + $IdleHours = floor(($FleetRow['fleet_start_time'] - $TargetUser['onlinetime']) / 3600); + if($IdleHours > 0) + { + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Owner_IdleHours'] = $IdleHours; + } + } + + // Create data arrays for attacker and main defender + $CurrentUserID = $FleetRow['fleet_owner']; + $DefendersIDs[] = $TargetUser['id']; + $AttackersIDs[] = $FleetRow['fleet_owner']; + $AttackingFleets = array(); + $DefendingFleets = array(); + + $DefendingTechs[0] = array + ( + 109 => $TargetUser['tech_weapons'], + 110 => $TargetUser['tech_armour'], + 111 => $TargetUser['tech_shielding'], + 120 => $TargetUser['tech_laser'], + 121 => $TargetUser['tech_ion'], + 122 => $TargetUser['tech_plasma'], + 125 => $TargetUser['tech_antimatter'], + 126 => $TargetUser['tech_disintegration'], + 199 => $TargetUser['tech_graviton'] + ); + $DefendersData[0] = array + ( + 'id' => $TargetUser['id'], + 'username' => $TargetUser['username'], + 'techs' => Array2String($DefendingTechs[0]), + 'pos' => "{$FleetRow['fleet_end_galaxy']}:{$FleetRow['fleet_end_system']}:{$FleetRow['fleet_end_planet']}" + ); + if(!empty($TargetUser['ally_tag'])) + { + $DefendersData[0]['ally'] = $TargetUser['ally_tag']; + } + + $AttackingTechs[0] = array + ( + 109 => $FleetRow['tech_weapons'], + 110 => $FleetRow['tech_armour'], + 111 => $FleetRow['tech_shielding'], + 120 => $FleetRow['tech_laser'], + 121 => $FleetRow['tech_ion'], + 122 => $FleetRow['tech_plasma'], + 125 => $FleetRow['tech_antimatter'], + 126 => $FleetRow['tech_disintegration'], + 199 => $FleetRow['tech_graviton'] + ); + $AttackersData[0] = array + ( + 'id' => $FleetRow['fleet_owner'], + 'username' => $FleetRow['username'], + 'techs' => Array2String($AttackingTechs[0]), + 'pos' => "{$FleetRow['fleet_start_galaxy']}:{$FleetRow['fleet_start_system']}:{$FleetRow['fleet_start_planet']}" + ); + if(!empty($FleetRow['ally_tag'])) + { + $AttackersData[0]['ally'] = $FleetRow['ally_tag']; + } + + // MoraleSystem Init + if(MORALE_ENABLED) + { + if(!empty($_FleetCache['MoraleCache'][$FleetRow['fleet_owner']])) + { + $FleetRow['morale_level'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['level']; + $FleetRow['morale_droptime'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['droptime']; + $FleetRow['morale_lastupdate'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['lastupdate']; + } + Morale_ReCalculate($FleetRow, $FleetRow['fleet_start_time']); + $AttackersData[0]['morale'] = $FleetRow['morale_level']; + $AttackersData[0]['moralePoints'] = $FleetRow['morale_points']; + + // Bonuses + if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETPOWERUP1) + { + $AttackingTechs[0]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; + } + if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETSHIELDUP1) + { + $AttackingTechs[0]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; + } + if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETSDADDITION) + { + $AttackingTechs[0]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; + } + // Penalties + if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN1) + { + $AttackingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; + } + if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN2) + { + $AttackingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; + } + if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) + { + $AttackingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; + } + if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) + { + $AttackingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; + } + if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSDDOWN) + { + $AttackingTechs[0]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; + } + + if(!$IsAbandoned) + { + if(!empty($_FleetCache['MoraleCache'][$TargetUser['id']])) + { + $TargetUser['morale_level'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['level']; + $TargetUser['morale_droptime'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['droptime']; + $TargetUser['morale_lastupdate'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['lastupdate']; + } + Morale_ReCalculate($TargetUser, $FleetRow['fleet_start_time']); + $DefendersData[0]['morale'] = $TargetUser['morale_level']; + $DefendersData[0]['moralePoints'] = $TargetUser['morale_points']; + + // Bonuses + if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETPOWERUP1) + { + $DefendingTechs[0]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; + } + if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETSHIELDUP1) + { + $DefendingTechs[0]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; + } + if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETSDADDITION) + { + $DefendingTechs[0]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; + } + // Penalties + if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN1) + { + $DefendingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; + } + if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN2) + { + $DefendingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; + } + if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) + { + $DefendingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; + } + if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) + { + $DefendingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; + } + if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSDDOWN) + { + $DefendingTechs[0]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; + } + } + } + + // Select All Defending Fleets on the Orbit from $_FleetCache + if(!empty($_FleetCache['defFleets'][$FleetRow['fleet_end_id']])) + { + $i = 1; + foreach($_FleetCache['defFleets'][$FleetRow['fleet_end_id']] as $FleetData) + { + if($_FleetCache['fleetRowStatus'][$FleetData['fleet_id']]['isDestroyed'] !== true) + { + $DefendingFleets[$i] = String2Array($FleetData['fleet_array']); + $DefendingFleetID[$i] = $FleetData['fleet_id']; + $DefendingTechs[$i] = array + ( + 109 => $FleetData['tech_weapons'], + 110 => $FleetData['tech_armour'], + 111 => $FleetData['tech_shielding'], + 120 => $FleetData['tech_laser'], + 121 => $FleetData['tech_ion'], + 122 => $FleetData['tech_plasma'], + 125 => $FleetData['tech_antimatter'], + 126 => $FleetData['tech_disintegration'], + 199 => $FleetData['tech_graviton'] + ); + $DefendersData[$i] = array + ( + 'id' => $FleetData['fleet_owner'], + 'username' => $FleetData['username'], + 'techs' => Array2String($DefendingTechs[$i]), + 'pos' => "{$FleetData['fleet_start_galaxy']}:{$FleetData['fleet_start_system']}:{$FleetData['fleet_start_planet']}" + ); + if(!empty($FleetData['ally_tag'])) + { + $DefendersData[$i]['ally'] = $FleetData['ally_tag']; + } + if(!in_array($FleetData['fleet_owner'], $DefendersIDs)) + { + $DefendersIDs[] = $FleetData['fleet_owner']; + } + $DefendingFleetOwners[$FleetData['fleet_id']] = $FleetData['fleet_owner']; + + if(MORALE_ENABLED) + { + if(empty($_TempCache['MoraleCache'][$FleetData['fleet_owner']])) + { + if(!empty($_FleetCache['MoraleCache'][$FleetData['fleet_owner']])) + { + $FleetData['morale_level'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['level']; + $FleetData['morale_droptime'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['droptime']; + $FleetData['morale_lastupdate'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['lastupdate']; + } + Morale_ReCalculate($FleetData, $FleetRow['fleet_start_time']); + $DefendersData[$i]['morale'] = $FleetData['morale_level']; + $DefendersData[$i]['moralePoints'] = $FleetData['morale_points']; + + $_TempCache['MoraleCache'][$FleetData['fleet_owner']] = array + ( + 'level' => $FleetData['morale_level'], + 'points' => $FleetData['morale_points'] + ); + } + else + { + $DefendersData[$i]['morale'] = $_TempCache['MoraleCache'][$FleetData['fleet_owner']]['level']; + $DefendersData[$i]['moralePoints'] = $_TempCache['MoraleCache'][$FleetData['fleet_owner']]['points']; + } + + // Bonuses + if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETPOWERUP1) + { + $DefendingTechs[$i]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; + } + if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETSHIELDUP1) + { + $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; + } + if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETSDADDITION) + { + $DefendingTechs[$i]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; + } + // Penalties + if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN1) + { + $DefendingTechs[$i]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; + } + if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN2) + { + $DefendingTechs[$i]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; + } + if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) + { + $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; + } + if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) + { + $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; + } + if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSDDOWN) + { + $DefendingTechs[$i]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; + } + } + + $i += 1; + } + } + } + + foreach($AttackersIDs as $ID) + { + if(empty($UserStatsData[$ID])) + { + $UserStatsData[$ID] = $UserStatsPattern; + } + } + foreach($DefendersIDs as $ID) + { + if(empty($UserStatsData[$ID])) + { + $UserStatsData[$ID] = $UserStatsPattern; + } + } + + // Create main defender fleet array + foreach($_Vars_ElementCategories['fleet'] as $ElementID) + { + if($TargetPlanet[$_Vars_GameElements[$ElementID]] > 0) + { + $DefendingFleets[0][$ElementID] = $TargetPlanet[$_Vars_GameElements[$ElementID]]; + } + } + foreach($_Vars_ElementCategories['defense'] as $ElementID) + { + if(in_array($ElementID, $_Vars_ElementCategories['rockets'])) + { + continue; + } + if($TargetPlanet[$_Vars_GameElements[$ElementID]] > 0) + { + $DefendingFleets[0][$ElementID] = $TargetPlanet[$_Vars_GameElements[$ElementID]]; + } + } + + // Create attacker fleet array + $AttackingFleets[0] = String2Array($FleetRow['fleet_array']); + + $StartTime = microtime(true); + + // Now start Combat calculations + $Combat = Combat($AttackingFleets, $DefendingFleets, $AttackingTechs, $DefendingTechs); + + // Get the calculations time + $EndTime = microtime(true); + $totaltime = sprintf('%0.6f', $EndTime - $StartTime); + + $RealDebrisMetalAtk = 0; + $RealDebrisCrystalAtk = 0; + $RealDebrisDeuteriumAtk = 0; + $RealDebrisMetalDef = 0; + $RealDebrisCrystalDef = 0; + $RealDebrisDeuteriumDef = 0; + $TotalMoonChance = 0; + $TotalLostMetal = 0; + $TotalLostCrystal = 0; + $DebrisMetalDef = 0; + $DebrisCrystalDef = 0; + + $MoonHasBeenCreated = false; + + $RoundsData = $Combat['rounds']; + $Result = $Combat['result']; + $AtkShips = $Combat['AttackerShips']; + $DefShips = $Combat['DefenderShips']; + $AtkLost = $Combat['AtkLose']; + $DefLost = $Combat['DefLose']; + $DefSysLost = $Combat['DefSysLost']; + $ShotDown = $Combat['ShotDown']; + + $FleetStorage = 0; + // Parse result data - attacker fleet + if(!empty($AtkShips[0])) + { + $QryUpdateFleets[0]['id'] = $FleetRow['fleet_id']; + foreach($AtkShips[0] as $ID => $Count) + { + $QryUpdateFleets[0]['mess'] = '1'; + if($Count > 0) + { + if(!isset($QryUpdateFleets[0]['count'])) + { + $QryUpdateFleets[0]['count'] = 0; + } + $QryUpdateFleets[0]['array'][] = "{$ID},{$Count}"; + $QryUpdateFleets[0]['count'] += $Count; + } + if($Result === COMBAT_ATK && (!isset($_Vars_Prices[$ID]['cantPillage']) || $_Vars_Prices[$ID]['cantPillage'] !== true)) + { + $FleetStorage += $_Vars_Prices[$ID]['capacity'] * $Count; + } + + if($Count < $AttackingFleets[0][$ID]) + { + $UserDev_UpFl[$FleetRow['fleet_id']][] = $ID.','.($AttackingFleets[0][$ID] - $Count); + } + } + + foreach($AttackingFleets[0] as $ID => $Count) + { + $Difference = $Count; + if(isset($AtkShips[0][$ID])) + { + $Difference -= $AtkShips[0][$ID]; + } + if($Difference > 0) + { + $QryUpdateFleets[0]['array_lost'][] = "{$ID},{$Difference}"; + } + } + if(!empty($QryUpdateFleets[0]['array_lost'])) + { + $QryUpdateFleets[0]['array_lost'] = implode(';', $QryUpdateFleets[0]['array_lost']); + } + + if($Result === COMBAT_ATK) + { + $FleetStorage -= $FleetRow['fleet_resource_metal']; + $FleetStorage -= $FleetRow['fleet_resource_crystal']; + $FleetStorage -= $FleetRow['fleet_resource_deuterium']; + + if($FleetStorage > 0) + { + $ResourceSteal_Factor = (COMBAT_RESOURCESTEAL_PERCENT / 100); + if(MORALE_ENABLED) + { + if(!$IsAbandoned AND $TargetUser['morale_level'] <= MORALE_PENALTY_RESOURCELOSE) + { + $ResourceSteal_NewFactor[] = MORALE_PENALTY_RESOURCELOSE_STEALPERCENT; + } + if($FleetRow['morale_level'] >= MORALE_BONUS_SOLOIDLERSTEAL AND $IdleHours >= (7 * 24)) + { + $ResourceSteal_NewFactor[] = MORALE_BONUS_SOLOIDLERSTEAL_STEALPERCENT; + } + if($FleetRow['morale_level'] <= MORALE_PENALTY_STEAL) + { + $ResourceSteal_NewFactor[] = MORALE_PENALTY_STEAL_STEALPERCENT; + } + else if($FleetRow['morale_level'] <= MORALE_PENALTY_IDLERSTEAL AND $IdleHours >= (7 * 24)) + { + $ResourceSteal_NewFactor[] = MORALE_PENALTY_IDLERSTEAL_STEALPERCENT; + } + + if(!empty($ResourceSteal_NewFactor)) + { + $ResourceSteal_Factor = (array_sum($ResourceSteal_NewFactor) / count($ResourceSteal_NewFactor)) / 100; + } + } + + $StolenMet = 0; + $StolenCry = 0; + $StolenDeu = 0; + + $AllowTakeMoreMet = 0; + $AllowTakeMoreCry = 0; + $AllowTakeMoreDeu = 0; + + $MaxMetSteal = $TargetPlanet['metal'] * $ResourceSteal_Factor; + $MaxCrySteal = $TargetPlanet['crystal'] * $ResourceSteal_Factor; + $MaxDeuSteal = $TargetPlanet['deuterium'] * $ResourceSteal_Factor; + + $StoragePerResource = $FleetStorage / 3; + + // First - calculate, if any resource will leave free storage + if($MaxMetSteal < $StoragePerResource) + { + $AllowTakeMore = ($StoragePerResource - $MaxMetSteal) / 2; + $AllowTakeMoreCry += $AllowTakeMore; + $AllowTakeMoreDeu += $AllowTakeMore; + $GiveAwayMet = true; + } + + if($MaxCrySteal < ($StoragePerResource + $AllowTakeMoreCry)) + { + $AllowTakeMore = (($StoragePerResource + $AllowTakeMoreCry) - $MaxCrySteal) / 2; + if($GiveAwayMet == false) + { + $AllowTakeMoreMet += $AllowTakeMore; + $AllowTakeMoreDeu += $AllowTakeMore; + } + else + { + $AllowTakeMoreDeu += $AllowTakeMore * 2; + } + $GiveAwayCry = true; + } + + if($MaxDeuSteal < ($StoragePerResource + $AllowTakeMoreDeu)) + { + $AllowTakeMore = (($StoragePerResource + $AllowTakeMoreDeu) - $MaxDeuSteal) / 2; + if($GiveAwayCry == false) + { + $AllowTakeMoreMet += $AllowTakeMore; + $AllowTakeMoreCry += $AllowTakeMore; + } + else + { + $AllowTakeMoreMet += $AllowTakeMore * 2; + } + } + + // Second - calculate stolen resources + if($MaxMetSteal > ($StoragePerResource + $AllowTakeMoreMet)) + { + $StolenMet = $StoragePerResource + $AllowTakeMoreMet; + } + else + { + $StolenMet = $MaxMetSteal; + } + if($MaxCrySteal > ($StoragePerResource + $AllowTakeMoreCry)) + { + $StolenCry = $StoragePerResource + $AllowTakeMoreCry; + } + else + { + $StolenCry = $MaxCrySteal; + } + if($MaxDeuSteal > ($StoragePerResource + $AllowTakeMoreDeu)) + { + $StolenDeu = $StoragePerResource + $AllowTakeMoreDeu; + } + else + { + $StolenDeu = $MaxDeuSteal; + } + + $StolenMet = floor($StolenMet); + $StolenCry = floor($StolenCry); + $StolenDeu = floor($StolenDeu); + if($StolenMet > 0) + { + $UserDev_UpFl[$FleetRow['fleet_id']][] = 'M,'.$StolenMet; + $TriggerTasksCheck['BATTLE_COLLECT_METAL'] = $StolenMet; + } + if($StolenCry > 0) + { + $UserDev_UpFl[$FleetRow['fleet_id']][] = 'C,'.$StolenCry; + $TriggerTasksCheck['BATTLE_COLLECT_CRYSTAL'] = $StolenCry; + } + if($StolenDeu > 0) + { + $UserDev_UpFl[$FleetRow['fleet_id']][] = 'D,'.$StolenDeu; + $TriggerTasksCheck['BATTLE_COLLECT_DEUTERIUM'] = $StolenDeu; + } + + $QryUpdateFleets[0]['metal'] = $StolenMet; + $QryUpdateFleets[0]['crystal'] = $StolenCry; + $QryUpdateFleets[0]['deuterium'] = $StolenDeu; + + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Metal'] = $StolenMet; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Crystal'] = $StolenCry; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Deuterium'] = $StolenDeu; + } + } + } + else + { + $DeleteFleet[] = $FleetRow['fleet_id']; + foreach($AttackingFleets[0] as $ShipID => $ShipCount) + { + $UserDev_UpFl[$FleetRow['fleet_id']][] = $ShipID.','.$ShipCount; + } + + $fleetHasBeenDeleted = true; + } + + // Parse result data - Defenders + $i = 1; + if(!empty($DefendingFleets)) + { + foreach($DefendingFleets as $User => $Ships) + { + if($User == 0) + { + $DefSysLostIDs = array_keys($DefSysLost); + $DefSysLostIDs[] = -1; + + foreach($Ships as $ID => $Count) + { + if(in_array($ID, $DefSysLostIDs)) + { + $Count = $DefShips[0][$ID]; + $Chance = mt_rand(60, 80 + (($TargetUser['engineer_time'] >= $FleetRow['fleet_start_time']) ? 20 : 0)); + $Fluctuation = mt_rand(-15, 15); + if($Fluctuation > 0) + { + $Fluctuation = 0; + } + $Rebuilt[$ID] = round($DefSysLost[$ID] * (($Chance + $Fluctuation) / 100)); + $Count += $Rebuilt[$ID]; + if($DefendingFleets[0][$ID] < $Count) + { + $Count = $DefendingFleets[0][$ID]; + } + unset($DefSysLost[$ID]); + } + else + { + $Count = $DefShips[0][$ID]; + } + if($Count == 0) + { + $Count = '0'; + } + $TargetPlanet[$_Vars_GameElements[$ID]] = $Count; + if($Count < $DefendingFleets[0][$ID]) + { + $UserDev_UpPl[] = $ID.','.($DefendingFleets[0][$ID] - $Count); + $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; + $HPQ_PlanetUpdatedFields[] = $_Vars_GameElements[$ID]; + } + } + } + else + { + $QryUpdateFleets[$i]['id'] = $DefendingFleetID[$User]; + if(!empty($DefShips[$User])) + { + foreach($Ships as $ID => $Count) + { + $ThisCount = 0; + if(!empty($DefShips[$User][$ID])) + { + $OldCount = $Count; + $Count = $DefShips[$User][$ID]; + $ThisCount = $Count; + if($Count > 0) + { + if(!isset($QryUpdateFleets[$i]['count'])) + { + $QryUpdateFleets[$i]['count'] = 0; + } + $QryUpdateFleets[$i]['array'][] = "{$ID},{$Count}"; + $QryUpdateFleets[$i]['count'] += $Count; + } + $Difference = $OldCount - $Count; + if($Difference > 0) + { + $QryUpdateFleets[$i]['array_lost'][] = "{$ID},{$Difference}"; + } + } + + if($ThisCount < $DefendingFleets[$User][$ID]) + { + $UserDev_UpFl[$DefendingFleetID[$User]][] = $ID.','.($DefendingFleets[$User][$ID] - $ThisCount); + } + } + + if(!empty($QryUpdateFleets[$i]['array_lost'])) + { + $QryUpdateFleets[$i]['array_lost'] = implode(';', $QryUpdateFleets[$i]['array_lost']); + } + } + else + { + $DeleteFleet[] = $DefendingFleetID[$User]; + foreach($DefendingFleets[$User] as $ShipID => $ShipCount) + { + $UserDev_UpFl[$DefendingFleetID[$User]][] = "{$ShipID},{$ShipCount}"; + } + } + } + $i += 1; + } + } + + if($StolenMet > 0) + { + $TargetPlanet['metal'] -= $StolenMet; + $UserDev_UpPl[] = 'M,'.$StolenMet; + $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; + } + if($StolenCry > 0) + { + $TargetPlanet['crystal'] -= $StolenCry; + $UserDev_UpPl[] = 'C,'.$StolenCry; + $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; + } + if($StolenDeu > 0) + { + $TargetPlanet['deuterium'] -= $StolenDeu; + $UserDev_UpPl[] = 'D,'.$StolenDeu; + $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; + } + + // Update all fleets (if necessary) + if(!empty($QryUpdateFleets)) + { + foreach($QryUpdateFleets as $Data) + { + if(!empty($Data)) + { + if($Data['metal'] <= 0) + { + $Data['metal'] = '0'; + } + if($Data['crystal'] <= 0) + { + $Data['crystal'] = '0'; + } + if($Data['deuterium'] <= 0) + { + $Data['deuterium'] = '0'; + } + + if(!empty($Data['array'])) + { + $Data['array'] = implode(';', $Data['array']); + if(!empty($Data['array_lost'])) + { + if(strlen($Data['array']) > strlen($Data['array_lost'])) + { + $Return['FleetArchive'][$Data['id']]['Fleet_Array_Changes'] = "\"+D;{$Data['array_lost']}|\""; + } + else + { + $Return['FleetArchive'][$Data['id']]['Fleet_Array_Changes'] = "\"+L;{$Data['array']}|\""; + } + $Return['FleetArchive'][$Data['id']]['Fleet_Info_HasLostShips'] = '!true'; + } + if($Data['id'] != $FleetRow['fleet_id']) + { + $_FleetCache['defFleets'][$FleetRow['fleet_end_id']][$Data['id']]['fleet_array'] = $Data['array']; + } + } + + if($Data['id'] == $FleetRow['fleet_id'] AND $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['calcCount'] == 2) + { + // Update $_FleetCache, instead of sending additional Query to Update FleetState + // This fleet will be restored in this Calculation, so don't waste our time + $CachePointer = &$_FleetCache['fleetRowUpdate'][$Data['id']]; + $CachePointer['fleet_array'] = $Data['array']; + $CachePointer['fleet_resource_metal'] = $FleetRow['fleet_resource_metal'] + $Data['metal']; + $CachePointer['fleet_resource_crystal'] = $FleetRow['fleet_resource_crystal'] + $Data['crystal']; + $CachePointer['fleet_resource_deuterium'] = $FleetRow['fleet_resource_deuterium'] + $Data['deuterium']; + } + else + { + // Create UpdateFleet record for $_FleetCache + $CachePointer = &$_FleetCache['updateFleets'][$Data['id']]; + $CachePointer['fleet_array'] = $Data['array']; + $CachePointer['fleet_amount'] = $Data['count']; + $CachePointer['fleet_mess'] = $Data['mess']; + if(!isset($CachePointer['fleet_resource_metal'])) + { + $CachePointer['fleet_resource_metal'] = 0; + } + if(!isset($CachePointer['fleet_resource_crystal'])) + { + $CachePointer['fleet_resource_crystal'] = 0; + } + if(!isset($CachePointer['fleet_resource_deuterium'])) + { + $CachePointer['fleet_resource_deuterium'] = 0; + } + $CachePointer['fleet_resource_metal'] += $Data['metal']; + $CachePointer['fleet_resource_crystal'] += $Data['crystal']; + $CachePointer['fleet_resource_deuterium'] += $Data['deuterium']; + } + } + } + } + + if(!empty($UserDev_UpFl)) + { + foreach($UserDev_UpFl as $FleetID => $DevArray) + { + if($FleetID == $FleetRow['fleet_id']) + { + $SetCode = '2'; + $FleetUserID = $FleetRow['fleet_owner']; + } + else + { + $SetCode = '3'; + $FleetUserID = $DefendingFleetOwners[$FleetID]; + } + $UserDev_Log[] = array('UserID' => $FleetUserID, 'PlanetID' => '0', 'Date' => $FleetRow['fleet_start_time'], 'Place' => 12, 'Code' => $SetCode, 'ElementID' => $FleetID, 'AdditionalData' => implode(';', $DevArray)); + } + } + + // Calculate Debris & Looses - Init + $DebrisFactor_Fleet = $_GameConfig['Fleet_Cdr'] / 100; + $DebrisFactor_Defense = $_GameConfig['Defs_Cdr'] / 100; + + // Calculate looses - attacker + if(!empty($AtkLost)) + { + $DebrisMetalAtk = 0; + $DebrisCrystalAtk = 0; + foreach($AtkLost as $ID => $Count) + { + if(in_array($ID, $_Vars_ElementCategories['fleet'])) + { + if($DebrisFactor_Fleet > 0) + { + $DebrisMetalAtk += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Fleet); + $DebrisCrystalAtk += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Fleet); + } + $RealDebrisMetalAtk += floor($_Vars_Prices[$ID]['metal'] * $Count); + $RealDebrisCrystalAtk += floor($_Vars_Prices[$ID]['crystal'] * $Count); + $RealDebrisDeuteriumAtk += floor($_Vars_Prices[$ID]['deuterium'] * $Count); + } + } + $TotalLostMetal = $DebrisMetalAtk; + $TotalLostCrystal = $DebrisCrystalAtk; + } + // Calculate looses - defender + if(!empty($DefLost)) + { + foreach($DefLost as $ID => $Count) + { + if(in_array($ID, $_Vars_ElementCategories['fleet'])) + { + if($DebrisFactor_Fleet > 0) + { + $DebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Fleet); + $DebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Fleet); + } + } + elseif(in_array($ID, $_Vars_ElementCategories['defense'])) + { + if($DebrisFactor_Defense > 0) + { + $DebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Defense); + $DebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Defense); + } + } + $RealDebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count); + $RealDebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count); + $RealDebrisDeuteriumDef += floor($_Vars_Prices[$ID]['deuterium'] * $Count); + } + $TotalLostMetal += $DebrisMetalDef; + $TotalLostCrystal += $DebrisCrystalDef; + } + + // Delete fleets (if necessary) + if(!empty($DeleteFleet)) + { + foreach($DeleteFleet as $FleetID) + { + $_FleetCache['fleetRowStatus'][$FleetID]['isDestroyed'] = true; + if(!empty($_FleetCache['updateFleets'][$FleetID])) + { + unset($_FleetCache['updateFleets'][$FleetID]); + } + $Return['FleetsToDelete'][] = $FleetID; + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed'] = true; + $Return['FleetArchive'][$FleetID]['Fleet_Info_HasLostShips'] = true; + if($FleetID == $FleetRow['fleet_id']) + { + if($Result === COMBAT_DEF AND ($RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef) <= 0) + { + if(count($RoundsData) == 2) + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 1; + } + else + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 11; + } + } + else + { + if(count($RoundsData) == 2) + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 12; + } + else + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 2; + } + } + } + else + { + unset($_FleetCache['defFleets'][$FleetRow['fleet_end_id']][$FleetID]); + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 3; + } + } + } + + if($Result === COMBAT_DRAW AND (($RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef) <= 0)) + { + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed_Reason'] = 4; + } + + // Create debris field on the orbit + if($TotalLostMetal > 0 || $TotalLostCrystal > 0) + { + if($TotalLostCrystal == 0) + { + $TotalLostCrystal = '0'; + } + if($TotalLostMetal == 0) + { + $TotalLostMetal = '0'; + } + if($TargetPlanet['planet_type'] == 1) + { + $Query_UpdateGalaxy_SearchField = 'id_planet'; + $CacheKey = 'byPlanet'; + } + else + { + $Query_UpdateGalaxy_SearchField = 'id_moon'; + $CacheKey = 'byMoon'; + } + + if(isset($_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]) && $_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']] > 0) + { + if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['metal'])) + { + $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['metal'] = 0; + } + if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'])) + { + $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'] = 0; + } + + $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['metal'] += $TotalLostMetal; + $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'] += $TotalLostCrystal; + $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['updated'] = true; + $_FleetCache['updated']['galaxy'] = true; + } + else + { + $Query_UpdateGalaxy = ''; + $Query_UpdateGalaxy .= "UPDATE {{table}} SET `metal` = `metal` + {$TotalLostMetal}, `crystal` = `crystal` + {$TotalLostCrystal} "; + $Query_UpdateGalaxy .= "WHERE `{$Query_UpdateGalaxy_SearchField}` = {$FleetRow['fleet_end_id']} LIMIT 1; "; + $Query_UpdateGalaxy .= "-- MISSION ATTACK [Q02][FID: {$FleetRow['fleet_id']}]"; + doquery($Query_UpdateGalaxy, 'galaxy'); + } + } + + // Check if Moon has been created + $FleetDebris = $TotalLostCrystal + $TotalLostMetal; + + $MoonChance = floor($FleetDebris / COMBAT_MOONPERCENT_RESOURCES); + if($MoonChance > 20) + { + $TotalMoonChance = $MoonChance; + $MoonChance = 20; + } + if($MoonChance < 1) + { + $UserChance = 0; + } + elseif($MoonChance >= 1) + { + $UserChance = mt_rand(1, 100); + } + + if(($UserChance > 0) AND ($UserChance <= $MoonChance)) + { + if($TargetPlanet['planet_type'] == 1) + { + $CreatedMoonID = CreateOneMoonRecord($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetUserID, '', $MoonChance); + if($CreatedMoonID !== false) + { + $TriggerTasksCheck['CREATE_MOON'] = true; + $MoonHasBeenCreated = true; + + $UserDev_UpPl[] = "L,{$CreatedMoonID}"; + + // Update User Stats + foreach($AttackersIDs as $UserID) + { + $UserStatsData[$UserID]['moons_created'] += 1; + } + } + else + { + $MoonHasBeenCreated = false; + } + } + else + { + $MoonHasBeenCreated = false; + } + } + elseif($UserChance = 0 or $UserChance > $MoonChance) + { + $MoonHasBeenCreated = false; + } + + // Create DevLog Record (PlanetDefender's) + if(!empty($UserDev_UpPl) AND !$IsAbandoned) + { + $UserDev_Log[] = array('UserID' => $TargetUserID, 'PlanetID' => $TargetPlanetID, 'Date' => $FleetRow['fleet_start_time'], 'Place' => 12, 'Code' => '1', 'ElementID' => '0', 'AdditionalData' => implode(';', $UserDev_UpPl)); + } + + // Morale System + if(MORALE_ENABLED AND !$IsAbandoned AND !$IsAllyFight AND $IdleHours < (7 * 24)) + { + $Morale_Factor = $FleetRow['morale_points'] / $TargetUser['morale_points']; + if($Morale_Factor < 1) + { + $Morale_Factor = pow($Morale_Factor, -1); + $Morale_AttackerStronger = false; + } + else + { + $Morale_AttackerStronger = true; + } + + if($Morale_Factor > MORALE_MINIMALFACTOR) + { + if($Morale_AttackerStronger) + { + $Morale_Update_Attacker_Type = MORALE_NEGATIVE; + if($Result === COMBAT_DEF OR $Result === COMBAT_DRAW) + { + $Morale_Update_Defender = true; + } + } + else + { + $Morale_Update_Attacker_Type = MORALE_POSITIVE; + } + + $Morale_Updated = Morale_AddMorale($FleetRow, $Morale_Update_Attacker_Type, $Morale_Factor, 1, 1, $FleetRow['fleet_start_time']); + if($Morale_Updated) + { + $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['level'] = $FleetRow['morale_level']; + $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['droptime'] = $FleetRow['morale_droptime']; + $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['lastupdate'] = $FleetRow['morale_lastupdate']; + + $ReportData['morale'][$FleetRow['fleet_owner']] = array + ( + 'usertype' => 'atk', + 'type' => $Morale_Update_Attacker_Type, + 'factor' => $Morale_Factor, + 'level' => $FleetRow['morale_level'] + ); + } + + if($Morale_Update_Defender === true) + { + if($Result === COMBAT_DRAW) + { + $Morale_LevelFactor = 1/2; + $Morale_TimeFactor = 1/2; + } + else + { + $Morale_LevelFactor = 1; + $Morale_TimeFactor = 1; + } + + $Morale_Updated = Morale_AddMorale($TargetUser, MORALE_POSITIVE, $Morale_Factor, $Morale_LevelFactor, $Morale_TimeFactor, $FleetRow['fleet_start_time']); + if($Morale_Updated) + { + $_FleetCache['MoraleCache'][$TargetUser['id']]['level'] = $TargetUser['morale_level']; + $_FleetCache['MoraleCache'][$TargetUser['id']]['droptime'] = $TargetUser['morale_droptime']; + $_FleetCache['MoraleCache'][$TargetUser['id']]['lastupdate'] = $TargetUser['morale_lastupdate']; + + $ReportData['morale'][$TargetUser['id']] = array + ( + 'usertype' => 'def', + 'type' => MORALE_POSITIVE, + 'factor' => $Morale_Factor, + 'level' => $TargetUser['morale_level'] + ); + } + } + } + } + + // CREATE BATTLE REPORT + $ReportData['init']['usr']['atk'] = $AttackersData; + $ReportData['init']['usr']['def'] = $DefendersData; + $ReportData['init']['time'] = $totaltime; + $ReportData['init']['date'] = $FleetRow['fleet_start_time']; + + $ReportData['init']['result'] = $Result; + $ReportData['init']['met'] = $StolenMet; + $ReportData['init']['cry'] = $StolenCry; + $ReportData['init']['deu'] = $StolenDeu; + $ReportData['init']['deb_met'] = $TotalLostMetal; + $ReportData['init']['deb_cry'] = $TotalLostCrystal; + $ReportData['init']['moon_chance'] = $MoonChance; + $ReportData['init']['moon_created'] = $MoonHasBeenCreated; + $ReportData['init']['total_moon_chance'] = $TotalMoonChance; + $ReportData['init']['moon_destroyed'] = false; + $ReportData['init']['moon_des_chance'] = 0; + $ReportData['init']['fleet_destroyed'] = false; + $ReportData['init']['fleet_des_chance'] = 0; + $ReportData['init']['planet_name'] = $TargetPlanetGetName; + $ReportData['init']['onMoon'] = ($FleetRow['fleet_end_type'] == 3 ? true : false); + $ReportData['init']['atk_lost'] = $RealDebrisMetalAtk + $RealDebrisCrystalAtk + $RealDebrisDeuteriumAtk; + $ReportData['init']['def_lost'] = $RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef; + + foreach($RoundsData as $RoundKey => $RoundData) + { + foreach($RoundData as $MainKey => $RoundData2) + { + if(!empty($RoundData2['ships'])) + { + foreach($RoundData2['ships'] as $UserKey => $UserData) + { + $RoundsData[$RoundKey][$MainKey]['ships'][$UserKey] = Array2String($UserData); + } + } + } + } + $ReportData['rounds'] = $RoundsData; + + if(count($RoundsData) <= 2 AND $Result === COMBAT_DEF) + { + $DisallowAttackers = true; + } + else + { + $DisallowAttackers = false; + } + + $CreatedReport = CreateBattleReport($ReportData, array('atk' => $AttackersIDs, 'def' => $DefendersIDs), $DisallowAttackers); + $ReportID = $CreatedReport['ID']; + $ReportHasHLinkRelative = 'battlereport.php?hash='.$CreatedReport['Hash']; + $ReportHasHLinkReal = GAMEURL.$ReportHasHLinkRelative; + + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_ReportID'] = $ReportID; + if(!empty($DefendingFleetID)) + { + foreach($DefendingFleetID as $FleetID) + { + $Return['FleetArchive'][$FleetID]['Fleet_DefenderReportIDs'] = "\"+,{$ReportID}\""; + } + } + + // Update battle stats & set Battle Report colors + if(!$IsAllyFight) + { + if($Result === COMBAT_ATK) + { + foreach($AttackersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_won'] += 1; + } + foreach($DefendersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_lost'] += 1; + } + $ReportColor = 'green'; + $ReportColor2 = 'red'; + } + elseif($Result === COMBAT_DRAW) + { + foreach($AttackersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_draw'] += 1; + } + foreach($DefendersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_draw'] += 1; + } + $ReportColor = 'orange'; + $ReportColor2 = 'orange'; + } + elseif($Result === COMBAT_DEF) + { + foreach($AttackersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_lost'] += 1; + } + foreach($DefendersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_won'] += 1; + } + $ReportColor = 'red'; + $ReportColor2 = 'green'; + } + + // Update User Destroyed & Lost Stats + if(!empty($ShotDown)) + { + foreach($ShotDown as $ThisType => $ThisData) + { + foreach($ThisData as $ThisType2 => $ThisData2) + { + if($ThisType2 == 'd') + { + $ThisKey = 'destroyed_'; + } + else + { + $ThisKey = 'lost_'; + } + foreach($ThisData2 as $UserID => $DestShips) + { + if($UserID == 0) + { + if($ThisType == 'atk') + { + $ThisUserID = $FleetRow['fleet_owner']; + } + else + { + $ThisUserID = $TargetUser['id']; + } + } + else + { + if($ThisType == 'atk') + { + $ThisUserID = $AttackingFleetOwners[$AttackingFleetID[$UserID]]; + } + else + { + $ThisUserID = $DefendingFleetOwners[$DefendingFleetID[$UserID]]; + } + } + foreach($DestShips as $ShipID => $ShipCount) + { + $UserStatsData[$ThisUserID][$ThisKey.$ShipID] += $ShipCount; + } + } + } + } + } + + if(!empty($ShotDown)) + { + if(!empty($ShotDown['atk']['d'][0])) + { + if(!isset($TriggerTasksCheck['BATTLE_DESTROY_MILITARYUNITS'])) + { + $TriggerTasksCheck['BATTLE_DESTROY_MILITARYUNITS'] = 0; + } + if(!isset($TriggerTasksCheck['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'])) + { + $TriggerTasksCheck['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'] = 0; + } + foreach($ShotDown['atk']['d'][0] as $ShipID => $ShipCount) + { + $TriggerTasksCheck['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'] += (($_Vars_Prices[$ShipID]['metal'] + $_Vars_Prices[$ShipID]['crystal'] + $_Vars_Prices[$ShipID]['deuterium']) * $ShipCount); + if(in_array($ShipID, $_Vars_ElementCategories['units']['military'])) + { + $TriggerTasksCheck['BATTLE_DESTROY_MILITARYUNITS'] += $ShipCount; + } + } + } + } + + if($Result === COMBAT_ATK) + { + $TriggerTasksCheck['BATTLE_WIN'] = true; + $TriggerTasksCheck['BATTLE_WINORDRAW_SOLO_TOTALLIMIT'] = true; + $TriggerTasksCheck['BATTLE_WINORDRAW_SOLO_LIMIT'] = true; + $TriggerTasksCheck['BATTLE_WINORDRAW_LIMIT'] = true; + } + elseif($Result === COMBAT_DRAW) + { + $TriggerTasksCheck['BATTLE_WINORDRAW_SOLO_TOTALLIMIT'] = true; + $TriggerTasksCheck['BATTLE_WINORDRAW_SOLO_LIMIT'] = true; + $TriggerTasksCheck['BATTLE_WINORDRAW_LIMIT'] = true; + } + elseif($Result === COMBAT_DEF) + { + $TriggerTasksCheck['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'] = 0; + } + } + else + { + if($MoonHasBeenCreated) + { + $TriggerTasksCheck['CREATE_MOON_FRIENDLY'] = true; + } + unset($TriggerTasksCheck['BATTLE_COLLECT_METAL']); + unset($TriggerTasksCheck['BATTLE_COLLECT_CRYSTAL']); + unset($TriggerTasksCheck['BATTLE_COLLECT_DEUTERIUM']); + + foreach($AttackersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_inAlly'] += 1; + } + foreach($DefendersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_inAlly'] += 1; + } + if($Result === COMBAT_ATK) + { + $ReportColor = 'green'; + $ReportColor2 = 'red'; + } + elseif($Result === COMBAT_DRAW) + { + $ReportColor = 'orange'; + $ReportColor2 = 'orange'; + } + elseif($Result === COMBAT_DEF) + { + $ReportColor = 'red'; + $ReportColor2 = 'green'; + } + } + + $TargetTypeMsg = $_Lang['BR_Target_'.$FleetRow['fleet_end_type']]; + $Message['msg_id'] = '071'; + $Message['args'] = array + ( + $ReportID, $ReportColor, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetTypeMsg, + prettyNumber($RealDebrisMetalAtk + $RealDebrisCrystalAtk + $RealDebrisDeuteriumAtk), + prettyNumber($RealDebrisCrystalDef + $RealDebrisMetalDef + $RealDebrisDeuteriumDef), + prettyNumber($StolenMet), prettyNumber($StolenCry), prettyNumber($StolenDeu), + prettyNumber(isset($TotalLostMetal) ? $TotalLostMetal : 0), prettyNumber(isset($TotalLostCrystal) ? $TotalLostCrystal : 0), + $ReportHasHLinkRelative, $ReportHasHLinkReal + ); + $Message = json_encode($Message); + Cache_Message($CurrentUserID, 0, $FleetRow['fleet_start_time'], 3, '003', '012', $Message); + + if(!$IsAbandoned) + { + $Message = false; + $Message['msg_id'] = '074'; + if(!empty($Rebuilt) AND (array)$Rebuilt === $Rebuilt) + { + foreach($Rebuilt as $SysID => $Count) + { + $RebuildReport[] = ''.$_Lang['tech'][$SysID].' - '.$Count; + } + $RebuildReport = implode('
    ', $RebuildReport); + } + else + { + if(!isset($DefSysLostIDs) || count($DefSysLostIDs) == 1) + { + $RebuildReport = $_Lang['no_loses_in_defence']; + } + else + { + $RebuildReport = $_Lang['nothing_have_been_rebuilt']; + } + } + $Message['args'] = array($ReportID, $ReportColor2, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetTypeMsg, $RebuildReport, $ReportHasHLinkRelative, $ReportHasHLinkReal); + $Message = json_encode($Message); + Cache_Message($TargetUserID, 0, $FleetRow['fleet_start_time'], 3, '003', '012', $Message); + } + + if(count($DefendersIDs) > 1) + { + $Message = false; + $Message['msg_id'] = '075'; + $Message['args'] = array($ReportID, $ReportColor2, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetTypeMsg, $ReportHasHLinkRelative, $ReportHasHLinkReal); + $Message = json_encode($Message); + unset($DefendersIDs[0]); + Cache_Message($DefendersIDs, 0, $FleetRow['fleet_start_time'], 3, '003', '017', $Message); + } + + if(!empty($TriggerTasksCheck)) + { + global $GlobalParsedTasks, $_User; + + if($_User['id'] == $FleetRow['fleet_owner']) + { + $ThisTaskUser = $_User; + } + else + { + if(empty($GlobalParsedTasks[$FleetRow['fleet_owner']]['tasks_done_parsed'])) + { + $GetUserTasksDone['tasks_done'] = $_FleetCache['userTasks'][$FleetRow['fleet_owner']]; + Tasks_CheckUservar($GetUserTasksDone); + $GlobalParsedTasks[$FleetRow['fleet_owner']] = $GetUserTasksDone; + } + $ThisTaskUser = $GlobalParsedTasks[$FleetRow['fleet_owner']]; + $ThisTaskUser['id'] = $FleetRow['fleet_owner']; + } + + if(isset($TriggerTasksCheck['BATTLE_WIN'])) + { + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WIN', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + if(isset($TriggerTasksCheck['BATTLE_WINORDRAW_SOLO_TOTALLIMIT']) && $TotalMoonChance > 0) + { + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WINORDRAW_SOLO_TOTALLIMIT', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TotalMoonChance) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TotalMoonChance); + } + )); + } + if(isset($TriggerTasksCheck['BATTLE_WINORDRAW_SOLO_LIMIT']) || isset($TriggerTasksCheck['BATTLE_WINORDRAW_LIMIT'])) + { + $Debris_Total_Def = ($DebrisMetalDef + $DebrisCrystalDef) / COMBAT_MOONPERCENT_RESOURCES; + if(isset($TriggerTasksCheck['BATTLE_WINORDRAW_SOLO_LIMIT'])) + { + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WINORDRAW_SOLO_LIMIT', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $Debris_Total_Def) + { + if($JobArray['minimalEnemyPercentLimit'] > $Debris_Total_Def) + { + return true; + } + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + if(isset($TriggerTasksCheck['BATTLE_WINORDRAW_LIMIT'])) + { + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WINORDRAW_LIMIT', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $Debris_Total_Def) + { + if($JobArray['minimalEnemyPercentLimit'] > $Debris_Total_Def) + { + return true; + } + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + } + if(isset($TriggerTasksCheck['BATTLE_COLLECT_METAL']) && $TriggerTasksCheck['BATTLE_COLLECT_METAL'] > 0) + { + $TaskTemp = $TriggerTasksCheck['BATTLE_COLLECT_METAL']; + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_METAL', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); + } + )); + } + if(isset($TriggerTasksCheck['BATTLE_COLLECT_CRYSTAL']) && $TriggerTasksCheck['BATTLE_COLLECT_CRYSTAL'] > 0) + { + $TaskTemp = $TriggerTasksCheck['BATTLE_COLLECT_CRYSTAL']; + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_CRYSTAL', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); + } + )); + } + if(isset($TriggerTasksCheck['BATTLE_COLLECT_DEUTERIUM']) && $TriggerTasksCheck['BATTLE_COLLECT_DEUTERIUM'] > 0) + { + $TaskTemp = $TriggerTasksCheck['BATTLE_COLLECT_DEUTERIUM']; + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_DEUTERIUM', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); + } + )); + } + if(isset($TriggerTasksCheck['CREATE_MOON'])) + { + Tasks_TriggerTask($ThisTaskUser, 'CREATE_MOON', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + if(isset($TriggerTasksCheck['CREATE_MOON_FRIENDLY'])) + { + Tasks_TriggerTask($ThisTaskUser, 'CREATE_MOON_FRIENDLY', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + if(isset($TriggerTasksCheck['BATTLE_DESTROY_MILITARYUNITS']) && $TriggerTasksCheck['BATTLE_DESTROY_MILITARYUNITS'] > 0) + { + $TaskTemp = $TriggerTasksCheck['BATTLE_DESTROY_MILITARYUNITS']; + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_DESTROY_MILITARYUNITS', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); + } + )); + } + if(isset($TriggerTasksCheck['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO']) && $TriggerTasksCheck['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'] > 0) + { + $TaskTemp2 = 0; + foreach($AttackingFleets[0] as $ShipID => $ShipCount) + { + $TaskTemp2 += (($_Vars_Prices[$ShipID]['metal'] + $_Vars_Prices[$ShipID]['crystal'] + $_Vars_Prices[$ShipID]['deuterium']) * $ShipCount); + } + $TaskTemp = $TriggerTasksCheck['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO']; + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp, $TaskTemp2) + { + if($JobArray['minimalEnemyCost'] > $TaskTemp) + { + return true; + } + if($TaskTemp2 > ($TaskTemp * $JobArray['maximalOwnValue'])) + { + return true; + } + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + } + } + + if($FleetRow['calcType'] == 3 && (!isset($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed']) || $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] !== true)) + { + if(!empty($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']])) + { + foreach($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']] as $Key => $Value) + { + $FleetRow[$Key] = $Value; + } + } + $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack'] = true; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack_Time'] = $Now; + RestoreFleetToPlanet($FleetRow, true, $_FleetCache); + } + + return $Return; +} + +?> diff --git a/includes/functions/MissionCaseColonisation.php b/includes/functions/MissionCaseColonisation.php index bacb71d75..99ac19276 100644 --- a/includes/functions/MissionCaseColonisation.php +++ b/includes/functions/MissionCaseColonisation.php @@ -1,258 +1,258 @@ -= $MaxPlanets) - { - $Message = false; - $Message['msg_id'] = '018'; - $Message['args'] = array($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $MaxPlanets); - $Message = json_encode($Message); - Cache_Message($FleetRow['fleet_owner'], 0, $FleetRow['fleet_start_time'], 4, '003', '008', $Message); - - $UpdateFleet['fleet_mess'] = 1; - } - else - { - $NewPlanetRecord = CreateOnePlanetRecord - ( - $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], - $FleetRow['fleet_owner'], $_Lang['sys_colo_defaultname'], false, - array - ( - 'metal' => $FleetRow['fleet_resource_metal'], - 'crystal' => $FleetRow['fleet_resource_crystal'], - 'deuterium' => $FleetRow['fleet_resource_deuterium'] - ), true, true - ); - if($NewPlanetRecord !== false) - { - $Message = false; - $Message['msg_id'] = '019'; - $Message['args'] = array($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet']); - $Message = json_encode($Message); - Cache_Message($FleetRow['fleet_owner'], 0, $FleetRow['fleet_start_time'], 4, '003', '008', $Message); - - if($FleetRow['fleet_amount'] == 1) - { - $fleetHasBeenDeleted = true; - $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed'] = true; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed_Reason'] = 8; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Info_HasLostShips'] = true; - $SetCode = '1'; - } - else - { - $FleetRebuild = explode(';', $FleetRow['fleet_array']); - foreach($FleetRebuild as $Index => &$Ships) - { - if(!empty($Ships)) - { - $ExplodeShips = explode(',', $Ships); - if($ExplodeShips[0] == 208) - { - $ExplodeShips[1] -= 1; - if($ExplodeShips[1] > 0) - { - $Ships = implode(',', $ExplodeShips); - break; - } - else - { - unset($FleetRebuild[$Index]); - } - } - } - else - { - unset($FleetRebuild[$Index]); - } - } - $NewFleet = implode(';', $FleetRebuild); - - $UpdateFleet['fleet_mess'] = 1; - $UpdateFleet['fleet_array'] = $NewFleet; - $UpdateFleet['fleet_amount'] = $FleetRow['fleet_amount'] - 1; - $UpdateFleet['fleet_resource_metal'] = -$FleetRow['fleet_resource_metal']; - $UpdateFleet['fleet_resource_crystal'] = -$FleetRow['fleet_resource_crystal']; - $UpdateFleet['fleet_resource_deuterium'] = -$FleetRow['fleet_resource_deuterium']; - - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Array_Changes'] = '"D;208,1"'; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Info_HasLostShips'] = true; - - $SetCode = '2'; - } - - // Trigger Tasks Check - if($_User['id'] == $FleetRow['fleet_owner']) - { - $CurrentUser = $_User; - } - else - { - if(empty($GlobalParsedTasks[$FleetRow['fleet_owner']]['tasks_done_parsed'])) - { - $GetUserTasksDone['tasks_done'] = $_FleetCache['userTasks'][$FleetRow['fleet_owner']]; - Tasks_CheckUservar($GetUserTasksDone); - $GlobalParsedTasks[$FleetRow['fleet_owner']] = $GetUserTasksDone; - } - $CurrentUser = $GlobalParsedTasks[$FleetRow['fleet_owner']]; - $CurrentUser['id'] = $FleetRow['fleet_owner']; - } - Tasks_TriggerTask($CurrentUser, 'COLONIZE_PLANET', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($CurrentUser) - { - global $UserTasksUpdate; - if(!empty($UserTasksUpdate[$CurrentUser['id']]['status'][$ThisCat][$TaskID][$JobID])) - { - $CurrentUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$CurrentUser['id']]['status'][$ThisCat][$TaskID][$JobID]; - } - if(!isset($CurrentUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID])) - { - $CurrentUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = 0; - } - $CurrentUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] += 1; - if($CurrentUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] < $JobArray['count']) - { - $UserTasksUpdate[$CurrentUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $CurrentUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; - return true; - } - } - )); - - $UserDev_Log[] = array('UserID' => $FleetRow['fleet_owner'], 'PlanetID' => $NewPlanetRecord['ID'], 'Date' => $FleetRow['fleet_start_time'], 'Place' => 14, 'Code' => $SetCode, 'ElementID' => $FleetRow['fleet_id'], 'AdditionalData' => "M,{$NewPlanetRecord['metal']};C,{$NewPlanetRecord['crystal']};D,{$NewPlanetRecord['deuterium']};T,{$NewPlanetRecord['temp_max']}"); - } - else - { - $Message = false; - $Message['msg_id'] = '020'; - $Message['args'] = array($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet']); - $Message = json_encode($Message); - Cache_Message($FleetRow['fleet_owner'], 0, $FleetRow['fleet_start_time'], 4, '003', '008', $Message); - - $UpdateFleet['fleet_mess'] = 1; - } - } - } - else - { - $Message = false; - $Message['msg_id'] = '021'; - $Message['args'] = array($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet']); - $Message = json_encode($Message); - Cache_Message($FleetRow['fleet_owner'], 0, $FleetRow['fleet_end_time'], 4, '003', '008', $Message); - - $UpdateFleet['fleet_mess'] = 1; - } - - if($fleetHasBeenDeleted !== true) - { - if($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['calcCount'] == 1) - { - // Create UpdateFleet record for $_FleetCache - $CachePointer = &$_FleetCache['updateFleets'][$FleetRow['fleet_id']]; - $CachePointer['fleet_array'] = $UpdateFleet['fleet_array']; - $CachePointer['fleet_amount'] = $UpdateFleet['fleet_amount']; - $CachePointer['fleet_mess'] = $UpdateFleet['fleet_mess']; - if(!isset($CachePointer['fleet_resource_metal'])) - { - $CachePointer['fleet_resource_metal'] = 0; - } - if(!isset($CachePointer['fleet_resource_crystal'])) - { - $CachePointer['fleet_resource_crystal'] = 0; - } - if(!isset($CachePointer['fleet_resource_deuterium'])) - { - $CachePointer['fleet_resource_deuterium'] = 0; - } - $CachePointer['fleet_resource_metal'] += $UpdateFleet['fleet_resource_metal']; - $CachePointer['fleet_resource_crystal'] += $UpdateFleet['fleet_resource_crystal']; - $CachePointer['fleet_resource_deuterium'] += $UpdateFleet['fleet_resource_deuterium']; - } - else - { - foreach($UpdateFleet as $Key => $Data) - { - $_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']][$Key] = $Data; - } - } - } - else - { - $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] = true; - } - } - - if($FleetRow['calcType'] == 3 && (!isset($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed']) || $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] !== true)) - { - if(!empty($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']])) - { - foreach($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']] as $Key => $Value) - { - $FleetRow[$Key] = $Value; - } - } - $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack'] = true; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack_Time'] = $Now; - RestoreFleetToPlanet($FleetRow, true, $_FleetCache); - } - - return $Return; -} - -?> \ No newline at end of file += $MaxPlanets) + { + $Message = false; + $Message['msg_id'] = '018'; + $Message['args'] = array($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $MaxPlanets); + $Message = json_encode($Message); + Cache_Message($FleetRow['fleet_owner'], 0, $FleetRow['fleet_start_time'], 4, '003', '008', $Message); + + $UpdateFleet['fleet_mess'] = 1; + } + else + { + $NewPlanetRecord = CreateOnePlanetRecord + ( + $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], + $FleetRow['fleet_owner'], $_Lang['sys_colo_defaultname'], false, + array + ( + 'metal' => $FleetRow['fleet_resource_metal'], + 'crystal' => $FleetRow['fleet_resource_crystal'], + 'deuterium' => $FleetRow['fleet_resource_deuterium'] + ), true, true + ); + if($NewPlanetRecord !== false) + { + $Message = false; + $Message['msg_id'] = '019'; + $Message['args'] = array($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet']); + $Message = json_encode($Message); + Cache_Message($FleetRow['fleet_owner'], 0, $FleetRow['fleet_start_time'], 4, '003', '008', $Message); + + if($FleetRow['fleet_amount'] == 1) + { + $fleetHasBeenDeleted = true; + $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed'] = true; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed_Reason'] = 8; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Info_HasLostShips'] = true; + $SetCode = '1'; + } + else + { + $FleetRebuild = explode(';', $FleetRow['fleet_array']); + foreach($FleetRebuild as $Index => &$Ships) + { + if(!empty($Ships)) + { + $ExplodeShips = explode(',', $Ships); + if($ExplodeShips[0] == 208) + { + $ExplodeShips[1] -= 1; + if($ExplodeShips[1] > 0) + { + $Ships = implode(',', $ExplodeShips); + break; + } + else + { + unset($FleetRebuild[$Index]); + } + } + } + else + { + unset($FleetRebuild[$Index]); + } + } + $NewFleet = implode(';', $FleetRebuild); + + $UpdateFleet['fleet_mess'] = 1; + $UpdateFleet['fleet_array'] = $NewFleet; + $UpdateFleet['fleet_amount'] = $FleetRow['fleet_amount'] - 1; + $UpdateFleet['fleet_resource_metal'] = -$FleetRow['fleet_resource_metal']; + $UpdateFleet['fleet_resource_crystal'] = -$FleetRow['fleet_resource_crystal']; + $UpdateFleet['fleet_resource_deuterium'] = -$FleetRow['fleet_resource_deuterium']; + + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Array_Changes'] = '"D;208,1"'; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Info_HasLostShips'] = true; + + $SetCode = '2'; + } + + // Trigger Tasks Check + if($_User['id'] == $FleetRow['fleet_owner']) + { + $CurrentUser = $_User; + } + else + { + if(empty($GlobalParsedTasks[$FleetRow['fleet_owner']]['tasks_done_parsed'])) + { + $GetUserTasksDone['tasks_done'] = $_FleetCache['userTasks'][$FleetRow['fleet_owner']]; + Tasks_CheckUservar($GetUserTasksDone); + $GlobalParsedTasks[$FleetRow['fleet_owner']] = $GetUserTasksDone; + } + $CurrentUser = $GlobalParsedTasks[$FleetRow['fleet_owner']]; + $CurrentUser['id'] = $FleetRow['fleet_owner']; + } + Tasks_TriggerTask($CurrentUser, 'COLONIZE_PLANET', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($CurrentUser) + { + global $UserTasksUpdate; + if(!empty($UserTasksUpdate[$CurrentUser['id']]['status'][$ThisCat][$TaskID][$JobID])) + { + $CurrentUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$CurrentUser['id']]['status'][$ThisCat][$TaskID][$JobID]; + } + if(!isset($CurrentUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID])) + { + $CurrentUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = 0; + } + $CurrentUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] += 1; + if($CurrentUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] < $JobArray['count']) + { + $UserTasksUpdate[$CurrentUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $CurrentUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; + return true; + } + } + )); + + $UserDev_Log[] = array('UserID' => $FleetRow['fleet_owner'], 'PlanetID' => $NewPlanetRecord['ID'], 'Date' => $FleetRow['fleet_start_time'], 'Place' => 14, 'Code' => $SetCode, 'ElementID' => $FleetRow['fleet_id'], 'AdditionalData' => "M,{$NewPlanetRecord['metal']};C,{$NewPlanetRecord['crystal']};D,{$NewPlanetRecord['deuterium']};T,{$NewPlanetRecord['temp_max']}"); + } + else + { + $Message = false; + $Message['msg_id'] = '020'; + $Message['args'] = array($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet']); + $Message = json_encode($Message); + Cache_Message($FleetRow['fleet_owner'], 0, $FleetRow['fleet_start_time'], 4, '003', '008', $Message); + + $UpdateFleet['fleet_mess'] = 1; + } + } + } + else + { + $Message = false; + $Message['msg_id'] = '021'; + $Message['args'] = array($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet']); + $Message = json_encode($Message); + Cache_Message($FleetRow['fleet_owner'], 0, $FleetRow['fleet_end_time'], 4, '003', '008', $Message); + + $UpdateFleet['fleet_mess'] = 1; + } + + if($fleetHasBeenDeleted !== true) + { + if($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['calcCount'] == 1) + { + // Create UpdateFleet record for $_FleetCache + $CachePointer = &$_FleetCache['updateFleets'][$FleetRow['fleet_id']]; + $CachePointer['fleet_array'] = $UpdateFleet['fleet_array']; + $CachePointer['fleet_amount'] = $UpdateFleet['fleet_amount']; + $CachePointer['fleet_mess'] = $UpdateFleet['fleet_mess']; + if(!isset($CachePointer['fleet_resource_metal'])) + { + $CachePointer['fleet_resource_metal'] = 0; + } + if(!isset($CachePointer['fleet_resource_crystal'])) + { + $CachePointer['fleet_resource_crystal'] = 0; + } + if(!isset($CachePointer['fleet_resource_deuterium'])) + { + $CachePointer['fleet_resource_deuterium'] = 0; + } + $CachePointer['fleet_resource_metal'] += $UpdateFleet['fleet_resource_metal']; + $CachePointer['fleet_resource_crystal'] += $UpdateFleet['fleet_resource_crystal']; + $CachePointer['fleet_resource_deuterium'] += $UpdateFleet['fleet_resource_deuterium']; + } + else + { + foreach($UpdateFleet as $Key => $Data) + { + $_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']][$Key] = $Data; + } + } + } + else + { + $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] = true; + } + } + + if($FleetRow['calcType'] == 3 && (!isset($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed']) || $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] !== true)) + { + if(!empty($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']])) + { + foreach($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']] as $Key => $Value) + { + $FleetRow[$Key] = $Value; + } + } + $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack'] = true; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack_Time'] = $Now; + RestoreFleetToPlanet($FleetRow, true, $_FleetCache); + } + + return $Return; +} + +?> diff --git a/includes/functions/MissionCaseDestruction.php b/includes/functions/MissionCaseDestruction.php index 07972df5d..f06068a7b 100644 --- a/includes/functions/MissionCaseDestruction.php +++ b/includes/functions/MissionCaseDestruction.php @@ -1,1808 +1,1808 @@ - 0 ? false : true); - $TargetPlanet = &$_FleetCache['planets'][$FleetRow['fleet_end_id']]; - $TargetUser = &$_FleetCache['users'][$FleetRow['fleet_target_owner']]; - $IsAllyFight = (($FleetRow['ally_id'] == 0 OR ($FleetRow['ally_id'] != $TargetUser['ally_id'])) ? false : true); - - // Update planet before attack begins - $UpdateResult = HandleFullUserUpdate($TargetUser, $TargetPlanet, $_FleetCache['planets'][$TargetUser['techQueue_Planet']], $FleetRow['fleet_start_time'], true, true); - if(!empty($UpdateResult)) - { - foreach($UpdateResult as $PlanetID => $Value) - { - if($Value === true) - { - $_FleetCache['updatePlanets'][$PlanetID] = true; - } - } - } - - $TargetUserID = $TargetPlanet['id_owner']; - $TargetPlanetGetName = $TargetPlanet['name']; - $TargetPlanetID = $TargetPlanet['id']; - - if(!$IsAbandoned) - { - $IdleHours = floor(($FleetRow['fleet_start_time'] - $TargetUser['onlinetime']) / 3600); - if($IdleHours > 0) - { - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Owner_IdleHours'] = $IdleHours; - } - } - - // Create data arrays for attacker and main defender - $CurrentUserID = $FleetRow['fleet_owner']; - $DefendersIDs[] = $TargetUser['id']; - $AttackersIDs[] = $FleetRow['fleet_owner']; - $AttackingFleets = array(); - $DefendingFleets = array(); - - $DefendingTechs[0] = array - ( - 109 => $TargetUser['tech_weapons'], - 110 => $TargetUser['tech_armour'], - 111 => $TargetUser['tech_shielding'], - 120 => $TargetUser['tech_laser'], - 121 => $TargetUser['tech_ion'], - 122 => $TargetUser['tech_plasma'], - 125 => $TargetUser['tech_antimatter'], - 126 => $TargetUser['tech_disintegration'], - 199 => $TargetUser['tech_graviton'] - ); - $DefendersData[0] = array - ( - 'id' => $TargetUser['id'], - 'username' => $TargetUser['username'], - 'techs' => Array2String($DefendingTechs[0]), - 'pos' => "{$FleetRow['fleet_end_galaxy']}:{$FleetRow['fleet_end_system']}:{$FleetRow['fleet_end_planet']}" - ); - if(!empty($TargetUser['ally_tag'])) - { - $DefendersData[0]['ally'] = $TargetUser['ally_tag']; - } - - $AttackingTechs[0] = array - ( - 109 => $FleetRow['tech_weapons'], - 110 => $FleetRow['tech_armour'], - 111 => $FleetRow['tech_shielding'], - 120 => $FleetRow['tech_laser'], - 121 => $FleetRow['tech_ion'], - 122 => $FleetRow['tech_plasma'], - 125 => $FleetRow['tech_antimatter'], - 126 => $FleetRow['tech_disintegration'], - 199 => $FleetRow['tech_graviton'] - ); - $AttackersData[0] = array - ( - 'id' => $FleetRow['fleet_owner'], - 'username' => $FleetRow['username'], - 'techs' => Array2String($AttackingTechs[0]), - 'pos' => "{$FleetRow['fleet_start_galaxy']}:{$FleetRow['fleet_start_system']}:{$FleetRow['fleet_start_planet']}" - ); - if(!empty($FleetRow['ally_tag'])) - { - $AttackersData[0]['ally'] = $FleetRow['ally_tag']; - } - - // MoraleSystem Init - if(MORALE_ENABLED) - { - if(!empty($_FleetCache['MoraleCache'][$FleetRow['fleet_owner']])) - { - $FleetRow['morale_level'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['level']; - $FleetRow['morale_droptime'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['droptime']; - $FleetRow['morale_lastupdate'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['lastupdate']; - } - Morale_ReCalculate($FleetRow, $FleetRow['fleet_start_time']); - $AttackersData[0]['morale'] = $FleetRow['morale_level']; - $AttackersData[0]['moralePoints'] = $FleetRow['morale_points']; - - // Bonuses - if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETPOWERUP1) - { - $AttackingTechs[0]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; - } - if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETSHIELDUP1) - { - $AttackingTechs[0]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; - } - if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETSDADDITION) - { - $AttackingTechs[0]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; - } - // Penalties - if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN1) - { - $AttackingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; - } - if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN2) - { - $AttackingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; - } - if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) - { - $AttackingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; - } - if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) - { - $AttackingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; - } - if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSDDOWN) - { - $AttackingTechs[0]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; - } - - if(!$IsAbandoned) - { - if(!empty($_FleetCache['MoraleCache'][$TargetUser['id']])) - { - $TargetUser['morale_level'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['level']; - $TargetUser['morale_droptime'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['droptime']; - $TargetUser['morale_lastupdate'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['lastupdate']; - } - Morale_ReCalculate($TargetUser, $FleetRow['fleet_start_time']); - $DefendersData[0]['morale'] = $TargetUser['morale_level']; - $DefendersData[0]['moralePoints'] = $TargetUser['morale_points']; - - // Bonuses - if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETPOWERUP1) - { - $DefendingTechs[0]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; - } - if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETSHIELDUP1) - { - $DefendingTechs[0]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; - } - if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETSDADDITION) - { - $DefendingTechs[0]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; - } - // Penalties - if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN1) - { - $DefendingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; - } - if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN2) - { - $DefendingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; - } - if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) - { - $DefendingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; - } - if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) - { - $DefendingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; - } - if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSDDOWN) - { - $DefendingTechs[0]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; - } - } - } - - // Select All Defending Fleets on the Orbit from $_FleetCache - if(!empty($_FleetCache['defFleets'][$FleetRow['fleet_end_id']])) - { - $i = 1; - foreach($_FleetCache['defFleets'][$FleetRow['fleet_end_id']] as $FleetData) - { - if($_FleetCache['fleetRowStatus'][$FleetData['fleet_id']]['isDestroyed'] !== true) - { - $DefendingFleets[$i] = String2Array($FleetData['fleet_array']); - $DefendingFleetID[$i] = $FleetData['fleet_id']; - $DefendingTechs[$i] = array - ( - 109 => $FleetData['tech_weapons'], - 110 => $FleetData['tech_armour'], - 111 => $FleetData['tech_shielding'], - 120 => $FleetData['tech_laser'], - 121 => $FleetData['tech_ion'], - 122 => $FleetData['tech_plasma'], - 125 => $FleetData['tech_antimatter'], - 126 => $FleetData['tech_disintegration'], - 199 => $FleetData['tech_graviton'] - ); - $DefendersData[$i] = array - ( - 'id' => $FleetData['fleet_owner'], - 'username' => $FleetData['username'], - 'techs' => Array2String($DefendingTechs[$i]), - 'pos' => "{$FleetData['fleet_start_galaxy']}:{$FleetData['fleet_start_system']}:{$FleetData['fleet_start_planet']}" - ); - if(!empty($FleetData['ally_tag'])) - { - $DefendersData[$i]['ally'] = $FleetData['ally_tag']; - } - if(!in_array($FleetData['fleet_owner'], $DefendersIDs)) - { - $DefendersIDs[] = $FleetData['fleet_owner']; - } - $DefendingFleetOwners[$FleetData['fleet_id']] = $FleetData['fleet_owner']; - - if(MORALE_ENABLED) - { - if(empty($_TempCache['MoraleCache'][$FleetData['fleet_owner']])) - { - if(!empty($_FleetCache['MoraleCache'][$FleetData['fleet_owner']])) - { - $FleetData['morale_level'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['level']; - $FleetData['morale_droptime'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['droptime']; - $FleetData['morale_lastupdate'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['lastupdate']; - } - Morale_ReCalculate($FleetData, $FleetRow['fleet_start_time']); - $DefendersData[$i]['morale'] = $FleetData['morale_level']; - $DefendersData[$i]['moralePoints'] = $FleetData['morale_points']; - - $_TempCache['MoraleCache'][$FleetData['fleet_owner']] = array - ( - 'level' => $FleetData['morale_level'], - 'points' => $FleetData['morale_points'] - ); - } - else - { - $DefendersData[$i]['morale'] = $_TempCache['MoraleCache'][$FleetData['fleet_owner']]['level']; - $DefendersData[$i]['moralePoints'] = $_TempCache['MoraleCache'][$FleetData['fleet_owner']]['points']; - } - - // Bonuses - if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETPOWERUP1) - { - $DefendingTechs[$i]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; - } - if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETSHIELDUP1) - { - $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; - } - if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETSDADDITION) - { - $DefendingTechs[$i]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; - } - // Penalties - if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN1) - { - $DefendingTechs[$i]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; - } - if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN2) - { - $DefendingTechs[$i]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; - } - if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) - { - $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; - } - if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) - { - $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; - } - if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSDDOWN) - { - $DefendingTechs[$i]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; - } - } - - $i += 1; - } - } - } - - foreach($AttackersIDs as $ID) - { - if(empty($UserStatsData[$ID])) - { - $UserStatsData[$ID] = $UserStatsPattern; - } - } - foreach($DefendersIDs as $ID) - { - if(empty($UserStatsData[$ID])) - { - $UserStatsData[$ID] = $UserStatsPattern; - } - } - - // Create main defender fleet array - foreach($_Vars_ElementCategories['fleet'] as $ElementID) - { - if($TargetPlanet[$_Vars_GameElements[$ElementID]] > 0) - { - $DefendingFleets[0][$ElementID] = $TargetPlanet[$_Vars_GameElements[$ElementID]]; - } - } - foreach($_Vars_ElementCategories['defense'] as $ElementID) - { - if(in_array($ElementID, $_Vars_ElementCategories['rockets'])) - { - continue; - } - if($TargetPlanet[$_Vars_GameElements[$ElementID]] > 0) - { - $DefendingFleets[0][$ElementID] = $TargetPlanet[$_Vars_GameElements[$ElementID]]; - } - } - - // Create attacker fleet array - $AttackingFleets[0] = String2Array($FleetRow['fleet_array']); - - $StartTime = microtime(true); - - // Now start Combat calculations - $Combat = Combat($AttackingFleets, $DefendingFleets, $AttackingTechs, $DefendingTechs); - - // Get the calculations time - $EndTime = microtime(true); - $totaltime = sprintf('%0.6f', $EndTime - $StartTime); - - $RealDebrisMetalAtk = 0; - $RealDebrisCrystalAtk = 0; - $RealDebrisDeuteriumAtk = 0; - $RealDebrisMetalDef = 0; - $RealDebrisCrystalDef = 0; - $RealDebrisDeuteriumDef = 0; - $TotalMoonChance = 0; - $TotalLostMetal = 0; - $TotalLostCrystal = 0; - $DebrisMetalDef = 0; - $DebrisCrystalDef = 0; - - $MoonHasBeenCreated = false; - $ThisDeathStarCount = 0; - - $RoundsData = $Combat['rounds']; - $Result = $Combat['result']; - $AtkShips = $Combat['AttackerShips']; - $DefShips = $Combat['DefenderShips']; - $AtkLost = $Combat['AtkLose']; - $DefLost = $Combat['DefLose']; - $DefSysLost = $Combat['DefSysLost']; - $ShotDown = $Combat['ShotDown']; - - $FleetStorage = 0; - - // Parse result data - attacker fleet - if(!empty($AtkShips[0])) - { - $QryUpdateFleets[0]['id'] = $FleetRow['fleet_id']; - foreach($AtkShips[0] as $ID => $Count) - { - $QryUpdateFleets[0]['mess'] = '1'; - if($Count > 0) - { - if($ID == 214) - { - $ThisDeathStarCount = $Count; - } - if(!isset($QryUpdateFleets[0]['count'])) - { - $QryUpdateFleets[0]['count'] = 0; - } - $QryUpdateFleets[0]['array'][] = "{$ID},{$Count}"; - $QryUpdateFleets[0]['count'] += $Count; - } - if($Result === COMBAT_ATK && (!isset($_Vars_Prices[$ID]['cantPillage']) || $_Vars_Prices[$ID]['cantPillage'] !== true)) - { - $FleetStorage += $_Vars_Prices[$ID]['capacity'] * $Count; - } - - if($Count < $AttackingFleets[0][$ID]) - { - $UserDev_UpFl[$FleetRow['fleet_id']][] = $ID.','.($AttackingFleets[0][$ID] - $Count); - } - } - - foreach($AttackingFleets[0] as $ID => $Count) - { - $Difference = $Count; - if(isset($AtkShips[0][$ID])) - { - $Difference -= $AtkShips[0][$ID]; - } - if($Difference > 0) - { - $QryUpdateFleets[0]['array_lost'][] = "{$ID},{$Difference}"; - } - } - if(!empty($QryUpdateFleets[0]['array_lost'])) - { - $QryUpdateFleets[0]['array_lost'] = implode(';', $QryUpdateFleets[0]['array_lost']); - } - - if($Result === COMBAT_ATK) - { - $FleetStorage -= $FleetRow['fleet_resource_metal']; - $FleetStorage -= $FleetRow['fleet_resource_crystal']; - $FleetStorage -= $FleetRow['fleet_resource_deuterium']; - - if($FleetStorage > 0) - { - $ResourceSteal_Factor = (COMBAT_RESOURCESTEAL_PERCENT / 100); - if(MORALE_ENABLED) - { - if(!$IsAbandoned AND $TargetUser['morale_level'] <= MORALE_PENALTY_RESOURCELOSE) - { - $ResourceSteal_NewFactor[] = MORALE_PENALTY_RESOURCELOSE_STEALPERCENT; - } - if($FleetRow['morale_level'] >= MORALE_BONUS_SOLOIDLERSTEAL AND $IdleHours >= (7 * 24)) - { - $ResourceSteal_NewFactor[] = MORALE_BONUS_SOLOIDLERSTEAL_STEALPERCENT; - } - if($FleetRow['morale_level'] <= MORALE_PENALTY_STEAL) - { - $ResourceSteal_NewFactor[] = MORALE_PENALTY_STEAL_STEALPERCENT; - } - else if($FleetRow['morale_level'] <= MORALE_PENALTY_IDLERSTEAL AND $IdleHours >= (7 * 24)) - { - $ResourceSteal_NewFactor[] = MORALE_PENALTY_IDLERSTEAL_STEALPERCENT; - } - - if(!empty($ResourceSteal_NewFactor)) - { - $ResourceSteal_Factor = (array_sum($ResourceSteal_NewFactor) / count($ResourceSteal_NewFactor)) / 100; - } - } - - $StolenMet = 0; - $StolenCry = 0; - $StolenDeu = 0; - - $AllowTakeMoreMet = 0; - $AllowTakeMoreCry = 0; - $AllowTakeMoreDeu = 0; - - $MaxMetSteal = $TargetPlanet['metal'] * $ResourceSteal_Factor; - $MaxCrySteal = $TargetPlanet['crystal'] * $ResourceSteal_Factor; - $MaxDeuSteal = $TargetPlanet['deuterium'] * $ResourceSteal_Factor; - - $StoragePerResource = $FleetStorage / 3; - - // First - calculate, if any resource will leave free storage - if($MaxMetSteal < $StoragePerResource) - { - $AllowTakeMore = ($StoragePerResource - $MaxMetSteal) / 2; - $AllowTakeMoreCry += $AllowTakeMore; - $AllowTakeMoreDeu += $AllowTakeMore; - $GiveAwayMet = true; - } - - if($MaxCrySteal < ($StoragePerResource + $AllowTakeMoreCry)) - { - $AllowTakeMore = (($StoragePerResource + $AllowTakeMoreCry) - $MaxCrySteal) / 2; - if($GiveAwayMet == false) - { - $AllowTakeMoreMet += $AllowTakeMore; - $AllowTakeMoreDeu += $AllowTakeMore; - } - else - { - $AllowTakeMoreDeu += $AllowTakeMore * 2; - } - $GiveAwayCry = true; - } - - if($MaxDeuSteal < ($StoragePerResource + $AllowTakeMoreDeu)) - { - $AllowTakeMore = (($StoragePerResource + $AllowTakeMoreDeu) - $MaxDeuSteal) / 2; - if($GiveAwayCry == false) - { - $AllowTakeMoreMet += $AllowTakeMore; - $AllowTakeMoreCry += $AllowTakeMore; - } - else - { - $AllowTakeMoreMet += $AllowTakeMore * 2; - } - } - - //Second - calculate stolen resources - if($MaxMetSteal > ($StoragePerResource + $AllowTakeMoreMet)) - { - $StolenMet = $StoragePerResource + $AllowTakeMoreMet; - } - else - { - $StolenMet = $MaxMetSteal; - } - if($MaxCrySteal > ($StoragePerResource + $AllowTakeMoreCry)) - { - $StolenCry = $StoragePerResource + $AllowTakeMoreCry; - } - else - { - $StolenCry = $MaxCrySteal; - } - if($MaxDeuSteal > ($StoragePerResource + $AllowTakeMoreDeu)) - { - $StolenDeu = $StoragePerResource + $AllowTakeMoreDeu; - } - else - { - $StolenDeu = $MaxDeuSteal; - } - - $StolenMet = floor($StolenMet); - $StolenCry = floor($StolenCry); - $StolenDeu = floor($StolenDeu); - if($StolenMet > 0) - { - $UserDev_UpFl[$FleetRow['fleet_id']][] = 'M,'.$StolenMet; - $TriggerTasksCheck['atk']['BATTLE_COLLECT_METAL'] = $StolenMet; - } - if($StolenCry > 0) - { - $UserDev_UpFl[$FleetRow['fleet_id']][] = 'C,'.$StolenCry; - $TriggerTasksCheck['atk']['BATTLE_COLLECT_CRYSTAL'] = $StolenCry; - } - if($StolenDeu > 0) - { - $UserDev_UpFl[$FleetRow['fleet_id']][] = 'D,'.$StolenDeu; - $TriggerTasksCheck['atk']['BATTLE_COLLECT_DEUTERIUM'] = $StolenDeu; - } - - $QryUpdateFleets[0]['metal'] = $StolenMet; - $QryUpdateFleets[0]['crystal'] = $StolenCry; - $QryUpdateFleets[0]['deuterium'] = $StolenDeu; - - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Metal'] = $StolenMet; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Crystal'] = $StolenCry; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Deuterium'] = $StolenDeu; - } - - //The aggressor has won the battle, let's check his chances of destroying this moon - if($ThisDeathStarCount > 0) - { - $DestructionDone = true; - - $ThisMoon_DestructionChance = (100 - sqrt($TargetPlanet['diameter'])) * sqrt($ThisDeathStarCount); - if($ThisMoon_DestructionChance > 100) - { - $ThisMoon_DestructionChance = 100; - } - else if($ThisMoon_DestructionChance <= 0) - { - $ThisMoon_DestructionChance = 0; - } - else - { - $ThisMoon_DestructionChance = round($ThisMoon_DestructionChance); - } - $ThisRand_MoonDestruction = mt_rand(1, 100); - - if($ThisRand_MoonDestruction <= $ThisMoon_DestructionChance) - { - $MoonHasBeenDestroyed = 1; - $Return['MoonDestroyed'] = true; - // Update User Stats - foreach($AttackersIDs as $UserID) - { - $UserStatsData[$UserID]['moons_destroyed'] += 1; - } - - // Get PlanetData to Redirect Fleets (from $_FleetCache) - $PlanetID = $_FleetCache['moonPlanets'][$TargetPlanet['id']]; - $PlanetName = $_FleetCache['planets'][$_FleetCache['moonPlanets'][$TargetPlanet['id']]]['name']; - - //Now delete moon from planet and moons list, and then from galaxy - $_FleetCache['deleteMoons'][] = $TargetPlanet['id']; - $GalaxyMoonID_NeedsUpdate = true; - - //Redirect fleets to a planet - $ChangeCoordinatesForFleets["{$PlanetID}<|>{$PlanetName}"] = $FleetRow['fleet_end_id']; - - $GetIDsToChangeArchive = ''; - $GetIDsToChangeArchive .= "SELECT `fleet_id`, `fleet_mission`, `fleet_start_id`, `fleet_end_id` FROM {{table}} "; - $GetIDsToChangeArchive .= "WHERE (`fleet_start_id` = {$FleetRow['fleet_end_id']} OR `fleet_end_id` = {$FleetRow['fleet_end_id']}) "; - $GetIDsToChangeArchive .= "AND `fleet_id` != {$FleetRow['fleet_id']}; -- MISSION DESTRUCTION [Q01][FID: {$FleetRow['fleet_id']}]"; - $GetData = doquery($GetIDsToChangeArchive, 'fleets'); - if(mysql_num_rows($GetData) > 0) - { - while($ParseFleet = mysql_fetch_assoc($GetData)) - { - $Pointer = &$Return['FleetArchive'][$ParseFleet['fleet_id']]; - if($ParseFleet['fleet_start_id'] == $FleetRow['fleet_end_id']) - { - $Pointer['Fleet_Start_Type_Changed'] = true; - $Pointer['Fleet_Start_ID_Changed'] = $PlanetID; - } - if($ParseFleet['fleet_end_id'] == $FleetRow['fleet_end_id']) - { - $Pointer['Fleet_End_Type_Changed'] = true; - $Pointer['Fleet_End_ID_Changed'] = $PlanetID; - if($ParseFleet['fleet_mission'] == 9) - { - $Pointer['Fleet_Mission_Changed'] = true; - } - } - } - } - - $Query_UpdateFleets = ''; - $Query_UpdateFleets .= "UPDATE {{table}} SET "; - $Query_UpdateFleets .= "`fleet_start_type` = IF(`fleet_start_id` = {$FleetRow['fleet_end_id']}, '1', `fleet_start_type`), "; - $Query_UpdateFleets .= "`fleet_start_id` = IF(`fleet_start_id` = {$FleetRow['fleet_end_id']}, {$PlanetID}, `fleet_start_id`), "; - $Query_UpdateFleets .= "`fleet_end_type` = IF(`fleet_end_id` = {$FleetRow['fleet_end_id']}, '1', `fleet_end_type`), "; - $Query_UpdateFleets .= "`fleet_mission` = IF(`fleet_end_id` = {$FleetRow['fleet_end_id']}, IF(`fleet_mission` = 9, 1, `fleet_mission`), `fleet_mission`), "; - $Query_UpdateFleets .= "`fleet_end_id` = IF(`fleet_end_id` = {$FleetRow['fleet_end_id']}, {$PlanetID}, `fleet_end_id`) "; - $Query_UpdateFleets .= "WHERE "; - $Query_UpdateFleets .= "(`fleet_start_id` = {$FleetRow['fleet_end_id']} OR `fleet_end_id` = {$FleetRow['fleet_end_id']}) "; - $Query_UpdateFleets .= "AND `fleet_id` != {$FleetRow['fleet_id']}; "; - $Query_UpdateFleets .= "-- MISSION DESTRUCTION [Q02][FID: {$FleetRow['fleet_id']}]"; - doquery($Query_UpdateFleets, 'fleets'); - - $QryChangeACS = "UPDATE {{table}} SET `end_type` = 1, `end_target_id` = {$PlanetID} WHERE `end_target_id` = {$FleetRow['fleet_end_id']}; -- MISSION DESTRUCTION [Q03][FID: {$FleetRow['fleet_id']}]"; - doquery($QryChangeACS, 'acs'); - - //maintenant on va verifier si la vue du joueur n est pas calee sur la lune qui est detruite - if($TargetUser['current_planet'] == $TargetPlanet['id'] AND $TargetUser['id'] != $_User['id']) - { - $_FleetCache['moonUserUpdate'][$TargetUser['id']] = $PlanetID; - } - } - - //Moon calculated so now check chances, that Fleet will be destroyed - $ThisFleet_DestructionChance = sqrt($TargetPlanet['diameter']) / 2; - if($ThisFleet_DestructionChance > 100) - { - $ThisFleet_DestructionChance = 100; - } - else if($ThisFleet_DestructionChance <= 0) - { - $ThisFleet_DestructionChance = 0; - } - else - { - $ThisFleet_DestructionChance = round($ThisFleet_DestructionChance); - } - $ThisRand_FleetDestruction = mt_rand(1, 100); - - if($ThisRand_FleetDestruction <= $ThisFleet_DestructionChance) - { - $FleetHasBeenDestroyed = true; - $FleetDestroyedByMoon = true; - - $DeleteFleet[] = $FleetRow['fleet_id']; - $UserDev_UpFl[$FleetRow['fleet_id']] = array(); - foreach($AttackingFleets[0] as $ShipID => $ShipCount) - { - $UserDev_UpFl[$FleetRow['fleet_id']][] = "{$ShipID},{$ShipCount}"; - } - - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Metal'] = 0; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Crystal'] = 0; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Deuterium'] = 0; - } - } - else - { - $MoonHasBeenDestroyed = -1; - } - } - } - else - { - $DeleteFleet[] = $FleetRow['fleet_id']; - foreach($AttackingFleets[0] as $ShipID => $ShipCount) - { - $UserDev_UpFl[$FleetRow['fleet_id']][] = "{$ShipID},{$ShipCount}"; - } - - $FleetHasBeenDestroyed = true; - } - - // Parse result data - Defenders - $i = 1; - if(!empty($DefendingFleets)) - { - foreach($DefendingFleets as $User => $Ships) - { - if($User == 0) - { - if($MoonHasBeenDestroyed !== 1) - { - $DefSysLostIDs = array_keys($DefSysLost); - $DefSysLostIDs[] = -1; - - foreach($Ships as $ID => $Count) - { - if(in_array($ID, $DefSysLostIDs)) - { - $Count = $DefShips[0][$ID]; - $Chance = mt_rand(60, 80 + (($TargetUser['engineer_time'] >= $FleetRow['fleet_start_time']) ? 20 : 0)); - $Fluctuation = mt_rand(-11, 11); - if($Fluctuation > 0) - { - $Fluctuation = 0; - } - $Rebuilt[$ID] = round($DefSysLost[$ID] * (($Chance + $Fluctuation) / 100)); - $Count += $Rebuilt[$ID]; - if($DefendingFleets[0][$ID] < $Count) - { - $Count = $DefendingFleets[0][$ID]; - } - unset($DefSysLost[$ID]); - } - else - { - $Count = $DefShips[0][$ID]; - } - if($Count == 0) - { - $Count = '0'; - } - $TargetPlanet[$_Vars_GameElements[$ID]] = $Count; - if($Count < $DefendingFleets[0][$ID]) - { - $UserDev_UpPl[] = $ID.','.($DefendingFleets[0][$ID] - $Count); - $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; - $HPQ_PlanetUpdatedFields[] = $_Vars_GameElements[$ID]; - } - } - } - } - else - { - $QryUpdateFleets[$i]['id'] = $DefendingFleetID[$User]; - if(!empty($DefShips[$User])) - { - foreach($Ships as $ID => $Count) - { - $ThisCount = 0; - if(!empty($DefShips[$User][$ID])) - { - $OldCount = $Count; - $Count = $DefShips[$User][$ID]; - $ThisCount = $Count; - if($Count > 0) - { - if(!isset($QryUpdateFleets[$i]['count'])) - { - $QryUpdateFleets[$i]['count'] = 0; - } - $QryUpdateFleets[$i]['array'][] = "{$ID},{$Count}"; - $QryUpdateFleets[$i]['count'] += $Count; - } - $Difference = $OldCount - $Count; - if($Difference > 0) - { - $QryUpdateFleets[$i]['array_lost'][] = "{$ID},{$Difference}"; - } - } - - if($ThisCount < $DefendingFleets[$User][$ID]) - { - $UserDev_UpFl[$DefendingFleetID[$User]][] = $ID.','.($DefendingFleets[$User][$ID] - $ThisCount); - } - } - - if(!empty($QryUpdateFleets[$i]['array_lost'])) - { - $QryUpdateFleets[$i]['array_lost'] = implode(';', $QryUpdateFleets[$i]['array_lost']); - } - } - else - { - $DeleteFleet[] = $DefendingFleetID[$User]; - foreach($DefendingFleets[$User] as $ShipID => $ShipCount) - { - $UserDev_UpFl[$DefendingFleetID[$User]][] = "{$ShipID},{$ShipCount}"; - } - } - } - $i += 1; - } - } - - if($MoonHasBeenDestroyed !== 1) - { - if($StolenMet > 0) - { - $TargetPlanet['metal'] -= $StolenMet; - $UserDev_UpPl[] = 'M,'.$StolenMet; - $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; - } - if($StolenCry > 0) - { - $TargetPlanet['crystal'] -= $StolenCry; - $UserDev_UpPl[] = 'C,'.$StolenCry; - $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; - } - if($StolenDeu > 0) - { - $TargetPlanet['deuterium'] -= $StolenDeu; - $UserDev_UpPl[] = 'D,'.$StolenDeu; - $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; - } - } - else - { - unset($_FleetCache['planets'][$FleetRow['fleet_end_id']]); - $_FleetCache['updatePlanets'][$TargetPlanet['id']] = false; - } - - // Update all fleets (if necessary) - if(!empty($QryUpdateFleets)) - { - foreach($QryUpdateFleets as $Data) - { - if(!empty($Data)) - { - if($Data['metal'] <= 0) - { - $Data['metal'] = '0'; - } - if($Data['crystal'] <= 0) - { - $Data['crystal'] = '0'; - } - if($Data['deuterium'] <= 0) - { - $Data['deuterium'] = '0'; - } - - if(!empty($Data['array'])) - { - $Data['array'] = implode(';', $Data['array']); - if(!empty($Data['array_lost'])) - { - if(strlen($Data['array']) > strlen($Data['array_lost'])) - { - $Return['FleetArchive'][$Data['id']]['Fleet_Array_Changes'] = "\"+D;{$Data['array_lost']}|\""; - } - else - { - $Return['FleetArchive'][$Data['id']]['Fleet_Array_Changes'] = "\"+L;{$Data['array']}|\""; - } - $Return['FleetArchive'][$Data['id']]['Fleet_Info_HasLostShips'] = '!true'; - } - if($Data['id'] != $FleetRow['fleet_id']) - { - $_FleetCache['defFleets'][$FleetRow['fleet_end_id']][$Data['id']]['fleet_array'] = $Data['array']; - } - } - - if($Data['id'] == $FleetRow['fleet_id'] AND $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['calcCount'] == 2) - { - // Update $_FleetCache, instead of sending additional Query to Update FleetState - // This fleet will be restored in this Calculation, so don't waste our time - $CachePointer = &$_FleetCache['fleetRowUpdate'][$Data['id']]; - $CachePointer['fleet_array'] = $Data['array']; - $CachePointer['fleet_resource_metal'] = $FleetRow['fleet_resource_metal'] + $Data['metal']; - $CachePointer['fleet_resource_crystal'] = $FleetRow['fleet_resource_crystal'] + $Data['crystal']; - $CachePointer['fleet_resource_deuterium'] = $FleetRow['fleet_resource_deuterium'] + $Data['deuterium']; - } - else - { - // Create UpdateFleet record for $_FleetCache - $CachePointer = &$_FleetCache['updateFleets'][$Data['id']]; - $CachePointer['fleet_array'] = $Data['array']; - $CachePointer['fleet_amount'] = $Data['count']; - $CachePointer['fleet_mess'] = $Data['mess']; - if(!isset($CachePointer['fleet_resource_metal'])) - { - $CachePointer['fleet_resource_metal'] = 0; - } - if(!isset($CachePointer['fleet_resource_crystal'])) - { - $CachePointer['fleet_resource_crystal'] = 0; - } - if(!isset($CachePointer['fleet_resource_deuterium'])) - { - $CachePointer['fleet_resource_deuterium'] = 0; - } - $CachePointer['fleet_resource_metal'] += $Data['metal']; - $CachePointer['fleet_resource_crystal'] += $Data['crystal']; - $CachePointer['fleet_resource_deuterium'] += $Data['deuterium']; - } - } - } - } - - if(!empty($UserDev_UpFl)) - { - foreach($UserDev_UpFl as $FleetID => $DevArray) - { - if($FleetID == $FleetRow['fleet_id']) - { - $SetCode = '2'; - $FleetUserID = $FleetRow['fleet_owner']; - } - else - { - $SetCode = '3'; - $FleetUserID = $DefendingFleetOwners[$FleetID]; - } - $UserDev_Log[] = array('UserID' => $FleetUserID, 'PlanetID' => '0', 'Date' => $FleetRow['fleet_start_time'], 'Place' => 15, 'Code' => $SetCode, 'ElementID' => $FleetID, 'AdditionalData' => implode(';', $DevArray)); - } - } - - // Calculate Debris & Looses - Init - $DebrisFactor_Fleet = $_GameConfig['Fleet_Cdr'] / 100; - $DebrisFactor_Defense = $_GameConfig['Defs_Cdr'] / 100; - - // Calculate looses - attacker - if(!empty($AtkLost)) - { - $DebrisMetalAtk = 0; - $DebrisCrystalAtk = 0; - foreach($AtkLost as $ID => $Count) - { - if(in_array($ID, $_Vars_ElementCategories['fleet'])) - { - if($DebrisFactor_Fleet > 0) - { - $DebrisMetalAtk += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Fleet); - $DebrisCrystalAtk += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Fleet); - } - $RealDebrisMetalAtk += floor($_Vars_Prices[$ID]['metal'] * $Count); - $RealDebrisCrystalAtk += floor($_Vars_Prices[$ID]['crystal'] * $Count); - $RealDebrisDeuteriumAtk += floor($_Vars_Prices[$ID]['deuterium'] * $Count); - } - } - $TotalLostMetal = $DebrisMetalAtk; - $TotalLostCrystal = $DebrisCrystalAtk; - } - - // Calculate looses - defender - if(!empty($DefLost)) - { - foreach($DefLost as $ID => $Count) - { - if(in_array($ID, $_Vars_ElementCategories['fleet'])) - { - if($DebrisFactor_Fleet > 0) - { - $DebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Fleet); - $DebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Fleet); - } - } - elseif(in_array($ID, $_Vars_ElementCategories['defense'])) - { - if($DebrisFactor_Defense > 0) - { - $DebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Defense); - $DebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Defense); - } - } - $RealDebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count); - $RealDebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count); - $RealDebrisDeuteriumDef += floor($_Vars_Prices[$ID]['deuterium'] * $Count); - } - $TotalLostMetal += $DebrisMetalDef; - $TotalLostCrystal += $DebrisCrystalDef; - } - - // Delete fleets (if necessary) - if(!empty($DeleteFleet)) - { - foreach($DeleteFleet as $FleetID) - { - $_FleetCache['fleetRowStatus'][$FleetID]['isDestroyed'] = true; - if(!empty($_FleetCache['updateFleets'][$FleetID])) - { - unset($_FleetCache['updateFleets'][$FleetID]); - } - $Return['FleetsToDelete'][] = $FleetID; - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed'] = true; - $Return['FleetArchive'][$FleetID]['Fleet_Info_HasLostShips'] = true; - if($FleetID == $FleetRow['fleet_id']) - { - if($FleetDestroyedByMoon) - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 7; - } - else - { - if($Result === COMBAT_DEF AND ($RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef) <= 0) - { - if(count($RoundsData) == 2) - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 1; - } - else - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 11; - } - } - else - { - if(count($RoundsData) == 2) - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 12; - } - else - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 2; - } - } - } - } - else - { - unset($_FleetCache['defFleets'][$FleetRow['fleet_end_id']][$FleetID]); - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 3; - } - } - } - - if($Result === COMBAT_DRAW AND (($RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef) <= 0)) - { - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed_Reason'] = 4; - } - - // Create debris field on the orbit - if($TotalLostMetal > 0 || $TotalLostCrystal > 0) - { - if($TotalLostCrystal == 0) - { - $TotalLostCrystal = '0'; - } - if($TotalLostMetal == 0) - { - $TotalLostMetal = '0'; - } - - if(isset($_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']]) && $_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']] > 0) - { - if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']]]['metal'])) - { - $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']]]['metal'] = 0; - } - if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']]]['crystal'])) - { - $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']]]['crystal'] = 0; - } - - $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']]]['metal'] += $TotalLostMetal; - $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']]]['crystal'] += $TotalLostCrystal; - $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']]]['updated'] = true; - $_FleetCache['updated']['galaxy'] = true; - } - else - { - $Query_UpdateGalaxy = ''; - $Query_UpdateGalaxy .= "UPDATE {{table}} SET `metal` = `metal` + {$TotalLostMetal}, `crystal` = `crystal` + {$TotalLostCrystal} "; - $Query_UpdateGalaxy .= "WHERE `id_moon` = {$FleetRow['fleet_end_id']} LIMIT 1; "; - $Query_UpdateGalaxy .= "-- MISSION DESTRUCTION [Q05][FID: {$FleetRow['fleet_id']}]"; - doquery($Query_UpdateGalaxy, 'galaxy'); - } - } - - // Check if Moon has been created - $FleetDebris = $TotalLostCrystal + $TotalLostMetal; - - $MoonChance = floor($FleetDebris / COMBAT_MOONPERCENT_RESOURCES); - if($MoonChance > 20) - { - $TotalMoonChance = $MoonChance; - $MoonChance = 20; - } - if($MoonChance < 1) - { - $UserChance = 0; - } - elseif($MoonChance >= 1) - { - $UserChance = mt_rand(1, 100); - } - - if($UserChance > 0 AND $UserChance <= $MoonChance AND $MoonHasBeenDestroyed === 1) - { - $CreatedMoonID = CreateOneMoonRecord($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetUserID, '', $MoonChance); - if($CreatedMoonID !== false) - { - $TriggerTasksCheck['atk']['CREATE_MOON'] = true; - $GalaxyMoonID_NeedsUpdate = false; - $MoonHasBeenCreated = true; - - $UserDev_UpPl[] = "L,{$CreatedMoonID}"; - - // Update User Stats - foreach($AttackersIDs as $UserID) - { - $UserStatsData[$UserID]['moons_created'] += 1; - } - } - } - - if(isset($GalaxyMoonID_NeedsUpdate) && $GalaxyMoonID_NeedsUpdate === true) - { - $_FleetCache['moonGalaxyUpdate'][] = $PlanetID; - } - - // Create DevLog Record (PlanetDefender's) - if(!empty($UserDev_UpPl) AND !$IsAbandoned) - { - $UserDev_Log[] = array('UserID' => $TargetUserID, 'PlanetID' => $TargetPlanetID, 'Date' => $FleetRow['fleet_start_time'], 'Place' => 15, 'Code' => '1', 'ElementID' => ($MoonHasBeenDestroyed === 1 ? '1' : '0'), 'AdditionalData' => implode(';', $UserDev_UpPl)); - } - - // Morale System - if(MORALE_ENABLED AND !$IsAbandoned AND !$IsAllyFight AND $IdleHours < (7 * 24)) - { - $Morale_Factor = $FleetRow['morale_points'] / $TargetUser['morale_points']; - if($Morale_Factor < 1) - { - $Morale_Factor = pow($Morale_Factor, -1); - $Morale_AttackerStronger = false; - } - else - { - $Morale_AttackerStronger = true; - } - - if($Morale_Factor > MORALE_MINIMALFACTOR) - { - if($Morale_AttackerStronger) - { - $Morale_Update_Attacker_Type = MORALE_NEGATIVE; - if($Result === COMBAT_DEF OR $Result === COMBAT_DRAW) - { - $Morale_Update_Defender_Type = MORALE_POSITIVE; - } - } - else - { - $Morale_Update_Attacker_Type = MORALE_POSITIVE; - } - - $Morale_Updated = Morale_AddMorale($FleetRow, $Morale_Update_Attacker_Type, $Morale_Factor, 1, 1, $FleetRow['fleet_start_time']); - if($Morale_Updated) - { - $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['level'] = $FleetRow['morale_level']; - $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['droptime'] = $FleetRow['morale_droptime']; - $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['lastupdate'] = $FleetRow['morale_lastupdate']; - - $ReportData['morale'][$FleetRow['fleet_owner']] = array - ( - 'usertype' => 'atk', - 'type' => $Morale_Update_Attacker_Type, - 'factor' => $Morale_Factor, - 'level' => $FleetRow['morale_level'] - ); - } - - if($Morale_Update_Defender_Type !== null) - { - if($Result === COMBAT_DRAW) - { - $Morale_LevelFactor = 1/2; - $Morale_TimeFactor = 1/2; - } - else - { - $Morale_LevelFactor = 1; - $Morale_TimeFactor = 1; - } - - $Morale_Updated = Morale_AddMorale($TargetUser, $Morale_Update_Defender_Type, $Morale_Factor, $Morale_LevelFactor, $Morale_TimeFactor, $FleetRow['fleet_start_time']); - if($Morale_Updated) - { - $_FleetCache['MoraleCache'][$TargetUser['id']]['level'] = $TargetUser['morale_level']; - $_FleetCache['MoraleCache'][$TargetUser['id']]['droptime'] = $TargetUser['morale_droptime']; - $_FleetCache['MoraleCache'][$TargetUser['id']]['lastupdate'] = $TargetUser['morale_lastupdate']; - - $ReportData['morale'][$TargetUser['id']] = array - ( - 'usertype' => 'def', - 'type' => MORALE_POSITIVE, - 'factor' => $Morale_Factor, - 'level' => $TargetUser['morale_level'] - ); - } - } - } - } - - // CREATE BATTLE REPORT - $ReportData['init']['usr']['atk'] = $AttackersData; - $ReportData['init']['usr']['def'] = $DefendersData; - - $ReportData['init']['time'] = $totaltime; - $ReportData['init']['date'] = $FleetRow['fleet_start_time']; - - $ReportData['init']['result'] = $Result; - $ReportData['init']['met'] = $StolenMet; - $ReportData['init']['cry'] = $StolenCry; - $ReportData['init']['deu'] = $StolenDeu; - $ReportData['init']['deb_met'] = $TotalLostMetal; - $ReportData['init']['deb_cry'] = $TotalLostCrystal; - $ReportData['init']['moon_chance'] = $MoonChance; - $ReportData['init']['total_moon_chance'] = $TotalMoonChance; - $ReportData['init']['moon_created'] = $MoonHasBeenCreated; - $ReportData['init']['moon_destroyed'] = $MoonHasBeenDestroyed; - $ReportData['init']['moon_des_chance'] = $ThisMoon_DestructionChance; - $ReportData['init']['fleet_destroyed'] = $FleetHasBeenDestroyed; - $ReportData['init']['fleet_des_chance'] = $ThisFleet_DestructionChance; - $ReportData['init']['planet_name'] = $TargetPlanetGetName; - $ReportData['init']['onMoon'] = true; - $ReportData['init']['atk_lost'] = $RealDebrisMetalAtk + $RealDebrisCrystalAtk + $RealDebrisDeuteriumAtk; - $ReportData['init']['def_lost'] = $RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef; - - foreach($RoundsData as $RoundKey => $RoundData) - { - foreach($RoundData as $MainKey => $RoundData2) - { - if(!empty($RoundData2['ships'])) - { - foreach($RoundData2['ships'] as $UserKey => $UserData) - { - $RoundsData[$RoundKey][$MainKey]['ships'][$UserKey] = Array2String($UserData); - } - } - } - } - $ReportData['rounds'] = $RoundsData; - - if(count($RoundsData) <= 2 AND $Result === COMBAT_DEF) - { - $DisallowAttackers = true; - } - else - { - $DisallowAttackers = false; - } - - $CreatedReport = CreateBattleReport($ReportData, array('atk' => $AttackersIDs, 'def' => $DefendersIDs), $DisallowAttackers); - $ReportID = $CreatedReport['ID']; - $ReportHasHLinkRelative = 'battlereport.php?hash='.$CreatedReport['Hash']; - $ReportHasHLinkReal = GAMEURL.$ReportHasHLinkRelative; - - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_ReportID'] = $ReportID; - if(!empty($DefendingFleetID)) - { - foreach($DefendingFleetID as $FleetID) - { - $Return['FleetArchive'][$FleetID]['Fleet_DefenderReportIDs'] = "\"+,{$ReportID}\""; - } - } - - // Update battle stats & set Battle Report colors - if(!$IsAllyFight) - { - if($Result === COMBAT_ATK) - { - foreach($AttackersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_won'] += 1; - } - foreach($DefendersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_lost'] += 1; - } - if($FleetDestroyedByMoon) - { - $ReportColor = '#AD5CD6'; - } - else - { - $ReportColor = 'green'; - } - if($MoonHasBeenDestroyed === 1) - { - $ReportColor3 = 'green'; - } - else - { - $ReportColor3 = 'orange'; - } - $ReportColor2 = 'red'; - } - elseif($Result === COMBAT_DRAW) - { - foreach($AttackersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_draw'] += 1; - } - foreach($DefendersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_draw'] += 1; - } - $ReportColor = 'orange'; - $ReportColor2 = 'orange'; - } - elseif($Result === COMBAT_DEF) - { - foreach($AttackersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_lost'] += 1; - } - foreach($DefendersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_won'] += 1; - } - $ReportColor = 'red'; - $ReportColor2 = 'green'; - } - - // Update User Destroyed & Lost Stats - if(!empty($ShotDown)) - { - foreach($ShotDown as $ThisType => $ThisData) - { - foreach($ThisData as $ThisType2 => $ThisData2) - { - if($ThisType2 == 'd') - { - $ThisKey = 'destroyed_'; - } - else - { - $ThisKey = 'lost_'; - } - foreach($ThisData2 as $UserID => $DestShips) - { - if($UserID == 0) - { - if($ThisType == 'atk') - { - $ThisUserID = $FleetRow['fleet_owner']; - } - else - { - $ThisUserID = $TargetUser['id']; - } - } - else - { - if($ThisType == 'atk') - { - $ThisUserID = $AttackingFleetOwners[$AttackingFleetID[$UserID]]; - } - else - { - $ThisUserID = $DefendingFleetOwners[$DefendingFleetID[$UserID]]; - } - } - foreach($DestShips as $ShipID => $ShipCount) - { - $UserStatsData[$ThisUserID][$ThisKey.$ShipID] += $ShipCount; - } - } - } - } - } - - if(!empty($ShotDown)) - { - if(!empty($ShotDown['atk']['d'][0])) - { - if(!isset($TriggerTasksCheck['atk']['BATTLE_DESTROY_MILITARYUNITS'])) - { - $TriggerTasksCheck['atk']['BATTLE_DESTROY_MILITARYUNITS'] = 0; - } - if(!isset($TriggerTasksCheck['atk']['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'])) - { - $TriggerTasksCheck['atk']['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'] = 0; - } - foreach($ShotDown['atk']['d'][0] as $ShipID => $ShipCount) - { - $TriggerTasksCheck['atk']['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'] += (($_Vars_Prices[$ShipID]['metal'] + $_Vars_Prices[$ShipID]['crystal'] + $_Vars_Prices[$ShipID]['deuterium']) * $ShipCount); - if(in_array($ShipID, $_Vars_ElementCategories['units']['military'])) - { - $TriggerTasksCheck['atk']['BATTLE_DESTROY_MILITARYUNITS'] += $ShipCount; - } - } - } - } - - if($Result === COMBAT_ATK) - { - $TriggerTasksCheck['atk']['BATTLE_WIN'] = true; - $TriggerTasksCheck['atk']['BATTLE_WINORDRAW_SOLO_TOTALLIMIT'] = true; - $TriggerTasksCheck['atk']['BATTLE_WINORDRAW_SOLO_LIMIT'] = true; - $TriggerTasksCheck['atk']['BATTLE_WINORDRAW_LIMIT'] = true; - } - else if($Result === COMBAT_DRAW) - { - $TriggerTasksCheck['atk']['BATTLE_WINORDRAW_SOLO_TOTALLIMIT'] = true; - $TriggerTasksCheck['atk']['BATTLE_WINORDRAW_SOLO_LIMIT'] = true; - $TriggerTasksCheck['atk']['BATTLE_WINORDRAW_LIMIT'] = true; - } - else if($Result === COMBAT_DEF) - { - $TriggerTasksCheck['atk']['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'] = 0; - } - if($MoonHasBeenDestroyed === 1) - { - $TriggerTasksCheck['atk']['DESTROY_MOON'] = true; - } - - if(!$IsAbandoned AND !$DestructionDone AND $AttackingFleets[0][214] >= 1000) - { - $TriggerTasksCheck['def']['BATTLE_BLOCK_MOONDESTROY'] = true; - } - } - else - { - if($MoonHasBeenCreated) - { - $TriggerTasksCheck['atk']['CREATE_MOON_FRIENDLY'] = true; - } - unset($TriggerTasksCheck['atk']['BATTLE_COLLECT_METAL']); - unset($TriggerTasksCheck['atk']['BATTLE_COLLECT_CRYSTAL']); - unset($TriggerTasksCheck['atk']['BATTLE_COLLECT_DEUTERIUM']); - - foreach($AttackersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_inAlly'] += 1; - } - foreach($DefendersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_inAlly'] += 1; - } - if($Result === COMBAT_ATK) - { - if($FleetDestroyedByMoon) - { - $ReportColor = '#AD5CD6'; - } - else - { - $ReportColor = 'green'; - } - if($MoonHasBeenDestroyed === 1) - { - $ReportColor3 = 'green'; - } - else - { - $ReportColor3 = 'orange'; - } - $ReportColor2 = 'red'; - } - elseif($Result === COMBAT_DRAW) - { - $ReportColor = 'orange'; - $ReportColor2 = 'orange'; - } - elseif($Result === COMBAT_DEF) - { - $ReportColor = 'red'; - $ReportColor2 = 'green'; - } - } - - $TargetTypeMsg = $_Lang['BR_Target_'.$FleetRow['fleet_end_type']]; - if(!empty($ReportColor3)) - { - $TargetTypeMsg = "{$TargetTypeMsg}"; - } - $Message['msg_id'] = '072'; - $Message['args'] = array - ( - $ReportID, $ReportColor, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetTypeMsg, - prettyNumber($RealDebrisMetalAtk + $RealDebrisCrystalAtk + $RealDebrisDeuteriumAtk), - prettyNumber($RealDebrisCrystalDef + $RealDebrisMetalDef + $RealDebrisDeuteriumDef), - ($FleetDestroyedByMoon != true ? prettyNumber($StolenMet) : 0), - ($FleetDestroyedByMoon != true ? prettyNumber($StolenCry) : 0), - ($FleetDestroyedByMoon != true ? prettyNumber($StolenDeu) : 0), - prettyNumber(isset($TotalLostMetal) ? $TotalLostMetal : 0), prettyNumber(isset($TotalLostCrystal) ? $TotalLostCrystal : 0), - $ReportHasHLinkRelative, $ReportHasHLinkReal - ); - $Message = json_encode($Message); - Cache_Message($CurrentUserID, 0, $FleetRow['fleet_start_time'], 3, '003', '012', $Message); - - if(!$IsAbandoned) - { - $Message = false; - $Message['msg_id'] = '074'; - if(!empty($Rebuilt) AND (array)$Rebuilt === $Rebuilt) - { - foreach($Rebuilt as $SysID => $Count) - { - $RebuildReport[] = ''.$_Lang['tech'][$SysID].' - '.$Count; - } - $RebuildReport = implode('
    ', $RebuildReport); - } - else - { - if($MoonHasBeenDestroyed !== 1) - { - if(!isset($DefSysLostIDs) || count($DefSysLostIDs) == 1) - { - $RebuildReport = $_Lang['no_loses_in_defence']; - } - else - { - $RebuildReport = $_Lang['nothing_have_been_rebuilt']; - } - } - else - { - $RebuildReport = $_Lang['moon_has_been_destroyed']; - } - } - $Message['args'] = array - ( - $ReportID, $ReportColor2, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], - $TargetTypeMsg, $RebuildReport, $ReportHasHLinkRelative, $ReportHasHLinkReal - ); - $Message = json_encode($Message); - Cache_Message($TargetUserID, 0, $FleetRow['fleet_start_time'], 3, '003', '012', $Message); - } - - if(count($DefendersIDs) > 1) - { - $Message = false; - $Message['msg_id'] = '075'; - $Message['args'] = array - ( - $ReportID, $ReportColor2, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], - $TargetTypeMsg, $ReportHasHLinkRelative, $ReportHasHLinkReal - ); - $Message = json_encode($Message); - unset($DefendersIDs[0]); - Cache_Message($DefendersIDs, 0, $FleetRow['fleet_start_time'], 3, '003', '017', $Message); - } - - if(!empty($TriggerTasksCheck)) - { - global $GlobalParsedTasks; - } - - if(!empty($TriggerTasksCheck['atk'])) - { - // Parse Attacker Tasks - if($_User['id'] == $FleetRow['fleet_owner']) - { - $ThisTaskUser = $_User; - } - else - { - if(empty($GlobalParsedTasks[$FleetRow['fleet_owner']]['tasks_done_parsed'])) - { - $GetUserTasksDone['tasks_done'] = $_FleetCache['userTasks'][$FleetRow['fleet_owner']]; - Tasks_CheckUservar($GetUserTasksDone); - $GlobalParsedTasks[$FleetRow['fleet_owner']] = $GetUserTasksDone; - } - $ThisTaskUser = $GlobalParsedTasks[$FleetRow['fleet_owner']]; - $ThisTaskUser['id'] = $FleetRow['fleet_owner']; - } - - if(isset($TriggerTasksCheck['atk']['BATTLE_WIN'])) - { - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WIN', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - if(isset($TriggerTasksCheck['atk']['BATTLE_WINORDRAW_SOLO_TOTALLIMIT']) && $TotalMoonChance > 0) - { - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WINORDRAW_SOLO_TOTALLIMIT', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TotalMoonChance) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TotalMoonChance); - } - )); - } - if(isset($TriggerTasksCheck['atk']['BATTLE_WINORDRAW_SOLO_LIMIT']) || isset($TriggerTasksCheck['atk']['BATTLE_WINORDRAW_LIMIT'])) - { - $Debris_Total_Def = ($DebrisMetalDef + $DebrisCrystalDef) / COMBAT_MOONPERCENT_RESOURCES; - if(isset($TriggerTasksCheck['atk']['BATTLE_WINORDRAW_SOLO_LIMIT'])) - { - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WINORDRAW_SOLO_LIMIT', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $Debris_Total_Def) - { - if($JobArray['minimalEnemyPercentLimit'] > $Debris_Total_Def) - { - return true; - } - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - if(isset($TriggerTasksCheck['atk']['BATTLE_WINORDRAW_LIMIT'])) - { - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WINORDRAW_LIMIT', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $Debris_Total_Def) - { - if($JobArray['minimalEnemyPercentLimit'] > $Debris_Total_Def) - { - return true; - } - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - } - if(isset($TriggerTasksCheck['atk']['DESTROY_MOON'])) - { - Tasks_TriggerTask($ThisTaskUser, 'DESTROY_MOON', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TargetPlanet) - { - if(isset($JobArray['minimalDiameter']) && $JobArray['minimalDiameter'] > $TargetPlanet['diameter']) - { - return true; - } - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - if(!$FleetHasBeenDestroyed) - { - Tasks_TriggerTask($ThisTaskUser, 'DESTROY_MOON_NOFLEETLOSS', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TargetPlanet) - { - if(isset($JobArray['minimalDiameter']) && $JobArray['minimalDiameter'] > $TargetPlanet['diameter']) - { - return true; - } - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - } - if(isset($TriggerTasksCheck['atk']['BATTLE_COLLECT_METAL']) && $TriggerTasksCheck['atk']['BATTLE_COLLECT_METAL'] > 0 && !$FleetHasBeenDestroyed) - { - $TaskTemp = $TriggerTasksCheck['atk']['BATTLE_COLLECT_METAL']; - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_METAL', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); - } - )); - } - if(isset($TriggerTasksCheck['atk']['BATTLE_COLLECT_CRYSTAL']) && $TriggerTasksCheck['atk']['BATTLE_COLLECT_CRYSTAL'] > 0 && !$FleetHasBeenDestroyed) - { - $TaskTemp = $TriggerTasksCheck['atk']['BATTLE_COLLECT_CRYSTAL']; - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_CRYSTAL', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); - } - )); - } - if(isset($TriggerTasksCheck['atk']['BATTLE_COLLECT_DEUTERIUM']) && $TriggerTasksCheck['atk']['BATTLE_COLLECT_DEUTERIUM'] > 0 && !$FleetHasBeenDestroyed) - { - $TaskTemp = $TriggerTasksCheck['atk']['BATTLE_COLLECT_DEUTERIUM']; - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_DEUTERIUM', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); - } - )); - } - if(isset($TriggerTasksCheck['atk']['CREATE_MOON'])) - { - Tasks_TriggerTask($ThisTaskUser, 'CREATE_MOON', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - if(isset($TriggerTasksCheck['atk']['CREATE_MOON_FRIENDLY'])) - { - Tasks_TriggerTask($ThisTaskUser, 'CREATE_MOON_FRIENDLY', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - if(isset($TriggerTasksCheck['atk']['BATTLE_DESTROY_MILITARYUNITS']) && $TriggerTasksCheck['atk']['BATTLE_DESTROY_MILITARYUNITS'] > 0) - { - $TaskTemp = $TriggerTasksCheck['atk']['BATTLE_DESTROY_MILITARYUNITS']; - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_DESTROY_MILITARYUNITS', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); - } - )); - } - if(isset($TriggerTasksCheck['atk']['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO']) && $TriggerTasksCheck['atk']['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'] > 0) - { - $TaskTemp2 = 0; - foreach($AttackingFleets[0] as $ShipID => $ShipCount) - { - $TaskTemp2 += (($_Vars_Prices[$ShipID]['metal'] + $_Vars_Prices[$ShipID]['crystal'] + $_Vars_Prices[$ShipID]['deuterium']) * $ShipCount); - } - $TaskTemp = $TriggerTasksCheck['atk']['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO']; - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp, $TaskTemp2) - { - if($JobArray['minimalEnemyCost'] > $TaskTemp) - { - return true; - } - if($TaskTemp2 > ($TaskTemp * $JobArray['maximalOwnValue'])) - { - return true; - } - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - } - - if(!empty($TriggerTasksCheck['def']) AND !$IsAbandoned) - { - // Parse Defender Tasks - if($_User['id'] == $FleetRow['fleet_target_owner']) - { - $ThisTaskUser = $_User; - } - else - { - if(empty($GlobalParsedTasks[$FleetRow['fleet_target_owner']]['tasks_done_parsed'])) - { - $GetUserTasksDone['tasks_done'] = $_FleetCache['userTasks'][$FleetRow['fleet_target_owner']]; - Tasks_CheckUservar($GetUserTasksDone); - $GlobalParsedTasks[$FleetRow['fleet_target_owner']] = $GetUserTasksDone; - } - $ThisTaskUser = $GlobalParsedTasks[$FleetRow['fleet_target_owner']]; - $ThisTaskUser['id'] = $FleetRow['fleet_target_owner']; - } - - if(isset($TriggerTasksCheck['def']['BATTLE_BLOCK_MOONDESTROY'])) - { - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_BLOCK_MOONDESTROY'); - } - } - } - - if($FleetRow['calcType'] == 3 && (!isset($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed']) || $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] !== true)) - { - if(!empty($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']])) - { - foreach($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']] as $Key => $Value) - { - $FleetRow[$Key] = $Value; - } - } - $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack'] = true; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack_Time'] = $Now; - RestoreFleetToPlanet($FleetRow, true, $_FleetCache); - } - - return $Return; -} - -?> \ No newline at end of file + 0 ? false : true); + $TargetPlanet = &$_FleetCache['planets'][$FleetRow['fleet_end_id']]; + $TargetUser = &$_FleetCache['users'][$FleetRow['fleet_target_owner']]; + $IsAllyFight = (($FleetRow['ally_id'] == 0 OR ($FleetRow['ally_id'] != $TargetUser['ally_id'])) ? false : true); + + // Update planet before attack begins + $UpdateResult = HandleFullUserUpdate($TargetUser, $TargetPlanet, $_FleetCache['planets'][$TargetUser['techQueue_Planet']], $FleetRow['fleet_start_time'], true, true); + if(!empty($UpdateResult)) + { + foreach($UpdateResult as $PlanetID => $Value) + { + if($Value === true) + { + $_FleetCache['updatePlanets'][$PlanetID] = true; + } + } + } + + $TargetUserID = $TargetPlanet['id_owner']; + $TargetPlanetGetName = $TargetPlanet['name']; + $TargetPlanetID = $TargetPlanet['id']; + + if(!$IsAbandoned) + { + $IdleHours = floor(($FleetRow['fleet_start_time'] - $TargetUser['onlinetime']) / 3600); + if($IdleHours > 0) + { + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Owner_IdleHours'] = $IdleHours; + } + } + + // Create data arrays for attacker and main defender + $CurrentUserID = $FleetRow['fleet_owner']; + $DefendersIDs[] = $TargetUser['id']; + $AttackersIDs[] = $FleetRow['fleet_owner']; + $AttackingFleets = array(); + $DefendingFleets = array(); + + $DefendingTechs[0] = array + ( + 109 => $TargetUser['tech_weapons'], + 110 => $TargetUser['tech_armour'], + 111 => $TargetUser['tech_shielding'], + 120 => $TargetUser['tech_laser'], + 121 => $TargetUser['tech_ion'], + 122 => $TargetUser['tech_plasma'], + 125 => $TargetUser['tech_antimatter'], + 126 => $TargetUser['tech_disintegration'], + 199 => $TargetUser['tech_graviton'] + ); + $DefendersData[0] = array + ( + 'id' => $TargetUser['id'], + 'username' => $TargetUser['username'], + 'techs' => Array2String($DefendingTechs[0]), + 'pos' => "{$FleetRow['fleet_end_galaxy']}:{$FleetRow['fleet_end_system']}:{$FleetRow['fleet_end_planet']}" + ); + if(!empty($TargetUser['ally_tag'])) + { + $DefendersData[0]['ally'] = $TargetUser['ally_tag']; + } + + $AttackingTechs[0] = array + ( + 109 => $FleetRow['tech_weapons'], + 110 => $FleetRow['tech_armour'], + 111 => $FleetRow['tech_shielding'], + 120 => $FleetRow['tech_laser'], + 121 => $FleetRow['tech_ion'], + 122 => $FleetRow['tech_plasma'], + 125 => $FleetRow['tech_antimatter'], + 126 => $FleetRow['tech_disintegration'], + 199 => $FleetRow['tech_graviton'] + ); + $AttackersData[0] = array + ( + 'id' => $FleetRow['fleet_owner'], + 'username' => $FleetRow['username'], + 'techs' => Array2String($AttackingTechs[0]), + 'pos' => "{$FleetRow['fleet_start_galaxy']}:{$FleetRow['fleet_start_system']}:{$FleetRow['fleet_start_planet']}" + ); + if(!empty($FleetRow['ally_tag'])) + { + $AttackersData[0]['ally'] = $FleetRow['ally_tag']; + } + + // MoraleSystem Init + if(MORALE_ENABLED) + { + if(!empty($_FleetCache['MoraleCache'][$FleetRow['fleet_owner']])) + { + $FleetRow['morale_level'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['level']; + $FleetRow['morale_droptime'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['droptime']; + $FleetRow['morale_lastupdate'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['lastupdate']; + } + Morale_ReCalculate($FleetRow, $FleetRow['fleet_start_time']); + $AttackersData[0]['morale'] = $FleetRow['morale_level']; + $AttackersData[0]['moralePoints'] = $FleetRow['morale_points']; + + // Bonuses + if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETPOWERUP1) + { + $AttackingTechs[0]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; + } + if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETSHIELDUP1) + { + $AttackingTechs[0]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; + } + if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETSDADDITION) + { + $AttackingTechs[0]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; + } + // Penalties + if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN1) + { + $AttackingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; + } + if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN2) + { + $AttackingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; + } + if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) + { + $AttackingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; + } + if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) + { + $AttackingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; + } + if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSDDOWN) + { + $AttackingTechs[0]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; + } + + if(!$IsAbandoned) + { + if(!empty($_FleetCache['MoraleCache'][$TargetUser['id']])) + { + $TargetUser['morale_level'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['level']; + $TargetUser['morale_droptime'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['droptime']; + $TargetUser['morale_lastupdate'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['lastupdate']; + } + Morale_ReCalculate($TargetUser, $FleetRow['fleet_start_time']); + $DefendersData[0]['morale'] = $TargetUser['morale_level']; + $DefendersData[0]['moralePoints'] = $TargetUser['morale_points']; + + // Bonuses + if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETPOWERUP1) + { + $DefendingTechs[0]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; + } + if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETSHIELDUP1) + { + $DefendingTechs[0]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; + } + if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETSDADDITION) + { + $DefendingTechs[0]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; + } + // Penalties + if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN1) + { + $DefendingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; + } + if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN2) + { + $DefendingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; + } + if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) + { + $DefendingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; + } + if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) + { + $DefendingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; + } + if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSDDOWN) + { + $DefendingTechs[0]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; + } + } + } + + // Select All Defending Fleets on the Orbit from $_FleetCache + if(!empty($_FleetCache['defFleets'][$FleetRow['fleet_end_id']])) + { + $i = 1; + foreach($_FleetCache['defFleets'][$FleetRow['fleet_end_id']] as $FleetData) + { + if($_FleetCache['fleetRowStatus'][$FleetData['fleet_id']]['isDestroyed'] !== true) + { + $DefendingFleets[$i] = String2Array($FleetData['fleet_array']); + $DefendingFleetID[$i] = $FleetData['fleet_id']; + $DefendingTechs[$i] = array + ( + 109 => $FleetData['tech_weapons'], + 110 => $FleetData['tech_armour'], + 111 => $FleetData['tech_shielding'], + 120 => $FleetData['tech_laser'], + 121 => $FleetData['tech_ion'], + 122 => $FleetData['tech_plasma'], + 125 => $FleetData['tech_antimatter'], + 126 => $FleetData['tech_disintegration'], + 199 => $FleetData['tech_graviton'] + ); + $DefendersData[$i] = array + ( + 'id' => $FleetData['fleet_owner'], + 'username' => $FleetData['username'], + 'techs' => Array2String($DefendingTechs[$i]), + 'pos' => "{$FleetData['fleet_start_galaxy']}:{$FleetData['fleet_start_system']}:{$FleetData['fleet_start_planet']}" + ); + if(!empty($FleetData['ally_tag'])) + { + $DefendersData[$i]['ally'] = $FleetData['ally_tag']; + } + if(!in_array($FleetData['fleet_owner'], $DefendersIDs)) + { + $DefendersIDs[] = $FleetData['fleet_owner']; + } + $DefendingFleetOwners[$FleetData['fleet_id']] = $FleetData['fleet_owner']; + + if(MORALE_ENABLED) + { + if(empty($_TempCache['MoraleCache'][$FleetData['fleet_owner']])) + { + if(!empty($_FleetCache['MoraleCache'][$FleetData['fleet_owner']])) + { + $FleetData['morale_level'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['level']; + $FleetData['morale_droptime'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['droptime']; + $FleetData['morale_lastupdate'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['lastupdate']; + } + Morale_ReCalculate($FleetData, $FleetRow['fleet_start_time']); + $DefendersData[$i]['morale'] = $FleetData['morale_level']; + $DefendersData[$i]['moralePoints'] = $FleetData['morale_points']; + + $_TempCache['MoraleCache'][$FleetData['fleet_owner']] = array + ( + 'level' => $FleetData['morale_level'], + 'points' => $FleetData['morale_points'] + ); + } + else + { + $DefendersData[$i]['morale'] = $_TempCache['MoraleCache'][$FleetData['fleet_owner']]['level']; + $DefendersData[$i]['moralePoints'] = $_TempCache['MoraleCache'][$FleetData['fleet_owner']]['points']; + } + + // Bonuses + if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETPOWERUP1) + { + $DefendingTechs[$i]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; + } + if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETSHIELDUP1) + { + $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; + } + if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETSDADDITION) + { + $DefendingTechs[$i]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; + } + // Penalties + if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN1) + { + $DefendingTechs[$i]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; + } + if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN2) + { + $DefendingTechs[$i]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; + } + if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) + { + $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; + } + if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) + { + $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; + } + if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSDDOWN) + { + $DefendingTechs[$i]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; + } + } + + $i += 1; + } + } + } + + foreach($AttackersIDs as $ID) + { + if(empty($UserStatsData[$ID])) + { + $UserStatsData[$ID] = $UserStatsPattern; + } + } + foreach($DefendersIDs as $ID) + { + if(empty($UserStatsData[$ID])) + { + $UserStatsData[$ID] = $UserStatsPattern; + } + } + + // Create main defender fleet array + foreach($_Vars_ElementCategories['fleet'] as $ElementID) + { + if($TargetPlanet[$_Vars_GameElements[$ElementID]] > 0) + { + $DefendingFleets[0][$ElementID] = $TargetPlanet[$_Vars_GameElements[$ElementID]]; + } + } + foreach($_Vars_ElementCategories['defense'] as $ElementID) + { + if(in_array($ElementID, $_Vars_ElementCategories['rockets'])) + { + continue; + } + if($TargetPlanet[$_Vars_GameElements[$ElementID]] > 0) + { + $DefendingFleets[0][$ElementID] = $TargetPlanet[$_Vars_GameElements[$ElementID]]; + } + } + + // Create attacker fleet array + $AttackingFleets[0] = String2Array($FleetRow['fleet_array']); + + $StartTime = microtime(true); + + // Now start Combat calculations + $Combat = Combat($AttackingFleets, $DefendingFleets, $AttackingTechs, $DefendingTechs); + + // Get the calculations time + $EndTime = microtime(true); + $totaltime = sprintf('%0.6f', $EndTime - $StartTime); + + $RealDebrisMetalAtk = 0; + $RealDebrisCrystalAtk = 0; + $RealDebrisDeuteriumAtk = 0; + $RealDebrisMetalDef = 0; + $RealDebrisCrystalDef = 0; + $RealDebrisDeuteriumDef = 0; + $TotalMoonChance = 0; + $TotalLostMetal = 0; + $TotalLostCrystal = 0; + $DebrisMetalDef = 0; + $DebrisCrystalDef = 0; + + $MoonHasBeenCreated = false; + $ThisDeathStarCount = 0; + + $RoundsData = $Combat['rounds']; + $Result = $Combat['result']; + $AtkShips = $Combat['AttackerShips']; + $DefShips = $Combat['DefenderShips']; + $AtkLost = $Combat['AtkLose']; + $DefLost = $Combat['DefLose']; + $DefSysLost = $Combat['DefSysLost']; + $ShotDown = $Combat['ShotDown']; + + $FleetStorage = 0; + + // Parse result data - attacker fleet + if(!empty($AtkShips[0])) + { + $QryUpdateFleets[0]['id'] = $FleetRow['fleet_id']; + foreach($AtkShips[0] as $ID => $Count) + { + $QryUpdateFleets[0]['mess'] = '1'; + if($Count > 0) + { + if($ID == 214) + { + $ThisDeathStarCount = $Count; + } + if(!isset($QryUpdateFleets[0]['count'])) + { + $QryUpdateFleets[0]['count'] = 0; + } + $QryUpdateFleets[0]['array'][] = "{$ID},{$Count}"; + $QryUpdateFleets[0]['count'] += $Count; + } + if($Result === COMBAT_ATK && (!isset($_Vars_Prices[$ID]['cantPillage']) || $_Vars_Prices[$ID]['cantPillage'] !== true)) + { + $FleetStorage += $_Vars_Prices[$ID]['capacity'] * $Count; + } + + if($Count < $AttackingFleets[0][$ID]) + { + $UserDev_UpFl[$FleetRow['fleet_id']][] = $ID.','.($AttackingFleets[0][$ID] - $Count); + } + } + + foreach($AttackingFleets[0] as $ID => $Count) + { + $Difference = $Count; + if(isset($AtkShips[0][$ID])) + { + $Difference -= $AtkShips[0][$ID]; + } + if($Difference > 0) + { + $QryUpdateFleets[0]['array_lost'][] = "{$ID},{$Difference}"; + } + } + if(!empty($QryUpdateFleets[0]['array_lost'])) + { + $QryUpdateFleets[0]['array_lost'] = implode(';', $QryUpdateFleets[0]['array_lost']); + } + + if($Result === COMBAT_ATK) + { + $FleetStorage -= $FleetRow['fleet_resource_metal']; + $FleetStorage -= $FleetRow['fleet_resource_crystal']; + $FleetStorage -= $FleetRow['fleet_resource_deuterium']; + + if($FleetStorage > 0) + { + $ResourceSteal_Factor = (COMBAT_RESOURCESTEAL_PERCENT / 100); + if(MORALE_ENABLED) + { + if(!$IsAbandoned AND $TargetUser['morale_level'] <= MORALE_PENALTY_RESOURCELOSE) + { + $ResourceSteal_NewFactor[] = MORALE_PENALTY_RESOURCELOSE_STEALPERCENT; + } + if($FleetRow['morale_level'] >= MORALE_BONUS_SOLOIDLERSTEAL AND $IdleHours >= (7 * 24)) + { + $ResourceSteal_NewFactor[] = MORALE_BONUS_SOLOIDLERSTEAL_STEALPERCENT; + } + if($FleetRow['morale_level'] <= MORALE_PENALTY_STEAL) + { + $ResourceSteal_NewFactor[] = MORALE_PENALTY_STEAL_STEALPERCENT; + } + else if($FleetRow['morale_level'] <= MORALE_PENALTY_IDLERSTEAL AND $IdleHours >= (7 * 24)) + { + $ResourceSteal_NewFactor[] = MORALE_PENALTY_IDLERSTEAL_STEALPERCENT; + } + + if(!empty($ResourceSteal_NewFactor)) + { + $ResourceSteal_Factor = (array_sum($ResourceSteal_NewFactor) / count($ResourceSteal_NewFactor)) / 100; + } + } + + $StolenMet = 0; + $StolenCry = 0; + $StolenDeu = 0; + + $AllowTakeMoreMet = 0; + $AllowTakeMoreCry = 0; + $AllowTakeMoreDeu = 0; + + $MaxMetSteal = $TargetPlanet['metal'] * $ResourceSteal_Factor; + $MaxCrySteal = $TargetPlanet['crystal'] * $ResourceSteal_Factor; + $MaxDeuSteal = $TargetPlanet['deuterium'] * $ResourceSteal_Factor; + + $StoragePerResource = $FleetStorage / 3; + + // First - calculate, if any resource will leave free storage + if($MaxMetSteal < $StoragePerResource) + { + $AllowTakeMore = ($StoragePerResource - $MaxMetSteal) / 2; + $AllowTakeMoreCry += $AllowTakeMore; + $AllowTakeMoreDeu += $AllowTakeMore; + $GiveAwayMet = true; + } + + if($MaxCrySteal < ($StoragePerResource + $AllowTakeMoreCry)) + { + $AllowTakeMore = (($StoragePerResource + $AllowTakeMoreCry) - $MaxCrySteal) / 2; + if($GiveAwayMet == false) + { + $AllowTakeMoreMet += $AllowTakeMore; + $AllowTakeMoreDeu += $AllowTakeMore; + } + else + { + $AllowTakeMoreDeu += $AllowTakeMore * 2; + } + $GiveAwayCry = true; + } + + if($MaxDeuSteal < ($StoragePerResource + $AllowTakeMoreDeu)) + { + $AllowTakeMore = (($StoragePerResource + $AllowTakeMoreDeu) - $MaxDeuSteal) / 2; + if($GiveAwayCry == false) + { + $AllowTakeMoreMet += $AllowTakeMore; + $AllowTakeMoreCry += $AllowTakeMore; + } + else + { + $AllowTakeMoreMet += $AllowTakeMore * 2; + } + } + + //Second - calculate stolen resources + if($MaxMetSteal > ($StoragePerResource + $AllowTakeMoreMet)) + { + $StolenMet = $StoragePerResource + $AllowTakeMoreMet; + } + else + { + $StolenMet = $MaxMetSteal; + } + if($MaxCrySteal > ($StoragePerResource + $AllowTakeMoreCry)) + { + $StolenCry = $StoragePerResource + $AllowTakeMoreCry; + } + else + { + $StolenCry = $MaxCrySteal; + } + if($MaxDeuSteal > ($StoragePerResource + $AllowTakeMoreDeu)) + { + $StolenDeu = $StoragePerResource + $AllowTakeMoreDeu; + } + else + { + $StolenDeu = $MaxDeuSteal; + } + + $StolenMet = floor($StolenMet); + $StolenCry = floor($StolenCry); + $StolenDeu = floor($StolenDeu); + if($StolenMet > 0) + { + $UserDev_UpFl[$FleetRow['fleet_id']][] = 'M,'.$StolenMet; + $TriggerTasksCheck['atk']['BATTLE_COLLECT_METAL'] = $StolenMet; + } + if($StolenCry > 0) + { + $UserDev_UpFl[$FleetRow['fleet_id']][] = 'C,'.$StolenCry; + $TriggerTasksCheck['atk']['BATTLE_COLLECT_CRYSTAL'] = $StolenCry; + } + if($StolenDeu > 0) + { + $UserDev_UpFl[$FleetRow['fleet_id']][] = 'D,'.$StolenDeu; + $TriggerTasksCheck['atk']['BATTLE_COLLECT_DEUTERIUM'] = $StolenDeu; + } + + $QryUpdateFleets[0]['metal'] = $StolenMet; + $QryUpdateFleets[0]['crystal'] = $StolenCry; + $QryUpdateFleets[0]['deuterium'] = $StolenDeu; + + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Metal'] = $StolenMet; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Crystal'] = $StolenCry; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Deuterium'] = $StolenDeu; + } + + //The aggressor has won the battle, let's check his chances of destroying this moon + if($ThisDeathStarCount > 0) + { + $DestructionDone = true; + + $ThisMoon_DestructionChance = (100 - sqrt($TargetPlanet['diameter'])) * sqrt($ThisDeathStarCount); + if($ThisMoon_DestructionChance > 100) + { + $ThisMoon_DestructionChance = 100; + } + else if($ThisMoon_DestructionChance <= 0) + { + $ThisMoon_DestructionChance = 0; + } + else + { + $ThisMoon_DestructionChance = round($ThisMoon_DestructionChance); + } + $ThisRand_MoonDestruction = mt_rand(1, 100); + + if($ThisRand_MoonDestruction <= $ThisMoon_DestructionChance) + { + $MoonHasBeenDestroyed = 1; + $Return['MoonDestroyed'] = true; + // Update User Stats + foreach($AttackersIDs as $UserID) + { + $UserStatsData[$UserID]['moons_destroyed'] += 1; + } + + // Get PlanetData to Redirect Fleets (from $_FleetCache) + $PlanetID = $_FleetCache['moonPlanets'][$TargetPlanet['id']]; + $PlanetName = $_FleetCache['planets'][$_FleetCache['moonPlanets'][$TargetPlanet['id']]]['name']; + + //Now delete moon from planet and moons list, and then from galaxy + $_FleetCache['deleteMoons'][] = $TargetPlanet['id']; + $GalaxyMoonID_NeedsUpdate = true; + + //Redirect fleets to a planet + $ChangeCoordinatesForFleets["{$PlanetID}<|>{$PlanetName}"] = $FleetRow['fleet_end_id']; + + $GetIDsToChangeArchive = ''; + $GetIDsToChangeArchive .= "SELECT `fleet_id`, `fleet_mission`, `fleet_start_id`, `fleet_end_id` FROM {{table}} "; + $GetIDsToChangeArchive .= "WHERE (`fleet_start_id` = {$FleetRow['fleet_end_id']} OR `fleet_end_id` = {$FleetRow['fleet_end_id']}) "; + $GetIDsToChangeArchive .= "AND `fleet_id` != {$FleetRow['fleet_id']}; -- MISSION DESTRUCTION [Q01][FID: {$FleetRow['fleet_id']}]"; + $GetData = doquery($GetIDsToChangeArchive, 'fleets'); + if(mysql_num_rows($GetData) > 0) + { + while($ParseFleet = mysql_fetch_assoc($GetData)) + { + $Pointer = &$Return['FleetArchive'][$ParseFleet['fleet_id']]; + if($ParseFleet['fleet_start_id'] == $FleetRow['fleet_end_id']) + { + $Pointer['Fleet_Start_Type_Changed'] = true; + $Pointer['Fleet_Start_ID_Changed'] = $PlanetID; + } + if($ParseFleet['fleet_end_id'] == $FleetRow['fleet_end_id']) + { + $Pointer['Fleet_End_Type_Changed'] = true; + $Pointer['Fleet_End_ID_Changed'] = $PlanetID; + if($ParseFleet['fleet_mission'] == 9) + { + $Pointer['Fleet_Mission_Changed'] = true; + } + } + } + } + + $Query_UpdateFleets = ''; + $Query_UpdateFleets .= "UPDATE {{table}} SET "; + $Query_UpdateFleets .= "`fleet_start_type` = IF(`fleet_start_id` = {$FleetRow['fleet_end_id']}, '1', `fleet_start_type`), "; + $Query_UpdateFleets .= "`fleet_start_id` = IF(`fleet_start_id` = {$FleetRow['fleet_end_id']}, {$PlanetID}, `fleet_start_id`), "; + $Query_UpdateFleets .= "`fleet_end_type` = IF(`fleet_end_id` = {$FleetRow['fleet_end_id']}, '1', `fleet_end_type`), "; + $Query_UpdateFleets .= "`fleet_mission` = IF(`fleet_end_id` = {$FleetRow['fleet_end_id']}, IF(`fleet_mission` = 9, 1, `fleet_mission`), `fleet_mission`), "; + $Query_UpdateFleets .= "`fleet_end_id` = IF(`fleet_end_id` = {$FleetRow['fleet_end_id']}, {$PlanetID}, `fleet_end_id`) "; + $Query_UpdateFleets .= "WHERE "; + $Query_UpdateFleets .= "(`fleet_start_id` = {$FleetRow['fleet_end_id']} OR `fleet_end_id` = {$FleetRow['fleet_end_id']}) "; + $Query_UpdateFleets .= "AND `fleet_id` != {$FleetRow['fleet_id']}; "; + $Query_UpdateFleets .= "-- MISSION DESTRUCTION [Q02][FID: {$FleetRow['fleet_id']}]"; + doquery($Query_UpdateFleets, 'fleets'); + + $QryChangeACS = "UPDATE {{table}} SET `end_type` = 1, `end_target_id` = {$PlanetID} WHERE `end_target_id` = {$FleetRow['fleet_end_id']}; -- MISSION DESTRUCTION [Q03][FID: {$FleetRow['fleet_id']}]"; + doquery($QryChangeACS, 'acs'); + + //maintenant on va verifier si la vue du joueur n est pas calee sur la lune qui est detruite + if($TargetUser['current_planet'] == $TargetPlanet['id'] AND $TargetUser['id'] != $_User['id']) + { + $_FleetCache['moonUserUpdate'][$TargetUser['id']] = $PlanetID; + } + } + + //Moon calculated so now check chances, that Fleet will be destroyed + $ThisFleet_DestructionChance = sqrt($TargetPlanet['diameter']) / 2; + if($ThisFleet_DestructionChance > 100) + { + $ThisFleet_DestructionChance = 100; + } + else if($ThisFleet_DestructionChance <= 0) + { + $ThisFleet_DestructionChance = 0; + } + else + { + $ThisFleet_DestructionChance = round($ThisFleet_DestructionChance); + } + $ThisRand_FleetDestruction = mt_rand(1, 100); + + if($ThisRand_FleetDestruction <= $ThisFleet_DestructionChance) + { + $FleetHasBeenDestroyed = true; + $FleetDestroyedByMoon = true; + + $DeleteFleet[] = $FleetRow['fleet_id']; + $UserDev_UpFl[$FleetRow['fleet_id']] = array(); + foreach($AttackingFleets[0] as $ShipID => $ShipCount) + { + $UserDev_UpFl[$FleetRow['fleet_id']][] = "{$ShipID},{$ShipCount}"; + } + + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Metal'] = 0; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Crystal'] = 0; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Deuterium'] = 0; + } + } + else + { + $MoonHasBeenDestroyed = -1; + } + } + } + else + { + $DeleteFleet[] = $FleetRow['fleet_id']; + foreach($AttackingFleets[0] as $ShipID => $ShipCount) + { + $UserDev_UpFl[$FleetRow['fleet_id']][] = "{$ShipID},{$ShipCount}"; + } + + $FleetHasBeenDestroyed = true; + } + + // Parse result data - Defenders + $i = 1; + if(!empty($DefendingFleets)) + { + foreach($DefendingFleets as $User => $Ships) + { + if($User == 0) + { + if($MoonHasBeenDestroyed !== 1) + { + $DefSysLostIDs = array_keys($DefSysLost); + $DefSysLostIDs[] = -1; + + foreach($Ships as $ID => $Count) + { + if(in_array($ID, $DefSysLostIDs)) + { + $Count = $DefShips[0][$ID]; + $Chance = mt_rand(60, 80 + (($TargetUser['engineer_time'] >= $FleetRow['fleet_start_time']) ? 20 : 0)); + $Fluctuation = mt_rand(-11, 11); + if($Fluctuation > 0) + { + $Fluctuation = 0; + } + $Rebuilt[$ID] = round($DefSysLost[$ID] * (($Chance + $Fluctuation) / 100)); + $Count += $Rebuilt[$ID]; + if($DefendingFleets[0][$ID] < $Count) + { + $Count = $DefendingFleets[0][$ID]; + } + unset($DefSysLost[$ID]); + } + else + { + $Count = $DefShips[0][$ID]; + } + if($Count == 0) + { + $Count = '0'; + } + $TargetPlanet[$_Vars_GameElements[$ID]] = $Count; + if($Count < $DefendingFleets[0][$ID]) + { + $UserDev_UpPl[] = $ID.','.($DefendingFleets[0][$ID] - $Count); + $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; + $HPQ_PlanetUpdatedFields[] = $_Vars_GameElements[$ID]; + } + } + } + } + else + { + $QryUpdateFleets[$i]['id'] = $DefendingFleetID[$User]; + if(!empty($DefShips[$User])) + { + foreach($Ships as $ID => $Count) + { + $ThisCount = 0; + if(!empty($DefShips[$User][$ID])) + { + $OldCount = $Count; + $Count = $DefShips[$User][$ID]; + $ThisCount = $Count; + if($Count > 0) + { + if(!isset($QryUpdateFleets[$i]['count'])) + { + $QryUpdateFleets[$i]['count'] = 0; + } + $QryUpdateFleets[$i]['array'][] = "{$ID},{$Count}"; + $QryUpdateFleets[$i]['count'] += $Count; + } + $Difference = $OldCount - $Count; + if($Difference > 0) + { + $QryUpdateFleets[$i]['array_lost'][] = "{$ID},{$Difference}"; + } + } + + if($ThisCount < $DefendingFleets[$User][$ID]) + { + $UserDev_UpFl[$DefendingFleetID[$User]][] = $ID.','.($DefendingFleets[$User][$ID] - $ThisCount); + } + } + + if(!empty($QryUpdateFleets[$i]['array_lost'])) + { + $QryUpdateFleets[$i]['array_lost'] = implode(';', $QryUpdateFleets[$i]['array_lost']); + } + } + else + { + $DeleteFleet[] = $DefendingFleetID[$User]; + foreach($DefendingFleets[$User] as $ShipID => $ShipCount) + { + $UserDev_UpFl[$DefendingFleetID[$User]][] = "{$ShipID},{$ShipCount}"; + } + } + } + $i += 1; + } + } + + if($MoonHasBeenDestroyed !== 1) + { + if($StolenMet > 0) + { + $TargetPlanet['metal'] -= $StolenMet; + $UserDev_UpPl[] = 'M,'.$StolenMet; + $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; + } + if($StolenCry > 0) + { + $TargetPlanet['crystal'] -= $StolenCry; + $UserDev_UpPl[] = 'C,'.$StolenCry; + $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; + } + if($StolenDeu > 0) + { + $TargetPlanet['deuterium'] -= $StolenDeu; + $UserDev_UpPl[] = 'D,'.$StolenDeu; + $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; + } + } + else + { + unset($_FleetCache['planets'][$FleetRow['fleet_end_id']]); + $_FleetCache['updatePlanets'][$TargetPlanet['id']] = false; + } + + // Update all fleets (if necessary) + if(!empty($QryUpdateFleets)) + { + foreach($QryUpdateFleets as $Data) + { + if(!empty($Data)) + { + if($Data['metal'] <= 0) + { + $Data['metal'] = '0'; + } + if($Data['crystal'] <= 0) + { + $Data['crystal'] = '0'; + } + if($Data['deuterium'] <= 0) + { + $Data['deuterium'] = '0'; + } + + if(!empty($Data['array'])) + { + $Data['array'] = implode(';', $Data['array']); + if(!empty($Data['array_lost'])) + { + if(strlen($Data['array']) > strlen($Data['array_lost'])) + { + $Return['FleetArchive'][$Data['id']]['Fleet_Array_Changes'] = "\"+D;{$Data['array_lost']}|\""; + } + else + { + $Return['FleetArchive'][$Data['id']]['Fleet_Array_Changes'] = "\"+L;{$Data['array']}|\""; + } + $Return['FleetArchive'][$Data['id']]['Fleet_Info_HasLostShips'] = '!true'; + } + if($Data['id'] != $FleetRow['fleet_id']) + { + $_FleetCache['defFleets'][$FleetRow['fleet_end_id']][$Data['id']]['fleet_array'] = $Data['array']; + } + } + + if($Data['id'] == $FleetRow['fleet_id'] AND $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['calcCount'] == 2) + { + // Update $_FleetCache, instead of sending additional Query to Update FleetState + // This fleet will be restored in this Calculation, so don't waste our time + $CachePointer = &$_FleetCache['fleetRowUpdate'][$Data['id']]; + $CachePointer['fleet_array'] = $Data['array']; + $CachePointer['fleet_resource_metal'] = $FleetRow['fleet_resource_metal'] + $Data['metal']; + $CachePointer['fleet_resource_crystal'] = $FleetRow['fleet_resource_crystal'] + $Data['crystal']; + $CachePointer['fleet_resource_deuterium'] = $FleetRow['fleet_resource_deuterium'] + $Data['deuterium']; + } + else + { + // Create UpdateFleet record for $_FleetCache + $CachePointer = &$_FleetCache['updateFleets'][$Data['id']]; + $CachePointer['fleet_array'] = $Data['array']; + $CachePointer['fleet_amount'] = $Data['count']; + $CachePointer['fleet_mess'] = $Data['mess']; + if(!isset($CachePointer['fleet_resource_metal'])) + { + $CachePointer['fleet_resource_metal'] = 0; + } + if(!isset($CachePointer['fleet_resource_crystal'])) + { + $CachePointer['fleet_resource_crystal'] = 0; + } + if(!isset($CachePointer['fleet_resource_deuterium'])) + { + $CachePointer['fleet_resource_deuterium'] = 0; + } + $CachePointer['fleet_resource_metal'] += $Data['metal']; + $CachePointer['fleet_resource_crystal'] += $Data['crystal']; + $CachePointer['fleet_resource_deuterium'] += $Data['deuterium']; + } + } + } + } + + if(!empty($UserDev_UpFl)) + { + foreach($UserDev_UpFl as $FleetID => $DevArray) + { + if($FleetID == $FleetRow['fleet_id']) + { + $SetCode = '2'; + $FleetUserID = $FleetRow['fleet_owner']; + } + else + { + $SetCode = '3'; + $FleetUserID = $DefendingFleetOwners[$FleetID]; + } + $UserDev_Log[] = array('UserID' => $FleetUserID, 'PlanetID' => '0', 'Date' => $FleetRow['fleet_start_time'], 'Place' => 15, 'Code' => $SetCode, 'ElementID' => $FleetID, 'AdditionalData' => implode(';', $DevArray)); + } + } + + // Calculate Debris & Looses - Init + $DebrisFactor_Fleet = $_GameConfig['Fleet_Cdr'] / 100; + $DebrisFactor_Defense = $_GameConfig['Defs_Cdr'] / 100; + + // Calculate looses - attacker + if(!empty($AtkLost)) + { + $DebrisMetalAtk = 0; + $DebrisCrystalAtk = 0; + foreach($AtkLost as $ID => $Count) + { + if(in_array($ID, $_Vars_ElementCategories['fleet'])) + { + if($DebrisFactor_Fleet > 0) + { + $DebrisMetalAtk += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Fleet); + $DebrisCrystalAtk += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Fleet); + } + $RealDebrisMetalAtk += floor($_Vars_Prices[$ID]['metal'] * $Count); + $RealDebrisCrystalAtk += floor($_Vars_Prices[$ID]['crystal'] * $Count); + $RealDebrisDeuteriumAtk += floor($_Vars_Prices[$ID]['deuterium'] * $Count); + } + } + $TotalLostMetal = $DebrisMetalAtk; + $TotalLostCrystal = $DebrisCrystalAtk; + } + + // Calculate looses - defender + if(!empty($DefLost)) + { + foreach($DefLost as $ID => $Count) + { + if(in_array($ID, $_Vars_ElementCategories['fleet'])) + { + if($DebrisFactor_Fleet > 0) + { + $DebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Fleet); + $DebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Fleet); + } + } + elseif(in_array($ID, $_Vars_ElementCategories['defense'])) + { + if($DebrisFactor_Defense > 0) + { + $DebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Defense); + $DebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Defense); + } + } + $RealDebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count); + $RealDebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count); + $RealDebrisDeuteriumDef += floor($_Vars_Prices[$ID]['deuterium'] * $Count); + } + $TotalLostMetal += $DebrisMetalDef; + $TotalLostCrystal += $DebrisCrystalDef; + } + + // Delete fleets (if necessary) + if(!empty($DeleteFleet)) + { + foreach($DeleteFleet as $FleetID) + { + $_FleetCache['fleetRowStatus'][$FleetID]['isDestroyed'] = true; + if(!empty($_FleetCache['updateFleets'][$FleetID])) + { + unset($_FleetCache['updateFleets'][$FleetID]); + } + $Return['FleetsToDelete'][] = $FleetID; + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed'] = true; + $Return['FleetArchive'][$FleetID]['Fleet_Info_HasLostShips'] = true; + if($FleetID == $FleetRow['fleet_id']) + { + if($FleetDestroyedByMoon) + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 7; + } + else + { + if($Result === COMBAT_DEF AND ($RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef) <= 0) + { + if(count($RoundsData) == 2) + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 1; + } + else + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 11; + } + } + else + { + if(count($RoundsData) == 2) + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 12; + } + else + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 2; + } + } + } + } + else + { + unset($_FleetCache['defFleets'][$FleetRow['fleet_end_id']][$FleetID]); + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 3; + } + } + } + + if($Result === COMBAT_DRAW AND (($RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef) <= 0)) + { + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed_Reason'] = 4; + } + + // Create debris field on the orbit + if($TotalLostMetal > 0 || $TotalLostCrystal > 0) + { + if($TotalLostCrystal == 0) + { + $TotalLostCrystal = '0'; + } + if($TotalLostMetal == 0) + { + $TotalLostMetal = '0'; + } + + if(isset($_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']]) && $_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']] > 0) + { + if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']]]['metal'])) + { + $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']]]['metal'] = 0; + } + if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']]]['crystal'])) + { + $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']]]['crystal'] = 0; + } + + $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']]]['metal'] += $TotalLostMetal; + $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']]]['crystal'] += $TotalLostCrystal; + $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byMoon'][$FleetRow['fleet_end_id']]]['updated'] = true; + $_FleetCache['updated']['galaxy'] = true; + } + else + { + $Query_UpdateGalaxy = ''; + $Query_UpdateGalaxy .= "UPDATE {{table}} SET `metal` = `metal` + {$TotalLostMetal}, `crystal` = `crystal` + {$TotalLostCrystal} "; + $Query_UpdateGalaxy .= "WHERE `id_moon` = {$FleetRow['fleet_end_id']} LIMIT 1; "; + $Query_UpdateGalaxy .= "-- MISSION DESTRUCTION [Q05][FID: {$FleetRow['fleet_id']}]"; + doquery($Query_UpdateGalaxy, 'galaxy'); + } + } + + // Check if Moon has been created + $FleetDebris = $TotalLostCrystal + $TotalLostMetal; + + $MoonChance = floor($FleetDebris / COMBAT_MOONPERCENT_RESOURCES); + if($MoonChance > 20) + { + $TotalMoonChance = $MoonChance; + $MoonChance = 20; + } + if($MoonChance < 1) + { + $UserChance = 0; + } + elseif($MoonChance >= 1) + { + $UserChance = mt_rand(1, 100); + } + + if($UserChance > 0 AND $UserChance <= $MoonChance AND $MoonHasBeenDestroyed === 1) + { + $CreatedMoonID = CreateOneMoonRecord($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetUserID, '', $MoonChance); + if($CreatedMoonID !== false) + { + $TriggerTasksCheck['atk']['CREATE_MOON'] = true; + $GalaxyMoonID_NeedsUpdate = false; + $MoonHasBeenCreated = true; + + $UserDev_UpPl[] = "L,{$CreatedMoonID}"; + + // Update User Stats + foreach($AttackersIDs as $UserID) + { + $UserStatsData[$UserID]['moons_created'] += 1; + } + } + } + + if(isset($GalaxyMoonID_NeedsUpdate) && $GalaxyMoonID_NeedsUpdate === true) + { + $_FleetCache['moonGalaxyUpdate'][] = $PlanetID; + } + + // Create DevLog Record (PlanetDefender's) + if(!empty($UserDev_UpPl) AND !$IsAbandoned) + { + $UserDev_Log[] = array('UserID' => $TargetUserID, 'PlanetID' => $TargetPlanetID, 'Date' => $FleetRow['fleet_start_time'], 'Place' => 15, 'Code' => '1', 'ElementID' => ($MoonHasBeenDestroyed === 1 ? '1' : '0'), 'AdditionalData' => implode(';', $UserDev_UpPl)); + } + + // Morale System + if(MORALE_ENABLED AND !$IsAbandoned AND !$IsAllyFight AND $IdleHours < (7 * 24)) + { + $Morale_Factor = $FleetRow['morale_points'] / $TargetUser['morale_points']; + if($Morale_Factor < 1) + { + $Morale_Factor = pow($Morale_Factor, -1); + $Morale_AttackerStronger = false; + } + else + { + $Morale_AttackerStronger = true; + } + + if($Morale_Factor > MORALE_MINIMALFACTOR) + { + if($Morale_AttackerStronger) + { + $Morale_Update_Attacker_Type = MORALE_NEGATIVE; + if($Result === COMBAT_DEF OR $Result === COMBAT_DRAW) + { + $Morale_Update_Defender_Type = MORALE_POSITIVE; + } + } + else + { + $Morale_Update_Attacker_Type = MORALE_POSITIVE; + } + + $Morale_Updated = Morale_AddMorale($FleetRow, $Morale_Update_Attacker_Type, $Morale_Factor, 1, 1, $FleetRow['fleet_start_time']); + if($Morale_Updated) + { + $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['level'] = $FleetRow['morale_level']; + $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['droptime'] = $FleetRow['morale_droptime']; + $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['lastupdate'] = $FleetRow['morale_lastupdate']; + + $ReportData['morale'][$FleetRow['fleet_owner']] = array + ( + 'usertype' => 'atk', + 'type' => $Morale_Update_Attacker_Type, + 'factor' => $Morale_Factor, + 'level' => $FleetRow['morale_level'] + ); + } + + if($Morale_Update_Defender_Type !== null) + { + if($Result === COMBAT_DRAW) + { + $Morale_LevelFactor = 1/2; + $Morale_TimeFactor = 1/2; + } + else + { + $Morale_LevelFactor = 1; + $Morale_TimeFactor = 1; + } + + $Morale_Updated = Morale_AddMorale($TargetUser, $Morale_Update_Defender_Type, $Morale_Factor, $Morale_LevelFactor, $Morale_TimeFactor, $FleetRow['fleet_start_time']); + if($Morale_Updated) + { + $_FleetCache['MoraleCache'][$TargetUser['id']]['level'] = $TargetUser['morale_level']; + $_FleetCache['MoraleCache'][$TargetUser['id']]['droptime'] = $TargetUser['morale_droptime']; + $_FleetCache['MoraleCache'][$TargetUser['id']]['lastupdate'] = $TargetUser['morale_lastupdate']; + + $ReportData['morale'][$TargetUser['id']] = array + ( + 'usertype' => 'def', + 'type' => MORALE_POSITIVE, + 'factor' => $Morale_Factor, + 'level' => $TargetUser['morale_level'] + ); + } + } + } + } + + // CREATE BATTLE REPORT + $ReportData['init']['usr']['atk'] = $AttackersData; + $ReportData['init']['usr']['def'] = $DefendersData; + + $ReportData['init']['time'] = $totaltime; + $ReportData['init']['date'] = $FleetRow['fleet_start_time']; + + $ReportData['init']['result'] = $Result; + $ReportData['init']['met'] = $StolenMet; + $ReportData['init']['cry'] = $StolenCry; + $ReportData['init']['deu'] = $StolenDeu; + $ReportData['init']['deb_met'] = $TotalLostMetal; + $ReportData['init']['deb_cry'] = $TotalLostCrystal; + $ReportData['init']['moon_chance'] = $MoonChance; + $ReportData['init']['total_moon_chance'] = $TotalMoonChance; + $ReportData['init']['moon_created'] = $MoonHasBeenCreated; + $ReportData['init']['moon_destroyed'] = $MoonHasBeenDestroyed; + $ReportData['init']['moon_des_chance'] = $ThisMoon_DestructionChance; + $ReportData['init']['fleet_destroyed'] = $FleetHasBeenDestroyed; + $ReportData['init']['fleet_des_chance'] = $ThisFleet_DestructionChance; + $ReportData['init']['planet_name'] = $TargetPlanetGetName; + $ReportData['init']['onMoon'] = true; + $ReportData['init']['atk_lost'] = $RealDebrisMetalAtk + $RealDebrisCrystalAtk + $RealDebrisDeuteriumAtk; + $ReportData['init']['def_lost'] = $RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef; + + foreach($RoundsData as $RoundKey => $RoundData) + { + foreach($RoundData as $MainKey => $RoundData2) + { + if(!empty($RoundData2['ships'])) + { + foreach($RoundData2['ships'] as $UserKey => $UserData) + { + $RoundsData[$RoundKey][$MainKey]['ships'][$UserKey] = Array2String($UserData); + } + } + } + } + $ReportData['rounds'] = $RoundsData; + + if(count($RoundsData) <= 2 AND $Result === COMBAT_DEF) + { + $DisallowAttackers = true; + } + else + { + $DisallowAttackers = false; + } + + $CreatedReport = CreateBattleReport($ReportData, array('atk' => $AttackersIDs, 'def' => $DefendersIDs), $DisallowAttackers); + $ReportID = $CreatedReport['ID']; + $ReportHasHLinkRelative = 'battlereport.php?hash='.$CreatedReport['Hash']; + $ReportHasHLinkReal = GAMEURL.$ReportHasHLinkRelative; + + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_ReportID'] = $ReportID; + if(!empty($DefendingFleetID)) + { + foreach($DefendingFleetID as $FleetID) + { + $Return['FleetArchive'][$FleetID]['Fleet_DefenderReportIDs'] = "\"+,{$ReportID}\""; + } + } + + // Update battle stats & set Battle Report colors + if(!$IsAllyFight) + { + if($Result === COMBAT_ATK) + { + foreach($AttackersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_won'] += 1; + } + foreach($DefendersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_lost'] += 1; + } + if($FleetDestroyedByMoon) + { + $ReportColor = '#AD5CD6'; + } + else + { + $ReportColor = 'green'; + } + if($MoonHasBeenDestroyed === 1) + { + $ReportColor3 = 'green'; + } + else + { + $ReportColor3 = 'orange'; + } + $ReportColor2 = 'red'; + } + elseif($Result === COMBAT_DRAW) + { + foreach($AttackersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_draw'] += 1; + } + foreach($DefendersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_draw'] += 1; + } + $ReportColor = 'orange'; + $ReportColor2 = 'orange'; + } + elseif($Result === COMBAT_DEF) + { + foreach($AttackersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_lost'] += 1; + } + foreach($DefendersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_won'] += 1; + } + $ReportColor = 'red'; + $ReportColor2 = 'green'; + } + + // Update User Destroyed & Lost Stats + if(!empty($ShotDown)) + { + foreach($ShotDown as $ThisType => $ThisData) + { + foreach($ThisData as $ThisType2 => $ThisData2) + { + if($ThisType2 == 'd') + { + $ThisKey = 'destroyed_'; + } + else + { + $ThisKey = 'lost_'; + } + foreach($ThisData2 as $UserID => $DestShips) + { + if($UserID == 0) + { + if($ThisType == 'atk') + { + $ThisUserID = $FleetRow['fleet_owner']; + } + else + { + $ThisUserID = $TargetUser['id']; + } + } + else + { + if($ThisType == 'atk') + { + $ThisUserID = $AttackingFleetOwners[$AttackingFleetID[$UserID]]; + } + else + { + $ThisUserID = $DefendingFleetOwners[$DefendingFleetID[$UserID]]; + } + } + foreach($DestShips as $ShipID => $ShipCount) + { + $UserStatsData[$ThisUserID][$ThisKey.$ShipID] += $ShipCount; + } + } + } + } + } + + if(!empty($ShotDown)) + { + if(!empty($ShotDown['atk']['d'][0])) + { + if(!isset($TriggerTasksCheck['atk']['BATTLE_DESTROY_MILITARYUNITS'])) + { + $TriggerTasksCheck['atk']['BATTLE_DESTROY_MILITARYUNITS'] = 0; + } + if(!isset($TriggerTasksCheck['atk']['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'])) + { + $TriggerTasksCheck['atk']['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'] = 0; + } + foreach($ShotDown['atk']['d'][0] as $ShipID => $ShipCount) + { + $TriggerTasksCheck['atk']['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'] += (($_Vars_Prices[$ShipID]['metal'] + $_Vars_Prices[$ShipID]['crystal'] + $_Vars_Prices[$ShipID]['deuterium']) * $ShipCount); + if(in_array($ShipID, $_Vars_ElementCategories['units']['military'])) + { + $TriggerTasksCheck['atk']['BATTLE_DESTROY_MILITARYUNITS'] += $ShipCount; + } + } + } + } + + if($Result === COMBAT_ATK) + { + $TriggerTasksCheck['atk']['BATTLE_WIN'] = true; + $TriggerTasksCheck['atk']['BATTLE_WINORDRAW_SOLO_TOTALLIMIT'] = true; + $TriggerTasksCheck['atk']['BATTLE_WINORDRAW_SOLO_LIMIT'] = true; + $TriggerTasksCheck['atk']['BATTLE_WINORDRAW_LIMIT'] = true; + } + else if($Result === COMBAT_DRAW) + { + $TriggerTasksCheck['atk']['BATTLE_WINORDRAW_SOLO_TOTALLIMIT'] = true; + $TriggerTasksCheck['atk']['BATTLE_WINORDRAW_SOLO_LIMIT'] = true; + $TriggerTasksCheck['atk']['BATTLE_WINORDRAW_LIMIT'] = true; + } + else if($Result === COMBAT_DEF) + { + $TriggerTasksCheck['atk']['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'] = 0; + } + if($MoonHasBeenDestroyed === 1) + { + $TriggerTasksCheck['atk']['DESTROY_MOON'] = true; + } + + if(!$IsAbandoned AND !$DestructionDone AND $AttackingFleets[0][214] >= 1000) + { + $TriggerTasksCheck['def']['BATTLE_BLOCK_MOONDESTROY'] = true; + } + } + else + { + if($MoonHasBeenCreated) + { + $TriggerTasksCheck['atk']['CREATE_MOON_FRIENDLY'] = true; + } + unset($TriggerTasksCheck['atk']['BATTLE_COLLECT_METAL']); + unset($TriggerTasksCheck['atk']['BATTLE_COLLECT_CRYSTAL']); + unset($TriggerTasksCheck['atk']['BATTLE_COLLECT_DEUTERIUM']); + + foreach($AttackersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_inAlly'] += 1; + } + foreach($DefendersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_inAlly'] += 1; + } + if($Result === COMBAT_ATK) + { + if($FleetDestroyedByMoon) + { + $ReportColor = '#AD5CD6'; + } + else + { + $ReportColor = 'green'; + } + if($MoonHasBeenDestroyed === 1) + { + $ReportColor3 = 'green'; + } + else + { + $ReportColor3 = 'orange'; + } + $ReportColor2 = 'red'; + } + elseif($Result === COMBAT_DRAW) + { + $ReportColor = 'orange'; + $ReportColor2 = 'orange'; + } + elseif($Result === COMBAT_DEF) + { + $ReportColor = 'red'; + $ReportColor2 = 'green'; + } + } + + $TargetTypeMsg = $_Lang['BR_Target_'.$FleetRow['fleet_end_type']]; + if(!empty($ReportColor3)) + { + $TargetTypeMsg = "{$TargetTypeMsg}"; + } + $Message['msg_id'] = '072'; + $Message['args'] = array + ( + $ReportID, $ReportColor, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetTypeMsg, + prettyNumber($RealDebrisMetalAtk + $RealDebrisCrystalAtk + $RealDebrisDeuteriumAtk), + prettyNumber($RealDebrisCrystalDef + $RealDebrisMetalDef + $RealDebrisDeuteriumDef), + ($FleetDestroyedByMoon != true ? prettyNumber($StolenMet) : 0), + ($FleetDestroyedByMoon != true ? prettyNumber($StolenCry) : 0), + ($FleetDestroyedByMoon != true ? prettyNumber($StolenDeu) : 0), + prettyNumber(isset($TotalLostMetal) ? $TotalLostMetal : 0), prettyNumber(isset($TotalLostCrystal) ? $TotalLostCrystal : 0), + $ReportHasHLinkRelative, $ReportHasHLinkReal + ); + $Message = json_encode($Message); + Cache_Message($CurrentUserID, 0, $FleetRow['fleet_start_time'], 3, '003', '012', $Message); + + if(!$IsAbandoned) + { + $Message = false; + $Message['msg_id'] = '074'; + if(!empty($Rebuilt) AND (array)$Rebuilt === $Rebuilt) + { + foreach($Rebuilt as $SysID => $Count) + { + $RebuildReport[] = ''.$_Lang['tech'][$SysID].' - '.$Count; + } + $RebuildReport = implode('
    ', $RebuildReport); + } + else + { + if($MoonHasBeenDestroyed !== 1) + { + if(!isset($DefSysLostIDs) || count($DefSysLostIDs) == 1) + { + $RebuildReport = $_Lang['no_loses_in_defence']; + } + else + { + $RebuildReport = $_Lang['nothing_have_been_rebuilt']; + } + } + else + { + $RebuildReport = $_Lang['moon_has_been_destroyed']; + } + } + $Message['args'] = array + ( + $ReportID, $ReportColor2, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], + $TargetTypeMsg, $RebuildReport, $ReportHasHLinkRelative, $ReportHasHLinkReal + ); + $Message = json_encode($Message); + Cache_Message($TargetUserID, 0, $FleetRow['fleet_start_time'], 3, '003', '012', $Message); + } + + if(count($DefendersIDs) > 1) + { + $Message = false; + $Message['msg_id'] = '075'; + $Message['args'] = array + ( + $ReportID, $ReportColor2, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], + $TargetTypeMsg, $ReportHasHLinkRelative, $ReportHasHLinkReal + ); + $Message = json_encode($Message); + unset($DefendersIDs[0]); + Cache_Message($DefendersIDs, 0, $FleetRow['fleet_start_time'], 3, '003', '017', $Message); + } + + if(!empty($TriggerTasksCheck)) + { + global $GlobalParsedTasks; + } + + if(!empty($TriggerTasksCheck['atk'])) + { + // Parse Attacker Tasks + if($_User['id'] == $FleetRow['fleet_owner']) + { + $ThisTaskUser = $_User; + } + else + { + if(empty($GlobalParsedTasks[$FleetRow['fleet_owner']]['tasks_done_parsed'])) + { + $GetUserTasksDone['tasks_done'] = $_FleetCache['userTasks'][$FleetRow['fleet_owner']]; + Tasks_CheckUservar($GetUserTasksDone); + $GlobalParsedTasks[$FleetRow['fleet_owner']] = $GetUserTasksDone; + } + $ThisTaskUser = $GlobalParsedTasks[$FleetRow['fleet_owner']]; + $ThisTaskUser['id'] = $FleetRow['fleet_owner']; + } + + if(isset($TriggerTasksCheck['atk']['BATTLE_WIN'])) + { + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WIN', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + if(isset($TriggerTasksCheck['atk']['BATTLE_WINORDRAW_SOLO_TOTALLIMIT']) && $TotalMoonChance > 0) + { + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WINORDRAW_SOLO_TOTALLIMIT', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TotalMoonChance) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TotalMoonChance); + } + )); + } + if(isset($TriggerTasksCheck['atk']['BATTLE_WINORDRAW_SOLO_LIMIT']) || isset($TriggerTasksCheck['atk']['BATTLE_WINORDRAW_LIMIT'])) + { + $Debris_Total_Def = ($DebrisMetalDef + $DebrisCrystalDef) / COMBAT_MOONPERCENT_RESOURCES; + if(isset($TriggerTasksCheck['atk']['BATTLE_WINORDRAW_SOLO_LIMIT'])) + { + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WINORDRAW_SOLO_LIMIT', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $Debris_Total_Def) + { + if($JobArray['minimalEnemyPercentLimit'] > $Debris_Total_Def) + { + return true; + } + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + if(isset($TriggerTasksCheck['atk']['BATTLE_WINORDRAW_LIMIT'])) + { + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WINORDRAW_LIMIT', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $Debris_Total_Def) + { + if($JobArray['minimalEnemyPercentLimit'] > $Debris_Total_Def) + { + return true; + } + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + } + if(isset($TriggerTasksCheck['atk']['DESTROY_MOON'])) + { + Tasks_TriggerTask($ThisTaskUser, 'DESTROY_MOON', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TargetPlanet) + { + if(isset($JobArray['minimalDiameter']) && $JobArray['minimalDiameter'] > $TargetPlanet['diameter']) + { + return true; + } + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + if(!$FleetHasBeenDestroyed) + { + Tasks_TriggerTask($ThisTaskUser, 'DESTROY_MOON_NOFLEETLOSS', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TargetPlanet) + { + if(isset($JobArray['minimalDiameter']) && $JobArray['minimalDiameter'] > $TargetPlanet['diameter']) + { + return true; + } + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + } + if(isset($TriggerTasksCheck['atk']['BATTLE_COLLECT_METAL']) && $TriggerTasksCheck['atk']['BATTLE_COLLECT_METAL'] > 0 && !$FleetHasBeenDestroyed) + { + $TaskTemp = $TriggerTasksCheck['atk']['BATTLE_COLLECT_METAL']; + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_METAL', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); + } + )); + } + if(isset($TriggerTasksCheck['atk']['BATTLE_COLLECT_CRYSTAL']) && $TriggerTasksCheck['atk']['BATTLE_COLLECT_CRYSTAL'] > 0 && !$FleetHasBeenDestroyed) + { + $TaskTemp = $TriggerTasksCheck['atk']['BATTLE_COLLECT_CRYSTAL']; + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_CRYSTAL', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); + } + )); + } + if(isset($TriggerTasksCheck['atk']['BATTLE_COLLECT_DEUTERIUM']) && $TriggerTasksCheck['atk']['BATTLE_COLLECT_DEUTERIUM'] > 0 && !$FleetHasBeenDestroyed) + { + $TaskTemp = $TriggerTasksCheck['atk']['BATTLE_COLLECT_DEUTERIUM']; + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_DEUTERIUM', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); + } + )); + } + if(isset($TriggerTasksCheck['atk']['CREATE_MOON'])) + { + Tasks_TriggerTask($ThisTaskUser, 'CREATE_MOON', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + if(isset($TriggerTasksCheck['atk']['CREATE_MOON_FRIENDLY'])) + { + Tasks_TriggerTask($ThisTaskUser, 'CREATE_MOON_FRIENDLY', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + if(isset($TriggerTasksCheck['atk']['BATTLE_DESTROY_MILITARYUNITS']) && $TriggerTasksCheck['atk']['BATTLE_DESTROY_MILITARYUNITS'] > 0) + { + $TaskTemp = $TriggerTasksCheck['atk']['BATTLE_DESTROY_MILITARYUNITS']; + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_DESTROY_MILITARYUNITS', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); + } + )); + } + if(isset($TriggerTasksCheck['atk']['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO']) && $TriggerTasksCheck['atk']['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO'] > 0) + { + $TaskTemp2 = 0; + foreach($AttackingFleets[0] as $ShipID => $ShipCount) + { + $TaskTemp2 += (($_Vars_Prices[$ShipID]['metal'] + $_Vars_Prices[$ShipID]['crystal'] + $_Vars_Prices[$ShipID]['deuterium']) * $ShipCount); + } + $TaskTemp = $TriggerTasksCheck['atk']['BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO']; + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp, $TaskTemp2) + { + if($JobArray['minimalEnemyCost'] > $TaskTemp) + { + return true; + } + if($TaskTemp2 > ($TaskTemp * $JobArray['maximalOwnValue'])) + { + return true; + } + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + } + + if(!empty($TriggerTasksCheck['def']) AND !$IsAbandoned) + { + // Parse Defender Tasks + if($_User['id'] == $FleetRow['fleet_target_owner']) + { + $ThisTaskUser = $_User; + } + else + { + if(empty($GlobalParsedTasks[$FleetRow['fleet_target_owner']]['tasks_done_parsed'])) + { + $GetUserTasksDone['tasks_done'] = $_FleetCache['userTasks'][$FleetRow['fleet_target_owner']]; + Tasks_CheckUservar($GetUserTasksDone); + $GlobalParsedTasks[$FleetRow['fleet_target_owner']] = $GetUserTasksDone; + } + $ThisTaskUser = $GlobalParsedTasks[$FleetRow['fleet_target_owner']]; + $ThisTaskUser['id'] = $FleetRow['fleet_target_owner']; + } + + if(isset($TriggerTasksCheck['def']['BATTLE_BLOCK_MOONDESTROY'])) + { + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_BLOCK_MOONDESTROY'); + } + } + } + + if($FleetRow['calcType'] == 3 && (!isset($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed']) || $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] !== true)) + { + if(!empty($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']])) + { + foreach($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']] as $Key => $Value) + { + $FleetRow[$Key] = $Value; + } + } + $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack'] = true; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack_Time'] = $Now; + RestoreFleetToPlanet($FleetRow, true, $_FleetCache); + } + + return $Return; +} + +?> diff --git a/includes/functions/MissionCaseExpedition.php b/includes/functions/MissionCaseExpedition.php index a8804cb55..934590ea6 100644 --- a/includes/functions/MissionCaseExpedition.php +++ b/includes/functions/MissionCaseExpedition.php @@ -1,476 +1,476 @@ - 1.0,// Small Cargo Ship - 203 => 1.5,// Big Cargo Ship - 204 => 0.5,// Light Hunter - 205 => 1.5,// Heavy Hunter - 206 => 2.0,// cruiser - 207 => 2.5,// Battle Ship - 208 => 0.5,// Colonisator - 209 => 1.0,// Recycler - 210 => 0.01, // Spy Probe - 211 => 3.0,// Bomber - 212 => 0.0,// Solar Satelite - 213 => 3.5,// Destroyer - 214 => 5.0,// Death Star - 215 => 3.2,// BattleShip - 216 => 0.0,// Orbital Station - 217 => 2.0,// Mega Cargo - 218 => 7.5,// Annihilator - 219 => 0.02// Space Shuttle - ); - - $RatioGain = array - ( - 202 => 0.25, // Small Cargo Ship - 203 => 0.2, // Big Cargo Ship - 204 => 0.25, // Light Hunter - 205 => 0.2, // Heavy Hunter - 206 => 0.155,// cruiser - 207 => 0.085, // Battle Ship - 208 => 0.1, // Colonisator - 209 => 0.2, // Recycler - 210 => 0.2, // Spy Probe - 211 => 0.0625,// Bomber - //212 => 0.0, // Solar Satelite - 213 => 0.04,// Destroyer - //214 => 0.0, // Death Star - 215 => 0.05,// BattleShip - //216 => 0.0, // Orbital Station - 217 => 0.0625,// Mega Cargo - //218 => 0.0, // Annihilator - 219 => 0.05// Space Shuttle - ); - - $FleetCapacity = -($FleetRow['fleet_resource_metal'] + $FleetRow['fleet_resource_crystal'] + $FleetRow['fleet_resource_deuterium']); - - $FleetArrTemp = explode(';', $FleetRow['fleet_array']); - foreach($FleetArrTemp as $Ships) - { - if(!empty($Ships)) - { - $ShipsTemp = explode(',', $Ships); - $FleetArray[$ShipsTemp[0]] = $ShipsTemp[1]; - - $FleetCapacity += $_Vars_Prices[$ShipsTemp[0]]['capacity'] * $ShipsTemp[1]; - $FleetPoints += ($PointsFlotte[$ShipsTemp[0]] / 10) * $ShipsTemp[1]; - $FleetMetalCost += $_Vars_Prices[$ShipsTemp[0]]['metal'] * $ShipsTemp[1]; - $FleetCrystCost += $_Vars_Prices[$ShipsTemp[0]]['crystal'] * $ShipsTemp[1]; - $FleetDeuteCost += $_Vars_Prices[$ShipsTemp[0]]['deuterium'] * $ShipsTemp[1]; - } - } - $FleetCount = $FleetRow['fleet_amount']; - $FleetStayDuration = ($FleetRow['fleet_end_stay'] - $FleetRow['fleet_start_time']) / 3600; - - $WhatHappened = rand(1,100); - - if($WhatHappened >= 1 AND $WhatHappened <= 15) - { - // Partial/Complete Destruction - - $DestructionPercent = rand(1,100); - foreach($FleetArray as $Ship => $Count) - { - $NewCount = floor($Count * ((100 - $DestructionPercent) / 100)); - $NewFleetArray[$Ship] = $NewCount; - $NewFleetCount += $NewCount; - if($NewCount < $FleetArray[$Ship]) - { - $DestroyedArray[$Ship] = $FleetArray[$Ship] - $NewCount; - } - } - - if($NewFleetCount < $FleetCount AND $NewFleetCount > 0) - { - foreach($NewFleetArray as $Ship => $Count) - { - $NewFleetArrayString[] = $Ship.','.$Count; - } - $NewFleetArray = implode(';', $NewFleetArrayString); - - $QryUpdateFleet = "UPDATE {{table}} SET "; - $QryUpdateFleet .= "`fleet_array` = '{$NewFleetArray}', "; - $QryUpdateFleet .= "`fleet_amount` = {$NewFleetCount}, "; - $QryUpdateFleet .= "`fleet_mess` = '1'"; - $QryUpdateFleet .= "WHERE "; - $QryUpdateFleet .= "`fleet_id` = '". $FleetRow['fleet_id'] ."'; -- EXPEDITION QUERY 1"; - doquery($QryUpdateFleet, 'fleets'); - - $return['fleet_end_amount'] = $NewFleetCount; - $return['fleet_end_array'] = '"'.$NewFleetArray.'"'; - - $Message = false; - $Message['msg_id'] = '0'.rand(42,44); - foreach($DestroyedArray as $Ship => $Count) - { - $Message['args'] .= '
    '.$_Lang['tech'][$Ship].' - '.$Count; - } - - $Message = json_encode($Message); - - Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_stay'], 15, $MessSender, $MessTitle, $Message); - - $FleetRow['fleet_array'] = $NewFleetArray; - $FleetRow['fleet_amount']= $NewFleetCount; - } - else if($NewFleetCount == $FleetCount) - { - $Message = false; - $Message['msg_id'] = '0'.rand(45,47); - $Message['args'] = array(''); - - $Message = json_encode($Message); - - Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_stay'], 15, $MessSender, $MessTitle, $Message); - } - else - { - $Message = false; - $Message['msg_id'] = '0'.rand(48,50); - $Message['args']= array(''); - - $Message = json_encode($Message); - - Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_stay'], 15, $MessSender, $MessTitle, $Message); - - doquery("DELETE FROM {{table}} WHERE `fleet_id` = {$FleetRow['fleet_id']}; -- EXPEDITION QUERY 2", 'fleets'); - $fleetHasBeenDeleted = TRUE; - - $return['fleet_destroyed'] = '1'; - $return['fleet_destroy_reason'] = '"expedition"'; - } - } - else if($WhatHappened >= 16 AND $WhatHappened <= 55) - { - // Resources found - - $MaxResources = 10000000; - - $MaxFoundMetal = $FleetMetalCost * 0.2; - $MaxFoundCrystal = $FleetCrystCost * 0.2; - $MaxFoundDeuterium = $FleetDeuteCost * 0.2; - if($MaxFoundMetal > $MaxResources) - { - $MaxFoundMetal = $MaxResources; - } - if($MaxFoundCrystal > $MaxResources) - { - $MaxFoundCrystal = $MaxResources; - } - if($MaxFoundDeuterium > $MaxResources) - { - $MaxFoundDeuterium = $MaxResources; - } - $FoundMetal = rand(round((($MaxFoundMetal * 0.001) + 1) * (pow(1.2, $FleetStayDuration) - 0.2)), $MaxFoundMetal); - $FoundCrystal = rand(round((($MaxFoundCrystal * 0.001) + 1) * (pow(1.2, $FleetStayDuration) - 0.2)), $MaxFoundCrystal); - $FoundDeuterium = rand(round((($MaxFoundDeuterium * 0.001) + 1) * (pow(1.2, $FleetStayDuration) - 0.2)), $MaxFoundDeuterium); - - $RandFirst = rand(0,2); - $RandSecond = rand(0,1); - $List = array('Metal', 'Crystal', 'Deuterium'); - $FleetInitCapacity = $FleetCapacity; - - if($FleetCapacity > 0) - { - eval('$FoundResource = $Found'.$List[$RandFirst].';'); - eval('$GottenResource = &$Gotten'.$List[$RandFirst].';'); - if($FleetCapacity > $FoundResource) - { - $GottenResource = $FoundResource; - } - else - { - $GottenResource = $FleetCapacity; - } - $FleetCapacity -= $GottenResource; - - array_splice($List, $RandFirst, 1); - - if($FleetCapacity > 0) - { - eval('$FoundResource = $Found'.$List[$RandSecond].';'); - eval('$GottenResource = &$Gotten'.$List[$RandSecond].';'); - if($FleetCapacity > $FoundResource) - { - $GottenResource = $FoundResource; - } - else - { - $GottenResource = $FleetCapacity; - } - $FleetCapacity -= $GottenResource; - - array_splice($List, $RandSecond, 1); - - if($FleetCapacity > 0) - { - eval('$FoundResource = $Found'.$List[0].';'); - eval('$GottenResource = &$Gotten'.$List[0].';'); - if($FleetCapacity > $FoundResource) - { - $GottenResource = $FoundResource; - } - else - { - $GottenResource = $FleetCapacity; - } - $FleetCapacity -= $GottenResource; - } - } - } - - $Message = false; - - if($FleetCapacity < $FleetInitCapacity) - { - if($GottenMetal > 0) - { - $QryUpdateResources[] = "`fleet_resource_metal` = `fleet_resource_metal` + {$GottenMetal}"; - $MsgGottenArray[] = $_Lang['Metal'].': '.prettyNumber($GottenMetal); - $FleetRow['fleet_resource_metal'] += $GottenMetal; - } - else - { - $GottenMetal = '0'; - } - if($GottenCrystal > 0) - { - $QryUpdateResources[] = "`fleet_resource_crystal` = `fleet_resource_crystal` + {$GottenCrystal}"; - $MsgGottenArray[] = $_Lang['Crystal'].': '.prettyNumber($GottenCrystal); - $FleetRow['fleet_resource_crystal'] += $GottenCrystal; - } - else - { - $GottenCrystal = '0'; - } - if($GottenDeuterium > 0) - { - $QryUpdateResources[] = "`fleet_resource_deuterium` = `fleet_resource_deuterium` + {$GottenDeuterium}"; - $MsgGottenArray[] = $_Lang['Deuterium'].': '.prettyNumber($GottenDeuterium); - $FleetRow['fleet_resource_deuterium'] += $GottenDeuterium; - } - else - { - $GottenDeuterium = '0'; - } - - $return['fleet_end_resource_metal'] = $GottenMetal; - $return['fleet_end_resource_crystal'] = $GottenCrystal; - $return['fleet_end_resource_deuterium'] = $GottenDeuterium; - - $QryUpdateFleet = "UPDATE {{table}} SET "; - $QryUpdateFleet .= implode(", ", $QryUpdateResources); - $QryUpdateFleet .= ", `fleet_mess` = 1 "; - $QryUpdateFleet .= "WHERE `fleet_id` = {$FleetRow['fleet_id']};"; - doquery($QryUpdateFleet, 'fleets'); - - $Message['msg_id'] = '0'.rand(51, 53); - $Message['args'] = implode('
    ', $MsgGottenArray); - } - else - { - $Message['msg_id'] = '0'.rand(54, 56); - $Message['args'] = array(''); - } - - $Message = json_encode($Message); - - Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_stay'], 15, $MessSender, $MessTitle, $Message); - } - else if($WhatHappened >= 56 AND $WhatHappened <= 65) - { - // Found Ships - - $MaxShipsPoints = 20000; - if($FleetPoints > $MaxShipsPoints) - { - $FleetPoints = $MaxShipsPoints; - } - - $HowManyShipsToRandom = rand(1,5); - $RandomizedShips = array_rand($RatioGain, $HowManyShipsToRandom); - $NewFleetArray = $FleetArray; - if((array)$RandomizedShips === $RandomizedShips) - { - foreach($RandomizedShips as $Ship) - { - $FoundShips[$Ship] = round((($FleetPoints * 5) * $RatioGain[$Ship] * (5 / $HowManyShipsToRandom)) * (pow(1.1, $FleetStayDuration) - 0.1)); - if($FleetArray[$Ship] > 0) - { - $ThisShipMaxCount = ($FleetPoints / ($PointsFlotte[$Ship] / 10)) * $RatioGain[$Ship] * 0.8; - } - else - { - $ThisShipMaxCount = ($FleetArray[$Ship] * 0.3 * 0.25 * 0.75 * (mt_rand(75,130) / 100)) + ((($FleetPoints - (($PointsFlotte[$Ship] / 10) * $FleetArray[$Ship])) / ($PointsFlotte[$Ship] / 10)) * $RatioGain[$Ship] * 0.8); - } - $ThisShipMaxCount = floor($ThisShipMaxCount); - if($FoundShips[$Ship] > $ThisShipMaxCount) - { - $FoundShips[$Ship] = $ThisShipMaxCount; - } - $FoundShipsTotal += $FoundShips[$Ship]; - $NewFleetArray[$Ship] += $FoundShips[$Ship]; - } - } - else - { - $FoundShips[$RandomizedShips] = round((($FleetPoints * 5) * $RatioGain[$RandomizedShips] * (5 / $HowManyShipsToRandom)) * (pow(1.1, $FleetStayDuration) - 0.1)); - $FoundShipsTotal += $FoundShips[$RandomizedShips]; - $NewFleetArray[$RandomizedShips] += $FoundShips[$RandomizedShips]; - } - - if($FoundShipsTotal > 0) - { - foreach($NewFleetArray as $Ship => $Count) - { - $NewFleetArrayString[] = $Ship.','.$Count; - } - $NewFleetArray = implode(';', $NewFleetArrayString); - - $QryUpdateFleet = "UPDATE {{table}} SET "; - $QryUpdateFleet .= "`fleet_array` = '{$NewFleetArray}', "; - $QryUpdateFleet .= "`fleet_amount` = `fleet_amount` + {$FoundShipsTotal}, "; - $QryUpdateFleet .= "`fleet_mess` = '1'"; - $QryUpdateFleet .= "WHERE "; - $QryUpdateFleet .= "`fleet_id` = {$FleetRow['fleet_id']}; -- EXPEDITION QUERY 1"; - doquery($QryUpdateFleet, 'fleets'); - - $return['fleet_end_amount'] = $FleetRow['fleet_amount'] + $FoundShipsTotal; - $return['fleet_end_array'] = '"'.$NewFleetArray.'"'; - - $Message = false; - $Message['msg_id'] = '0'.rand(57,58); - foreach($FoundShips as $Ship => $Count) - { - $Message['args'] .= '
    '.$_Lang['tech'][$Ship].' - '.$Count; - } - - $FleetRow['fleet_array'] = $NewFleetArray; - $FleetRow['fleet_amount']+= $FoundShipsTotal; - } - else - { - $Message = false; - $Message['msg_id'] = '0'.rand(59,60); - $Message['args'] = array(''); - } - - $Message = json_encode($Message); - - Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_stay'], 15, $MessSender, $MessTitle, $Message); - } - else if($WhatHappened >= 66 AND $WhatHappened <= 85) - { - // Nothing happened - - doquery("UPDATE {{table}} SET `fleet_mess` = '1' WHERE `fleet_id` = {$FleetRow['fleet_id']};", 'fleets'); - - $Message = false; - $Message['msg_id'] = '015'; - $Message['args'] = array(''); - - $Message = json_encode($Message); - - Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_stay'], 15, $MessSender, $MessTitle, $Message); - } - else if($WhatHappened >= 86 AND $WhatHappened <= 100) - { - // Error in Navigation System - - $RandomTimeError = rand(900, TIME_DAY); - doquery("UPDATE {{table}} SET `fleet_mess` = '1', `fleet_end_time` = `fleet_end_time` + {$RandomTimeError} WHERE `fleet_id` = {$FleetRow['fleet_id']};", 'fleets'); - - $Message = false; - $Message['msg_id'] = '061'; - $Message['args'] = array(pretty_time($RandomTimeError)); - - $Message = json_encode($Message); - - Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_stay'], 15, $MessSender, $MessTitle, $Message); - - $FleetRow['fleet_end_time'] += $RandomTimeError; - } - else - { - // Nothing (yet) - - doquery("UPDATE {{table}} SET `fleet_mess` = '1' WHERE `fleet_id` = {$FleetRow['fleet_id']};", 'fleets'); - - $Message = false; - $Message['msg_id'] = '015'; - $Message['args'] = array(''); - - $Message = json_encode($Message); - - Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_stay'], 15, $MessSender, $MessTitle, $Message); - } - } - } - - if($FleetRow['fleet_end_time'] < time() AND $fleetHasBeenDeleted === false) - { - - $AllowSendReturn = true; - $return['fleet_came_back'] = '1'; - RestoreFleetToPlanet($FleetRow, true); - doquery("DELETE FROM {{table}} WHERE `fleet_id` = {$FleetRow['fleet_id']}; -- EXPEDITION QUERY 2", 'fleets'); - - $enforceSQLUpdate = 1; - - $Message = false; - $Message['msg_id'] = '017'; - $Message['args'] = array(''); - - $Message = json_encode($Message); - - Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_time'], 15, $MessSender, $MessTitle, $Message); - } - - if($AllowSendReturn) - { - return $return; - } -} - -?> \ No newline at end of file + 1.0,// Small Cargo Ship + 203 => 1.5,// Big Cargo Ship + 204 => 0.5,// Light Hunter + 205 => 1.5,// Heavy Hunter + 206 => 2.0,// cruiser + 207 => 2.5,// Battle Ship + 208 => 0.5,// Colonisator + 209 => 1.0,// Recycler + 210 => 0.01, // Spy Probe + 211 => 3.0,// Bomber + 212 => 0.0,// Solar Satelite + 213 => 3.5,// Destroyer + 214 => 5.0,// Death Star + 215 => 3.2,// BattleShip + 216 => 0.0,// Orbital Station + 217 => 2.0,// Mega Cargo + 218 => 7.5,// Annihilator + 219 => 0.02// Space Shuttle + ); + + $RatioGain = array + ( + 202 => 0.25, // Small Cargo Ship + 203 => 0.2, // Big Cargo Ship + 204 => 0.25, // Light Hunter + 205 => 0.2, // Heavy Hunter + 206 => 0.155,// cruiser + 207 => 0.085, // Battle Ship + 208 => 0.1, // Colonisator + 209 => 0.2, // Recycler + 210 => 0.2, // Spy Probe + 211 => 0.0625,// Bomber + //212 => 0.0, // Solar Satelite + 213 => 0.04,// Destroyer + //214 => 0.0, // Death Star + 215 => 0.05,// BattleShip + //216 => 0.0, // Orbital Station + 217 => 0.0625,// Mega Cargo + //218 => 0.0, // Annihilator + 219 => 0.05// Space Shuttle + ); + + $FleetCapacity = -($FleetRow['fleet_resource_metal'] + $FleetRow['fleet_resource_crystal'] + $FleetRow['fleet_resource_deuterium']); + + $FleetArrTemp = explode(';', $FleetRow['fleet_array']); + foreach($FleetArrTemp as $Ships) + { + if(!empty($Ships)) + { + $ShipsTemp = explode(',', $Ships); + $FleetArray[$ShipsTemp[0]] = $ShipsTemp[1]; + + $FleetCapacity += $_Vars_Prices[$ShipsTemp[0]]['capacity'] * $ShipsTemp[1]; + $FleetPoints += ($PointsFlotte[$ShipsTemp[0]] / 10) * $ShipsTemp[1]; + $FleetMetalCost += $_Vars_Prices[$ShipsTemp[0]]['metal'] * $ShipsTemp[1]; + $FleetCrystCost += $_Vars_Prices[$ShipsTemp[0]]['crystal'] * $ShipsTemp[1]; + $FleetDeuteCost += $_Vars_Prices[$ShipsTemp[0]]['deuterium'] * $ShipsTemp[1]; + } + } + $FleetCount = $FleetRow['fleet_amount']; + $FleetStayDuration = ($FleetRow['fleet_end_stay'] - $FleetRow['fleet_start_time']) / 3600; + + $WhatHappened = rand(1,100); + + if($WhatHappened >= 1 AND $WhatHappened <= 15) + { + // Partial/Complete Destruction + + $DestructionPercent = rand(1,100); + foreach($FleetArray as $Ship => $Count) + { + $NewCount = floor($Count * ((100 - $DestructionPercent) / 100)); + $NewFleetArray[$Ship] = $NewCount; + $NewFleetCount += $NewCount; + if($NewCount < $FleetArray[$Ship]) + { + $DestroyedArray[$Ship] = $FleetArray[$Ship] - $NewCount; + } + } + + if($NewFleetCount < $FleetCount AND $NewFleetCount > 0) + { + foreach($NewFleetArray as $Ship => $Count) + { + $NewFleetArrayString[] = $Ship.','.$Count; + } + $NewFleetArray = implode(';', $NewFleetArrayString); + + $QryUpdateFleet = "UPDATE {{table}} SET "; + $QryUpdateFleet .= "`fleet_array` = '{$NewFleetArray}', "; + $QryUpdateFleet .= "`fleet_amount` = {$NewFleetCount}, "; + $QryUpdateFleet .= "`fleet_mess` = '1'"; + $QryUpdateFleet .= "WHERE "; + $QryUpdateFleet .= "`fleet_id` = '". $FleetRow['fleet_id'] ."'; -- EXPEDITION QUERY 1"; + doquery($QryUpdateFleet, 'fleets'); + + $return['fleet_end_amount'] = $NewFleetCount; + $return['fleet_end_array'] = '"'.$NewFleetArray.'"'; + + $Message = false; + $Message['msg_id'] = '0'.rand(42,44); + foreach($DestroyedArray as $Ship => $Count) + { + $Message['args'] .= '
    '.$_Lang['tech'][$Ship].' - '.$Count; + } + + $Message = json_encode($Message); + + Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_stay'], 15, $MessSender, $MessTitle, $Message); + + $FleetRow['fleet_array'] = $NewFleetArray; + $FleetRow['fleet_amount']= $NewFleetCount; + } + else if($NewFleetCount == $FleetCount) + { + $Message = false; + $Message['msg_id'] = '0'.rand(45,47); + $Message['args'] = array(''); + + $Message = json_encode($Message); + + Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_stay'], 15, $MessSender, $MessTitle, $Message); + } + else + { + $Message = false; + $Message['msg_id'] = '0'.rand(48,50); + $Message['args']= array(''); + + $Message = json_encode($Message); + + Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_stay'], 15, $MessSender, $MessTitle, $Message); + + doquery("DELETE FROM {{table}} WHERE `fleet_id` = {$FleetRow['fleet_id']}; -- EXPEDITION QUERY 2", 'fleets'); + $fleetHasBeenDeleted = TRUE; + + $return['fleet_destroyed'] = '1'; + $return['fleet_destroy_reason'] = '"expedition"'; + } + } + else if($WhatHappened >= 16 AND $WhatHappened <= 55) + { + // Resources found + + $MaxResources = 10000000; + + $MaxFoundMetal = $FleetMetalCost * 0.2; + $MaxFoundCrystal = $FleetCrystCost * 0.2; + $MaxFoundDeuterium = $FleetDeuteCost * 0.2; + if($MaxFoundMetal > $MaxResources) + { + $MaxFoundMetal = $MaxResources; + } + if($MaxFoundCrystal > $MaxResources) + { + $MaxFoundCrystal = $MaxResources; + } + if($MaxFoundDeuterium > $MaxResources) + { + $MaxFoundDeuterium = $MaxResources; + } + $FoundMetal = rand(round((($MaxFoundMetal * 0.001) + 1) * (pow(1.2, $FleetStayDuration) - 0.2)), $MaxFoundMetal); + $FoundCrystal = rand(round((($MaxFoundCrystal * 0.001) + 1) * (pow(1.2, $FleetStayDuration) - 0.2)), $MaxFoundCrystal); + $FoundDeuterium = rand(round((($MaxFoundDeuterium * 0.001) + 1) * (pow(1.2, $FleetStayDuration) - 0.2)), $MaxFoundDeuterium); + + $RandFirst = rand(0,2); + $RandSecond = rand(0,1); + $List = array('Metal', 'Crystal', 'Deuterium'); + $FleetInitCapacity = $FleetCapacity; + + if($FleetCapacity > 0) + { + eval('$FoundResource = $Found'.$List[$RandFirst].';'); + eval('$GottenResource = &$Gotten'.$List[$RandFirst].';'); + if($FleetCapacity > $FoundResource) + { + $GottenResource = $FoundResource; + } + else + { + $GottenResource = $FleetCapacity; + } + $FleetCapacity -= $GottenResource; + + array_splice($List, $RandFirst, 1); + + if($FleetCapacity > 0) + { + eval('$FoundResource = $Found'.$List[$RandSecond].';'); + eval('$GottenResource = &$Gotten'.$List[$RandSecond].';'); + if($FleetCapacity > $FoundResource) + { + $GottenResource = $FoundResource; + } + else + { + $GottenResource = $FleetCapacity; + } + $FleetCapacity -= $GottenResource; + + array_splice($List, $RandSecond, 1); + + if($FleetCapacity > 0) + { + eval('$FoundResource = $Found'.$List[0].';'); + eval('$GottenResource = &$Gotten'.$List[0].';'); + if($FleetCapacity > $FoundResource) + { + $GottenResource = $FoundResource; + } + else + { + $GottenResource = $FleetCapacity; + } + $FleetCapacity -= $GottenResource; + } + } + } + + $Message = false; + + if($FleetCapacity < $FleetInitCapacity) + { + if($GottenMetal > 0) + { + $QryUpdateResources[] = "`fleet_resource_metal` = `fleet_resource_metal` + {$GottenMetal}"; + $MsgGottenArray[] = $_Lang['Metal'].': '.prettyNumber($GottenMetal); + $FleetRow['fleet_resource_metal'] += $GottenMetal; + } + else + { + $GottenMetal = '0'; + } + if($GottenCrystal > 0) + { + $QryUpdateResources[] = "`fleet_resource_crystal` = `fleet_resource_crystal` + {$GottenCrystal}"; + $MsgGottenArray[] = $_Lang['Crystal'].': '.prettyNumber($GottenCrystal); + $FleetRow['fleet_resource_crystal'] += $GottenCrystal; + } + else + { + $GottenCrystal = '0'; + } + if($GottenDeuterium > 0) + { + $QryUpdateResources[] = "`fleet_resource_deuterium` = `fleet_resource_deuterium` + {$GottenDeuterium}"; + $MsgGottenArray[] = $_Lang['Deuterium'].': '.prettyNumber($GottenDeuterium); + $FleetRow['fleet_resource_deuterium'] += $GottenDeuterium; + } + else + { + $GottenDeuterium = '0'; + } + + $return['fleet_end_resource_metal'] = $GottenMetal; + $return['fleet_end_resource_crystal'] = $GottenCrystal; + $return['fleet_end_resource_deuterium'] = $GottenDeuterium; + + $QryUpdateFleet = "UPDATE {{table}} SET "; + $QryUpdateFleet .= implode(", ", $QryUpdateResources); + $QryUpdateFleet .= ", `fleet_mess` = 1 "; + $QryUpdateFleet .= "WHERE `fleet_id` = {$FleetRow['fleet_id']};"; + doquery($QryUpdateFleet, 'fleets'); + + $Message['msg_id'] = '0'.rand(51, 53); + $Message['args'] = implode('
    ', $MsgGottenArray); + } + else + { + $Message['msg_id'] = '0'.rand(54, 56); + $Message['args'] = array(''); + } + + $Message = json_encode($Message); + + Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_stay'], 15, $MessSender, $MessTitle, $Message); + } + else if($WhatHappened >= 56 AND $WhatHappened <= 65) + { + // Found Ships + + $MaxShipsPoints = 20000; + if($FleetPoints > $MaxShipsPoints) + { + $FleetPoints = $MaxShipsPoints; + } + + $HowManyShipsToRandom = rand(1,5); + $RandomizedShips = array_rand($RatioGain, $HowManyShipsToRandom); + $NewFleetArray = $FleetArray; + if((array)$RandomizedShips === $RandomizedShips) + { + foreach($RandomizedShips as $Ship) + { + $FoundShips[$Ship] = round((($FleetPoints * 5) * $RatioGain[$Ship] * (5 / $HowManyShipsToRandom)) * (pow(1.1, $FleetStayDuration) - 0.1)); + if($FleetArray[$Ship] > 0) + { + $ThisShipMaxCount = ($FleetPoints / ($PointsFlotte[$Ship] / 10)) * $RatioGain[$Ship] * 0.8; + } + else + { + $ThisShipMaxCount = ($FleetArray[$Ship] * 0.3 * 0.25 * 0.75 * (mt_rand(75,130) / 100)) + ((($FleetPoints - (($PointsFlotte[$Ship] / 10) * $FleetArray[$Ship])) / ($PointsFlotte[$Ship] / 10)) * $RatioGain[$Ship] * 0.8); + } + $ThisShipMaxCount = floor($ThisShipMaxCount); + if($FoundShips[$Ship] > $ThisShipMaxCount) + { + $FoundShips[$Ship] = $ThisShipMaxCount; + } + $FoundShipsTotal += $FoundShips[$Ship]; + $NewFleetArray[$Ship] += $FoundShips[$Ship]; + } + } + else + { + $FoundShips[$RandomizedShips] = round((($FleetPoints * 5) * $RatioGain[$RandomizedShips] * (5 / $HowManyShipsToRandom)) * (pow(1.1, $FleetStayDuration) - 0.1)); + $FoundShipsTotal += $FoundShips[$RandomizedShips]; + $NewFleetArray[$RandomizedShips] += $FoundShips[$RandomizedShips]; + } + + if($FoundShipsTotal > 0) + { + foreach($NewFleetArray as $Ship => $Count) + { + $NewFleetArrayString[] = $Ship.','.$Count; + } + $NewFleetArray = implode(';', $NewFleetArrayString); + + $QryUpdateFleet = "UPDATE {{table}} SET "; + $QryUpdateFleet .= "`fleet_array` = '{$NewFleetArray}', "; + $QryUpdateFleet .= "`fleet_amount` = `fleet_amount` + {$FoundShipsTotal}, "; + $QryUpdateFleet .= "`fleet_mess` = '1'"; + $QryUpdateFleet .= "WHERE "; + $QryUpdateFleet .= "`fleet_id` = {$FleetRow['fleet_id']}; -- EXPEDITION QUERY 1"; + doquery($QryUpdateFleet, 'fleets'); + + $return['fleet_end_amount'] = $FleetRow['fleet_amount'] + $FoundShipsTotal; + $return['fleet_end_array'] = '"'.$NewFleetArray.'"'; + + $Message = false; + $Message['msg_id'] = '0'.rand(57,58); + foreach($FoundShips as $Ship => $Count) + { + $Message['args'] .= '
    '.$_Lang['tech'][$Ship].' - '.$Count; + } + + $FleetRow['fleet_array'] = $NewFleetArray; + $FleetRow['fleet_amount']+= $FoundShipsTotal; + } + else + { + $Message = false; + $Message['msg_id'] = '0'.rand(59,60); + $Message['args'] = array(''); + } + + $Message = json_encode($Message); + + Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_stay'], 15, $MessSender, $MessTitle, $Message); + } + else if($WhatHappened >= 66 AND $WhatHappened <= 85) + { + // Nothing happened + + doquery("UPDATE {{table}} SET `fleet_mess` = '1' WHERE `fleet_id` = {$FleetRow['fleet_id']};", 'fleets'); + + $Message = false; + $Message['msg_id'] = '015'; + $Message['args'] = array(''); + + $Message = json_encode($Message); + + Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_stay'], 15, $MessSender, $MessTitle, $Message); + } + else if($WhatHappened >= 86 AND $WhatHappened <= 100) + { + // Error in Navigation System + + $RandomTimeError = rand(900, TIME_DAY); + doquery("UPDATE {{table}} SET `fleet_mess` = '1', `fleet_end_time` = `fleet_end_time` + {$RandomTimeError} WHERE `fleet_id` = {$FleetRow['fleet_id']};", 'fleets'); + + $Message = false; + $Message['msg_id'] = '061'; + $Message['args'] = array(pretty_time($RandomTimeError)); + + $Message = json_encode($Message); + + Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_stay'], 15, $MessSender, $MessTitle, $Message); + + $FleetRow['fleet_end_time'] += $RandomTimeError; + } + else + { + // Nothing (yet) + + doquery("UPDATE {{table}} SET `fleet_mess` = '1' WHERE `fleet_id` = {$FleetRow['fleet_id']};", 'fleets'); + + $Message = false; + $Message['msg_id'] = '015'; + $Message['args'] = array(''); + + $Message = json_encode($Message); + + Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_stay'], 15, $MessSender, $MessTitle, $Message); + } + } + } + + if($FleetRow['fleet_end_time'] < time() AND $fleetHasBeenDeleted === false) + { + + $AllowSendReturn = true; + $return['fleet_came_back'] = '1'; + RestoreFleetToPlanet($FleetRow, true); + doquery("DELETE FROM {{table}} WHERE `fleet_id` = {$FleetRow['fleet_id']}; -- EXPEDITION QUERY 2", 'fleets'); + + $enforceSQLUpdate = 1; + + $Message = false; + $Message['msg_id'] = '017'; + $Message['args'] = array(''); + + $Message = json_encode($Message); + + Cache_Message($FleetOwner, 0, $FleetRow['fleet_end_time'], 15, $MessSender, $MessTitle, $Message); + } + + if($AllowSendReturn) + { + return $return; + } +} + +?> diff --git a/includes/functions/MissionCaseGroupAttack.php b/includes/functions/MissionCaseGroupAttack.php index d10b5fb0e..13a33ddeb 100644 --- a/includes/functions/MissionCaseGroupAttack.php +++ b/includes/functions/MissionCaseGroupAttack.php @@ -1,1934 +1,1934 @@ - 0 ? false : true); - $TargetPlanet = &$_FleetCache['planets'][$FleetRow['fleet_end_id']]; - $TargetUser = &$_FleetCache['users'][$FleetRow['fleet_target_owner']]; - $IsAllyFight = (($FleetRow['ally_id'] == 0 OR ($FleetRow['ally_id'] != $TargetUser['ally_id'])) ? false : true); - - // Update planet before attack begins - $UpdateResult = HandleFullUserUpdate($TargetUser, $TargetPlanet, $_FleetCache['planets'][$TargetUser['techQueue_Planet']], $FleetRow['fleet_start_time'], true, true); - if(!empty($UpdateResult)) - { - foreach($UpdateResult as $PlanetID => $Value) - { - if($Value === true) - { - $_FleetCache['updatePlanets'][$PlanetID] = true; - } - } - } - - $TargetUserID = $TargetPlanet['id_owner']; - $TargetPlanetGetName= $TargetPlanet['name']; - $TargetPlanetID = $TargetPlanet['id']; - - if(!$IsAbandoned) - { - $IdleHours = floor(($FleetRow['fleet_start_time'] - $TargetUser['onlinetime']) / 3600); - if($IdleHours > 0) - { - $UseIdleHours = true; - } - } - - $AttackingFleets = array(); - $DefendingFleets = array(); - // Create data arrays for attacker and main defender - $DefendersIDs[] = $TargetUser['id']; - - $DefendingTechs[0] = array - ( - 109 => $TargetUser['tech_weapons'], - 110 => $TargetUser['tech_armour'], - 111 => $TargetUser['tech_shielding'], - 120 => $TargetUser['tech_laser'], - 121 => $TargetUser['tech_ion'], - 122 => $TargetUser['tech_plasma'], - 125 => $TargetUser['tech_antimatter'], - 126 => $TargetUser['tech_disintegration'], - 199 => $TargetUser['tech_graviton'] - ); - $DefendersData[0] = array - ( - 'id' => $TargetUser['id'], - 'username' => $TargetUser['username'], - 'techs' => Array2String($DefendingTechs[0]), - 'pos' => "{$FleetRow['fleet_end_galaxy']}:{$FleetRow['fleet_end_system']}:{$FleetRow['fleet_end_planet']}" - ); - if(!empty($TargetUser['ally_tag'])) - { - $DefendersData[0]['ally'] = $TargetUser['ally_tag']; - } - - // Select All Defending Fleets on the Orbit from $_FleetCache - if(!empty($_FleetCache['defFleets'][$FleetRow['fleet_end_id']])) - { - $i = 1; - foreach($_FleetCache['defFleets'][$FleetRow['fleet_end_id']] as $FleetData) - { - if($_FleetCache['fleetRowStatus'][$FleetData['fleet_id']]['isDestroyed'] !== true) - { - $DefendingFleets[$i] = String2Array($FleetData['fleet_array']); - $DefendingFleetID[$i] = $FleetData['fleet_id']; - $DefendingTechs[$i] = array - ( - 109 => $FleetData['tech_weapons'], - 110 => $FleetData['tech_armour'], - 111 => $FleetData['tech_shielding'], - 120 => $FleetData['tech_laser'], - 121 => $FleetData['tech_ion'], - 122 => $FleetData['tech_plasma'], - 125 => $FleetData['tech_antimatter'], - 126 => $FleetData['tech_disintegration'], - 199 => $FleetData['tech_graviton'] - ); - $DefendersData[$i] = array - ( - 'id' => $FleetData['fleet_owner'], - 'username' => $FleetData['username'], - 'techs' => Array2String($DefendingTechs[$i]), - 'pos' => "{$FleetData['fleet_start_galaxy']}:{$FleetData['fleet_start_system']}:{$FleetData['fleet_start_planet']}" - ); - if(!empty($FleetData['ally_tag'])) - { - $DefendersData[$i]['ally'] = $FleetData['ally_tag']; - } - if(!in_array($FleetData['fleet_owner'], $DefendersIDs)) - { - $DefendersIDs[] = $FleetData['fleet_owner']; - } - $DefendingFleetOwners[$FleetData['fleet_id']] = $FleetData['fleet_owner']; - - if(MORALE_ENABLED) - { - if(empty($_TempCache['MoraleCache'][$FleetData['fleet_owner']])) - { - if(!empty($_FleetCache['MoraleCache'][$FleetData['fleet_owner']])) - { - $FleetData['morale_level'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['level']; - $FleetData['morale_droptime'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['droptime']; - $FleetData['morale_lastupdate'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['lastupdate']; - } - Morale_ReCalculate($FleetData, $FleetRow['fleet_start_time']); - $DefendersData[$i]['morale'] = $FleetData['morale_level']; - $DefendersData[$i]['moralePoints'] = $FleetData['morale_points']; - - $_TempCache['MoraleCache'][$FleetData['fleet_owner']] = array - ( - 'level' => $FleetData['morale_level'], - 'points' => $FleetData['morale_points'] - ); - } - else - { - $DefendersData[$i]['morale'] = $_TempCache['MoraleCache'][$FleetData['fleet_owner']]['level']; - $DefendersData[$i]['moralePoints'] = $_TempCache['MoraleCache'][$FleetData['fleet_owner']]['points']; - } - - // Bonuses - if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETPOWERUP1) - { - $DefendingTechs[$i]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; - } - if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETSHIELDUP1) - { - $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; - } - if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETSDADDITION) - { - $DefendingTechs[$i]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; - } - // Penalties - if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN1) - { - $DefendingTechs[$i]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; - } - if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN2) - { - $DefendingTechs[$i]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; - } - if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) - { - $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; - } - if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) - { - $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; - } - if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSDDOWN) - { - $DefendingTechs[$i]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; - } - } - - $i += 1; - } - } - } - - $AttackersIDs[] = $FleetRow['fleet_owner']; - $AttackingFleetOwners[$FleetRow['fleet_id']] = $FleetRow['fleet_owner']; - $AttackingFleetID[0] = $FleetRow['fleet_id']; - $AttackingFleetRes[$FleetRow['fleet_id']]['metal'] = (isset($FleetRow['fleet_resouce_metal']) ? $FleetRow['fleet_resouce_metal'] : 0); - $AttackingFleetRes[$FleetRow['fleet_id']]['crystal'] = (isset($FleetRow['fleet_resouce_crystal']) ? $FleetRow['fleet_resouce_crystal'] : 0); - $AttackingFleetRes[$FleetRow['fleet_id']]['deuterium'] = (isset($FleetRow['fleet_resouce_deuterium']) ? $FleetRow['fleet_resouce_deuterium'] : 0); - - $AttackingTechs[0] = array - ( - 109 => $FleetRow['tech_weapons'], - 110 => $FleetRow['tech_armour'], - 111 => $FleetRow['tech_shielding'], - 120 => $FleetRow['tech_laser'], - 121 => $FleetRow['tech_ion'], - 122 => $FleetRow['tech_plasma'], - 125 => $FleetRow['tech_antimatter'], - 126 => $FleetRow['tech_disintegration'], - 199 => $FleetRow['tech_graviton'] - ); - $AttackersData[0] = array - ( - 'id' => $FleetRow['fleet_owner'], - 'username' => $FleetRow['username'], - 'techs' => Array2String($AttackingTechs[0]), - 'pos' => "{$FleetRow['fleet_start_galaxy']}:{$FleetRow['fleet_start_system']}:{$FleetRow['fleet_start_planet']}" - ); - if(!empty($FleetRow['ally_tag'])) - { - $AttackersAllys[$FleetRow['fleet_owner']] = $FleetRow['ally_id']; - $AttackersData[0]['ally'] = $FleetRow['ally_tag']; - } - - // Select All Fleets from this ACS from $_FleetCache - if(!empty($_FleetCache['acsFleets'][$FleetRow['fleet_id']])) - { - $i = 1; - foreach($_FleetCache['acsFleets'][$FleetRow['fleet_id']] as $FleetData) - { - $AttackingFleets[$i] = String2Array($FleetData['fleet_array']); - $AttackingFleetRes[$FleetData['fleet_id']]['metal'] = (isset($FleetData['fleet_resouce_metal']) ? $FleetData['fleet_resouce_metal'] : 0); - $AttackingFleetRes[$FleetData['fleet_id']]['crystal'] = (isset($FleetData['fleet_resouce_crystal']) ? $FleetData['fleet_resouce_crystal'] : 0); - $AttackingFleetRes[$FleetData['fleet_id']]['deuterium'] = (isset($FleetData['fleet_resouce_deuterium']) ? $FleetData['fleet_resouce_deuterium'] : 0); - $AttackingFleetID[$i] = $FleetData['fleet_id']; - $AttackingTechs[$i] = array - ( - 109 => $FleetData['tech_weapons'], - 110 => $FleetData['tech_armour'], - 111 => $FleetData['tech_shielding'], - 120 => $FleetData['tech_laser'], - 121 => $FleetData['tech_ion'], - 122 => $FleetData['tech_plasma'], - 125 => $FleetData['tech_antimatter'], - 126 => $FleetData['tech_disintegration'], - 199 => $FleetData['tech_graviton'] - ); - $AttackersData[$i] = array - ( - 'id' => $FleetData['fleet_owner'], - 'username' => $FleetData['username'], - 'techs' => Array2String($AttackingTechs[$i]), - 'pos' => "{$FleetData['fleet_start_galaxy']}:{$FleetData['fleet_start_system']}:{$FleetData['fleet_start_planet']}" - ); - if(!empty($FleetData['ally_tag'])) - { - $AttackersAllys[$FleetData['fleet_owner']] = $FleetData['ally_id']; - $AttackersData[$i]['ally'] = $FleetData['ally_tag']; - } - if(!in_array($FleetData['fleet_owner'], $AttackersIDs)) - { - $AttackersIDs[] = $FleetData['fleet_owner']; - } - $AttackingFleetOwners[$FleetData['fleet_id']] = $FleetData['fleet_owner']; - - if(MORALE_ENABLED) - { - if(empty($_TempCache['MoraleCache'][$FleetData['fleet_owner']])) - { - if(!empty($_FleetCache['MoraleCache'][$FleetData['fleet_owner']])) - { - $FleetData['morale_level'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['level']; - $FleetData['morale_droptime'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['droptime']; - $FleetData['morale_lastupdate'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['lastupdate']; - } - Morale_ReCalculate($FleetData, $FleetRow['fleet_start_time']); - $AttackersData[$i]['morale'] = $FleetData['morale_level']; - $AttackersData[$i]['moralePoints'] = $FleetData['morale_points']; - - $_TempCache['MoraleCache'][$FleetData['fleet_owner']] = array - ( - 'level' => $FleetData['morale_level'], - 'points' => $FleetData['morale_points'] - ); - - $AttackersMorale[$FleetData['fleet_owner']] = array - ( - 'morale_level' => $FleetData['morale_level'], - 'morale_droptime' => $FleetData['morale_droptime'], - 'morale_lastupdate' => $FleetData['morale_lastupdate'], - 'morale_points' => $FleetData['morale_points'] - ); - } - else - { - $AttackersData[$i]['morale'] = $_TempCache['MoraleCache'][$FleetData['fleet_owner']]['level']; - $AttackersData[$i]['moralePoints'] = $_TempCache['MoraleCache'][$FleetData['fleet_owner']]['points']; - } - - // Bonuses - if($AttackersData[$i]['morale'] >= MORALE_BONUS_FLEETPOWERUP1) - { - $AttackingTechs[$i]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; - } - if($AttackersData[$i]['morale'] >= MORALE_BONUS_FLEETSHIELDUP1) - { - $AttackingTechs[$i]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; - } - if($AttackersData[$i]['morale'] >= MORALE_BONUS_FLEETSDADDITION) - { - $AttackingTechs[$i]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; - } - // Penalties - if($AttackersData[$i]['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN1) - { - $AttackingTechs[$i]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; - } - if($AttackersData[$i]['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN2) - { - $AttackingTechs[$i]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; - } - if($AttackersData[$i]['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) - { - $AttackingTechs[$i]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; - } - if($AttackersData[$i]['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) - { - $AttackingTechs[$i]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; - } - if($AttackersData[$i]['morale'] <= MORALE_PENALTY_FLEETSDDOWN) - { - $AttackingTechs[$i]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; - } - } - - $i += 1; - } - } - - // MoraleSystem Init - if(MORALE_ENABLED) - { - if(!empty($_FleetCache['MoraleCache'][$FleetRow['fleet_owner']])) - { - $FleetRow['morale_level'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['level']; - $FleetRow['morale_droptime'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['droptime']; - $FleetRow['morale_lastupdate'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['lastupdate']; - } - Morale_ReCalculate($FleetRow, $FleetRow['fleet_start_time']); - $AttackersData[0]['morale'] = $FleetRow['morale_level']; - $AttackersData[0]['moralePoints'] = $FleetRow['morale_points']; - - if(empty($AttackersMorale[$FleetRow['fleet_owner']])) - { - $AttackersMorale[$FleetRow['fleet_owner']] = array - ( - 'morale_level' => $FleetRow['morale_level'], - 'morale_droptime' => $FleetRow['morale_droptime'], - 'morale_lastupdate' => $FleetRow['morale_lastupdate'], - 'morale_points' => $FleetRow['morale_points'] - ); - } - - // Bonuses - if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETPOWERUP1) - { - $AttackingTechs[0]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; - } - if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETSHIELDUP1) - { - $AttackingTechs[0]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; - } - if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETSDADDITION) - { - $AttackingTechs[0]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; - } - // Penalties - if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN1) - { - $AttackingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; - } - if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN2) - { - $AttackingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; - } - if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) - { - $AttackingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; - } - if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) - { - $AttackingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; - } - if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSDDOWN) - { - $AttackingTechs[0]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; - } - - if(!$IsAbandoned) - { - if(!empty($_FleetCache['MoraleCache'][$TargetUser['id']])) - { - $TargetUser['morale_level'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['level']; - $TargetUser['morale_droptime'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['droptime']; - $TargetUser['morale_lastupdate'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['lastupdate']; - } - Morale_ReCalculate($TargetUser, $FleetRow['fleet_start_time']); - $DefendersData[0]['morale'] = $TargetUser['morale_level']; - $DefendersData[0]['moralePoints'] = $TargetUser['morale_points']; - - // Bonuses - if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETPOWERUP1) - { - $DefendingTechs[0]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; - } - if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETSHIELDUP1) - { - $DefendingTechs[0]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; - } - if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETSDADDITION) - { - $DefendingTechs[0]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; - } - // Penalties - if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN1) - { - $DefendingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; - } - if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN2) - { - $DefendingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; - } - if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) - { - $DefendingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; - } - if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) - { - $DefendingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; - } - if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSDDOWN) - { - $DefendingTechs[0]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; - } - } - } - - foreach($AttackingFleetID as $FleetID) - { - $Return['FleetArchive'][$FleetID]['Fleet_Calculated_Mission'] = true; - $Return['FleetArchive'][$FleetID]['Fleet_Calculated_Mission_Time'] = $Now; - if($UseIdleHours === true) - { - $Return['FleetArchive'][$FleetID]['Fleet_End_Owner_IdleHours'] = $IdleHours; - } - } - - foreach($AttackersIDs as $ID) - { - if(empty($UserStatsData[$ID])) - { - $UserStatsData[$ID] = $UserStatsPattern; - } - } - foreach($DefendersIDs as $ID) - { - if(empty($UserStatsData[$ID])) - { - $UserStatsData[$ID] = $UserStatsPattern; - } - } - - // Create main defender fleet array - foreach($_Vars_ElementCategories['fleet'] as $ElementID) - { - if($TargetPlanet[$_Vars_GameElements[$ElementID]] > 0) - { - $DefendingFleets[0][$ElementID] = $TargetPlanet[$_Vars_GameElements[$ElementID]]; - } - } - foreach($_Vars_ElementCategories['defense'] as $ElementID) - { - if(in_array($ElementID, $_Vars_ElementCategories['rockets'])) - { - continue; - } - if($TargetPlanet[$_Vars_GameElements[$ElementID]] > 0) - { - $DefendingFleets[0][$ElementID] = $TargetPlanet[$_Vars_GameElements[$ElementID]]; - } - } - - // Create attacker fleet array - $AttackingFleets[0] = String2Array($FleetRow['fleet_array']); - - $StartTime = microtime(true); - - // Now start Combat calculations - $Combat = Combat($AttackingFleets, $DefendingFleets, $AttackingTechs, $DefendingTechs); - - // Get the calculations time - $EndTime = microtime(true); - $totaltime = sprintf('%0.6f', $EndTime - $StartTime); - - $RealDebrisMetalAtk = 0; - $RealDebrisCrystalAtk = 0; - $RealDebrisDeuteriumAtk = 0; - $RealDebrisMetalDef = 0; - $RealDebrisCrystalDef = 0; - $RealDebrisDeuteriumDef = 0; - $TotalMoonChance = 0; - $TotalLostMetal = 0; - $TotalLostCrystal = 0; - $DebrisMetalDef = 0; - $DebrisCrystalDef = 0; - - $MoonHasBeenCreated = false; - - $RoundsData = $Combat['rounds']; - $Result = $Combat['result']; - $AtkShips = $Combat['AttackerShips']; - $DefShips = $Combat['DefenderShips']; - $AtkLost = $Combat['AtkLose']; - $DefLost = $Combat['DefLose']; - $DefSysLost = $Combat['DefSysLost']; - $ShotDown = $Combat['ShotDown']; - $ForceContribution = $Combat['ForceContribution']; - - $FleetStorage = 0; - - $i = 0; - // Parse result data - attackers fleet - $TotalMetStolen = 0; - $TotalCryStolen = 0; - $TotalDeuStolen = 0; - - if(!empty($AtkShips)) - { - if($Result === COMBAT_ATK) - { - $ResourceSteal_Factor = (COMBAT_RESOURCESTEAL_PERCENT / 100); - if(MORALE_ENABLED) - { - if(!$IsAbandoned AND $TargetUser['morale_level'] <= MORALE_PENALTY_RESOURCELOSE) - { - $ResourceSteal_NewFactor[] = MORALE_PENALTY_RESOURCELOSE_STEALPERCENT; - } - if($FleetRow['morale_level'] <= MORALE_PENALTY_STEAL) - { - $ResourceSteal_NewFactor[] = MORALE_PENALTY_STEAL_STEALPERCENT; - } - else if($FleetRow['morale_level'] <= MORALE_PENALTY_IDLERSTEAL AND $IdleHours >= (7 * 24)) - { - $ResourceSteal_NewFactor[] = MORALE_PENALTY_IDLERSTEAL_STEALPERCENT; - } - - if(!empty($ResourceSteal_NewFactor)) - { - $ResourceSteal_Factor = (array_sum($ResourceSteal_NewFactor) / count($ResourceSteal_NewFactor)) / 100; - } - } - - $MaxMetSteal = $TargetPlanet['metal'] * $ResourceSteal_Factor; - $MaxCrySteal = $TargetPlanet['crystal'] * $ResourceSteal_Factor; - $MaxDeuSteal = $TargetPlanet['deuterium'] * $ResourceSteal_Factor; - } - - foreach($AtkShips as $User => $Ships) - { - $FleetStorage = 0; - $CalculatedAtkFleets[] = $AttackingFleetID[$User]; - if(!empty($Ships)) - { - $QryUpdateFleets[$i]['id'] = $AttackingFleetID[$User]; - $QryUpdateFleets[$i]['mess'] = '1'; - $QryUpdateFleets[$i]['mission'] = '1'; - - foreach($AttackingFleets[$User] as $ID => $Count) - { - $Difference = $Count; - if(isset($Ships[$ID])) - { - $Difference -= $Ships[$ID]; - } - if($Difference > 0) - { - $QryUpdateFleets[$i]['array_lost'][] = "{$ID},{$Difference}"; - } - } - if(!empty($QryUpdateFleets[$i]['array_lost'])) - { - $QryUpdateFleets[$i]['array_lost'] = implode(';', $QryUpdateFleets[$i]['array_lost']); - } - - foreach($Ships as $ID => $Count) - { - if($Count > 0) - { - if(!isset($QryUpdateFleets[$i]['count'])) - { - $QryUpdateFleets[$i]['count'] = 0; - } - $QryUpdateFleets[$i]['array'][] = "{$ID},{$Count}"; - $QryUpdateFleets[$i]['count'] += $Count; - } - if($Result === COMBAT_ATK && (!isset($_Vars_Prices[$ID]['cantPillage']) || $_Vars_Prices[$ID]['cantPillage'] !== true)) - { - $FleetStorage += $_Vars_Prices[$ID]['capacity'] * $Count; - } - - if($Count < $AttackingFleets[$User][$ID]) - { - $UserDev_UpFl[$AttackingFleetID[$User]][] = $ID.','.($AttackingFleets[$User][$ID] - $Count); - } - } - - if($Result === COMBAT_ATK) - { - // New SYSTEM - $FleetStorage -= $AttackingFleetRes[$AttackingFleetID[$User]]['metal']; - $FleetStorage -= $AttackingFleetRes[$AttackingFleetID[$User]]['crystal']; - $FleetStorage -= $AttackingFleetRes[$AttackingFleetID[$User]]['deuterium']; - - if($FleetStorage > 0) - { - $GiveAwayMet = false; - $GiveAwayCry = false; - - $AllowTakeMoreMet = 0; - $AllowTakeMoreCry = 0; - $AllowTakeMoreDeu = 0; - - $StoragePerResource = $FleetStorage / 3; - - // First - calculate, if any resource will leave free storage - if($MaxMetSteal < $StoragePerResource) - { - $AllowTakeMore = ($StoragePerResource - $MaxMetSteal) / 2; - $AllowTakeMoreCry += $AllowTakeMore; - $AllowTakeMoreDeu += $AllowTakeMore; - $GiveAwayMet = true; - } - - if($MaxCrySteal < ($StoragePerResource + $AllowTakeMoreCry)) - { - $AllowTakeMore = (($StoragePerResource + $AllowTakeMoreCry) - $MaxCrySteal) / 2; - if($GiveAwayMet == false) - { - $AllowTakeMoreMet += $AllowTakeMore; - $AllowTakeMoreDeu += $AllowTakeMore; - } - else - { - $AllowTakeMoreDeu += $AllowTakeMore * 2; - } - $GiveAwayCry = true; - } - - if($MaxDeuSteal < ($StoragePerResource + $AllowTakeMoreDeu)) - { - $AllowTakeMore = (($StoragePerResource + $AllowTakeMoreDeu) - $MaxDeuSteal) / 2; - if($GiveAwayCry == false) - { - $AllowTakeMoreMet += $AllowTakeMore; - $AllowTakeMoreCry += $AllowTakeMore; - } - else - { - $AllowTakeMoreMet += $AllowTakeMore * 2; - } - } - - //Second - calculate stolen resources - if($MaxMetSteal > ($StoragePerResource + $AllowTakeMoreMet)) - { - $QryUpdateFleets[$i]['metal'] = floor($StoragePerResource + $AllowTakeMoreMet); - $MaxMetSteal -= $QryUpdateFleets[$i]['metal']; - $TotalMetStolen += $QryUpdateFleets[$i]['metal']; - } - else - { - $QryUpdateFleets[$i]['metal'] = floor($MaxMetSteal); - $MaxMetSteal -= $QryUpdateFleets[$i]['metal']; - $TotalMetStolen += $QryUpdateFleets[$i]['metal']; - } - if($MaxCrySteal > ($StoragePerResource + $AllowTakeMoreCry)) - { - $QryUpdateFleets[$i]['crystal'] = floor($StoragePerResource + $AllowTakeMoreCry); - $MaxCrySteal -= $QryUpdateFleets[$i]['crystal']; - $TotalCryStolen += $QryUpdateFleets[$i]['crystal']; - } - else - { - $QryUpdateFleets[$i]['crystal'] = floor($MaxCrySteal); - $MaxCrySteal -= $QryUpdateFleets[$i]['crystal']; - $TotalCryStolen += $QryUpdateFleets[$i]['crystal']; - } - if($MaxDeuSteal > ($StoragePerResource + $AllowTakeMoreDeu)) - { - $QryUpdateFleets[$i]['deuterium'] = floor($StoragePerResource + $AllowTakeMoreDeu); - $MaxDeuSteal -= $QryUpdateFleets[$i]['deuterium']; - $TotalDeuStolen += $QryUpdateFleets[$i]['deuterium']; - } - else - { - $QryUpdateFleets[$i]['deuterium'] = floor($MaxDeuSteal); - $MaxDeuSteal -= $QryUpdateFleets[$i]['deuterium']; - $TotalDeuStolen += $QryUpdateFleets[$i]['deuterium']; - } - - $Return['FleetArchive'][$AttackingFleetID[$User]]['Fleet_End_Res_Metal'] = $QryUpdateFleets[$i]['metal']; - $Return['FleetArchive'][$AttackingFleetID[$User]]['Fleet_End_Res_Crystal'] = $QryUpdateFleets[$i]['crystal']; - $Return['FleetArchive'][$AttackingFleetID[$User]]['Fleet_End_Res_Deuterium'] = $QryUpdateFleets[$i]['deuterium']; - - if($QryUpdateFleets[$i]['metal'] > 0) - { - if(!isset($TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_METAL'])) - { - $TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_METAL'] = 0; - } - $UserDev_UpFl[$AttackingFleetID[$User]][] = 'M,'.$QryUpdateFleets[$i]['metal']; - $TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_METAL'] += $QryUpdateFleets[$i]['metal']; - } - if($QryUpdateFleets[$i]['crystal'] > 0) - { - if(!isset($TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_CRYSTAL'])) - { - $TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_CRYSTAL'] = 0; - } - $UserDev_UpFl[$AttackingFleetID[$User]][] = 'C,'.$QryUpdateFleets[$i]['crystal']; - $TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_CRYSTAL'] += $QryUpdateFleets[$i]['crystal']; - } - if($QryUpdateFleets[$i]['deuterium'] > 0) - { - if(!isset($TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_DEUTERIUM'])) - { - $TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_DEUTERIUM'] = 0; - } - $UserDev_UpFl[$AttackingFleetID[$User]][] = 'D,'.$QryUpdateFleets[$i]['deuterium']; - $TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_DEUTERIUM'] += $QryUpdateFleets[$i]['deuterium']; - } - } - // END OF NEW SYSTEM - } - } - else - { - $DeleteFleet[] = $AttackingFleetID[$User]; - foreach($AttackingFleets[$User] as $ShipID => $ShipCount) - { - $UserDev_UpFl[$AttackingFleetID[$User]][] = "{$ShipID},{$ShipCount}"; - } - - if($User == 0) - { - $fleetHasBeenDeleted = true; - } - } - $i += 1; - } - - if(!empty($AttackingFleetID)) - { - foreach($AttackingFleetID as $User => $ID) - { - if(!in_array($ID, $CalculatedAtkFleets)) - { - $DeleteFleet[] = $ID; - foreach($AttackingFleets[$User] as $ShipID => $ShipCount) - { - $UserDev_UpFl[$ID][] = "{$ShipID},{$ShipCount}"; - } - - if($User == 0) - { - $fleetHasBeenDeleted = true; - } - } - } - } - } - else - { - if(!empty($AttackingFleetID)) - { - foreach($AttackingFleetID as $User => $ID) - { - $DeleteFleet[] = $ID; - foreach($AttackingFleets[$User] as $ShipID => $ShipCount) - { - $UserDev_UpFl[$ID][] = "{$ShipID},{$ShipCount}"; - } - - if($User == 0) - { - $fleetHasBeenDeleted = true; - } - } - } - } - - // Parse result data - Defenders - if(!empty($DefendingFleets)) - { - foreach($DefendingFleets as $User => $Ships) - { - if($User == 0) - { - $DefSysLostIDs = array_keys($DefSysLost); - $DefSysLostIDs[] = -1; - - foreach($Ships as $ID => $Count) - { - if(in_array($ID, $DefSysLostIDs)) - { - $Count = $DefShips[0][$ID]; - $Chance = mt_rand(60, 80 + (($TargetUser['engineer_time'] >= $FleetRow['fleet_start_time']) ? 20 : 0)); - $Fluctuation = mt_rand(-11, 11); - if($Fluctuation > 0) - { - $Fluctuation = 0; - } - $Rebuilt[$ID] = round($DefSysLost[$ID] * (($Chance + $Fluctuation) / 100)); - $Count += $Rebuilt[$ID]; - if($DefendingFleets[0][$ID] < $Count) - { - $Count = $DefendingFleets[0][$ID]; - } - unset($DefSysLost[$ID]); - } - else - { - $Count = $DefShips[0][$ID]; - } - if($Count == 0) - { - $Count = '0'; - } - $TargetPlanet[$_Vars_GameElements[$ID]] = $Count; - if($Count < $DefendingFleets[0][$ID]) - { - $UserDev_UpPl[] = $ID.','.($DefendingFleets[0][$ID] - $Count); - $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; - $HPQ_PlanetUpdatedFields[] = $_Vars_GameElements[$ID]; - } - } - } - else - { - $QryUpdateFleets[$i]['id'] = $DefendingFleetID[$User]; - if(!empty($DefShips[$User])) - { - foreach($Ships as $ID => $Count) - { - $ThisCount = 0; - if(!empty($DefShips[$User][$ID])) - { - $OldCount = $Count; - $Count = $DefShips[$User][$ID]; - $ThisCount = $Count; - if($Count > 0) - { - if(!isset($QryUpdateFleets[$i]['count'])) - { - $QryUpdateFleets[$i]['count'] = 0; - } - $QryUpdateFleets[$i]['array'][] = "{$ID},{$Count}"; - $QryUpdateFleets[$i]['count'] += $Count; - } - $Difference = $OldCount - $Count; - if($Difference > 0) - { - $QryUpdateFleets[$i]['array_lost'][] = "{$ID},{$Difference}"; - } - } - - if($ThisCount < $DefendingFleets[$User][$ID]) - { - $UserDev_UpFl[$DefendingFleetID[$User]][] = $ID.','.($DefendingFleets[$User][$ID] - $ThisCount); - } - } - - if(!empty($QryUpdateFleets[$i]['array_lost'])) - { - $QryUpdateFleets[$i]['array_lost'] = implode(';', $QryUpdateFleets[$i]['array_lost']); - } - } - else - { - $DeleteFleet[] = $DefendingFleetID[$User]; - foreach($DefendingFleets[$User] as $ShipID => $ShipCount) - { - $UserDev_UpFl[$DefendingFleetID[$User]][] = "{$ShipID},{$ShipCount}"; - } - } - } - $i += 1; - } - } - - if($TotalMetStolen > 0) - { - $TargetPlanet['metal'] -= $TotalMetStolen; - $UserDev_UpPl[] = 'M,'.$TotalMetStolen; - $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; - } - if($TotalCryStolen > 0) - { - $TargetPlanet['crystal'] -= $TotalCryStolen; - $UserDev_UpPl[] = 'C,'.$TotalCryStolen; - $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; - } - if($TotalDeuStolen > 0) - { - $TargetPlanet['deuterium'] -= $TotalDeuStolen; - $UserDev_UpPl[] = 'D,'.$TotalDeuStolen; - $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; - } - - // Update all fleets (if necessary) - if(!empty($QryUpdateFleets)) - { - foreach($QryUpdateFleets as $Data) - { - if(!empty($Data)) - { - if($Data['metal'] <= 0) - { - $Data['metal'] = '0'; - } - if($Data['crystal'] <= 0) - { - $Data['crystal'] = '0'; - } - if($Data['deuterium'] <= 0) - { - $Data['deuterium'] = '0'; - } - - if(!empty($Data['array'])) - { - $Data['array'] = implode(';', $Data['array']); - if(!empty($Data['array_lost'])) - { - if(strlen($Data['array']) > strlen($Data['array_lost'])) - { - $Return['FleetArchive'][$Data['id']]['Fleet_Array_Changes'] = "\"+D;{$Data['array_lost']}|\""; - } - else - { - $Return['FleetArchive'][$Data['id']]['Fleet_Array_Changes'] = "\"+L;{$Data['array']}|\""; - } - $Return['FleetArchive'][$Data['id']]['Fleet_Info_HasLostShips'] = '!true'; - } - if($Data['id'] != $FleetRow['fleet_id'] AND !empty($DefendingFleetID) AND in_array($Data['id'], $DefendingFleetID)) - { - $_FleetCache['defFleets'][$FleetRow['fleet_end_id']][$Data['id']]['fleet_array'] = $Data['array']; - } - } - - if($Data['id'] == $FleetRow['fleet_id'] AND $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['calcCount'] == 2) - { - // Update $_FleetCache, instead of sending additional Query to Update FleetState - // This fleet will be restored in this Calculation, so don't waste our time - $CachePointer = &$_FleetCache['fleetRowUpdate'][$Data['id']]; - $CachePointer['fleet_array'] = $Data['array']; - $CachePointer['fleet_resource_metal'] = $FleetRow['fleet_resource_metal'] + $Data['metal']; - $CachePointer['fleet_resource_crystal'] = $FleetRow['fleet_resource_crystal'] + $Data['crystal']; - $CachePointer['fleet_resource_deuterium'] = $FleetRow['fleet_resource_deuterium'] + $Data['deuterium']; - } - else - { - // Create UpdateFleet record for $_FleetCache - $CachePointer = &$_FleetCache['updateFleets'][$Data['id']]; - $CachePointer['fleet_array'] = $Data['array']; - $CachePointer['fleet_amount'] = $Data['count']; - $CachePointer['fleet_mess'] = $Data['mess']; - if(!isset($CachePointer['fleet_resource_metal'])) - { - $CachePointer['fleet_resource_metal'] = 0; - } - if(!isset($CachePointer['fleet_resource_crystal'])) - { - $CachePointer['fleet_resource_crystal'] = 0; - } - if(!isset($CachePointer['fleet_resource_deuterium'])) - { - $CachePointer['fleet_resource_deuterium'] = 0; - } - $CachePointer['fleet_resource_metal'] += $Data['metal']; - $CachePointer['fleet_resource_crystal'] += $Data['crystal']; - $CachePointer['fleet_resource_deuterium'] += $Data['deuterium']; - if($Data['id'] != $FleetRow['fleet_id'] AND (empty($DefendingFleetID) OR !in_array($Data['id'], $DefendingFleetID))) - { - $CachePointer = &$_FleetCache['fleetRowUpdate'][$Data['id']]; - $CachePointer['fleet_array'] = $Data['array']; - $CachePointer['fleet_resource_metal'] = (isset($_FleetCache['acsFleets'][$Data['id']]['fleet_resource_metal']) ? $_FleetCache['acsFleets'][$Data['id']]['fleet_resource_metal'] : 0) + $Data['metal']; - $CachePointer['fleet_resource_crystal'] = (isset($_FleetCache['acsFleets'][$Data['id']]['fleet_resource_crystal']) ? $_FleetCache['acsFleets'][$Data['id']]['fleet_resource_crystal'] : 0) + $Data['crystal']; - $CachePointer['fleet_resource_deuterium'] = (isset($_FleetCache['acsFleets'][$Data['id']]['fleet_resource_deuterium']) ? $_FleetCache['acsFleets'][$Data['id']]['fleet_resource_deuterium'] : 0) + $Data['deuterium']; - } - } - } - } - } - - if(!empty($UserDev_UpFl)) - { - foreach($UserDev_UpFl as $FleetID => $DevArray) - { - if($FleetID == $FleetRow['fleet_id']) - { - $SetCode = '2'; - $FleetUserID = $FleetRow['fleet_owner']; - } - else - { - if(!empty($DefendingFleetID) AND in_array($FleetID, $DefendingFleetID)) - { - $SetCode = '3'; - $FleetUserID = $DefendingFleetOwners[$FleetID]; - } - else - { - $SetCode = '4'; - $FleetUserID = $AttackingFleetOwners[$FleetID]; - } - } - $UserDev_Log[] = array('UserID' => $FleetUserID, 'PlanetID' => '0', 'Date' => $FleetRow['fleet_start_time'], 'Place' => 13, 'Code' => $SetCode, 'ElementID' => $FleetID, 'AdditionalData' => implode(';', $DevArray)); - } - } - - // Calculate Debris & Looses - Init - $DebrisFactor_Fleet = $_GameConfig['Fleet_Cdr'] / 100; - $DebrisFactor_Defense = $_GameConfig['Defs_Cdr'] / 100; - - // Calculate looses - attacker - if(!empty($AtkLost)) - { - $DebrisMetalAtk = 0; - $DebrisCrystalAtk = 0; - foreach($AtkLost as $ID => $Count) - { - if(in_array($ID, $_Vars_ElementCategories['fleet'])) - { - if($DebrisFactor_Fleet > 0) - { - $DebrisMetalAtk += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Fleet); - $DebrisCrystalAtk += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Fleet); - } - $RealDebrisMetalAtk += floor($_Vars_Prices[$ID]['metal'] * $Count); - $RealDebrisCrystalAtk += floor($_Vars_Prices[$ID]['crystal'] * $Count); - $RealDebrisDeuteriumAtk += floor($_Vars_Prices[$ID]['deuterium'] * $Count); - } - } - $TotalLostMetal = $DebrisMetalAtk; - $TotalLostCrystal = $DebrisCrystalAtk; - } - - // Calculate looses - defender - if(!empty($DefLost)) - { - foreach($DefLost as $ID => $Count) - { - if(in_array($ID, $_Vars_ElementCategories['fleet'])) - { - if($DebrisFactor_Fleet > 0) - { - $DebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Fleet); - $DebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Fleet); - } - } - elseif(in_array($ID, $_Vars_ElementCategories['defense'])) - { - if($DebrisFactor_Defense > 0) - { - $DebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Defense); - $DebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Defense); - } - } - $RealDebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count); - $RealDebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count); - $RealDebrisDeuteriumDef += floor($_Vars_Prices[$ID]['deuterium'] * $Count); - } - $TotalLostMetal += $DebrisMetalDef; - $TotalLostCrystal += $DebrisCrystalDef; - } - - // Delete fleets (if necessary) - if(!empty($DeleteFleet)) - { - foreach($DeleteFleet as $FleetID) - { - $_FleetCache['fleetRowStatus'][$FleetID]['isDestroyed'] = true; - if(!empty($_FleetCache['updateFleets'][$FleetID])) - { - unset($_FleetCache['updateFleets'][$FleetID]); - } - $Return['FleetsToDelete'][] = $FleetID; - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed'] = true; - $Return['FleetArchive'][$FleetID]['Fleet_Info_HasLostShips'] = true; - if($FleetID == $FleetRow['fleet_id']) - { - if($Result === COMBAT_DEF AND ($RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef) <= 0) - { - if(count($RoundsData) == 2) - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 1; - } - else - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 11; - } - } - else - { - if(count($RoundsData) == 2) - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 12; - } - else - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 5; - } - } - } - elseif(in_array($FleetID, $AttackingFleetID)) - { - if($Result === COMBAT_DEF AND ($RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef) <= 0) - { - if(count($RoundsData) == 2) - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 1; - } - else - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 11; - } - } - else - { - if(count($RoundsData) == 2) - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 12; - } - else - { - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 6; - } - } - } - else - { - unset($_FleetCache['defFleets'][$FleetRow['fleet_end_id']][$FleetID]); - $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 3; - } - } - } - - if($Result === COMBAT_DRAW AND ($RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef) <= 0) - { - foreach($AttackingFleetID as $ThisFleetID) - { - if(empty($DeleteFleet) OR !in_array($ThisFleetID, $DeleteFleet)) - { - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed_Reason'] = 4; - } - else - { - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed_Reason'] = 1; - } - } - } - - // Create debris field on the orbit - if($TotalLostMetal > 0 || $TotalLostCrystal > 0) - { - if($TotalLostCrystal == 0) - { - $TotalLostCrystal = '0'; - } - if($TotalLostMetal == 0) - { - $TotalLostMetal = '0'; - } - if($TargetPlanet['planet_type'] == 1) - { - $Query_UpdateGalaxy_SearchField = 'id_planet'; - $CacheKey = 'byPlanet'; - } - else - { - $Query_UpdateGalaxy_SearchField = 'id_moon'; - $CacheKey = 'byMoon'; - } - - if(isset($_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]) && $_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']] > 0) - { - if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['metal'])) - { - $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['metal'] = 0; - } - if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'])) - { - $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'] = 0; - } - - $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['metal'] += $TotalLostMetal; - $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'] += $TotalLostCrystal; - $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['updated'] = true; - $_FleetCache['updated']['galaxy'] = true; - } - else - { - $Query_UpdateGalaxy = ''; - $Query_UpdateGalaxy .= "UPDATE {{table}} SET `metal` = `metal` + {$TotalLostMetal}, `crystal` = `crystal` + {$TotalLostCrystal} "; - $Query_UpdateGalaxy .= "WHERE `{$Query_UpdateGalaxy_SearchField}` = {$FleetRow['fleet_end_id']} LIMIT 1; "; - $Query_UpdateGalaxy .= "-- MISSION GROUP_ATTACK [Q02][FID: {$FleetRow['fleet_id']}]"; - doquery($Query_UpdateGalaxy, 'galaxy'); - } - } - - // Check if Moon has been created - $FleetDebris = $TotalLostCrystal + $TotalLostMetal; - - $MoonChance = floor($FleetDebris / COMBAT_MOONPERCENT_RESOURCES); - if($MoonChance > 20) - { - $TotalMoonChance = $MoonChance; - $MoonChance = 20; - } - if($MoonChance < 1) - { - $UserChance = 0; - } - elseif($MoonChance >= 1) - { - $UserChance = mt_rand(1, 100); - } - - if(($UserChance > 0) AND ($UserChance <= $MoonChance)) - { - if($TargetPlanet['planet_type'] == 1) - { - $CreatedMoonID = CreateOneMoonRecord($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetUserID, '', $MoonChance); - if($CreatedMoonID !== false) - { - foreach($AttackersIDs as $ThisID) - { - $TriggerTasksCheck[$ThisID]['CREATE_MOON'] = true; - } - $MoonHasBeenCreated = true; - - $UserDev_UpPl[] = "L,{$CreatedMoonID}"; - - // Update User Stats - foreach($AttackersIDs as $UserID) - { - $UserStatsData[$UserID]['moons_created'] += 1; - } - } - else - { - $MoonHasBeenCreated = false; - } - } - else - { - $MoonHasBeenCreated = false; - } - } - elseif($UserChance = 0 or $UserChance > $MoonChance) - { - $MoonHasBeenCreated = false; - } - - // Create DevLog Record (PlanetDefender's) - if(!empty($UserDev_UpPl) AND !$IsAbandoned) - { - $UserDev_Log[] = array('UserID' => $TargetUserID, 'PlanetID' => $TargetPlanetID, 'Date' => $FleetRow['fleet_start_time'], 'Place' => 13, 'Code' => '1', 'ElementID' => '0', 'AdditionalData' => implode(';', $UserDev_UpPl)); - } - - // Morale System - if(MORALE_ENABLED AND !$IsAbandoned AND !$IsAllyFight AND $IdleHours < (7 * 24)) - { - foreach($AttackersMorale as $ThisUserID => $ThisData) - { - $Morale_TotalFactor += $ThisData['morale_points']; - } - $Morale_TotalFactor /= $TargetUser['morale_points']; - - if($Morale_TotalFactor > MORALE_MINIMALFACTOR) - { - $Morale_UsedTotalFactor = true; - $Morale_DefenderTotalFactor = $Morale_TotalFactor; - foreach($AttackersMorale as $ThisUserID => &$ThisData) - { - $ThisData['factor'] = $Morale_TotalFactor; - } - } - else - { - foreach($AttackersMorale as $ThisUserID => &$ThisData) - { - $ThisData['factor'] = $ThisData['morale_points'] / $TargetUser['morale_points']; - } - } - - foreach($AttackersMorale as $ThisUserID => &$ThisData) - { - $Morale_Factor = $ThisData['factor']; - if($Morale_Factor < 1) - { - $Morale_Factor = pow($Morale_Factor, -1); - $Morale_AttackerStronger = false; - } - else - { - $Morale_AttackerStronger = true; - } - - if($Morale_Factor > MORALE_MINIMALFACTOR) - { - if($Morale_AttackerStronger) - { - $Morale_Update_Attacker_Type = MORALE_NEGATIVE; - if(($Result === COMBAT_DEF OR $Result === COMBAT_DRAW) AND !$Morale_UsedTotalFactor) - { - $Morale_DefenderTotalFactor += $Morale_Factor; - } - } - else - { - $Morale_Update_Attacker_Type = MORALE_POSITIVE; - } - - $Morale_Updated = Morale_AddMorale($ThisData, $Morale_Update_Attacker_Type, $Morale_Factor, 1, 1, $FleetRow['fleet_start_time']); - if($Morale_Updated) - { - $_FleetCache['MoraleCache'][$ThisUserID]['level'] = $ThisData['morale_level']; - $_FleetCache['MoraleCache'][$ThisUserID]['droptime'] = $ThisData['morale_droptime']; - $_FleetCache['MoraleCache'][$ThisUserID]['lastupdate'] = $ThisData['morale_lastupdate']; - - $ReportData['morale'][$ThisUserID] = array - ( - 'usertype' => 'atk', - 'type' => $Morale_Update_Attacker_Type, - 'factor' => $Morale_Factor, - 'level' => $ThisData['morale_level'] - ); - } - } - } - - if($Morale_DefenderTotalFactor > 0) - { - if($Result === COMBAT_DRAW) - { - $Morale_LevelFactor = 1/2; - $Morale_TimeFactor = 1/2; - } - else - { - $Morale_LevelFactor = 1; - $Morale_TimeFactor = 1; - } - - $Morale_Updated = Morale_AddMorale($TargetUser, MORALE_POSITIVE, $Morale_DefenderTotalFactor, $Morale_LevelFactor, $Morale_TimeFactor, $FleetRow['fleet_start_time']); - if($Morale_Updated) - { - $_FleetCache['MoraleCache'][$TargetUser['id']]['level'] = $TargetUser['morale_level']; - $_FleetCache['MoraleCache'][$TargetUser['id']]['droptime'] = $TargetUser['morale_droptime']; - $_FleetCache['MoraleCache'][$TargetUser['id']]['lastupdate'] = $TargetUser['morale_lastupdate']; - - $ReportData['morale'][$TargetUser['id']] = array - ( - 'usertype' => 'def', - 'type' => MORALE_POSITIVE, - 'factor' => $Morale_DefenderTotalFactor, - 'level' => $TargetUser['morale_level'] - ); - } - } - } - - // CREATE BATTLE REPORT - $ReportData['init']['usr']['atk'] = $AttackersData; - $ReportData['init']['usr']['def'] = $DefendersData; - - $ReportData['init']['time'] = $totaltime; - $ReportData['init']['date'] = $FleetRow['fleet_start_time']; - - $ReportData['init']['result'] = $Result; - $ReportData['init']['met'] = $TotalMetStolen; - $ReportData['init']['cry'] = $TotalCryStolen; - $ReportData['init']['deu'] = $TotalDeuStolen; - $ReportData['init']['deb_met'] = $TotalLostMetal; - $ReportData['init']['deb_cry'] = $TotalLostCrystal; - $ReportData['init']['moon_chance'] = $MoonChance; - $ReportData['init']['total_moon_chance'] = $TotalMoonChance; - $ReportData['init']['moon_created'] = $MoonHasBeenCreated; - $ReportData['init']['moon_destroyed'] = false; - $ReportData['init']['moon_des_chance'] = 0; - $ReportData['init']['fleet_destroyed'] = false; - $ReportData['init']['fleet_des_chance'] = 0; - $ReportData['init']['planet_name'] = $TargetPlanetGetName; - $ReportData['init']['onMoon'] = ($FleetRow['fleet_end_type'] == 3 ? true : false); - $ReportData['init']['atk_lost'] = $RealDebrisMetalAtk + $RealDebrisCrystalAtk + $RealDebrisDeuteriumAtk; - $ReportData['init']['def_lost'] = $RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef; - - foreach($RoundsData as $RoundKey => $RoundData) - { - foreach($RoundData as $MainKey => $RoundData2) - { - if(!empty($RoundData2['ships'])) - { - foreach($RoundData2['ships'] as $UserKey => $UserData) - { - $RoundsData[$RoundKey][$MainKey]['ships'][$UserKey] = Array2String($UserData); - } - } - } - } - $ReportData['rounds'] = $RoundsData; - - if(count($RoundsData) <= 2 AND $Result === COMBAT_DEF) - { - $DisallowAttackers = true; - } - else - { - $DisallowAttackers = false; - } - - $CreatedReport = CreateBattleReport($ReportData, array('atk' => $AttackersIDs, 'def' => $DefendersIDs), $DisallowAttackers); - $ReportID = $CreatedReport['ID']; - $ReportHasHLinkRelative = 'battlereport.php?hash='.$CreatedReport['Hash']; - $ReportHasHLinkReal = GAMEURL.$ReportHasHLinkRelative; - - foreach($AttackingFleetID as $FleetID) - { - $Return['FleetArchive'][$FleetID]['Fleet_ReportID'] = $ReportID; - } - if(!empty($DefendingFleetID)) - { - foreach($DefendingFleetID as $FleetID) - { - $Return['FleetArchive'][$FleetID]['Fleet_DefenderReportIDs'] = "\"+,{$ReportID}\""; - } - } - - // Update battle stats & set Battle Report colors - if(!$IsAllyFight) - { - $InACSBattle[$FleetRow['fleet_owner']] = $FleetRow['fleet_owner']; - if($Result === COMBAT_ATK OR $Result === COMBAT_DRAW) - { - if(!empty($ForceContribution['atk'])) - { - $AttackersCount = count($AttackersIDs); - $ForceUsed_Total = array_sum($ForceContribution['atk']); - $ForceUsed_Array = array(); - foreach($ForceContribution['atk'] as $UserID => $UsedForce) - { - if($UserID == 0) - { - $UserID = $FleetRow['fleet_owner']; - } - else - { - $UserID = $AttackingFleetOwners[$AttackingFleetID[$UserID]]; - } - if(!isset($ForceUsed_Array[$UserID])) - { - $ForceUsed_Array[$UserID] = 0; - } - $ForceUsed_Array[$UserID] += $UsedForce; - } - $AttackersCount -= ($AttackersCount - count($ForceUsed_Array)); - } - else - { - $AttackersCount = 1; - } - } - - if($Result === COMBAT_ATK) - { - foreach($AttackersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_won'] += 1; - if($AttackersCount > 1) - { - if(($ForceUsed_Array[$UserID] / $ForceUsed_Total) >= ACS_MINIMALFORCECONTRIBUTION) - { - $InACSBattle[$UserID] = $UserID; - $UserStatsData[$UserID]['raids_acs_won'] += 1; - } - } - } - foreach($DefendersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_lost'] += 1; - } - $ReportColor = 'green'; - $ReportColor2 = 'red'; - } - else if($Result === COMBAT_DRAW) - { - foreach($AttackersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_draw'] += 1; - if($AttackersCount > 1) - { - if(($ForceUsed_Array[$UserID] / $ForceUsed_Total) >= ACS_MINIMALFORCECONTRIBUTION) - { - $InACSBattle[$UserID] = $UserID; - } - } - } - foreach($DefendersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_draw'] += 1; - } - $ReportColor = 'orange'; - $ReportColor2 = 'orange'; - } - else if($Result === COMBAT_DEF) - { - foreach($AttackersIDs as $UserID){ - $UserStatsData[$UserID]['raids_lost'] += 1; - } - foreach($DefendersIDs as $UserID){ - $UserStatsData[$UserID]['raids_won'] += 1; - } - $ReportColor = 'red'; - $ReportColor2 = 'green'; - } - - // Update User Destroyed & Lost Stats - if(!empty($ShotDown)) - { - foreach($ShotDown as $ThisType => $ThisData) - { - foreach($ThisData as $ThisType2 => $ThisData2) - { - if($ThisType2 == 'd') - { - $ThisKey = 'destroyed_'; - } - else - { - $ThisKey = 'lost_'; - } - foreach($ThisData2 as $UserID => $DestShips) - { - if($UserID == 0) - { - if($ThisType == 'atk') - { - $ThisUserID = $FleetRow['fleet_owner']; - } - else - { - $ThisUserID = $TargetUser['id']; - } - } - else - { - if($ThisType == 'atk') - { - $ThisUserID = $AttackingFleetOwners[$AttackingFleetID[$UserID]]; - } - else - { - $ThisUserID = $DefendingFleetOwners[$DefendingFleetID[$UserID]]; - } - } - foreach($DestShips as $ShipID => $ShipCount) - { - $UserStatsData[$ThisUserID][$ThisKey.$ShipID] += $ShipCount; - } - } - } - } - } - - $DestroyedDefendersShips_TotalPrice = 0; - if(!empty($ShotDown['atk']['d'])) - { - foreach($ShotDown['atk']['d'] as $UserID => $DestShips) - { - if($UserID == 0) - { - $ThisUserID = $FleetRow['fleet_owner']; - } - else - { - $ThisUserID = $AttackingFleetOwners[$AttackingFleetID[$UserID]]; - } - if(!isset($TriggerTasksCheck[$ThisUserID]['BATTLE_DESTROY_MILITARYUNITS'])) - { - $TriggerTasksCheck[$ThisUserID]['BATTLE_DESTROY_MILITARYUNITS'] = 0; - } - foreach($DestShips as $ShipID => $ShipCount) - { - $DestroyedDefendersShips_TotalPrice += (($_Vars_Prices[$ShipID]['metal'] + $_Vars_Prices[$ShipID]['crystal'] + $_Vars_Prices[$ShipID]['deuterium']) * $ShipCount); - if(in_array($ShipID, $_Vars_ElementCategories['units']['military'])) - { - $TriggerTasksCheck[$ThisUserID]['BATTLE_DESTROY_MILITARYUNITS'] += $ShipCount; - } - } - } - } - - $IsACSBattle = (count($InACSBattle) > 1 ? true : false); - if(!$IsACSBattle) - { - $DestroyedDefendersShips_TotalPrice = 0; - } - - if($Result === COMBAT_ATK OR $Result === COMBAT_DRAW) - { - if($Result === COMBAT_ATK) - { - foreach($InACSBattle as $ThisUserID) - { - $TriggerTasksCheck[$ThisUserID]['BATTLE_WIN'] = true; - } - } - foreach($InACSBattle as $ThisUserID) - { - $TriggerTasksCheck[$ThisUserID]['BATTLE_WINORDRAW_LIMIT'] = true; - $TriggerTasksCheck[$ThisUserID]['BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS'] = $DestroyedDefendersShips_TotalPrice; - } - if($IsACSBattle) - { - foreach($InACSBattle as $ThisUserID) - { - $TriggerTasksCheck[$ThisUserID]['BATTLE_WINORDRAW_ACS_LIMIT'] = true; - } - } - } - } - else - { - if(!empty($TriggerTasksCheck)) - { - foreach($TriggerTasksCheck as $ThisIndex => $ThisArray) - { - unset($TriggerTasksCheck[$ThisIndex]['BATTLE_COLLECT_METAL']); - unset($TriggerTasksCheck[$ThisIndex]['BATTLE_COLLECT_CRYSTAL']); - unset($TriggerTasksCheck[$ThisIndex]['BATTLE_COLLECT_DEUTERIUM']); - } - } - - foreach($AttackersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_inAlly'] += 1; - } - foreach($DefendersIDs as $UserID) - { - $UserStatsData[$UserID]['raids_inAlly'] += 1; - } - if($Result === COMBAT_ATK) - { - $ReportColor = 'green'; - $ReportColor2 = 'red'; - } - else if($Result === COMBAT_DRAW) - { - $ReportColor = 'orange'; - $ReportColor2 = 'orange'; - } - else if($Result === COMBAT_DEF) - { - $ReportColor = 'red'; - $ReportColor2 = 'green'; - } - } - - if($MoonHasBeenCreated AND $TargetUser['ally_id'] > 0) - { - foreach($AttackersIDs as $ThisID) - { - if($AttackersAllys[$ThisID] == $TargetUser['ally_id']) - { - $TriggerTasksCheck[$ThisID]['CREATE_MOON_FRIENDLY'] = true; - } - } - } - - $TargetTypeMsg = $_Lang['BR_Target_'.$FleetRow['fleet_end_type']]; - - if(!$IsAbandoned) - { - $Message = false; - $Message['msg_id'] = '074'; - if(!empty($Rebuilt) AND (array)$Rebuilt === $Rebuilt) - { - foreach($Rebuilt as $SysID => $Count) - { - $RebuildReport[] = ''.$_Lang['tech'][$SysID].' - '.$Count; - } - $RebuildReport = implode('
    ', $RebuildReport); - } - else - { - if(!isset($DefSysLostIDs) || count($DefSysLostIDs) == 1) - { - $RebuildReport = $_Lang['no_loses_in_defence']; - } - else - { - $RebuildReport = $_Lang['nothing_have_been_rebuilt']; - } - } - $Message['args'] = array($ReportID, $ReportColor2, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetTypeMsg, $RebuildReport, $ReportHasHLinkRelative, $ReportHasHLinkReal); - $Message = json_encode($Message); - Cache_Message($TargetUserID, 0, $FleetRow['fleet_start_time'], 3, '003', '012', $Message); - } - - if(count($DefendersIDs) > 1) - { - $Message = false; - $Message['msg_id'] = '075'; - $Message['args'] = array($ReportID, $ReportColor2, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetTypeMsg, $ReportHasHLinkRelative, $ReportHasHLinkReal); - $Message = json_encode($Message); - unset($DefendersIDs[0]); - Cache_Message($DefendersIDs, 0, $FleetRow['fleet_start_time'], 3, '003', '017', $Message); - } - - $Message = false; - $Message['msg_id'] = '071'; - $Message['args'] = array - ( - $ReportID, $ReportColor, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetTypeMsg, - prettyNumber($RealDebrisMetalAtk + $RealDebrisCrystalAtk + $RealDebrisDeuteriumAtk), - prettyNumber($RealDebrisCrystalDef + $RealDebrisMetalDef + $RealDebrisDeuteriumDef), - prettyNumber($TotalMetStolen), prettyNumber($TotalCryStolen), prettyNumber($TotalDeuStolen), - prettyNumber(isset($TotalLostMetal) ? $TotalLostMetal : 0), prettyNumber(isset($TotalLostCrystal) ? $TotalLostCrystal : 0), - $ReportHasHLinkRelative, $ReportHasHLinkReal - ); - $Message = json_encode($Message); - Cache_Message($AttackersIDs, 0, $FleetRow['fleet_start_time'], 3, '003', '017', $Message); - - $Return['DeleteACS'] = $FleetRow['acs_id']; - - if(!empty($TriggerTasksCheck)) - { - global $GlobalParsedTasks, $_User; - - $Debris_Total_Def = ($DebrisMetalDef + $DebrisCrystalDef) / COMBAT_MOONPERCENT_RESOURCES; - - foreach($TriggerTasksCheck as $ThisTaskUserID => $TriggerTasksData) - { - if($_User['id'] == $ThisTaskUserID) - { - $ThisTaskUser = $_User; - } - else - { - if(empty($GlobalParsedTasks[$ThisTaskUserID]['tasks_done_parsed'])) - { - $GetUserTasksDone = array(); - $GetUserTasksDone['tasks_done'] = $_FleetCache['userTasks'][$ThisTaskUserID]; - Tasks_CheckUservar($GetUserTasksDone); - $GlobalParsedTasks[$ThisTaskUserID] = $GetUserTasksDone; - } - $ThisTaskUser = $GlobalParsedTasks[$ThisTaskUserID]; - $ThisTaskUser['id'] = $ThisTaskUserID; - } - if($FleetRow['fleet_owner'] == $ThisTaskUser['id']) - { - $ThisTaskUser['isACSLeader'] = true; - } - - if(isset($TriggerTasksData['BATTLE_WIN'])) - { - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WIN', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - if(isset($TriggerTasksData['BATTLE_WINORDRAW_LIMIT'])) - { - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WINORDRAW_LIMIT', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $Debris_Total_Def) - { - if($JobArray['minimalEnemyPercentLimit'] > $Debris_Total_Def) - { - return true; - } - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - if(isset($TriggerTasksData['BATTLE_WINORDRAW_ACS_LIMIT'])) - { - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WINORDRAW_ACS_LIMIT', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $Debris_Total_Def) - { - if(isset($JobArray['hasToBeLeader']) && $JobArray['hasToBeLeader'] === true && $ThisTaskUser['isACSLeader'] !== true) - { - return true; - } - if($JobArray['minimalEnemyPercentLimit'] > $Debris_Total_Def) - { - return true; - } - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - if(isset($TriggerTasksData['BATTLE_COLLECT_METAL']) && $TriggerTasksData['BATTLE_COLLECT_METAL'] > 0) - { - $TaskTemp = $TriggerTasksData['BATTLE_COLLECT_METAL']; - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_METAL', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); - } - )); - } - if(isset($TriggerTasksData['BATTLE_COLLECT_CRYSTAL']) && $TriggerTasksData['BATTLE_COLLECT_CRYSTAL'] > 0) - { - $TaskTemp = $TriggerTasksData['BATTLE_COLLECT_CRYSTAL']; - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_CRYSTAL', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); - } - )); - } - if(isset($TriggerTasksData['BATTLE_COLLECT_DEUTERIUM']) && $TriggerTasksData['BATTLE_COLLECT_DEUTERIUM'] > 0) - { - $TaskTemp = $TriggerTasksData['BATTLE_COLLECT_DEUTERIUM']; - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_DEUTERIUM', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); - } - )); - } - if(isset($TriggerTasksData['CREATE_MOON']) && $TriggerTasksData['CREATE_MOON']) - { - Tasks_TriggerTask($ThisTaskUser, 'CREATE_MOON', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - if(isset($TriggerTasksData['CREATE_MOON_FRIENDLY']) && $TriggerTasksData['CREATE_MOON_FRIENDLY']) - { - Tasks_TriggerTask($ThisTaskUser, 'CREATE_MOON_FRIENDLY', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - if(isset($TriggerTasksData['BATTLE_DESTROY_MILITARYUNITS']) && $TriggerTasksData['BATTLE_DESTROY_MILITARYUNITS'] > 0) - { - $TaskTemp = $TriggerTasksData['BATTLE_DESTROY_MILITARYUNITS']; - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_DESTROY_MILITARYUNITS', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) - { - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); - } - )); - } - if(isset($TriggerTasksData['BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS']) && $TriggerTasksData['BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS'] > 0) - { - $TaskTemp2 = 0; - foreach($AttackingFleets as $FleetIndex => $FleetArray) - { - if($AttackingFleetOwners[$AttackingFleetID[$FleetIndex]] != $ThisTaskUser['id']) - { - continue; - } - foreach($FleetArray as $ShipID => $ShipCount) - { - $TaskTemp2 += (($_Vars_Prices[$ShipID]['metal'] + $_Vars_Prices[$ShipID]['crystal'] + $_Vars_Prices[$ShipID]['deuterium']) * $ShipCount); - } - } - $TaskTemp = $TriggerTasksData['BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS']; - Tasks_TriggerTask($ThisTaskUser, 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp, $TaskTemp2) - { - if($JobArray['minimalEnemyCost'] > $TaskTemp) - { - return true; - } - if($TaskTemp2 > ($TaskTemp * $JobArray['maximalOwnValue'])) - { - return true; - } - return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - } - )); - } - } - } - } - - if($FleetRow['calcType'] == 3 && (!isset($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed']) || $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] !== true)) - { - if(!empty($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']])) - { - foreach($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']] as $Key => $Value) - { - $FleetRow[$Key] = $Value; - } - } - $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack'] = true; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack_Time'] = $Now; - RestoreFleetToPlanet($FleetRow, true, $_FleetCache); - } - - return $Return; -} - -?> \ No newline at end of file + 0 ? false : true); + $TargetPlanet = &$_FleetCache['planets'][$FleetRow['fleet_end_id']]; + $TargetUser = &$_FleetCache['users'][$FleetRow['fleet_target_owner']]; + $IsAllyFight = (($FleetRow['ally_id'] == 0 OR ($FleetRow['ally_id'] != $TargetUser['ally_id'])) ? false : true); + + // Update planet before attack begins + $UpdateResult = HandleFullUserUpdate($TargetUser, $TargetPlanet, $_FleetCache['planets'][$TargetUser['techQueue_Planet']], $FleetRow['fleet_start_time'], true, true); + if(!empty($UpdateResult)) + { + foreach($UpdateResult as $PlanetID => $Value) + { + if($Value === true) + { + $_FleetCache['updatePlanets'][$PlanetID] = true; + } + } + } + + $TargetUserID = $TargetPlanet['id_owner']; + $TargetPlanetGetName= $TargetPlanet['name']; + $TargetPlanetID = $TargetPlanet['id']; + + if(!$IsAbandoned) + { + $IdleHours = floor(($FleetRow['fleet_start_time'] - $TargetUser['onlinetime']) / 3600); + if($IdleHours > 0) + { + $UseIdleHours = true; + } + } + + $AttackingFleets = array(); + $DefendingFleets = array(); + // Create data arrays for attacker and main defender + $DefendersIDs[] = $TargetUser['id']; + + $DefendingTechs[0] = array + ( + 109 => $TargetUser['tech_weapons'], + 110 => $TargetUser['tech_armour'], + 111 => $TargetUser['tech_shielding'], + 120 => $TargetUser['tech_laser'], + 121 => $TargetUser['tech_ion'], + 122 => $TargetUser['tech_plasma'], + 125 => $TargetUser['tech_antimatter'], + 126 => $TargetUser['tech_disintegration'], + 199 => $TargetUser['tech_graviton'] + ); + $DefendersData[0] = array + ( + 'id' => $TargetUser['id'], + 'username' => $TargetUser['username'], + 'techs' => Array2String($DefendingTechs[0]), + 'pos' => "{$FleetRow['fleet_end_galaxy']}:{$FleetRow['fleet_end_system']}:{$FleetRow['fleet_end_planet']}" + ); + if(!empty($TargetUser['ally_tag'])) + { + $DefendersData[0]['ally'] = $TargetUser['ally_tag']; + } + + // Select All Defending Fleets on the Orbit from $_FleetCache + if(!empty($_FleetCache['defFleets'][$FleetRow['fleet_end_id']])) + { + $i = 1; + foreach($_FleetCache['defFleets'][$FleetRow['fleet_end_id']] as $FleetData) + { + if($_FleetCache['fleetRowStatus'][$FleetData['fleet_id']]['isDestroyed'] !== true) + { + $DefendingFleets[$i] = String2Array($FleetData['fleet_array']); + $DefendingFleetID[$i] = $FleetData['fleet_id']; + $DefendingTechs[$i] = array + ( + 109 => $FleetData['tech_weapons'], + 110 => $FleetData['tech_armour'], + 111 => $FleetData['tech_shielding'], + 120 => $FleetData['tech_laser'], + 121 => $FleetData['tech_ion'], + 122 => $FleetData['tech_plasma'], + 125 => $FleetData['tech_antimatter'], + 126 => $FleetData['tech_disintegration'], + 199 => $FleetData['tech_graviton'] + ); + $DefendersData[$i] = array + ( + 'id' => $FleetData['fleet_owner'], + 'username' => $FleetData['username'], + 'techs' => Array2String($DefendingTechs[$i]), + 'pos' => "{$FleetData['fleet_start_galaxy']}:{$FleetData['fleet_start_system']}:{$FleetData['fleet_start_planet']}" + ); + if(!empty($FleetData['ally_tag'])) + { + $DefendersData[$i]['ally'] = $FleetData['ally_tag']; + } + if(!in_array($FleetData['fleet_owner'], $DefendersIDs)) + { + $DefendersIDs[] = $FleetData['fleet_owner']; + } + $DefendingFleetOwners[$FleetData['fleet_id']] = $FleetData['fleet_owner']; + + if(MORALE_ENABLED) + { + if(empty($_TempCache['MoraleCache'][$FleetData['fleet_owner']])) + { + if(!empty($_FleetCache['MoraleCache'][$FleetData['fleet_owner']])) + { + $FleetData['morale_level'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['level']; + $FleetData['morale_droptime'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['droptime']; + $FleetData['morale_lastupdate'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['lastupdate']; + } + Morale_ReCalculate($FleetData, $FleetRow['fleet_start_time']); + $DefendersData[$i]['morale'] = $FleetData['morale_level']; + $DefendersData[$i]['moralePoints'] = $FleetData['morale_points']; + + $_TempCache['MoraleCache'][$FleetData['fleet_owner']] = array + ( + 'level' => $FleetData['morale_level'], + 'points' => $FleetData['morale_points'] + ); + } + else + { + $DefendersData[$i]['morale'] = $_TempCache['MoraleCache'][$FleetData['fleet_owner']]['level']; + $DefendersData[$i]['moralePoints'] = $_TempCache['MoraleCache'][$FleetData['fleet_owner']]['points']; + } + + // Bonuses + if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETPOWERUP1) + { + $DefendingTechs[$i]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; + } + if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETSHIELDUP1) + { + $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; + } + if($DefendersData[$i]['morale'] >= MORALE_BONUS_FLEETSDADDITION) + { + $DefendingTechs[$i]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; + } + // Penalties + if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN1) + { + $DefendingTechs[$i]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; + } + if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN2) + { + $DefendingTechs[$i]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; + } + if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) + { + $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; + } + if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) + { + $DefendingTechs[$i]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; + } + if($DefendersData[$i]['morale'] <= MORALE_PENALTY_FLEETSDDOWN) + { + $DefendingTechs[$i]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; + } + } + + $i += 1; + } + } + } + + $AttackersIDs[] = $FleetRow['fleet_owner']; + $AttackingFleetOwners[$FleetRow['fleet_id']] = $FleetRow['fleet_owner']; + $AttackingFleetID[0] = $FleetRow['fleet_id']; + $AttackingFleetRes[$FleetRow['fleet_id']]['metal'] = (isset($FleetRow['fleet_resouce_metal']) ? $FleetRow['fleet_resouce_metal'] : 0); + $AttackingFleetRes[$FleetRow['fleet_id']]['crystal'] = (isset($FleetRow['fleet_resouce_crystal']) ? $FleetRow['fleet_resouce_crystal'] : 0); + $AttackingFleetRes[$FleetRow['fleet_id']]['deuterium'] = (isset($FleetRow['fleet_resouce_deuterium']) ? $FleetRow['fleet_resouce_deuterium'] : 0); + + $AttackingTechs[0] = array + ( + 109 => $FleetRow['tech_weapons'], + 110 => $FleetRow['tech_armour'], + 111 => $FleetRow['tech_shielding'], + 120 => $FleetRow['tech_laser'], + 121 => $FleetRow['tech_ion'], + 122 => $FleetRow['tech_plasma'], + 125 => $FleetRow['tech_antimatter'], + 126 => $FleetRow['tech_disintegration'], + 199 => $FleetRow['tech_graviton'] + ); + $AttackersData[0] = array + ( + 'id' => $FleetRow['fleet_owner'], + 'username' => $FleetRow['username'], + 'techs' => Array2String($AttackingTechs[0]), + 'pos' => "{$FleetRow['fleet_start_galaxy']}:{$FleetRow['fleet_start_system']}:{$FleetRow['fleet_start_planet']}" + ); + if(!empty($FleetRow['ally_tag'])) + { + $AttackersAllys[$FleetRow['fleet_owner']] = $FleetRow['ally_id']; + $AttackersData[0]['ally'] = $FleetRow['ally_tag']; + } + + // Select All Fleets from this ACS from $_FleetCache + if(!empty($_FleetCache['acsFleets'][$FleetRow['fleet_id']])) + { + $i = 1; + foreach($_FleetCache['acsFleets'][$FleetRow['fleet_id']] as $FleetData) + { + $AttackingFleets[$i] = String2Array($FleetData['fleet_array']); + $AttackingFleetRes[$FleetData['fleet_id']]['metal'] = (isset($FleetData['fleet_resouce_metal']) ? $FleetData['fleet_resouce_metal'] : 0); + $AttackingFleetRes[$FleetData['fleet_id']]['crystal'] = (isset($FleetData['fleet_resouce_crystal']) ? $FleetData['fleet_resouce_crystal'] : 0); + $AttackingFleetRes[$FleetData['fleet_id']]['deuterium'] = (isset($FleetData['fleet_resouce_deuterium']) ? $FleetData['fleet_resouce_deuterium'] : 0); + $AttackingFleetID[$i] = $FleetData['fleet_id']; + $AttackingTechs[$i] = array + ( + 109 => $FleetData['tech_weapons'], + 110 => $FleetData['tech_armour'], + 111 => $FleetData['tech_shielding'], + 120 => $FleetData['tech_laser'], + 121 => $FleetData['tech_ion'], + 122 => $FleetData['tech_plasma'], + 125 => $FleetData['tech_antimatter'], + 126 => $FleetData['tech_disintegration'], + 199 => $FleetData['tech_graviton'] + ); + $AttackersData[$i] = array + ( + 'id' => $FleetData['fleet_owner'], + 'username' => $FleetData['username'], + 'techs' => Array2String($AttackingTechs[$i]), + 'pos' => "{$FleetData['fleet_start_galaxy']}:{$FleetData['fleet_start_system']}:{$FleetData['fleet_start_planet']}" + ); + if(!empty($FleetData['ally_tag'])) + { + $AttackersAllys[$FleetData['fleet_owner']] = $FleetData['ally_id']; + $AttackersData[$i]['ally'] = $FleetData['ally_tag']; + } + if(!in_array($FleetData['fleet_owner'], $AttackersIDs)) + { + $AttackersIDs[] = $FleetData['fleet_owner']; + } + $AttackingFleetOwners[$FleetData['fleet_id']] = $FleetData['fleet_owner']; + + if(MORALE_ENABLED) + { + if(empty($_TempCache['MoraleCache'][$FleetData['fleet_owner']])) + { + if(!empty($_FleetCache['MoraleCache'][$FleetData['fleet_owner']])) + { + $FleetData['morale_level'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['level']; + $FleetData['morale_droptime'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['droptime']; + $FleetData['morale_lastupdate'] = $_FleetCache['MoraleCache'][$FleetData['fleet_owner']]['lastupdate']; + } + Morale_ReCalculate($FleetData, $FleetRow['fleet_start_time']); + $AttackersData[$i]['morale'] = $FleetData['morale_level']; + $AttackersData[$i]['moralePoints'] = $FleetData['morale_points']; + + $_TempCache['MoraleCache'][$FleetData['fleet_owner']] = array + ( + 'level' => $FleetData['morale_level'], + 'points' => $FleetData['morale_points'] + ); + + $AttackersMorale[$FleetData['fleet_owner']] = array + ( + 'morale_level' => $FleetData['morale_level'], + 'morale_droptime' => $FleetData['morale_droptime'], + 'morale_lastupdate' => $FleetData['morale_lastupdate'], + 'morale_points' => $FleetData['morale_points'] + ); + } + else + { + $AttackersData[$i]['morale'] = $_TempCache['MoraleCache'][$FleetData['fleet_owner']]['level']; + $AttackersData[$i]['moralePoints'] = $_TempCache['MoraleCache'][$FleetData['fleet_owner']]['points']; + } + + // Bonuses + if($AttackersData[$i]['morale'] >= MORALE_BONUS_FLEETPOWERUP1) + { + $AttackingTechs[$i]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; + } + if($AttackersData[$i]['morale'] >= MORALE_BONUS_FLEETSHIELDUP1) + { + $AttackingTechs[$i]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; + } + if($AttackersData[$i]['morale'] >= MORALE_BONUS_FLEETSDADDITION) + { + $AttackingTechs[$i]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; + } + // Penalties + if($AttackersData[$i]['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN1) + { + $AttackingTechs[$i]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; + } + if($AttackersData[$i]['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN2) + { + $AttackingTechs[$i]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; + } + if($AttackersData[$i]['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) + { + $AttackingTechs[$i]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; + } + if($AttackersData[$i]['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) + { + $AttackingTechs[$i]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; + } + if($AttackersData[$i]['morale'] <= MORALE_PENALTY_FLEETSDDOWN) + { + $AttackingTechs[$i]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; + } + } + + $i += 1; + } + } + + // MoraleSystem Init + if(MORALE_ENABLED) + { + if(!empty($_FleetCache['MoraleCache'][$FleetRow['fleet_owner']])) + { + $FleetRow['morale_level'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['level']; + $FleetRow['morale_droptime'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['droptime']; + $FleetRow['morale_lastupdate'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['lastupdate']; + } + Morale_ReCalculate($FleetRow, $FleetRow['fleet_start_time']); + $AttackersData[0]['morale'] = $FleetRow['morale_level']; + $AttackersData[0]['moralePoints'] = $FleetRow['morale_points']; + + if(empty($AttackersMorale[$FleetRow['fleet_owner']])) + { + $AttackersMorale[$FleetRow['fleet_owner']] = array + ( + 'morale_level' => $FleetRow['morale_level'], + 'morale_droptime' => $FleetRow['morale_droptime'], + 'morale_lastupdate' => $FleetRow['morale_lastupdate'], + 'morale_points' => $FleetRow['morale_points'] + ); + } + + // Bonuses + if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETPOWERUP1) + { + $AttackingTechs[0]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; + } + if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETSHIELDUP1) + { + $AttackingTechs[0]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; + } + if($FleetRow['morale_level'] >= MORALE_BONUS_FLEETSDADDITION) + { + $AttackingTechs[0]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; + } + // Penalties + if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN1) + { + $AttackingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; + } + if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN2) + { + $AttackingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; + } + if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) + { + $AttackingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; + } + if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) + { + $AttackingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; + } + if($FleetRow['morale_level'] <= MORALE_PENALTY_FLEETSDDOWN) + { + $AttackingTechs[0]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; + } + + if(!$IsAbandoned) + { + if(!empty($_FleetCache['MoraleCache'][$TargetUser['id']])) + { + $TargetUser['morale_level'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['level']; + $TargetUser['morale_droptime'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['droptime']; + $TargetUser['morale_lastupdate'] = $_FleetCache['MoraleCache'][$TargetUser['id']]['lastupdate']; + } + Morale_ReCalculate($TargetUser, $FleetRow['fleet_start_time']); + $DefendersData[0]['morale'] = $TargetUser['morale_level']; + $DefendersData[0]['moralePoints'] = $TargetUser['morale_points']; + + // Bonuses + if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETPOWERUP1) + { + $DefendingTechs[0]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; + } + if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETSHIELDUP1) + { + $DefendingTechs[0]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; + } + if($TargetUser['morale_level'] >= MORALE_BONUS_FLEETSDADDITION) + { + $DefendingTechs[0]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; + } + // Penalties + if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN1) + { + $DefendingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; + } + if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETPOWERDOWN2) + { + $DefendingTechs[0]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; + } + if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) + { + $DefendingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; + } + if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) + { + $DefendingTechs[0]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; + } + if($TargetUser['morale_level'] <= MORALE_PENALTY_FLEETSDDOWN) + { + $DefendingTechs[0]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; + } + } + } + + foreach($AttackingFleetID as $FleetID) + { + $Return['FleetArchive'][$FleetID]['Fleet_Calculated_Mission'] = true; + $Return['FleetArchive'][$FleetID]['Fleet_Calculated_Mission_Time'] = $Now; + if($UseIdleHours === true) + { + $Return['FleetArchive'][$FleetID]['Fleet_End_Owner_IdleHours'] = $IdleHours; + } + } + + foreach($AttackersIDs as $ID) + { + if(empty($UserStatsData[$ID])) + { + $UserStatsData[$ID] = $UserStatsPattern; + } + } + foreach($DefendersIDs as $ID) + { + if(empty($UserStatsData[$ID])) + { + $UserStatsData[$ID] = $UserStatsPattern; + } + } + + // Create main defender fleet array + foreach($_Vars_ElementCategories['fleet'] as $ElementID) + { + if($TargetPlanet[$_Vars_GameElements[$ElementID]] > 0) + { + $DefendingFleets[0][$ElementID] = $TargetPlanet[$_Vars_GameElements[$ElementID]]; + } + } + foreach($_Vars_ElementCategories['defense'] as $ElementID) + { + if(in_array($ElementID, $_Vars_ElementCategories['rockets'])) + { + continue; + } + if($TargetPlanet[$_Vars_GameElements[$ElementID]] > 0) + { + $DefendingFleets[0][$ElementID] = $TargetPlanet[$_Vars_GameElements[$ElementID]]; + } + } + + // Create attacker fleet array + $AttackingFleets[0] = String2Array($FleetRow['fleet_array']); + + $StartTime = microtime(true); + + // Now start Combat calculations + $Combat = Combat($AttackingFleets, $DefendingFleets, $AttackingTechs, $DefendingTechs); + + // Get the calculations time + $EndTime = microtime(true); + $totaltime = sprintf('%0.6f', $EndTime - $StartTime); + + $RealDebrisMetalAtk = 0; + $RealDebrisCrystalAtk = 0; + $RealDebrisDeuteriumAtk = 0; + $RealDebrisMetalDef = 0; + $RealDebrisCrystalDef = 0; + $RealDebrisDeuteriumDef = 0; + $TotalMoonChance = 0; + $TotalLostMetal = 0; + $TotalLostCrystal = 0; + $DebrisMetalDef = 0; + $DebrisCrystalDef = 0; + + $MoonHasBeenCreated = false; + + $RoundsData = $Combat['rounds']; + $Result = $Combat['result']; + $AtkShips = $Combat['AttackerShips']; + $DefShips = $Combat['DefenderShips']; + $AtkLost = $Combat['AtkLose']; + $DefLost = $Combat['DefLose']; + $DefSysLost = $Combat['DefSysLost']; + $ShotDown = $Combat['ShotDown']; + $ForceContribution = $Combat['ForceContribution']; + + $FleetStorage = 0; + + $i = 0; + // Parse result data - attackers fleet + $TotalMetStolen = 0; + $TotalCryStolen = 0; + $TotalDeuStolen = 0; + + if(!empty($AtkShips)) + { + if($Result === COMBAT_ATK) + { + $ResourceSteal_Factor = (COMBAT_RESOURCESTEAL_PERCENT / 100); + if(MORALE_ENABLED) + { + if(!$IsAbandoned AND $TargetUser['morale_level'] <= MORALE_PENALTY_RESOURCELOSE) + { + $ResourceSteal_NewFactor[] = MORALE_PENALTY_RESOURCELOSE_STEALPERCENT; + } + if($FleetRow['morale_level'] <= MORALE_PENALTY_STEAL) + { + $ResourceSteal_NewFactor[] = MORALE_PENALTY_STEAL_STEALPERCENT; + } + else if($FleetRow['morale_level'] <= MORALE_PENALTY_IDLERSTEAL AND $IdleHours >= (7 * 24)) + { + $ResourceSteal_NewFactor[] = MORALE_PENALTY_IDLERSTEAL_STEALPERCENT; + } + + if(!empty($ResourceSteal_NewFactor)) + { + $ResourceSteal_Factor = (array_sum($ResourceSteal_NewFactor) / count($ResourceSteal_NewFactor)) / 100; + } + } + + $MaxMetSteal = $TargetPlanet['metal'] * $ResourceSteal_Factor; + $MaxCrySteal = $TargetPlanet['crystal'] * $ResourceSteal_Factor; + $MaxDeuSteal = $TargetPlanet['deuterium'] * $ResourceSteal_Factor; + } + + foreach($AtkShips as $User => $Ships) + { + $FleetStorage = 0; + $CalculatedAtkFleets[] = $AttackingFleetID[$User]; + if(!empty($Ships)) + { + $QryUpdateFleets[$i]['id'] = $AttackingFleetID[$User]; + $QryUpdateFleets[$i]['mess'] = '1'; + $QryUpdateFleets[$i]['mission'] = '1'; + + foreach($AttackingFleets[$User] as $ID => $Count) + { + $Difference = $Count; + if(isset($Ships[$ID])) + { + $Difference -= $Ships[$ID]; + } + if($Difference > 0) + { + $QryUpdateFleets[$i]['array_lost'][] = "{$ID},{$Difference}"; + } + } + if(!empty($QryUpdateFleets[$i]['array_lost'])) + { + $QryUpdateFleets[$i]['array_lost'] = implode(';', $QryUpdateFleets[$i]['array_lost']); + } + + foreach($Ships as $ID => $Count) + { + if($Count > 0) + { + if(!isset($QryUpdateFleets[$i]['count'])) + { + $QryUpdateFleets[$i]['count'] = 0; + } + $QryUpdateFleets[$i]['array'][] = "{$ID},{$Count}"; + $QryUpdateFleets[$i]['count'] += $Count; + } + if($Result === COMBAT_ATK && (!isset($_Vars_Prices[$ID]['cantPillage']) || $_Vars_Prices[$ID]['cantPillage'] !== true)) + { + $FleetStorage += $_Vars_Prices[$ID]['capacity'] * $Count; + } + + if($Count < $AttackingFleets[$User][$ID]) + { + $UserDev_UpFl[$AttackingFleetID[$User]][] = $ID.','.($AttackingFleets[$User][$ID] - $Count); + } + } + + if($Result === COMBAT_ATK) + { + // New SYSTEM + $FleetStorage -= $AttackingFleetRes[$AttackingFleetID[$User]]['metal']; + $FleetStorage -= $AttackingFleetRes[$AttackingFleetID[$User]]['crystal']; + $FleetStorage -= $AttackingFleetRes[$AttackingFleetID[$User]]['deuterium']; + + if($FleetStorage > 0) + { + $GiveAwayMet = false; + $GiveAwayCry = false; + + $AllowTakeMoreMet = 0; + $AllowTakeMoreCry = 0; + $AllowTakeMoreDeu = 0; + + $StoragePerResource = $FleetStorage / 3; + + // First - calculate, if any resource will leave free storage + if($MaxMetSteal < $StoragePerResource) + { + $AllowTakeMore = ($StoragePerResource - $MaxMetSteal) / 2; + $AllowTakeMoreCry += $AllowTakeMore; + $AllowTakeMoreDeu += $AllowTakeMore; + $GiveAwayMet = true; + } + + if($MaxCrySteal < ($StoragePerResource + $AllowTakeMoreCry)) + { + $AllowTakeMore = (($StoragePerResource + $AllowTakeMoreCry) - $MaxCrySteal) / 2; + if($GiveAwayMet == false) + { + $AllowTakeMoreMet += $AllowTakeMore; + $AllowTakeMoreDeu += $AllowTakeMore; + } + else + { + $AllowTakeMoreDeu += $AllowTakeMore * 2; + } + $GiveAwayCry = true; + } + + if($MaxDeuSteal < ($StoragePerResource + $AllowTakeMoreDeu)) + { + $AllowTakeMore = (($StoragePerResource + $AllowTakeMoreDeu) - $MaxDeuSteal) / 2; + if($GiveAwayCry == false) + { + $AllowTakeMoreMet += $AllowTakeMore; + $AllowTakeMoreCry += $AllowTakeMore; + } + else + { + $AllowTakeMoreMet += $AllowTakeMore * 2; + } + } + + //Second - calculate stolen resources + if($MaxMetSteal > ($StoragePerResource + $AllowTakeMoreMet)) + { + $QryUpdateFleets[$i]['metal'] = floor($StoragePerResource + $AllowTakeMoreMet); + $MaxMetSteal -= $QryUpdateFleets[$i]['metal']; + $TotalMetStolen += $QryUpdateFleets[$i]['metal']; + } + else + { + $QryUpdateFleets[$i]['metal'] = floor($MaxMetSteal); + $MaxMetSteal -= $QryUpdateFleets[$i]['metal']; + $TotalMetStolen += $QryUpdateFleets[$i]['metal']; + } + if($MaxCrySteal > ($StoragePerResource + $AllowTakeMoreCry)) + { + $QryUpdateFleets[$i]['crystal'] = floor($StoragePerResource + $AllowTakeMoreCry); + $MaxCrySteal -= $QryUpdateFleets[$i]['crystal']; + $TotalCryStolen += $QryUpdateFleets[$i]['crystal']; + } + else + { + $QryUpdateFleets[$i]['crystal'] = floor($MaxCrySteal); + $MaxCrySteal -= $QryUpdateFleets[$i]['crystal']; + $TotalCryStolen += $QryUpdateFleets[$i]['crystal']; + } + if($MaxDeuSteal > ($StoragePerResource + $AllowTakeMoreDeu)) + { + $QryUpdateFleets[$i]['deuterium'] = floor($StoragePerResource + $AllowTakeMoreDeu); + $MaxDeuSteal -= $QryUpdateFleets[$i]['deuterium']; + $TotalDeuStolen += $QryUpdateFleets[$i]['deuterium']; + } + else + { + $QryUpdateFleets[$i]['deuterium'] = floor($MaxDeuSteal); + $MaxDeuSteal -= $QryUpdateFleets[$i]['deuterium']; + $TotalDeuStolen += $QryUpdateFleets[$i]['deuterium']; + } + + $Return['FleetArchive'][$AttackingFleetID[$User]]['Fleet_End_Res_Metal'] = $QryUpdateFleets[$i]['metal']; + $Return['FleetArchive'][$AttackingFleetID[$User]]['Fleet_End_Res_Crystal'] = $QryUpdateFleets[$i]['crystal']; + $Return['FleetArchive'][$AttackingFleetID[$User]]['Fleet_End_Res_Deuterium'] = $QryUpdateFleets[$i]['deuterium']; + + if($QryUpdateFleets[$i]['metal'] > 0) + { + if(!isset($TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_METAL'])) + { + $TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_METAL'] = 0; + } + $UserDev_UpFl[$AttackingFleetID[$User]][] = 'M,'.$QryUpdateFleets[$i]['metal']; + $TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_METAL'] += $QryUpdateFleets[$i]['metal']; + } + if($QryUpdateFleets[$i]['crystal'] > 0) + { + if(!isset($TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_CRYSTAL'])) + { + $TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_CRYSTAL'] = 0; + } + $UserDev_UpFl[$AttackingFleetID[$User]][] = 'C,'.$QryUpdateFleets[$i]['crystal']; + $TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_CRYSTAL'] += $QryUpdateFleets[$i]['crystal']; + } + if($QryUpdateFleets[$i]['deuterium'] > 0) + { + if(!isset($TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_DEUTERIUM'])) + { + $TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_DEUTERIUM'] = 0; + } + $UserDev_UpFl[$AttackingFleetID[$User]][] = 'D,'.$QryUpdateFleets[$i]['deuterium']; + $TriggerTasksCheck[$AttackingFleetOwners[$AttackingFleetID[$User]]]['BATTLE_COLLECT_DEUTERIUM'] += $QryUpdateFleets[$i]['deuterium']; + } + } + // END OF NEW SYSTEM + } + } + else + { + $DeleteFleet[] = $AttackingFleetID[$User]; + foreach($AttackingFleets[$User] as $ShipID => $ShipCount) + { + $UserDev_UpFl[$AttackingFleetID[$User]][] = "{$ShipID},{$ShipCount}"; + } + + if($User == 0) + { + $fleetHasBeenDeleted = true; + } + } + $i += 1; + } + + if(!empty($AttackingFleetID)) + { + foreach($AttackingFleetID as $User => $ID) + { + if(!in_array($ID, $CalculatedAtkFleets)) + { + $DeleteFleet[] = $ID; + foreach($AttackingFleets[$User] as $ShipID => $ShipCount) + { + $UserDev_UpFl[$ID][] = "{$ShipID},{$ShipCount}"; + } + + if($User == 0) + { + $fleetHasBeenDeleted = true; + } + } + } + } + } + else + { + if(!empty($AttackingFleetID)) + { + foreach($AttackingFleetID as $User => $ID) + { + $DeleteFleet[] = $ID; + foreach($AttackingFleets[$User] as $ShipID => $ShipCount) + { + $UserDev_UpFl[$ID][] = "{$ShipID},{$ShipCount}"; + } + + if($User == 0) + { + $fleetHasBeenDeleted = true; + } + } + } + } + + // Parse result data - Defenders + if(!empty($DefendingFleets)) + { + foreach($DefendingFleets as $User => $Ships) + { + if($User == 0) + { + $DefSysLostIDs = array_keys($DefSysLost); + $DefSysLostIDs[] = -1; + + foreach($Ships as $ID => $Count) + { + if(in_array($ID, $DefSysLostIDs)) + { + $Count = $DefShips[0][$ID]; + $Chance = mt_rand(60, 80 + (($TargetUser['engineer_time'] >= $FleetRow['fleet_start_time']) ? 20 : 0)); + $Fluctuation = mt_rand(-11, 11); + if($Fluctuation > 0) + { + $Fluctuation = 0; + } + $Rebuilt[$ID] = round($DefSysLost[$ID] * (($Chance + $Fluctuation) / 100)); + $Count += $Rebuilt[$ID]; + if($DefendingFleets[0][$ID] < $Count) + { + $Count = $DefendingFleets[0][$ID]; + } + unset($DefSysLost[$ID]); + } + else + { + $Count = $DefShips[0][$ID]; + } + if($Count == 0) + { + $Count = '0'; + } + $TargetPlanet[$_Vars_GameElements[$ID]] = $Count; + if($Count < $DefendingFleets[0][$ID]) + { + $UserDev_UpPl[] = $ID.','.($DefendingFleets[0][$ID] - $Count); + $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; + $HPQ_PlanetUpdatedFields[] = $_Vars_GameElements[$ID]; + } + } + } + else + { + $QryUpdateFleets[$i]['id'] = $DefendingFleetID[$User]; + if(!empty($DefShips[$User])) + { + foreach($Ships as $ID => $Count) + { + $ThisCount = 0; + if(!empty($DefShips[$User][$ID])) + { + $OldCount = $Count; + $Count = $DefShips[$User][$ID]; + $ThisCount = $Count; + if($Count > 0) + { + if(!isset($QryUpdateFleets[$i]['count'])) + { + $QryUpdateFleets[$i]['count'] = 0; + } + $QryUpdateFleets[$i]['array'][] = "{$ID},{$Count}"; + $QryUpdateFleets[$i]['count'] += $Count; + } + $Difference = $OldCount - $Count; + if($Difference > 0) + { + $QryUpdateFleets[$i]['array_lost'][] = "{$ID},{$Difference}"; + } + } + + if($ThisCount < $DefendingFleets[$User][$ID]) + { + $UserDev_UpFl[$DefendingFleetID[$User]][] = $ID.','.($DefendingFleets[$User][$ID] - $ThisCount); + } + } + + if(!empty($QryUpdateFleets[$i]['array_lost'])) + { + $QryUpdateFleets[$i]['array_lost'] = implode(';', $QryUpdateFleets[$i]['array_lost']); + } + } + else + { + $DeleteFleet[] = $DefendingFleetID[$User]; + foreach($DefendingFleets[$User] as $ShipID => $ShipCount) + { + $UserDev_UpFl[$DefendingFleetID[$User]][] = "{$ShipID},{$ShipCount}"; + } + } + } + $i += 1; + } + } + + if($TotalMetStolen > 0) + { + $TargetPlanet['metal'] -= $TotalMetStolen; + $UserDev_UpPl[] = 'M,'.$TotalMetStolen; + $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; + } + if($TotalCryStolen > 0) + { + $TargetPlanet['crystal'] -= $TotalCryStolen; + $UserDev_UpPl[] = 'C,'.$TotalCryStolen; + $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; + } + if($TotalDeuStolen > 0) + { + $TargetPlanet['deuterium'] -= $TotalDeuStolen; + $UserDev_UpPl[] = 'D,'.$TotalDeuStolen; + $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; + } + + // Update all fleets (if necessary) + if(!empty($QryUpdateFleets)) + { + foreach($QryUpdateFleets as $Data) + { + if(!empty($Data)) + { + if($Data['metal'] <= 0) + { + $Data['metal'] = '0'; + } + if($Data['crystal'] <= 0) + { + $Data['crystal'] = '0'; + } + if($Data['deuterium'] <= 0) + { + $Data['deuterium'] = '0'; + } + + if(!empty($Data['array'])) + { + $Data['array'] = implode(';', $Data['array']); + if(!empty($Data['array_lost'])) + { + if(strlen($Data['array']) > strlen($Data['array_lost'])) + { + $Return['FleetArchive'][$Data['id']]['Fleet_Array_Changes'] = "\"+D;{$Data['array_lost']}|\""; + } + else + { + $Return['FleetArchive'][$Data['id']]['Fleet_Array_Changes'] = "\"+L;{$Data['array']}|\""; + } + $Return['FleetArchive'][$Data['id']]['Fleet_Info_HasLostShips'] = '!true'; + } + if($Data['id'] != $FleetRow['fleet_id'] AND !empty($DefendingFleetID) AND in_array($Data['id'], $DefendingFleetID)) + { + $_FleetCache['defFleets'][$FleetRow['fleet_end_id']][$Data['id']]['fleet_array'] = $Data['array']; + } + } + + if($Data['id'] == $FleetRow['fleet_id'] AND $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['calcCount'] == 2) + { + // Update $_FleetCache, instead of sending additional Query to Update FleetState + // This fleet will be restored in this Calculation, so don't waste our time + $CachePointer = &$_FleetCache['fleetRowUpdate'][$Data['id']]; + $CachePointer['fleet_array'] = $Data['array']; + $CachePointer['fleet_resource_metal'] = $FleetRow['fleet_resource_metal'] + $Data['metal']; + $CachePointer['fleet_resource_crystal'] = $FleetRow['fleet_resource_crystal'] + $Data['crystal']; + $CachePointer['fleet_resource_deuterium'] = $FleetRow['fleet_resource_deuterium'] + $Data['deuterium']; + } + else + { + // Create UpdateFleet record for $_FleetCache + $CachePointer = &$_FleetCache['updateFleets'][$Data['id']]; + $CachePointer['fleet_array'] = $Data['array']; + $CachePointer['fleet_amount'] = $Data['count']; + $CachePointer['fleet_mess'] = $Data['mess']; + if(!isset($CachePointer['fleet_resource_metal'])) + { + $CachePointer['fleet_resource_metal'] = 0; + } + if(!isset($CachePointer['fleet_resource_crystal'])) + { + $CachePointer['fleet_resource_crystal'] = 0; + } + if(!isset($CachePointer['fleet_resource_deuterium'])) + { + $CachePointer['fleet_resource_deuterium'] = 0; + } + $CachePointer['fleet_resource_metal'] += $Data['metal']; + $CachePointer['fleet_resource_crystal'] += $Data['crystal']; + $CachePointer['fleet_resource_deuterium'] += $Data['deuterium']; + if($Data['id'] != $FleetRow['fleet_id'] AND (empty($DefendingFleetID) OR !in_array($Data['id'], $DefendingFleetID))) + { + $CachePointer = &$_FleetCache['fleetRowUpdate'][$Data['id']]; + $CachePointer['fleet_array'] = $Data['array']; + $CachePointer['fleet_resource_metal'] = (isset($_FleetCache['acsFleets'][$Data['id']]['fleet_resource_metal']) ? $_FleetCache['acsFleets'][$Data['id']]['fleet_resource_metal'] : 0) + $Data['metal']; + $CachePointer['fleet_resource_crystal'] = (isset($_FleetCache['acsFleets'][$Data['id']]['fleet_resource_crystal']) ? $_FleetCache['acsFleets'][$Data['id']]['fleet_resource_crystal'] : 0) + $Data['crystal']; + $CachePointer['fleet_resource_deuterium'] = (isset($_FleetCache['acsFleets'][$Data['id']]['fleet_resource_deuterium']) ? $_FleetCache['acsFleets'][$Data['id']]['fleet_resource_deuterium'] : 0) + $Data['deuterium']; + } + } + } + } + } + + if(!empty($UserDev_UpFl)) + { + foreach($UserDev_UpFl as $FleetID => $DevArray) + { + if($FleetID == $FleetRow['fleet_id']) + { + $SetCode = '2'; + $FleetUserID = $FleetRow['fleet_owner']; + } + else + { + if(!empty($DefendingFleetID) AND in_array($FleetID, $DefendingFleetID)) + { + $SetCode = '3'; + $FleetUserID = $DefendingFleetOwners[$FleetID]; + } + else + { + $SetCode = '4'; + $FleetUserID = $AttackingFleetOwners[$FleetID]; + } + } + $UserDev_Log[] = array('UserID' => $FleetUserID, 'PlanetID' => '0', 'Date' => $FleetRow['fleet_start_time'], 'Place' => 13, 'Code' => $SetCode, 'ElementID' => $FleetID, 'AdditionalData' => implode(';', $DevArray)); + } + } + + // Calculate Debris & Looses - Init + $DebrisFactor_Fleet = $_GameConfig['Fleet_Cdr'] / 100; + $DebrisFactor_Defense = $_GameConfig['Defs_Cdr'] / 100; + + // Calculate looses - attacker + if(!empty($AtkLost)) + { + $DebrisMetalAtk = 0; + $DebrisCrystalAtk = 0; + foreach($AtkLost as $ID => $Count) + { + if(in_array($ID, $_Vars_ElementCategories['fleet'])) + { + if($DebrisFactor_Fleet > 0) + { + $DebrisMetalAtk += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Fleet); + $DebrisCrystalAtk += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Fleet); + } + $RealDebrisMetalAtk += floor($_Vars_Prices[$ID]['metal'] * $Count); + $RealDebrisCrystalAtk += floor($_Vars_Prices[$ID]['crystal'] * $Count); + $RealDebrisDeuteriumAtk += floor($_Vars_Prices[$ID]['deuterium'] * $Count); + } + } + $TotalLostMetal = $DebrisMetalAtk; + $TotalLostCrystal = $DebrisCrystalAtk; + } + + // Calculate looses - defender + if(!empty($DefLost)) + { + foreach($DefLost as $ID => $Count) + { + if(in_array($ID, $_Vars_ElementCategories['fleet'])) + { + if($DebrisFactor_Fleet > 0) + { + $DebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Fleet); + $DebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Fleet); + } + } + elseif(in_array($ID, $_Vars_ElementCategories['defense'])) + { + if($DebrisFactor_Defense > 0) + { + $DebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count * $DebrisFactor_Defense); + $DebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count * $DebrisFactor_Defense); + } + } + $RealDebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count); + $RealDebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count); + $RealDebrisDeuteriumDef += floor($_Vars_Prices[$ID]['deuterium'] * $Count); + } + $TotalLostMetal += $DebrisMetalDef; + $TotalLostCrystal += $DebrisCrystalDef; + } + + // Delete fleets (if necessary) + if(!empty($DeleteFleet)) + { + foreach($DeleteFleet as $FleetID) + { + $_FleetCache['fleetRowStatus'][$FleetID]['isDestroyed'] = true; + if(!empty($_FleetCache['updateFleets'][$FleetID])) + { + unset($_FleetCache['updateFleets'][$FleetID]); + } + $Return['FleetsToDelete'][] = $FleetID; + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed'] = true; + $Return['FleetArchive'][$FleetID]['Fleet_Info_HasLostShips'] = true; + if($FleetID == $FleetRow['fleet_id']) + { + if($Result === COMBAT_DEF AND ($RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef) <= 0) + { + if(count($RoundsData) == 2) + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 1; + } + else + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 11; + } + } + else + { + if(count($RoundsData) == 2) + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 12; + } + else + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 5; + } + } + } + elseif(in_array($FleetID, $AttackingFleetID)) + { + if($Result === COMBAT_DEF AND ($RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef) <= 0) + { + if(count($RoundsData) == 2) + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 1; + } + else + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 11; + } + } + else + { + if(count($RoundsData) == 2) + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 12; + } + else + { + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 6; + } + } + } + else + { + unset($_FleetCache['defFleets'][$FleetRow['fleet_end_id']][$FleetID]); + $Return['FleetArchive'][$FleetID]['Fleet_Destroyed_Reason'] = 3; + } + } + } + + if($Result === COMBAT_DRAW AND ($RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef) <= 0) + { + foreach($AttackingFleetID as $ThisFleetID) + { + if(empty($DeleteFleet) OR !in_array($ThisFleetID, $DeleteFleet)) + { + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed_Reason'] = 4; + } + else + { + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed_Reason'] = 1; + } + } + } + + // Create debris field on the orbit + if($TotalLostMetal > 0 || $TotalLostCrystal > 0) + { + if($TotalLostCrystal == 0) + { + $TotalLostCrystal = '0'; + } + if($TotalLostMetal == 0) + { + $TotalLostMetal = '0'; + } + if($TargetPlanet['planet_type'] == 1) + { + $Query_UpdateGalaxy_SearchField = 'id_planet'; + $CacheKey = 'byPlanet'; + } + else + { + $Query_UpdateGalaxy_SearchField = 'id_moon'; + $CacheKey = 'byMoon'; + } + + if(isset($_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]) && $_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']] > 0) + { + if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['metal'])) + { + $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['metal'] = 0; + } + if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'])) + { + $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'] = 0; + } + + $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['metal'] += $TotalLostMetal; + $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'] += $TotalLostCrystal; + $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['updated'] = true; + $_FleetCache['updated']['galaxy'] = true; + } + else + { + $Query_UpdateGalaxy = ''; + $Query_UpdateGalaxy .= "UPDATE {{table}} SET `metal` = `metal` + {$TotalLostMetal}, `crystal` = `crystal` + {$TotalLostCrystal} "; + $Query_UpdateGalaxy .= "WHERE `{$Query_UpdateGalaxy_SearchField}` = {$FleetRow['fleet_end_id']} LIMIT 1; "; + $Query_UpdateGalaxy .= "-- MISSION GROUP_ATTACK [Q02][FID: {$FleetRow['fleet_id']}]"; + doquery($Query_UpdateGalaxy, 'galaxy'); + } + } + + // Check if Moon has been created + $FleetDebris = $TotalLostCrystal + $TotalLostMetal; + + $MoonChance = floor($FleetDebris / COMBAT_MOONPERCENT_RESOURCES); + if($MoonChance > 20) + { + $TotalMoonChance = $MoonChance; + $MoonChance = 20; + } + if($MoonChance < 1) + { + $UserChance = 0; + } + elseif($MoonChance >= 1) + { + $UserChance = mt_rand(1, 100); + } + + if(($UserChance > 0) AND ($UserChance <= $MoonChance)) + { + if($TargetPlanet['planet_type'] == 1) + { + $CreatedMoonID = CreateOneMoonRecord($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetUserID, '', $MoonChance); + if($CreatedMoonID !== false) + { + foreach($AttackersIDs as $ThisID) + { + $TriggerTasksCheck[$ThisID]['CREATE_MOON'] = true; + } + $MoonHasBeenCreated = true; + + $UserDev_UpPl[] = "L,{$CreatedMoonID}"; + + // Update User Stats + foreach($AttackersIDs as $UserID) + { + $UserStatsData[$UserID]['moons_created'] += 1; + } + } + else + { + $MoonHasBeenCreated = false; + } + } + else + { + $MoonHasBeenCreated = false; + } + } + elseif($UserChance = 0 or $UserChance > $MoonChance) + { + $MoonHasBeenCreated = false; + } + + // Create DevLog Record (PlanetDefender's) + if(!empty($UserDev_UpPl) AND !$IsAbandoned) + { + $UserDev_Log[] = array('UserID' => $TargetUserID, 'PlanetID' => $TargetPlanetID, 'Date' => $FleetRow['fleet_start_time'], 'Place' => 13, 'Code' => '1', 'ElementID' => '0', 'AdditionalData' => implode(';', $UserDev_UpPl)); + } + + // Morale System + if(MORALE_ENABLED AND !$IsAbandoned AND !$IsAllyFight AND $IdleHours < (7 * 24)) + { + foreach($AttackersMorale as $ThisUserID => $ThisData) + { + $Morale_TotalFactor += $ThisData['morale_points']; + } + $Morale_TotalFactor /= $TargetUser['morale_points']; + + if($Morale_TotalFactor > MORALE_MINIMALFACTOR) + { + $Morale_UsedTotalFactor = true; + $Morale_DefenderTotalFactor = $Morale_TotalFactor; + foreach($AttackersMorale as $ThisUserID => &$ThisData) + { + $ThisData['factor'] = $Morale_TotalFactor; + } + } + else + { + foreach($AttackersMorale as $ThisUserID => &$ThisData) + { + $ThisData['factor'] = $ThisData['morale_points'] / $TargetUser['morale_points']; + } + } + + foreach($AttackersMorale as $ThisUserID => &$ThisData) + { + $Morale_Factor = $ThisData['factor']; + if($Morale_Factor < 1) + { + $Morale_Factor = pow($Morale_Factor, -1); + $Morale_AttackerStronger = false; + } + else + { + $Morale_AttackerStronger = true; + } + + if($Morale_Factor > MORALE_MINIMALFACTOR) + { + if($Morale_AttackerStronger) + { + $Morale_Update_Attacker_Type = MORALE_NEGATIVE; + if(($Result === COMBAT_DEF OR $Result === COMBAT_DRAW) AND !$Morale_UsedTotalFactor) + { + $Morale_DefenderTotalFactor += $Morale_Factor; + } + } + else + { + $Morale_Update_Attacker_Type = MORALE_POSITIVE; + } + + $Morale_Updated = Morale_AddMorale($ThisData, $Morale_Update_Attacker_Type, $Morale_Factor, 1, 1, $FleetRow['fleet_start_time']); + if($Morale_Updated) + { + $_FleetCache['MoraleCache'][$ThisUserID]['level'] = $ThisData['morale_level']; + $_FleetCache['MoraleCache'][$ThisUserID]['droptime'] = $ThisData['morale_droptime']; + $_FleetCache['MoraleCache'][$ThisUserID]['lastupdate'] = $ThisData['morale_lastupdate']; + + $ReportData['morale'][$ThisUserID] = array + ( + 'usertype' => 'atk', + 'type' => $Morale_Update_Attacker_Type, + 'factor' => $Morale_Factor, + 'level' => $ThisData['morale_level'] + ); + } + } + } + + if($Morale_DefenderTotalFactor > 0) + { + if($Result === COMBAT_DRAW) + { + $Morale_LevelFactor = 1/2; + $Morale_TimeFactor = 1/2; + } + else + { + $Morale_LevelFactor = 1; + $Morale_TimeFactor = 1; + } + + $Morale_Updated = Morale_AddMorale($TargetUser, MORALE_POSITIVE, $Morale_DefenderTotalFactor, $Morale_LevelFactor, $Morale_TimeFactor, $FleetRow['fleet_start_time']); + if($Morale_Updated) + { + $_FleetCache['MoraleCache'][$TargetUser['id']]['level'] = $TargetUser['morale_level']; + $_FleetCache['MoraleCache'][$TargetUser['id']]['droptime'] = $TargetUser['morale_droptime']; + $_FleetCache['MoraleCache'][$TargetUser['id']]['lastupdate'] = $TargetUser['morale_lastupdate']; + + $ReportData['morale'][$TargetUser['id']] = array + ( + 'usertype' => 'def', + 'type' => MORALE_POSITIVE, + 'factor' => $Morale_DefenderTotalFactor, + 'level' => $TargetUser['morale_level'] + ); + } + } + } + + // CREATE BATTLE REPORT + $ReportData['init']['usr']['atk'] = $AttackersData; + $ReportData['init']['usr']['def'] = $DefendersData; + + $ReportData['init']['time'] = $totaltime; + $ReportData['init']['date'] = $FleetRow['fleet_start_time']; + + $ReportData['init']['result'] = $Result; + $ReportData['init']['met'] = $TotalMetStolen; + $ReportData['init']['cry'] = $TotalCryStolen; + $ReportData['init']['deu'] = $TotalDeuStolen; + $ReportData['init']['deb_met'] = $TotalLostMetal; + $ReportData['init']['deb_cry'] = $TotalLostCrystal; + $ReportData['init']['moon_chance'] = $MoonChance; + $ReportData['init']['total_moon_chance'] = $TotalMoonChance; + $ReportData['init']['moon_created'] = $MoonHasBeenCreated; + $ReportData['init']['moon_destroyed'] = false; + $ReportData['init']['moon_des_chance'] = 0; + $ReportData['init']['fleet_destroyed'] = false; + $ReportData['init']['fleet_des_chance'] = 0; + $ReportData['init']['planet_name'] = $TargetPlanetGetName; + $ReportData['init']['onMoon'] = ($FleetRow['fleet_end_type'] == 3 ? true : false); + $ReportData['init']['atk_lost'] = $RealDebrisMetalAtk + $RealDebrisCrystalAtk + $RealDebrisDeuteriumAtk; + $ReportData['init']['def_lost'] = $RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef; + + foreach($RoundsData as $RoundKey => $RoundData) + { + foreach($RoundData as $MainKey => $RoundData2) + { + if(!empty($RoundData2['ships'])) + { + foreach($RoundData2['ships'] as $UserKey => $UserData) + { + $RoundsData[$RoundKey][$MainKey]['ships'][$UserKey] = Array2String($UserData); + } + } + } + } + $ReportData['rounds'] = $RoundsData; + + if(count($RoundsData) <= 2 AND $Result === COMBAT_DEF) + { + $DisallowAttackers = true; + } + else + { + $DisallowAttackers = false; + } + + $CreatedReport = CreateBattleReport($ReportData, array('atk' => $AttackersIDs, 'def' => $DefendersIDs), $DisallowAttackers); + $ReportID = $CreatedReport['ID']; + $ReportHasHLinkRelative = 'battlereport.php?hash='.$CreatedReport['Hash']; + $ReportHasHLinkReal = GAMEURL.$ReportHasHLinkRelative; + + foreach($AttackingFleetID as $FleetID) + { + $Return['FleetArchive'][$FleetID]['Fleet_ReportID'] = $ReportID; + } + if(!empty($DefendingFleetID)) + { + foreach($DefendingFleetID as $FleetID) + { + $Return['FleetArchive'][$FleetID]['Fleet_DefenderReportIDs'] = "\"+,{$ReportID}\""; + } + } + + // Update battle stats & set Battle Report colors + if(!$IsAllyFight) + { + $InACSBattle[$FleetRow['fleet_owner']] = $FleetRow['fleet_owner']; + if($Result === COMBAT_ATK OR $Result === COMBAT_DRAW) + { + if(!empty($ForceContribution['atk'])) + { + $AttackersCount = count($AttackersIDs); + $ForceUsed_Total = array_sum($ForceContribution['atk']); + $ForceUsed_Array = array(); + foreach($ForceContribution['atk'] as $UserID => $UsedForce) + { + if($UserID == 0) + { + $UserID = $FleetRow['fleet_owner']; + } + else + { + $UserID = $AttackingFleetOwners[$AttackingFleetID[$UserID]]; + } + if(!isset($ForceUsed_Array[$UserID])) + { + $ForceUsed_Array[$UserID] = 0; + } + $ForceUsed_Array[$UserID] += $UsedForce; + } + $AttackersCount -= ($AttackersCount - count($ForceUsed_Array)); + } + else + { + $AttackersCount = 1; + } + } + + if($Result === COMBAT_ATK) + { + foreach($AttackersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_won'] += 1; + if($AttackersCount > 1) + { + if(($ForceUsed_Array[$UserID] / $ForceUsed_Total) >= ACS_MINIMALFORCECONTRIBUTION) + { + $InACSBattle[$UserID] = $UserID; + $UserStatsData[$UserID]['raids_acs_won'] += 1; + } + } + } + foreach($DefendersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_lost'] += 1; + } + $ReportColor = 'green'; + $ReportColor2 = 'red'; + } + else if($Result === COMBAT_DRAW) + { + foreach($AttackersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_draw'] += 1; + if($AttackersCount > 1) + { + if(($ForceUsed_Array[$UserID] / $ForceUsed_Total) >= ACS_MINIMALFORCECONTRIBUTION) + { + $InACSBattle[$UserID] = $UserID; + } + } + } + foreach($DefendersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_draw'] += 1; + } + $ReportColor = 'orange'; + $ReportColor2 = 'orange'; + } + else if($Result === COMBAT_DEF) + { + foreach($AttackersIDs as $UserID){ + $UserStatsData[$UserID]['raids_lost'] += 1; + } + foreach($DefendersIDs as $UserID){ + $UserStatsData[$UserID]['raids_won'] += 1; + } + $ReportColor = 'red'; + $ReportColor2 = 'green'; + } + + // Update User Destroyed & Lost Stats + if(!empty($ShotDown)) + { + foreach($ShotDown as $ThisType => $ThisData) + { + foreach($ThisData as $ThisType2 => $ThisData2) + { + if($ThisType2 == 'd') + { + $ThisKey = 'destroyed_'; + } + else + { + $ThisKey = 'lost_'; + } + foreach($ThisData2 as $UserID => $DestShips) + { + if($UserID == 0) + { + if($ThisType == 'atk') + { + $ThisUserID = $FleetRow['fleet_owner']; + } + else + { + $ThisUserID = $TargetUser['id']; + } + } + else + { + if($ThisType == 'atk') + { + $ThisUserID = $AttackingFleetOwners[$AttackingFleetID[$UserID]]; + } + else + { + $ThisUserID = $DefendingFleetOwners[$DefendingFleetID[$UserID]]; + } + } + foreach($DestShips as $ShipID => $ShipCount) + { + $UserStatsData[$ThisUserID][$ThisKey.$ShipID] += $ShipCount; + } + } + } + } + } + + $DestroyedDefendersShips_TotalPrice = 0; + if(!empty($ShotDown['atk']['d'])) + { + foreach($ShotDown['atk']['d'] as $UserID => $DestShips) + { + if($UserID == 0) + { + $ThisUserID = $FleetRow['fleet_owner']; + } + else + { + $ThisUserID = $AttackingFleetOwners[$AttackingFleetID[$UserID]]; + } + if(!isset($TriggerTasksCheck[$ThisUserID]['BATTLE_DESTROY_MILITARYUNITS'])) + { + $TriggerTasksCheck[$ThisUserID]['BATTLE_DESTROY_MILITARYUNITS'] = 0; + } + foreach($DestShips as $ShipID => $ShipCount) + { + $DestroyedDefendersShips_TotalPrice += (($_Vars_Prices[$ShipID]['metal'] + $_Vars_Prices[$ShipID]['crystal'] + $_Vars_Prices[$ShipID]['deuterium']) * $ShipCount); + if(in_array($ShipID, $_Vars_ElementCategories['units']['military'])) + { + $TriggerTasksCheck[$ThisUserID]['BATTLE_DESTROY_MILITARYUNITS'] += $ShipCount; + } + } + } + } + + $IsACSBattle = (count($InACSBattle) > 1 ? true : false); + if(!$IsACSBattle) + { + $DestroyedDefendersShips_TotalPrice = 0; + } + + if($Result === COMBAT_ATK OR $Result === COMBAT_DRAW) + { + if($Result === COMBAT_ATK) + { + foreach($InACSBattle as $ThisUserID) + { + $TriggerTasksCheck[$ThisUserID]['BATTLE_WIN'] = true; + } + } + foreach($InACSBattle as $ThisUserID) + { + $TriggerTasksCheck[$ThisUserID]['BATTLE_WINORDRAW_LIMIT'] = true; + $TriggerTasksCheck[$ThisUserID]['BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS'] = $DestroyedDefendersShips_TotalPrice; + } + if($IsACSBattle) + { + foreach($InACSBattle as $ThisUserID) + { + $TriggerTasksCheck[$ThisUserID]['BATTLE_WINORDRAW_ACS_LIMIT'] = true; + } + } + } + } + else + { + if(!empty($TriggerTasksCheck)) + { + foreach($TriggerTasksCheck as $ThisIndex => $ThisArray) + { + unset($TriggerTasksCheck[$ThisIndex]['BATTLE_COLLECT_METAL']); + unset($TriggerTasksCheck[$ThisIndex]['BATTLE_COLLECT_CRYSTAL']); + unset($TriggerTasksCheck[$ThisIndex]['BATTLE_COLLECT_DEUTERIUM']); + } + } + + foreach($AttackersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_inAlly'] += 1; + } + foreach($DefendersIDs as $UserID) + { + $UserStatsData[$UserID]['raids_inAlly'] += 1; + } + if($Result === COMBAT_ATK) + { + $ReportColor = 'green'; + $ReportColor2 = 'red'; + } + else if($Result === COMBAT_DRAW) + { + $ReportColor = 'orange'; + $ReportColor2 = 'orange'; + } + else if($Result === COMBAT_DEF) + { + $ReportColor = 'red'; + $ReportColor2 = 'green'; + } + } + + if($MoonHasBeenCreated AND $TargetUser['ally_id'] > 0) + { + foreach($AttackersIDs as $ThisID) + { + if($AttackersAllys[$ThisID] == $TargetUser['ally_id']) + { + $TriggerTasksCheck[$ThisID]['CREATE_MOON_FRIENDLY'] = true; + } + } + } + + $TargetTypeMsg = $_Lang['BR_Target_'.$FleetRow['fleet_end_type']]; + + if(!$IsAbandoned) + { + $Message = false; + $Message['msg_id'] = '074'; + if(!empty($Rebuilt) AND (array)$Rebuilt === $Rebuilt) + { + foreach($Rebuilt as $SysID => $Count) + { + $RebuildReport[] = ''.$_Lang['tech'][$SysID].' - '.$Count; + } + $RebuildReport = implode('
    ', $RebuildReport); + } + else + { + if(!isset($DefSysLostIDs) || count($DefSysLostIDs) == 1) + { + $RebuildReport = $_Lang['no_loses_in_defence']; + } + else + { + $RebuildReport = $_Lang['nothing_have_been_rebuilt']; + } + } + $Message['args'] = array($ReportID, $ReportColor2, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetTypeMsg, $RebuildReport, $ReportHasHLinkRelative, $ReportHasHLinkReal); + $Message = json_encode($Message); + Cache_Message($TargetUserID, 0, $FleetRow['fleet_start_time'], 3, '003', '012', $Message); + } + + if(count($DefendersIDs) > 1) + { + $Message = false; + $Message['msg_id'] = '075'; + $Message['args'] = array($ReportID, $ReportColor2, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetTypeMsg, $ReportHasHLinkRelative, $ReportHasHLinkReal); + $Message = json_encode($Message); + unset($DefendersIDs[0]); + Cache_Message($DefendersIDs, 0, $FleetRow['fleet_start_time'], 3, '003', '017', $Message); + } + + $Message = false; + $Message['msg_id'] = '071'; + $Message['args'] = array + ( + $ReportID, $ReportColor, $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $TargetTypeMsg, + prettyNumber($RealDebrisMetalAtk + $RealDebrisCrystalAtk + $RealDebrisDeuteriumAtk), + prettyNumber($RealDebrisCrystalDef + $RealDebrisMetalDef + $RealDebrisDeuteriumDef), + prettyNumber($TotalMetStolen), prettyNumber($TotalCryStolen), prettyNumber($TotalDeuStolen), + prettyNumber(isset($TotalLostMetal) ? $TotalLostMetal : 0), prettyNumber(isset($TotalLostCrystal) ? $TotalLostCrystal : 0), + $ReportHasHLinkRelative, $ReportHasHLinkReal + ); + $Message = json_encode($Message); + Cache_Message($AttackersIDs, 0, $FleetRow['fleet_start_time'], 3, '003', '017', $Message); + + $Return['DeleteACS'] = $FleetRow['acs_id']; + + if(!empty($TriggerTasksCheck)) + { + global $GlobalParsedTasks, $_User; + + $Debris_Total_Def = ($DebrisMetalDef + $DebrisCrystalDef) / COMBAT_MOONPERCENT_RESOURCES; + + foreach($TriggerTasksCheck as $ThisTaskUserID => $TriggerTasksData) + { + if($_User['id'] == $ThisTaskUserID) + { + $ThisTaskUser = $_User; + } + else + { + if(empty($GlobalParsedTasks[$ThisTaskUserID]['tasks_done_parsed'])) + { + $GetUserTasksDone = array(); + $GetUserTasksDone['tasks_done'] = $_FleetCache['userTasks'][$ThisTaskUserID]; + Tasks_CheckUservar($GetUserTasksDone); + $GlobalParsedTasks[$ThisTaskUserID] = $GetUserTasksDone; + } + $ThisTaskUser = $GlobalParsedTasks[$ThisTaskUserID]; + $ThisTaskUser['id'] = $ThisTaskUserID; + } + if($FleetRow['fleet_owner'] == $ThisTaskUser['id']) + { + $ThisTaskUser['isACSLeader'] = true; + } + + if(isset($TriggerTasksData['BATTLE_WIN'])) + { + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WIN', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + if(isset($TriggerTasksData['BATTLE_WINORDRAW_LIMIT'])) + { + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WINORDRAW_LIMIT', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $Debris_Total_Def) + { + if($JobArray['minimalEnemyPercentLimit'] > $Debris_Total_Def) + { + return true; + } + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + if(isset($TriggerTasksData['BATTLE_WINORDRAW_ACS_LIMIT'])) + { + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_WINORDRAW_ACS_LIMIT', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $Debris_Total_Def) + { + if(isset($JobArray['hasToBeLeader']) && $JobArray['hasToBeLeader'] === true && $ThisTaskUser['isACSLeader'] !== true) + { + return true; + } + if($JobArray['minimalEnemyPercentLimit'] > $Debris_Total_Def) + { + return true; + } + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + if(isset($TriggerTasksData['BATTLE_COLLECT_METAL']) && $TriggerTasksData['BATTLE_COLLECT_METAL'] > 0) + { + $TaskTemp = $TriggerTasksData['BATTLE_COLLECT_METAL']; + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_METAL', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); + } + )); + } + if(isset($TriggerTasksData['BATTLE_COLLECT_CRYSTAL']) && $TriggerTasksData['BATTLE_COLLECT_CRYSTAL'] > 0) + { + $TaskTemp = $TriggerTasksData['BATTLE_COLLECT_CRYSTAL']; + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_CRYSTAL', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); + } + )); + } + if(isset($TriggerTasksData['BATTLE_COLLECT_DEUTERIUM']) && $TriggerTasksData['BATTLE_COLLECT_DEUTERIUM'] > 0) + { + $TaskTemp = $TriggerTasksData['BATTLE_COLLECT_DEUTERIUM']; + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_COLLECT_DEUTERIUM', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); + } + )); + } + if(isset($TriggerTasksData['CREATE_MOON']) && $TriggerTasksData['CREATE_MOON']) + { + Tasks_TriggerTask($ThisTaskUser, 'CREATE_MOON', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + if(isset($TriggerTasksData['CREATE_MOON_FRIENDLY']) && $TriggerTasksData['CREATE_MOON_FRIENDLY']) + { + Tasks_TriggerTask($ThisTaskUser, 'CREATE_MOON_FRIENDLY', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + if(isset($TriggerTasksData['BATTLE_DESTROY_MILITARYUNITS']) && $TriggerTasksData['BATTLE_DESTROY_MILITARYUNITS'] > 0) + { + $TaskTemp = $TriggerTasksData['BATTLE_DESTROY_MILITARYUNITS']; + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_DESTROY_MILITARYUNITS', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) + { + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, $TaskTemp); + } + )); + } + if(isset($TriggerTasksData['BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS']) && $TriggerTasksData['BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS'] > 0) + { + $TaskTemp2 = 0; + foreach($AttackingFleets as $FleetIndex => $FleetArray) + { + if($AttackingFleetOwners[$AttackingFleetID[$FleetIndex]] != $ThisTaskUser['id']) + { + continue; + } + foreach($FleetArray as $ShipID => $ShipCount) + { + $TaskTemp2 += (($_Vars_Prices[$ShipID]['metal'] + $_Vars_Prices[$ShipID]['crystal'] + $_Vars_Prices[$ShipID]['deuterium']) * $ShipCount); + } + } + $TaskTemp = $TriggerTasksData['BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS']; + Tasks_TriggerTask($ThisTaskUser, 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp, $TaskTemp2) + { + if($JobArray['minimalEnemyCost'] > $TaskTemp) + { + return true; + } + if($TaskTemp2 > ($TaskTemp * $JobArray['maximalOwnValue'])) + { + return true; + } + return Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + } + )); + } + } + } + } + + if($FleetRow['calcType'] == 3 && (!isset($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed']) || $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] !== true)) + { + if(!empty($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']])) + { + foreach($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']] as $Key => $Value) + { + $FleetRow[$Key] = $Value; + } + } + $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack'] = true; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack_Time'] = $Now; + RestoreFleetToPlanet($FleetRow, true, $_FleetCache); + } + + return $Return; +} + +?> diff --git a/includes/functions/MissionCaseMIP.php b/includes/functions/MissionCaseMIP.php index 9dfd30404..743ae1290 100644 --- a/includes/functions/MissionCaseMIP.php +++ b/includes/functions/MissionCaseMIP.php @@ -1,369 +1,369 @@ - 0 ? false : true); - $TargetPlanet = &$_FleetCache['planets'][$FleetRow['fleet_end_id']]; - $TargetUser = &$_FleetCache['users'][$FleetRow['fleet_target_owner']]; - $IsAllyFight = (($FleetRow['ally_id'] == 0 OR ($FleetRow['ally_id'] != $TargetUser['ally_id'])) ? false : true); - - // Update planet before attack begins - $UpdateResult = HandleFullUserUpdate($TargetUser, $TargetPlanet, $_FleetCache['planets'][$TargetUser['techQueue_Planet']], $FleetRow['fleet_start_time'], true, true); - if(!empty($UpdateResult)) - { - foreach($UpdateResult as $PlanetID => $Value) - { - if($Value === true) - { - $_FleetCache['updatePlanets'][$PlanetID] = true; - } - } - } - - if(!$IsAbandoned) - { - $IdleHours = floor(($FleetRow['fleet_start_time'] - $TargetUser['onlinetime']) / TIME_HOUR); - if($IdleHours > 0) - { - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Owner_IdleHours'] = $IdleHours; - } - } - - if(empty($UserStatsData[$FleetRow['fleet_owner']])) - { - $UserStatsData[$FleetRow['fleet_owner']] = $UserStatsPattern; - } - if(!$IsAllyFight) - { - $UserStatsData[$FleetRow['fleet_owner']]['raids_missileAttack'] += 1; - } - else - { - $UserStatsData[$FleetRow['fleet_owner']]['raids_inAlly'] += 1; - } - - //Get sending planet name - $SendingPlanetName = $FleetRow['attacking_planet_name']; - //Get the attacker military technology level - $AttackerMiliTech = $FleetRow['tech_weapons']; - - $DefSystemsPlanet = false; - - foreach($_Vars_ElementCategories['defense'] as $ElementID) - { - if(in_array($ElementID, $_Vars_ElementCategories['rockets'])) - { - continue; - } - if($TargetPlanet[$_Vars_GameElements[$ElementID]] > 0) - { - $DefSystemsPlanet[$ElementID] = $TargetPlanet[$_Vars_GameElements[$ElementID]]; - } - } - - $TheFleet = explode(';', $FleetRow['fleet_array']); - $PrimaryTarget = false; - foreach($TheFleet as $key => $val) - { - if($val != '') - { - $key = explode(',', $val); - if($key[0] == $IPMissileID) - { - $IPMissiles += $key[1]; - } - else if($key[0] == 'primary_target') - { - $PrimaryTarget = intval($key[1]); - if($PrimaryTarget == 0) - { - $PrimaryTarget = '0'; - } - } - } - } - - if($PrimaryTarget < 0 OR $PrimaryTarget > 99 OR $PrimaryTarget === false) - { - $PrimaryTarget = 0; - } - - $InitialIPMissiles = $IPMissiles; - $ICMissiles = $TargetPlanet['antiballistic_missile']; - - switch($FleetRow['fleet_start_type']) - { - case 1: - $SendingType = $_Lang['sys_MIP_sending_planet']; - break; - case 2: - $SendingType = $_Lang['sys_MIP_sending_moon']; - break; - } - - switch($FleetRow['fleet_end_type']) - { - case 1: - $AttackedType = $_Lang['sys_MIP_attacked_planet']; - break; - case 2: - $AttackedType = $_Lang['sys_MIP_attacked_moon']; - break; - } - - $SendingPlanetLink = CreatePlanetLink($FleetRow['fleet_start_galaxy'], $FleetRow['fleet_start_system'], $FleetRow['fleet_start_planet']); - $AttackedPlanetLink = CreatePlanetLink($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet']); - - $AttackerReport[] = array('{MIP_A_rp_h}', prettyNumber($InitialIPMissiles), $SendingType, $SendingPlanetName, $SendingPlanetLink, $AttackedType, $TargetPlanet['name'], $AttackedPlanetLink); - $DefenderReport[] = array('{MIP_D_rp_h}', prettyNumber($InitialIPMissiles), $SendingType, $SendingPlanetName, $SendingPlanetLink, $AttackedType, $TargetPlanet['name'], $AttackedPlanetLink); - - if($IPMissiles <= $ICMissiles) - { - $AttackerReport[] = array('{MIP_A_M_Cap}', prettyNumber($IPMissiles)); - $DefenderReport[] = array('{MIP_D_M_Cap}', prettyNumber($IPMissiles)); - - $TargetPlanet['antiballistic_missile'] -= $IPMissiles; - $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; - $HPQ_PlanetUpdatedFields[] = 'antiballistic_missile'; - $UserDev_UpPl[] = '502,'.$IPMissiles; - - $Defender_HasLoses = true; - } - else - { - if($ICMissiles > 0) - { - $IPMissiles -= $ICMissiles; - - $AttackerReport[] = array('{MIP_Cap_M}', prettyNumber($ICMissiles)); - $DefenderReport[] = array('{MIP_Cap_M}', prettyNumber($ICMissiles)); - - $TargetPlanet['antiballistic_missile'] = 0; - $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; - $HPQ_PlanetUpdatedFields[] = 'antiballistic_missile'; - $UserDev_UpPl[] = '502,'.$IPMissiles; - - $Defender_HasLoses = true; - } - - if($DefSystemsPlanet !== false) - { - if($FunctionIncluded === false) - { - include($_EnginePath.'includes/functions/CalcInterplanetaryAttack.php'); - $FunctionIncluded = true; - } - $Attack = CalcInterplanetaryAttack($TargetUser['tech_shielding'], $AttackerMiliTech, $IPMissiles, $DefSystemsPlanet, $PrimaryTarget); - - if($Attack['DestroyedTotal'] > 0) - { - foreach($Attack['LeftDefs'] as $ElementID => $Value) - { - if($Value == 0) - { - $Value = '0'; - } - $TargetPlanet[$_Vars_GameElements[$ElementID]] = $Value; - $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; - $HPQ_PlanetUpdatedFields[] = $_Vars_GameElements[$ElementID]; - } - - $DestroyedSomething = false; - foreach($Attack['Destroyed'] as $key => $val) - { - if($val > 0) - { - if($DestroyedSomething !== true) - { - $DestroyedSomething = true; - $AttackerReport[] = '{MIP_destroy}'; - $DefenderReport[] = '{MIP_destroy}'; - - if(empty($UserStatsData[$TargetPlanet['id_owner']])) - { - $UserStatsData[$TargetPlanet['id_owner']] = $UserStatsPattern; - } - } - $CreateThisLine = '• '.$_Lang['tech'][$key].' ( -'.prettyNumber($val).') ['.prettyNumber($Attack['LeftDefs'][$key]).'/'.prettyNumber($Attack['LeftDefs'][$key] + $val).']'; - $AttackerReport[] = $CreateThisLine; - $DefenderReport[] = $CreateThisLine; - $UserDev_UpPl[] = "{$key},{$val}"; - - if(!$IsAllyFight) - { - $UserStatsData[$FleetRow['fleet_owner']]['destroyed_'.$key] += $val; - $UserStatsData[$TargetPlanet['id_owner']]['lost_'.$key] += $val; - } - } - } - - if($DestroyedSomething) - { - $Defender_HasLoses = true; - } - - // Create debris field on the orbit - if($Attack['Debris']['metal'] > 0 OR $Attack['Debris']['crystal'] > 0) - { - if($Attack['Debris']['metal'] == 0) - { - $Attack['Debris']['metal'] = '0'; - } - if($Attack['Debris']['crystal'] == 0) - { - $Attack['Debris']['crystal'] = '0'; - } - - $AttackerReport[] = '{MIP_Debris}'; - $AttackerReport[] = prettyNumber($Attack['Debris']['metal']).' {MIP_Units} {MIP_DebMet}'; - $AttackerReport[] = prettyNumber($Attack['Debris']['crystal']).' {MIP_Units} {MIP_DebCry}'; - - if(isset($_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']]) && $_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']] > 0) - { - if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']]]['metal'])) - { - $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']]]['metal'] = 0; - } - if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']]]['crystal'])) - { - $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']]]['crystal'] = 0; - } - $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']]]['metal'] += $Attack['Debris']['metal']; - $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']]]['crystal'] += $Attack['Debris']['crystal']; - $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']]]['updated'] = true; - $_FleetCache['updated']['galaxy'] = true; - } - else - { - $Query_UpdateGalaxy = ''; - $Query_UpdateGalaxy .= "UPDATE {{table}} SET `metal` = `metal` + {$Attack['Debris']['metal']}, `crystal` = `crystal` + {$Attack['Debris']['crystal']} "; - $Query_UpdateGalaxy .= "WHERE `id_planet` = {$FleetRow['fleet_end_id']} LIMIT 1; "; - $Query_UpdateGalaxy .= "-- MISSION MIP [Q01][FID: {$FleetRow['fleet_id']}]"; - doquery($Query_UpdateGalaxy, 'galaxy'); - } - } - } - else - { - $AttackerReport[] = '{MIP_nodef}'; - $DefenderReport[] = '{MIP_nodef}'; - } - } - else - { - $AttackerReport[] = '{MIP_nodef}'; - $DefenderReport[] = '{MIP_nodef}'; - } - } - - // Morale System - if(MORALE_ENABLED AND !$IsAbandoned AND !$IsAllyFight AND $IdleHours < (7 * 24) AND $Defender_HasLoses) - { - if(!empty($_FleetCache['MoraleCache'][$FleetRow['fleet_owner']])) - { - $FleetRow['morale_level'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['level']; - $FleetRow['morale_droptime'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['droptime']; - $FleetRow['morale_lastupdate'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['lastupdate']; - } - Morale_ReCalculate($FleetRow, $FleetRow['fleet_start_time']); - - $Morale_Factor = $FleetRow['morale_points'] / $TargetUser['morale_points']; - if($Morale_Factor > MORALE_MINIMALFACTOR) - { - $Morale_Updated = Morale_AddMorale($FleetRow, MORALE_NEGATIVE, $Morale_Factor, MORALE_ROCKETATTACK_MODIFIER, MORALE_ROCKETATTACK_MODIFIER, $FleetRow['fleet_start_time']); - if($Morale_Updated) - { - $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['level'] = $FleetRow['morale_level']; - $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['droptime'] = $FleetRow['morale_droptime']; - $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['lastupdate'] = $FleetRow['morale_lastupdate']; - - $CreateAtkMsg_MoraleInfo = sprintf($_Lang['RocketReport_Morale_Attacker_Negative'], sprintf('%0.2f', $Morale_Factor), $FleetRow['morale_level']); - } - } - } - - $first = true; - foreach($AttackerReport as $val) - { - if($first === true) - { - $first = false; - } - else - { - $CreateAtkMsg[] = '
    '; - } - $CreateAtkMsg[] = $val; - } - - if(!empty($CreateAtkMsg_MoraleInfo)) - { - $CreateAtkMsg[] = '

    '; - $CreateAtkMsg[] = $CreateAtkMsg_MoraleInfo; - } - - $first = true; - foreach($DefenderReport as $val) - { - if($first === true) - { - $first = false; - } - else - { - $CreateDefMsg[] = '
    '; - } - $CreateDefMsg[] = $val; - } - - $Message = false; - $Message['msg_text'] = $CreateAtkMsg; - $Message = json_encode($Message); - Cache_Message($FleetRow['fleet_owner'], 0, $FleetRow['fleet_start_time'], 5, '003', '006', $Message); - - if(!$IsAbandoned) - { - $Message = false; - $Message['msg_text'] = $CreateDefMsg; - $Message = json_encode($Message); - Cache_Message($FleetRow['fleet_target_owner'], 0, $FleetRow['fleet_start_time'], 5, '003', '006', $Message); - } - - if(!empty($UserDev_UpPl) AND !$IsAbandoned) - { - $UserDev_Log[] = array('UserID' => $TargetPlanet['id_owner'], 'PlanetID' => $TargetPlanet['id'], 'Date' => $FleetRow['fleet_start_time'], 'Place' => 16, 'Code' => '1', 'ElementID' => $FleetRow['fleet_id'], 'AdditionalData' => implode(';', $UserDev_UpPl)); - } - - $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_Mission'] = true; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_Mission_Time'] = $Now; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed'] = true; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed_Reason'] = 9; - } - - return $Return; -} - -?> \ No newline at end of file + 0 ? false : true); + $TargetPlanet = &$_FleetCache['planets'][$FleetRow['fleet_end_id']]; + $TargetUser = &$_FleetCache['users'][$FleetRow['fleet_target_owner']]; + $IsAllyFight = (($FleetRow['ally_id'] == 0 OR ($FleetRow['ally_id'] != $TargetUser['ally_id'])) ? false : true); + + // Update planet before attack begins + $UpdateResult = HandleFullUserUpdate($TargetUser, $TargetPlanet, $_FleetCache['planets'][$TargetUser['techQueue_Planet']], $FleetRow['fleet_start_time'], true, true); + if(!empty($UpdateResult)) + { + foreach($UpdateResult as $PlanetID => $Value) + { + if($Value === true) + { + $_FleetCache['updatePlanets'][$PlanetID] = true; + } + } + } + + if(!$IsAbandoned) + { + $IdleHours = floor(($FleetRow['fleet_start_time'] - $TargetUser['onlinetime']) / TIME_HOUR); + if($IdleHours > 0) + { + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Owner_IdleHours'] = $IdleHours; + } + } + + if(empty($UserStatsData[$FleetRow['fleet_owner']])) + { + $UserStatsData[$FleetRow['fleet_owner']] = $UserStatsPattern; + } + if(!$IsAllyFight) + { + $UserStatsData[$FleetRow['fleet_owner']]['raids_missileAttack'] += 1; + } + else + { + $UserStatsData[$FleetRow['fleet_owner']]['raids_inAlly'] += 1; + } + + //Get sending planet name + $SendingPlanetName = $FleetRow['attacking_planet_name']; + //Get the attacker military technology level + $AttackerMiliTech = $FleetRow['tech_weapons']; + + $DefSystemsPlanet = false; + + foreach($_Vars_ElementCategories['defense'] as $ElementID) + { + if(in_array($ElementID, $_Vars_ElementCategories['rockets'])) + { + continue; + } + if($TargetPlanet[$_Vars_GameElements[$ElementID]] > 0) + { + $DefSystemsPlanet[$ElementID] = $TargetPlanet[$_Vars_GameElements[$ElementID]]; + } + } + + $TheFleet = explode(';', $FleetRow['fleet_array']); + $PrimaryTarget = false; + foreach($TheFleet as $key => $val) + { + if($val != '') + { + $key = explode(',', $val); + if($key[0] == $IPMissileID) + { + $IPMissiles += $key[1]; + } + else if($key[0] == 'primary_target') + { + $PrimaryTarget = intval($key[1]); + if($PrimaryTarget == 0) + { + $PrimaryTarget = '0'; + } + } + } + } + + if($PrimaryTarget < 0 OR $PrimaryTarget > 99 OR $PrimaryTarget === false) + { + $PrimaryTarget = 0; + } + + $InitialIPMissiles = $IPMissiles; + $ICMissiles = $TargetPlanet['antiballistic_missile']; + + switch($FleetRow['fleet_start_type']) + { + case 1: + $SendingType = $_Lang['sys_MIP_sending_planet']; + break; + case 2: + $SendingType = $_Lang['sys_MIP_sending_moon']; + break; + } + + switch($FleetRow['fleet_end_type']) + { + case 1: + $AttackedType = $_Lang['sys_MIP_attacked_planet']; + break; + case 2: + $AttackedType = $_Lang['sys_MIP_attacked_moon']; + break; + } + + $SendingPlanetLink = CreatePlanetLink($FleetRow['fleet_start_galaxy'], $FleetRow['fleet_start_system'], $FleetRow['fleet_start_planet']); + $AttackedPlanetLink = CreatePlanetLink($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet']); + + $AttackerReport[] = array('{MIP_A_rp_h}', prettyNumber($InitialIPMissiles), $SendingType, $SendingPlanetName, $SendingPlanetLink, $AttackedType, $TargetPlanet['name'], $AttackedPlanetLink); + $DefenderReport[] = array('{MIP_D_rp_h}', prettyNumber($InitialIPMissiles), $SendingType, $SendingPlanetName, $SendingPlanetLink, $AttackedType, $TargetPlanet['name'], $AttackedPlanetLink); + + if($IPMissiles <= $ICMissiles) + { + $AttackerReport[] = array('{MIP_A_M_Cap}', prettyNumber($IPMissiles)); + $DefenderReport[] = array('{MIP_D_M_Cap}', prettyNumber($IPMissiles)); + + $TargetPlanet['antiballistic_missile'] -= $IPMissiles; + $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; + $HPQ_PlanetUpdatedFields[] = 'antiballistic_missile'; + $UserDev_UpPl[] = '502,'.$IPMissiles; + + $Defender_HasLoses = true; + } + else + { + if($ICMissiles > 0) + { + $IPMissiles -= $ICMissiles; + + $AttackerReport[] = array('{MIP_Cap_M}', prettyNumber($ICMissiles)); + $DefenderReport[] = array('{MIP_Cap_M}', prettyNumber($ICMissiles)); + + $TargetPlanet['antiballistic_missile'] = 0; + $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; + $HPQ_PlanetUpdatedFields[] = 'antiballistic_missile'; + $UserDev_UpPl[] = '502,'.$IPMissiles; + + $Defender_HasLoses = true; + } + + if($DefSystemsPlanet !== false) + { + if($FunctionIncluded === false) + { + include($_EnginePath.'includes/functions/CalcInterplanetaryAttack.php'); + $FunctionIncluded = true; + } + $Attack = CalcInterplanetaryAttack($TargetUser['tech_shielding'], $AttackerMiliTech, $IPMissiles, $DefSystemsPlanet, $PrimaryTarget); + + if($Attack['DestroyedTotal'] > 0) + { + foreach($Attack['LeftDefs'] as $ElementID => $Value) + { + if($Value == 0) + { + $Value = '0'; + } + $TargetPlanet[$_Vars_GameElements[$ElementID]] = $Value; + $_FleetCache['updatePlanets'][$TargetPlanet['id']] = true; + $HPQ_PlanetUpdatedFields[] = $_Vars_GameElements[$ElementID]; + } + + $DestroyedSomething = false; + foreach($Attack['Destroyed'] as $key => $val) + { + if($val > 0) + { + if($DestroyedSomething !== true) + { + $DestroyedSomething = true; + $AttackerReport[] = '{MIP_destroy}'; + $DefenderReport[] = '{MIP_destroy}'; + + if(empty($UserStatsData[$TargetPlanet['id_owner']])) + { + $UserStatsData[$TargetPlanet['id_owner']] = $UserStatsPattern; + } + } + $CreateThisLine = '• '.$_Lang['tech'][$key].' ( -'.prettyNumber($val).') ['.prettyNumber($Attack['LeftDefs'][$key]).'/'.prettyNumber($Attack['LeftDefs'][$key] + $val).']'; + $AttackerReport[] = $CreateThisLine; + $DefenderReport[] = $CreateThisLine; + $UserDev_UpPl[] = "{$key},{$val}"; + + if(!$IsAllyFight) + { + $UserStatsData[$FleetRow['fleet_owner']]['destroyed_'.$key] += $val; + $UserStatsData[$TargetPlanet['id_owner']]['lost_'.$key] += $val; + } + } + } + + if($DestroyedSomething) + { + $Defender_HasLoses = true; + } + + // Create debris field on the orbit + if($Attack['Debris']['metal'] > 0 OR $Attack['Debris']['crystal'] > 0) + { + if($Attack['Debris']['metal'] == 0) + { + $Attack['Debris']['metal'] = '0'; + } + if($Attack['Debris']['crystal'] == 0) + { + $Attack['Debris']['crystal'] = '0'; + } + + $AttackerReport[] = '{MIP_Debris}'; + $AttackerReport[] = prettyNumber($Attack['Debris']['metal']).' {MIP_Units} {MIP_DebMet}'; + $AttackerReport[] = prettyNumber($Attack['Debris']['crystal']).' {MIP_Units} {MIP_DebCry}'; + + if(isset($_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']]) && $_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']] > 0) + { + if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']]]['metal'])) + { + $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']]]['metal'] = 0; + } + if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']]]['crystal'])) + { + $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']]]['crystal'] = 0; + } + $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']]]['metal'] += $Attack['Debris']['metal']; + $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']]]['crystal'] += $Attack['Debris']['crystal']; + $_FleetCache['galaxy'][$_FleetCache['galaxyMap']['byPlanet'][$FleetRow['fleet_end_id']]]['updated'] = true; + $_FleetCache['updated']['galaxy'] = true; + } + else + { + $Query_UpdateGalaxy = ''; + $Query_UpdateGalaxy .= "UPDATE {{table}} SET `metal` = `metal` + {$Attack['Debris']['metal']}, `crystal` = `crystal` + {$Attack['Debris']['crystal']} "; + $Query_UpdateGalaxy .= "WHERE `id_planet` = {$FleetRow['fleet_end_id']} LIMIT 1; "; + $Query_UpdateGalaxy .= "-- MISSION MIP [Q01][FID: {$FleetRow['fleet_id']}]"; + doquery($Query_UpdateGalaxy, 'galaxy'); + } + } + } + else + { + $AttackerReport[] = '{MIP_nodef}'; + $DefenderReport[] = '{MIP_nodef}'; + } + } + else + { + $AttackerReport[] = '{MIP_nodef}'; + $DefenderReport[] = '{MIP_nodef}'; + } + } + + // Morale System + if(MORALE_ENABLED AND !$IsAbandoned AND !$IsAllyFight AND $IdleHours < (7 * 24) AND $Defender_HasLoses) + { + if(!empty($_FleetCache['MoraleCache'][$FleetRow['fleet_owner']])) + { + $FleetRow['morale_level'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['level']; + $FleetRow['morale_droptime'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['droptime']; + $FleetRow['morale_lastupdate'] = $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['lastupdate']; + } + Morale_ReCalculate($FleetRow, $FleetRow['fleet_start_time']); + + $Morale_Factor = $FleetRow['morale_points'] / $TargetUser['morale_points']; + if($Morale_Factor > MORALE_MINIMALFACTOR) + { + $Morale_Updated = Morale_AddMorale($FleetRow, MORALE_NEGATIVE, $Morale_Factor, MORALE_ROCKETATTACK_MODIFIER, MORALE_ROCKETATTACK_MODIFIER, $FleetRow['fleet_start_time']); + if($Morale_Updated) + { + $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['level'] = $FleetRow['morale_level']; + $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['droptime'] = $FleetRow['morale_droptime']; + $_FleetCache['MoraleCache'][$FleetRow['fleet_owner']]['lastupdate'] = $FleetRow['morale_lastupdate']; + + $CreateAtkMsg_MoraleInfo = sprintf($_Lang['RocketReport_Morale_Attacker_Negative'], sprintf('%0.2f', $Morale_Factor), $FleetRow['morale_level']); + } + } + } + + $first = true; + foreach($AttackerReport as $val) + { + if($first === true) + { + $first = false; + } + else + { + $CreateAtkMsg[] = '
    '; + } + $CreateAtkMsg[] = $val; + } + + if(!empty($CreateAtkMsg_MoraleInfo)) + { + $CreateAtkMsg[] = '

    '; + $CreateAtkMsg[] = $CreateAtkMsg_MoraleInfo; + } + + $first = true; + foreach($DefenderReport as $val) + { + if($first === true) + { + $first = false; + } + else + { + $CreateDefMsg[] = '
    '; + } + $CreateDefMsg[] = $val; + } + + $Message = false; + $Message['msg_text'] = $CreateAtkMsg; + $Message = json_encode($Message); + Cache_Message($FleetRow['fleet_owner'], 0, $FleetRow['fleet_start_time'], 5, '003', '006', $Message); + + if(!$IsAbandoned) + { + $Message = false; + $Message['msg_text'] = $CreateDefMsg; + $Message = json_encode($Message); + Cache_Message($FleetRow['fleet_target_owner'], 0, $FleetRow['fleet_start_time'], 5, '003', '006', $Message); + } + + if(!empty($UserDev_UpPl) AND !$IsAbandoned) + { + $UserDev_Log[] = array('UserID' => $TargetPlanet['id_owner'], 'PlanetID' => $TargetPlanet['id'], 'Date' => $FleetRow['fleet_start_time'], 'Place' => 16, 'Code' => '1', 'ElementID' => $FleetRow['fleet_id'], 'AdditionalData' => implode(';', $UserDev_UpPl)); + } + + $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_Mission'] = true; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_Mission_Time'] = $Now; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed'] = true; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed_Reason'] = 9; + } + + return $Return; +} + +?> diff --git a/includes/functions/MissionCaseRecycling.php b/includes/functions/MissionCaseRecycling.php index dd3079f04..b4f30f8b4 100644 --- a/includes/functions/MissionCaseRecycling.php +++ b/includes/functions/MissionCaseRecycling.php @@ -1,218 +1,218 @@ - 0 OR $TargetGalaxy['crystal'] > 0) - { - $RecyclerCapacity = 0; - $OtherFleetCapacity = 0; - $FleetRecord = String2Array($FleetRow['fleet_array']); - foreach($FleetRecord as $ShipID => $ShipCount) - { - if($ShipID == 209) - { - $RecyclerCapacity += $_Vars_Prices[$ShipID]['capacity'] * $ShipCount; - } - else - { - $OtherFleetCapacity += $_Vars_Prices[$ShipID]['capacity'] * $ShipCount; - } - } - - $IncomingFleetGoods = $FleetRow['fleet_resource_metal'] + $FleetRow['fleet_resource_crystal'] + $FleetRow['fleet_resource_deuterium']; - if($IncomingFleetGoods > $OtherFleetCapacity) - { - $RecyclerCapacity -= ($IncomingFleetGoods - $OtherFleetCapacity); - } - - // Storage Management here - $MaxStorage_Metal = $MaxStorage_Crystal = $RecyclerCapacity / 2; - if($TargetGalaxy['metal'] < $MaxStorage_Metal) - { - $MaxStorage_Crystal += ($MaxStorage_Metal - $TargetGalaxy['metal']); - } - if($TargetGalaxy['crystal'] < $MaxStorage_Crystal) - { - $MaxStorage_Metal += ($MaxStorage_Crystal - $TargetGalaxy['crystal']); - } - if($TargetGalaxy['metal'] > $MaxStorage_Metal) - { - $RecycledGoods['metal'] = $MaxStorage_Metal; - } - else - { - $RecycledGoods['metal'] = $TargetGalaxy['metal']; - } - if($TargetGalaxy['crystal'] > $MaxStorage_Crystal) - { - $RecycledGoods['crystal'] = $MaxStorage_Crystal; - } - else - { - $RecycledGoods['crystal'] = $TargetGalaxy['crystal']; - } - - if(!isset($_FleetCache['galaxy'][$FleetRow['fleet_end_id_galaxy']]['metal'])) - { - $_FleetCache['galaxy'][$FleetRow['fleet_end_id_galaxy']]['metal'] = 0; - } - if(!isset($_FleetCache['galaxy'][$FleetRow['fleet_end_id_galaxy']]['crystal'])) - { - $_FleetCache['galaxy'][$FleetRow['fleet_end_id_galaxy']]['crystal'] = 0; - } - $_FleetCache['galaxy'][$FleetRow['fleet_end_id_galaxy']]['metal'] -= $RecycledGoods['metal']; - $_FleetCache['galaxy'][$FleetRow['fleet_end_id_galaxy']]['crystal'] -= $RecycledGoods['crystal']; - $_FleetCache['galaxy'][$FleetRow['fleet_end_id_galaxy']]['updated'] = true; - $_FleetCache['updated']['galaxy'] = true; - - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Metal'] = $RecycledGoods['metal']; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Crystal'] = $RecycledGoods['crystal']; - - // Trigger Tasks Check - if($_User['id'] == $FleetRow['fleet_owner']) - { - $ThisTaskUser = $_User; - } - else - { - if(empty($GlobalParsedTasks[$FleetRow['fleet_owner']]['tasks_done_parsed'])) - { - $GetUserTasksDone['tasks_done'] = $_FleetCache['userTasks'][$FleetRow['fleet_owner']]; - Tasks_CheckUservar($GetUserTasksDone); - $GlobalParsedTasks[$FleetRow['fleet_owner']] = $GetUserTasksDone; - } - $ThisTaskUser = $GlobalParsedTasks[$FleetRow['fleet_owner']]; - $ThisTaskUser['id'] = $FleetRow['fleet_owner']; - } - - Tasks_TriggerTask($ThisTaskUser, 'RECYCLE_DEBRIS'); - if($RecycledGoods['metal'] > 0) - { - $TaskTemp = $RecycledGoods['metal']; - Tasks_TriggerTask($ThisTaskUser, 'DEBRIS_COLLECT_METAL', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) - { - global $UserTasksUpdate; - if(!empty($UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID])) - { - $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID]; - } - if(!isset($ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID])) - { - $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = 0; - } - $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] += $TaskTemp; - if($ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] < $JobArray['count']) - { - $UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; - return true; - } - } - )); - } - if($RecycledGoods['crystal'] > 0) - { - $TaskTemp = $RecycledGoods['crystal']; - Tasks_TriggerTask($ThisTaskUser, 'DEBRIS_COLLECT_CRYSTAL', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) - { - global $UserTasksUpdate; - if(!empty($UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID])) - { - $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID]; - } - if(!isset($ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID])) - { - $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = 0; - } - $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] += $TaskTemp; - if($ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] < $JobArray['count']) - { - $UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; - return true; - } - } - )); - } - - $UserDev_Log[] = array('UserID' => $FleetRow['fleet_owner'], 'PlanetID' => '0', 'Date' => $FleetRow['fleet_start_time'], 'Place' => 17, 'Code' => '0', 'ElementID' => '0', 'AdditionalData' => "M,{$RecycledGoods['metal']};C,{$RecycledGoods['crystal']}"); - } - - if($RecycledGoods['metal'] == 0) - { - $RecycledGoods['metal'] = '0'; - } - if($RecycledGoods['crystal'] == 0) - { - $RecycledGoods['crystal'] = '0'; - } - - $Message['msg_id'] = '011'; - $Message['args'] = array($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], prettyNumber($RecycledGoods['metal']), prettyNumber($RecycledGoods['crystal'])); - $Message = json_encode($Message); - Cache_Message($FleetRow['fleet_owner'], 0, $FleetRow['fleet_start_time'], 4, '002', '005', $Message); - - if($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['calcCount'] == 1) - { - // Create UpdateFleet record for $_FleetCache - $CachePointer = &$_FleetCache['updateFleets'][$FleetRow['fleet_id']]; - $CachePointer['fleet_mess'] = 1; - if(!isset($CachePointer['fleet_resource_metal'])) - { - $CachePointer['fleet_resource_metal'] = 0; - } - if(!isset($CachePointer['fleet_resource_crystal'])) - { - $CachePointer['fleet_resource_crystal'] = 0; - } - $CachePointer['fleet_resource_metal'] += $RecycledGoods['metal']; - $CachePointer['fleet_resource_crystal'] += $RecycledGoods['crystal']; - } - else - { - if($RecycledGoods['metal'] > 0 || $RecycledGoods['crystal'] > 0) - { - $_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']] = array - ( - 'fleet_resource_metal' => $FleetRow['fleet_resource_metal'] + $RecycledGoods['metal'], - 'fleet_resource_crystal' => $FleetRow['fleet_resource_crystal'] + $RecycledGoods['crystal'], - ); - } - } - } - - if($FleetRow['calcType'] == 3) - { - if(!empty($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']])) - { - foreach($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']] as $Key => $Value) - { - $FleetRow[$Key] = $Value; - } - } - - // Return fleet back to the planet - $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack'] = true; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack_Time'] = $Now; - - RestoreFleetToPlanet($FleetRow, true, $_FleetCache); - } - - return $Return; -} - -?> \ No newline at end of file + 0 OR $TargetGalaxy['crystal'] > 0) + { + $RecyclerCapacity = 0; + $OtherFleetCapacity = 0; + $FleetRecord = String2Array($FleetRow['fleet_array']); + foreach($FleetRecord as $ShipID => $ShipCount) + { + if($ShipID == 209) + { + $RecyclerCapacity += $_Vars_Prices[$ShipID]['capacity'] * $ShipCount; + } + else + { + $OtherFleetCapacity += $_Vars_Prices[$ShipID]['capacity'] * $ShipCount; + } + } + + $IncomingFleetGoods = $FleetRow['fleet_resource_metal'] + $FleetRow['fleet_resource_crystal'] + $FleetRow['fleet_resource_deuterium']; + if($IncomingFleetGoods > $OtherFleetCapacity) + { + $RecyclerCapacity -= ($IncomingFleetGoods - $OtherFleetCapacity); + } + + // Storage Management here + $MaxStorage_Metal = $MaxStorage_Crystal = $RecyclerCapacity / 2; + if($TargetGalaxy['metal'] < $MaxStorage_Metal) + { + $MaxStorage_Crystal += ($MaxStorage_Metal - $TargetGalaxy['metal']); + } + if($TargetGalaxy['crystal'] < $MaxStorage_Crystal) + { + $MaxStorage_Metal += ($MaxStorage_Crystal - $TargetGalaxy['crystal']); + } + if($TargetGalaxy['metal'] > $MaxStorage_Metal) + { + $RecycledGoods['metal'] = $MaxStorage_Metal; + } + else + { + $RecycledGoods['metal'] = $TargetGalaxy['metal']; + } + if($TargetGalaxy['crystal'] > $MaxStorage_Crystal) + { + $RecycledGoods['crystal'] = $MaxStorage_Crystal; + } + else + { + $RecycledGoods['crystal'] = $TargetGalaxy['crystal']; + } + + if(!isset($_FleetCache['galaxy'][$FleetRow['fleet_end_id_galaxy']]['metal'])) + { + $_FleetCache['galaxy'][$FleetRow['fleet_end_id_galaxy']]['metal'] = 0; + } + if(!isset($_FleetCache['galaxy'][$FleetRow['fleet_end_id_galaxy']]['crystal'])) + { + $_FleetCache['galaxy'][$FleetRow['fleet_end_id_galaxy']]['crystal'] = 0; + } + $_FleetCache['galaxy'][$FleetRow['fleet_end_id_galaxy']]['metal'] -= $RecycledGoods['metal']; + $_FleetCache['galaxy'][$FleetRow['fleet_end_id_galaxy']]['crystal'] -= $RecycledGoods['crystal']; + $_FleetCache['galaxy'][$FleetRow['fleet_end_id_galaxy']]['updated'] = true; + $_FleetCache['updated']['galaxy'] = true; + + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Metal'] = $RecycledGoods['metal']; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_End_Res_Crystal'] = $RecycledGoods['crystal']; + + // Trigger Tasks Check + if($_User['id'] == $FleetRow['fleet_owner']) + { + $ThisTaskUser = $_User; + } + else + { + if(empty($GlobalParsedTasks[$FleetRow['fleet_owner']]['tasks_done_parsed'])) + { + $GetUserTasksDone['tasks_done'] = $_FleetCache['userTasks'][$FleetRow['fleet_owner']]; + Tasks_CheckUservar($GetUserTasksDone); + $GlobalParsedTasks[$FleetRow['fleet_owner']] = $GetUserTasksDone; + } + $ThisTaskUser = $GlobalParsedTasks[$FleetRow['fleet_owner']]; + $ThisTaskUser['id'] = $FleetRow['fleet_owner']; + } + + Tasks_TriggerTask($ThisTaskUser, 'RECYCLE_DEBRIS'); + if($RecycledGoods['metal'] > 0) + { + $TaskTemp = $RecycledGoods['metal']; + Tasks_TriggerTask($ThisTaskUser, 'DEBRIS_COLLECT_METAL', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) + { + global $UserTasksUpdate; + if(!empty($UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID])) + { + $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID]; + } + if(!isset($ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID])) + { + $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = 0; + } + $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] += $TaskTemp; + if($ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] < $JobArray['count']) + { + $UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; + return true; + } + } + )); + } + if($RecycledGoods['crystal'] > 0) + { + $TaskTemp = $RecycledGoods['crystal']; + Tasks_TriggerTask($ThisTaskUser, 'DEBRIS_COLLECT_CRYSTAL', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($ThisTaskUser, $TaskTemp) + { + global $UserTasksUpdate; + if(!empty($UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID])) + { + $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID]; + } + if(!isset($ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID])) + { + $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = 0; + } + $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] += $TaskTemp; + if($ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] < $JobArray['count']) + { + $UserTasksUpdate[$ThisTaskUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; + return true; + } + } + )); + } + + $UserDev_Log[] = array('UserID' => $FleetRow['fleet_owner'], 'PlanetID' => '0', 'Date' => $FleetRow['fleet_start_time'], 'Place' => 17, 'Code' => '0', 'ElementID' => '0', 'AdditionalData' => "M,{$RecycledGoods['metal']};C,{$RecycledGoods['crystal']}"); + } + + if($RecycledGoods['metal'] == 0) + { + $RecycledGoods['metal'] = '0'; + } + if($RecycledGoods['crystal'] == 0) + { + $RecycledGoods['crystal'] = '0'; + } + + $Message['msg_id'] = '011'; + $Message['args'] = array($FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], prettyNumber($RecycledGoods['metal']), prettyNumber($RecycledGoods['crystal'])); + $Message = json_encode($Message); + Cache_Message($FleetRow['fleet_owner'], 0, $FleetRow['fleet_start_time'], 4, '002', '005', $Message); + + if($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['calcCount'] == 1) + { + // Create UpdateFleet record for $_FleetCache + $CachePointer = &$_FleetCache['updateFleets'][$FleetRow['fleet_id']]; + $CachePointer['fleet_mess'] = 1; + if(!isset($CachePointer['fleet_resource_metal'])) + { + $CachePointer['fleet_resource_metal'] = 0; + } + if(!isset($CachePointer['fleet_resource_crystal'])) + { + $CachePointer['fleet_resource_crystal'] = 0; + } + $CachePointer['fleet_resource_metal'] += $RecycledGoods['metal']; + $CachePointer['fleet_resource_crystal'] += $RecycledGoods['crystal']; + } + else + { + if($RecycledGoods['metal'] > 0 || $RecycledGoods['crystal'] > 0) + { + $_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']] = array + ( + 'fleet_resource_metal' => $FleetRow['fleet_resource_metal'] + $RecycledGoods['metal'], + 'fleet_resource_crystal' => $FleetRow['fleet_resource_crystal'] + $RecycledGoods['crystal'], + ); + } + } + } + + if($FleetRow['calcType'] == 3) + { + if(!empty($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']])) + { + foreach($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']] as $Key => $Value) + { + $FleetRow[$Key] = $Value; + } + } + + // Return fleet back to the planet + $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack'] = true; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack_Time'] = $Now; + + RestoreFleetToPlanet($FleetRow, true, $_FleetCache); + } + + return $Return; +} + +?> diff --git a/includes/functions/MissionCaseSpy.php b/includes/functions/MissionCaseSpy.php index f56024508..aeeb8e90c 100644 --- a/includes/functions/MissionCaseSpy.php +++ b/includes/functions/MissionCaseSpy.php @@ -1,408 +1,408 @@ - 0 ? false : true); - $TargetPlanet = &$_FleetCache['planets'][$FleetRow['fleet_end_id']]; - $TargetUser = &$_FleetCache['users'][$FleetRow['fleet_target_owner']]; - - $Morale_IsEmptyReport = false; - if(MORALE_ENABLED) - { - Morale_ReCalculate($FleetRow, $FleetRow['fleet_start_time']); - - if($FleetRow['morale_level'] <= MORALE_PENALTY_EMPTYSPYREPORT) - { - $Morale_RandomizeEmptySpyReport = mt_rand(1, 100); - if($Morale_RandomizeEmptySpyReport <= MORALE_PENALTY_EMPTYSPYREPORT_CHANCE) - { - $Morale_IsEmptyReport = true; - } - } - } - - // Update planet before attack begins - $UpdateResult = HandleFullUserUpdate($TargetUser, $TargetPlanet, $_FleetCache['planets'][$TargetUser['techQueue_Planet']], $FleetRow['fleet_start_time'], true, true); - if(!empty($UpdateResult)) - { - foreach($UpdateResult as $PlanetID => $Value) - { - if($Value === true) - { - $_FleetCache['updatePlanets'][$PlanetID] = true; - } - } - } - - $CurrentUserID = $FleetRow['fleet_owner']; - $TargetUserID = $TargetPlanet['id_owner']; - $CurrentSpyLvl = $FleetRow['tech_espionage']; - $TargetSpyLvl = $TargetUser['tech_espionage']; - if($TargetUser['spy_jam_time'] > $Now) - { - $TargetSpyLvl += 5; - } - - // Select All Defending Fleets on the Orbit from $_FleetCache - $DefendingFleets = array(); - if(!empty($_FleetCache['defFleets'][$FleetRow['fleet_end_id']])) - { - global $_Vars_GameElements; - foreach($_FleetCache['defFleets'][$FleetRow['fleet_end_id']] as $FleetData) - { - if($_FleetCache['fleetRowStatus'][$FleetData['fleet_id']]['isDestroyed'] !== true) - { - $TempShips = String2Array($FleetData['fleet_array']); - foreach($TempShips as $ShipID => $ShipCount) - { - if(!isset($DefendingFleets[$_Vars_GameElements[$ShipID]])) - { - $DefendingFleets[$_Vars_GameElements[$ShipID]] = 0; - } - $DefendingFleets[$_Vars_GameElements[$ShipID]] += $ShipCount; - } - } - } - } - - // Trigger Tasks Check - if($_User['id'] == $FleetRow['fleet_owner']) - { - $CurrentUser = $_User; - } - else - { - if(empty($GlobalParsedTasks[$FleetRow['fleet_owner']]['tasks_done_parsed'])) - { - $GetUserTasksDone['tasks_done'] = $_FleetCache['userTasks'][$FleetRow['fleet_owner']]; - Tasks_CheckUservar($GetUserTasksDone); - $GlobalParsedTasks[$FleetRow['fleet_owner']] = $GetUserTasksDone; - } - $CurrentUser = $GlobalParsedTasks[$FleetRow['fleet_owner']]; - $CurrentUser['id'] = $FleetRow['fleet_owner']; - } - Tasks_TriggerTask($CurrentUser, 'SPY_OTHER_USER'); - - $ShipsCount = 0; - $FleetArray = explode(';', $FleetRow['fleet_array']); - foreach($FleetArray as $FleetData) - { - $FleetData = explode(',', $FleetData); - if($FleetData[0] == '210') - { - $ShipsCount += $FleetData[1]; - } - } - - if($ShipsCount > 0) - { - static $LangIncluded = false; - if(!$LangIncluded) - { - includeLang('spyReport'); - $LangIncluded = true; - } - - $SpyToolDebris = $ShipsCount * $_Vars_Prices[210]['crystal'] * ($_GameConfig['Fleet_Cdr'] / 100); - - $SimData = array(); - - $MaterialsInfo = SpyTarget($TargetPlanet, 0, $_Lang['sys_spy_maretials'], array('uid' => $TargetUser['id'], 'username' => $TargetUser['username'], 'isEmptyReport' => $Morale_IsEmptyReport)); - $Materials = $MaterialsInfo['Array']; - - $PlanetFleetInfo = SpyTarget($TargetPlanet, 1, $_Lang['sys_spy_fleet']); - $PlanetDefendingFleetsInfo = SpyTarget($DefendingFleets, 1, $_Lang['sys_spy_deffleet']); - $PlanetFleet = $Materials; - $PlanetFleet = array_merge($PlanetFleet, $PlanetFleetInfo['Array'], $PlanetDefendingFleetsInfo['Array']); - - $PlanetDefenInfo = SpyTarget($TargetPlanet, 2, $_Lang['sys_spy_defenses']); - $PlanetDefense = $PlanetFleet; - $PlanetDefense = array_merge($PlanetDefense, $PlanetDefenInfo['Array']); - - $PlanetBuildInfo = SpyTarget($TargetPlanet, 3, $_Lang['tech'][0]); - $PlanetBuildings = $PlanetDefense; - $PlanetBuildings = array_merge($PlanetBuildings, $PlanetBuildInfo['Array']); - - $TargetTechnInfo = SpyTarget($TargetUser, 4, $_Lang['tech'][100]); - $TargetTechnos = $PlanetBuildings; - $TargetTechnos = array_merge($TargetTechnos, $TargetTechnInfo['Array']); - - $TargetMoraleInfo = SpyTarget($TargetUser, 5, '', array('SpyTime' => $FleetRow['fleet_start_time'])); - $TargetMorale = $TargetTechnos; - $TargetMorale = array_merge($TargetMorale, $TargetMoraleInfo['Array']); - - $Difference = $CurrentSpyLvl - $TargetSpyLvl; - if($Difference == 0) - { - $Difference = 1; - } - elseif($Difference > 0) - { - $Difference = pow(2, $Difference); - } - else - { - $Difference = pow(2, ($Difference * -1)); - $Difference = 1 / $Difference; - } - $TargetForce = (($PlanetFleetInfo['Count'] + $PlanetDefendingFleetsInfo['Count']) * $ShipsCount) / (4 * $Difference); - - if($TargetForce > 100) - { - $TargetForce = 100; - } - $TargetChances = rand(0, $TargetForce); - $SpyerChances = rand(1, 100); - if($TargetChances >= $SpyerChances) - { - $DestProba = array('{spdes2}', $TargetChances); - $FleetDestroyed = true; - } - elseif($TargetChances < $SpyerChances) - { - $DestProba = array('{spdes1}', $TargetChances); - } - - if($Morale_IsEmptyReport) - { - $ST = -1; - } - else - { - if($TargetSpyLvl > $CurrentSpyLvl) - { - $Diff = $TargetSpyLvl - $CurrentSpyLvl; - $ST = sqrt($ShipsCount) - ($Diff * $Diff); - } - elseif($TargetSpyLvl == $CurrentSpyLvl) - { - $ST = sqrt($ShipsCount); - } - else - { - $Diff = $CurrentSpyLvl - $TargetSpyLvl; - $ST = sqrt($ShipsCount) + ($Diff * $Diff); - } - } - - if($IsAbandoned AND $ST >= 7) - { - $ST = 6; - } - - $General = array('{spatk}{GoToSimButton}', $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $FleetRow['fleet_end_type']); - if($ST <= 1) - { - $Materials[] = $General; - $Materials[] = $DestProba; - $Message['msg_text'] = $Materials; - } - if($ST > 1 AND $ST <= 2) - { - $PlanetFleet[] = $General; - $PlanetFleet[] = $DestProba; - $Message['msg_text'] = $PlanetFleet; - foreach($PlanetFleetInfo['Sim'] as $ID => $Count) - { - $SimData[$ID] = $Count; - } - } - if($ST > 2 AND $ST <= 4) - { - $PlanetDefense[] = $General; - $PlanetDefense[] = $DestProba; - $Message['msg_text'] = $PlanetDefense; - foreach($PlanetFleetInfo['Sim'] as $ID => $Count) - { - $SimData[$ID] = $Count; - } - foreach($PlanetDefenInfo['Sim'] as $ID => $Count) - { - $SimData[$ID] = $Count; - } - } - if($ST > 4 AND $ST < 7) - { - $PlanetBuildings[] = $General; - $PlanetBuildings[] = $DestProba; - $Message['msg_text'] = $PlanetBuildings; - foreach($PlanetFleetInfo['Sim'] as $ID => $Count) - { - $SimData[$ID] = $Count; - } - foreach($PlanetDefenInfo['Sim'] as $ID => $Count) - { - $SimData[$ID] = $Count; - } - } - if($ST >= 7 AND $ST < 14) - { - $TargetTechnos[] = $General; - $TargetTechnos[] = $DestProba; - $Message['msg_text'] = $TargetTechnos; - foreach($PlanetFleetInfo['Sim'] as $ID => $Count) - { - $SimData[$ID] = $Count; - } - foreach($PlanetDefenInfo['Sim'] as $ID => $Count) - { - $SimData[$ID] = $Count; - } - foreach($TargetTechnInfo['Sim'] as $ID => $Count) - { - $SimData[$ID] = $Count; - } - } - if($ST >= 14) - { - $TargetMorale[] = $General; - $TargetMorale[] = $DestProba; - $Message['msg_text'] = $TargetMorale; - foreach($PlanetFleetInfo['Sim'] as $ID => $Count) - { - $SimData[$ID] = $Count; - } - foreach($PlanetDefenInfo['Sim'] as $ID => $Count) - { - $SimData[$ID] = $Count; - } - foreach($TargetTechnInfo['Sim'] as $ID => $Count) - { - $SimData[$ID] = $Count; - } - } - - if(!empty($SimData)) - { - $Message['sim'] = ''; - foreach($SimData as $ID => $Count) - { - $Message['sim'] .= "{$ID},{$Count};"; - } - } - - $Message = json_encode($Message); - Cache_Message($CurrentUserID, 0, $FleetRow['fleet_start_time'], 0, '003', '014', $Message); - - if(!$IsAbandoned) - { - $Message = false; - $Message['msg_id'] = '076'; - $PlanetOrMoon = ($FleetRow['fleet_start_type'] == 1) ? $_Lang['sys_MIP_sending_planet'] : $_Lang['sys_MIP_sending_moon']; - $PlanetOrMoonYour = ($TargetPlanet['planet_type'] == 1) ? $_Lang['your_planet'] : $_Lang['your_moon']; - $Message['args'] = array - ( - $PlanetOrMoon, $FleetRow['attacking_planet_name'], $FleetRow['fleet_start_galaxy'], - $FleetRow['fleet_start_system'], $FleetRow['fleet_start_galaxy'], $FleetRow['fleet_start_system'], - $FleetRow['fleet_start_planet'], $CurrentUserID, $FleetRow['username'], $PlanetOrMoonYour, $TargetPlanet['name'], $TargetPlanet['galaxy'], - $TargetPlanet['system'], $TargetPlanet['galaxy'], $TargetPlanet['system'], $TargetPlanet['planet'], - $TargetChances.'%'.(($FleetDestroyed === true) ? '
    '.$_Lang['spy_dest_dest'] : '') - ); - $Message = json_encode($Message); - Cache_Message($TargetUserID, 0, $FleetRow['fleet_start_time'], 0, '006', '015', $Message); - } - - if($FleetDestroyed === true) - { - if($FleetRow['ally_id'] == 0 OR ($TargetUser['ally_id'] != $FleetRow['ally_id'])) - { - if(empty($UserStatsData[$FleetRow['fleet_owner']])) - { - $UserStatsData[$FleetRow['fleet_owner']] = $UserStatsPattern; - } - if(empty($UserStatsData[$TargetPlanet['id_owner']])) - { - $UserStatsData[$TargetPlanet['id_owner']] = $UserStatsPattern; - } - $UserStatsData[$FleetRow['fleet_owner']]['lost_210'] += $ShipsCount; - $UserStatsData[$TargetPlanet['id_owner']]['destroyed_210'] += $ShipsCount; - } - - if($SpyToolDebris <= 0) - { - if($TargetPlanet['planet_type'] == 1) - { - $Query_UpdateGalaxy_SearchField = 'id_planet'; - $CacheKey = 'byPlanet'; - } - else - { - $Query_UpdateGalaxy_SearchField = 'id_moon'; - $CacheKey = 'byMoon'; - } - - if(isset($_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]) && $_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']] > 0) - { - if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['metal'])) - { - $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['metal'] = 0; - } - if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'])) - { - $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'] = 0; - } - - $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'] += $SpyToolDebris; - $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['updated'] = true; - $_FleetCache['updated']['galaxy'] = true; - } - else - { - $Query_UpdateGalaxy = ''; - $Query_UpdateGalaxy .= "UPDATE {{table}} SET `crystal` = `crystal` + {$SpyToolDebris} "; - $Query_UpdateGalaxy .= "WHERE `{$Query_UpdateGalaxy_SearchField}` = {$FleetRow['fleet_end_id']} LIMIT 1; "; - $Query_UpdateGalaxy .= "MISSION SPY [Q01][FID: {$FleetRow['fleet_id']}]"; - doquery($Query_UpdateGalaxy, 'galaxy'); - } - } - - $UserDev_Log[] = array('UserID' => $FleetRow['fleet_owner'], 'PlanetID' => '0', 'Date' => $FleetRow['fleet_start_time'], 'Place' => 18, 'Code' => '1', 'ElementID' => '210', 'AdditionalData' => $ShipsCount); - $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed'] = true; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed_Reason'] = 10; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Info_HasLostShips'] = true; - - $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] = true; - } - else - { - if($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['calcCount'] == 1) - { - $_FleetCache['updateFleets'][$FleetRow['fleet_id']]['fleet_mess'] = 1; - } - } - } - } - if($FleetRow['calcType'] == 3 && (!isset($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed']) || $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] !== true)) - { - $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack'] = true; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack_Time'] = $Now; - RestoreFleetToPlanet($FleetRow, true, $_FleetCache); - } - - return $Return; -} - -?> \ No newline at end of file + 0 ? false : true); + $TargetPlanet = &$_FleetCache['planets'][$FleetRow['fleet_end_id']]; + $TargetUser = &$_FleetCache['users'][$FleetRow['fleet_target_owner']]; + + $Morale_IsEmptyReport = false; + if(MORALE_ENABLED) + { + Morale_ReCalculate($FleetRow, $FleetRow['fleet_start_time']); + + if($FleetRow['morale_level'] <= MORALE_PENALTY_EMPTYSPYREPORT) + { + $Morale_RandomizeEmptySpyReport = mt_rand(1, 100); + if($Morale_RandomizeEmptySpyReport <= MORALE_PENALTY_EMPTYSPYREPORT_CHANCE) + { + $Morale_IsEmptyReport = true; + } + } + } + + // Update planet before attack begins + $UpdateResult = HandleFullUserUpdate($TargetUser, $TargetPlanet, $_FleetCache['planets'][$TargetUser['techQueue_Planet']], $FleetRow['fleet_start_time'], true, true); + if(!empty($UpdateResult)) + { + foreach($UpdateResult as $PlanetID => $Value) + { + if($Value === true) + { + $_FleetCache['updatePlanets'][$PlanetID] = true; + } + } + } + + $CurrentUserID = $FleetRow['fleet_owner']; + $TargetUserID = $TargetPlanet['id_owner']; + $CurrentSpyLvl = $FleetRow['tech_espionage']; + $TargetSpyLvl = $TargetUser['tech_espionage']; + if($TargetUser['spy_jam_time'] > $Now) + { + $TargetSpyLvl += 5; + } + + // Select All Defending Fleets on the Orbit from $_FleetCache + $DefendingFleets = array(); + if(!empty($_FleetCache['defFleets'][$FleetRow['fleet_end_id']])) + { + global $_Vars_GameElements; + foreach($_FleetCache['defFleets'][$FleetRow['fleet_end_id']] as $FleetData) + { + if($_FleetCache['fleetRowStatus'][$FleetData['fleet_id']]['isDestroyed'] !== true) + { + $TempShips = String2Array($FleetData['fleet_array']); + foreach($TempShips as $ShipID => $ShipCount) + { + if(!isset($DefendingFleets[$_Vars_GameElements[$ShipID]])) + { + $DefendingFleets[$_Vars_GameElements[$ShipID]] = 0; + } + $DefendingFleets[$_Vars_GameElements[$ShipID]] += $ShipCount; + } + } + } + } + + // Trigger Tasks Check + if($_User['id'] == $FleetRow['fleet_owner']) + { + $CurrentUser = $_User; + } + else + { + if(empty($GlobalParsedTasks[$FleetRow['fleet_owner']]['tasks_done_parsed'])) + { + $GetUserTasksDone['tasks_done'] = $_FleetCache['userTasks'][$FleetRow['fleet_owner']]; + Tasks_CheckUservar($GetUserTasksDone); + $GlobalParsedTasks[$FleetRow['fleet_owner']] = $GetUserTasksDone; + } + $CurrentUser = $GlobalParsedTasks[$FleetRow['fleet_owner']]; + $CurrentUser['id'] = $FleetRow['fleet_owner']; + } + Tasks_TriggerTask($CurrentUser, 'SPY_OTHER_USER'); + + $ShipsCount = 0; + $FleetArray = explode(';', $FleetRow['fleet_array']); + foreach($FleetArray as $FleetData) + { + $FleetData = explode(',', $FleetData); + if($FleetData[0] == '210') + { + $ShipsCount += $FleetData[1]; + } + } + + if($ShipsCount > 0) + { + static $LangIncluded = false; + if(!$LangIncluded) + { + includeLang('spyReport'); + $LangIncluded = true; + } + + $SpyToolDebris = $ShipsCount * $_Vars_Prices[210]['crystal'] * ($_GameConfig['Fleet_Cdr'] / 100); + + $SimData = array(); + + $MaterialsInfo = SpyTarget($TargetPlanet, 0, $_Lang['sys_spy_maretials'], array('uid' => $TargetUser['id'], 'username' => $TargetUser['username'], 'isEmptyReport' => $Morale_IsEmptyReport)); + $Materials = $MaterialsInfo['Array']; + + $PlanetFleetInfo = SpyTarget($TargetPlanet, 1, $_Lang['sys_spy_fleet']); + $PlanetDefendingFleetsInfo = SpyTarget($DefendingFleets, 1, $_Lang['sys_spy_deffleet']); + $PlanetFleet = $Materials; + $PlanetFleet = array_merge($PlanetFleet, $PlanetFleetInfo['Array'], $PlanetDefendingFleetsInfo['Array']); + + $PlanetDefenInfo = SpyTarget($TargetPlanet, 2, $_Lang['sys_spy_defenses']); + $PlanetDefense = $PlanetFleet; + $PlanetDefense = array_merge($PlanetDefense, $PlanetDefenInfo['Array']); + + $PlanetBuildInfo = SpyTarget($TargetPlanet, 3, $_Lang['tech'][0]); + $PlanetBuildings = $PlanetDefense; + $PlanetBuildings = array_merge($PlanetBuildings, $PlanetBuildInfo['Array']); + + $TargetTechnInfo = SpyTarget($TargetUser, 4, $_Lang['tech'][100]); + $TargetTechnos = $PlanetBuildings; + $TargetTechnos = array_merge($TargetTechnos, $TargetTechnInfo['Array']); + + $TargetMoraleInfo = SpyTarget($TargetUser, 5, '', array('SpyTime' => $FleetRow['fleet_start_time'])); + $TargetMorale = $TargetTechnos; + $TargetMorale = array_merge($TargetMorale, $TargetMoraleInfo['Array']); + + $Difference = $CurrentSpyLvl - $TargetSpyLvl; + if($Difference == 0) + { + $Difference = 1; + } + elseif($Difference > 0) + { + $Difference = pow(2, $Difference); + } + else + { + $Difference = pow(2, ($Difference * -1)); + $Difference = 1 / $Difference; + } + $TargetForce = (($PlanetFleetInfo['Count'] + $PlanetDefendingFleetsInfo['Count']) * $ShipsCount) / (4 * $Difference); + + if($TargetForce > 100) + { + $TargetForce = 100; + } + $TargetChances = rand(0, $TargetForce); + $SpyerChances = rand(1, 100); + if($TargetChances >= $SpyerChances) + { + $DestProba = array('{spdes2}', $TargetChances); + $FleetDestroyed = true; + } + elseif($TargetChances < $SpyerChances) + { + $DestProba = array('{spdes1}', $TargetChances); + } + + if($Morale_IsEmptyReport) + { + $ST = -1; + } + else + { + if($TargetSpyLvl > $CurrentSpyLvl) + { + $Diff = $TargetSpyLvl - $CurrentSpyLvl; + $ST = sqrt($ShipsCount) - ($Diff * $Diff); + } + elseif($TargetSpyLvl == $CurrentSpyLvl) + { + $ST = sqrt($ShipsCount); + } + else + { + $Diff = $CurrentSpyLvl - $TargetSpyLvl; + $ST = sqrt($ShipsCount) + ($Diff * $Diff); + } + } + + if($IsAbandoned AND $ST >= 7) + { + $ST = 6; + } + + $General = array('{spatk}{GoToSimButton}', $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], $FleetRow['fleet_end_type']); + if($ST <= 1) + { + $Materials[] = $General; + $Materials[] = $DestProba; + $Message['msg_text'] = $Materials; + } + if($ST > 1 AND $ST <= 2) + { + $PlanetFleet[] = $General; + $PlanetFleet[] = $DestProba; + $Message['msg_text'] = $PlanetFleet; + foreach($PlanetFleetInfo['Sim'] as $ID => $Count) + { + $SimData[$ID] = $Count; + } + } + if($ST > 2 AND $ST <= 4) + { + $PlanetDefense[] = $General; + $PlanetDefense[] = $DestProba; + $Message['msg_text'] = $PlanetDefense; + foreach($PlanetFleetInfo['Sim'] as $ID => $Count) + { + $SimData[$ID] = $Count; + } + foreach($PlanetDefenInfo['Sim'] as $ID => $Count) + { + $SimData[$ID] = $Count; + } + } + if($ST > 4 AND $ST < 7) + { + $PlanetBuildings[] = $General; + $PlanetBuildings[] = $DestProba; + $Message['msg_text'] = $PlanetBuildings; + foreach($PlanetFleetInfo['Sim'] as $ID => $Count) + { + $SimData[$ID] = $Count; + } + foreach($PlanetDefenInfo['Sim'] as $ID => $Count) + { + $SimData[$ID] = $Count; + } + } + if($ST >= 7 AND $ST < 14) + { + $TargetTechnos[] = $General; + $TargetTechnos[] = $DestProba; + $Message['msg_text'] = $TargetTechnos; + foreach($PlanetFleetInfo['Sim'] as $ID => $Count) + { + $SimData[$ID] = $Count; + } + foreach($PlanetDefenInfo['Sim'] as $ID => $Count) + { + $SimData[$ID] = $Count; + } + foreach($TargetTechnInfo['Sim'] as $ID => $Count) + { + $SimData[$ID] = $Count; + } + } + if($ST >= 14) + { + $TargetMorale[] = $General; + $TargetMorale[] = $DestProba; + $Message['msg_text'] = $TargetMorale; + foreach($PlanetFleetInfo['Sim'] as $ID => $Count) + { + $SimData[$ID] = $Count; + } + foreach($PlanetDefenInfo['Sim'] as $ID => $Count) + { + $SimData[$ID] = $Count; + } + foreach($TargetTechnInfo['Sim'] as $ID => $Count) + { + $SimData[$ID] = $Count; + } + } + + if(!empty($SimData)) + { + $Message['sim'] = ''; + foreach($SimData as $ID => $Count) + { + $Message['sim'] .= "{$ID},{$Count};"; + } + } + + $Message = json_encode($Message); + Cache_Message($CurrentUserID, 0, $FleetRow['fleet_start_time'], 0, '003', '014', $Message); + + if(!$IsAbandoned) + { + $Message = false; + $Message['msg_id'] = '076'; + $PlanetOrMoon = ($FleetRow['fleet_start_type'] == 1) ? $_Lang['sys_MIP_sending_planet'] : $_Lang['sys_MIP_sending_moon']; + $PlanetOrMoonYour = ($TargetPlanet['planet_type'] == 1) ? $_Lang['your_planet'] : $_Lang['your_moon']; + $Message['args'] = array + ( + $PlanetOrMoon, $FleetRow['attacking_planet_name'], $FleetRow['fleet_start_galaxy'], + $FleetRow['fleet_start_system'], $FleetRow['fleet_start_galaxy'], $FleetRow['fleet_start_system'], + $FleetRow['fleet_start_planet'], $CurrentUserID, $FleetRow['username'], $PlanetOrMoonYour, $TargetPlanet['name'], $TargetPlanet['galaxy'], + $TargetPlanet['system'], $TargetPlanet['galaxy'], $TargetPlanet['system'], $TargetPlanet['planet'], + $TargetChances.'%'.(($FleetDestroyed === true) ? '
    '.$_Lang['spy_dest_dest'] : '') + ); + $Message = json_encode($Message); + Cache_Message($TargetUserID, 0, $FleetRow['fleet_start_time'], 0, '006', '015', $Message); + } + + if($FleetDestroyed === true) + { + if($FleetRow['ally_id'] == 0 OR ($TargetUser['ally_id'] != $FleetRow['ally_id'])) + { + if(empty($UserStatsData[$FleetRow['fleet_owner']])) + { + $UserStatsData[$FleetRow['fleet_owner']] = $UserStatsPattern; + } + if(empty($UserStatsData[$TargetPlanet['id_owner']])) + { + $UserStatsData[$TargetPlanet['id_owner']] = $UserStatsPattern; + } + $UserStatsData[$FleetRow['fleet_owner']]['lost_210'] += $ShipsCount; + $UserStatsData[$TargetPlanet['id_owner']]['destroyed_210'] += $ShipsCount; + } + + if($SpyToolDebris <= 0) + { + if($TargetPlanet['planet_type'] == 1) + { + $Query_UpdateGalaxy_SearchField = 'id_planet'; + $CacheKey = 'byPlanet'; + } + else + { + $Query_UpdateGalaxy_SearchField = 'id_moon'; + $CacheKey = 'byMoon'; + } + + if(isset($_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]) && $_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']] > 0) + { + if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['metal'])) + { + $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['metal'] = 0; + } + if(!isset($_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'])) + { + $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'] = 0; + } + + $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['crystal'] += $SpyToolDebris; + $_FleetCache['galaxy'][$_FleetCache['galaxyMap'][$CacheKey][$FleetRow['fleet_end_id']]]['updated'] = true; + $_FleetCache['updated']['galaxy'] = true; + } + else + { + $Query_UpdateGalaxy = ''; + $Query_UpdateGalaxy .= "UPDATE {{table}} SET `crystal` = `crystal` + {$SpyToolDebris} "; + $Query_UpdateGalaxy .= "WHERE `{$Query_UpdateGalaxy_SearchField}` = {$FleetRow['fleet_end_id']} LIMIT 1; "; + $Query_UpdateGalaxy .= "MISSION SPY [Q01][FID: {$FleetRow['fleet_id']}]"; + doquery($Query_UpdateGalaxy, 'galaxy'); + } + } + + $UserDev_Log[] = array('UserID' => $FleetRow['fleet_owner'], 'PlanetID' => '0', 'Date' => $FleetRow['fleet_start_time'], 'Place' => 18, 'Code' => '1', 'ElementID' => '210', 'AdditionalData' => $ShipsCount); + $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed'] = true; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Destroyed_Reason'] = 10; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Info_HasLostShips'] = true; + + $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] = true; + } + else + { + if($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['calcCount'] == 1) + { + $_FleetCache['updateFleets'][$FleetRow['fleet_id']]['fleet_mess'] = 1; + } + } + } + } + if($FleetRow['calcType'] == 3 && (!isset($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed']) || $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] !== true)) + { + $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack'] = true; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack_Time'] = $Now; + RestoreFleetToPlanet($FleetRow, true, $_FleetCache); + } + + return $Return; +} + +?> diff --git a/includes/functions/MissionCaseStay.php b/includes/functions/MissionCaseStay.php index b9c795d70..7e1306403 100644 --- a/includes/functions/MissionCaseStay.php +++ b/includes/functions/MissionCaseStay.php @@ -1,94 +1,94 @@ -'.prettyNumber($ShipRow[1]).')'; - } - - $Message['msg_id'] = '009'; - $Message['args'] = array - ( - ($FleetRow['fleet_end_type'] == 1) ? $_Lang['to_planet'] : $_Lang['to_moon'], $FleetRow['endtarget_planet_name'], - $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], - $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], - implode(', ', $Ships), $_Lang['Metal'], prettyNumber($FleetRow['fleet_resource_metal']), $_Lang['Crystal'], - prettyNumber($FleetRow['fleet_resource_crystal']), $_Lang['Deuterium'], prettyNumber($FleetRow['fleet_resource_deuterium']) - ); - $Message = json_encode($Message); - Cache_Message($FleetRow['fleet_owner'], 0, $FleetRow['fleet_start_time'], 5, '003', '004', $Message); - - RestoreFleetToPlanet($FleetRow, false, $_FleetCache); - $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] = true; - $DoFleetDelete = true; - $LandingTime = $FleetRow['fleet_start_time']; - } - - if($FleetRow['calcType'] == 3 && (!isset($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed']) || $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] !== true)) - { - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack'] = true; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack_Time'] = $Now; - - $Message = false; - $Message['msg_id'] = '010'; - $Message['args'] = array - ( - ($FleetRow['fleet_end_type'] == 1) ? $_Lang['to_planet'] : $_Lang['to_moon'], $FleetRow['attacking_planet_name'], - $FleetRow['fleet_start_galaxy'], $FleetRow['fleet_start_system'], - $FleetRow['fleet_start_galaxy'], $FleetRow['fleet_start_system'], $FleetRow['fleet_start_planet'], - $_Lang['Metal'], prettyNumber($FleetRow['fleet_resource_metal']), - $_Lang['Crystal'], prettyNumber($FleetRow['fleet_resource_crystal']), - $_Lang['Deuterium'], prettyNumber($FleetRow['fleet_resource_deuterium']) - ); - $Message = json_encode($Message); - Cache_Message($FleetRow['fleet_owner'], 0, $FleetRow['fleet_end_time'], 5, '003', '003', $Message); - - RestoreFleetToPlanet($FleetRow, true, $_FleetCache); - $DoFleetDelete = true; - $LandingTime = $FleetRow['fleet_end_time']; - } - - if($DoFleetDelete === true) - { - $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; - // Check Task - if($FleetRow['fleet_start_type'] == 3 AND $FleetRow['fleet_end_type'] == 3 AND ($LandingTime - $FleetRow['fleet_send_time']) > 21600) - { - if($_User['id'] == $FleetRow['fleet_owner']) - { - $CurrentUser = $_User; - } - else - { - if(empty($GlobalParsedTasks[$FleetRow['fleet_owner']]['tasks_done_parsed'])) - { - $GetUserTasksDone['tasks_done'] = $_FleetCache['userTasks'][$FleetRow['fleet_owner']]; - Tasks_CheckUservar($GetUserTasksDone); - $GlobalParsedTasks[$FleetRow['fleet_owner']] = $GetUserTasksDone; - } - $CurrentUser = $GlobalParsedTasks[$FleetRow['fleet_owner']]; - $CurrentUser['id'] = $FleetRow['fleet_owner']; - } - Tasks_TriggerTask($CurrentUser, 'INTRODUCTION_FLEETSAVE_END'); - } - } - - return $Return; -} - -?> \ No newline at end of file +'.prettyNumber($ShipRow[1]).')'; + } + + $Message['msg_id'] = '009'; + $Message['args'] = array + ( + ($FleetRow['fleet_end_type'] == 1) ? $_Lang['to_planet'] : $_Lang['to_moon'], $FleetRow['endtarget_planet_name'], + $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], + $FleetRow['fleet_end_galaxy'], $FleetRow['fleet_end_system'], $FleetRow['fleet_end_planet'], + implode(', ', $Ships), $_Lang['Metal'], prettyNumber($FleetRow['fleet_resource_metal']), $_Lang['Crystal'], + prettyNumber($FleetRow['fleet_resource_crystal']), $_Lang['Deuterium'], prettyNumber($FleetRow['fleet_resource_deuterium']) + ); + $Message = json_encode($Message); + Cache_Message($FleetRow['fleet_owner'], 0, $FleetRow['fleet_start_time'], 5, '003', '004', $Message); + + RestoreFleetToPlanet($FleetRow, false, $_FleetCache); + $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] = true; + $DoFleetDelete = true; + $LandingTime = $FleetRow['fleet_start_time']; + } + + if($FleetRow['calcType'] == 3 && (!isset($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed']) || $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['isDestroyed'] !== true)) + { + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack'] = true; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack_Time'] = $Now; + + $Message = false; + $Message['msg_id'] = '010'; + $Message['args'] = array + ( + ($FleetRow['fleet_end_type'] == 1) ? $_Lang['to_planet'] : $_Lang['to_moon'], $FleetRow['attacking_planet_name'], + $FleetRow['fleet_start_galaxy'], $FleetRow['fleet_start_system'], + $FleetRow['fleet_start_galaxy'], $FleetRow['fleet_start_system'], $FleetRow['fleet_start_planet'], + $_Lang['Metal'], prettyNumber($FleetRow['fleet_resource_metal']), + $_Lang['Crystal'], prettyNumber($FleetRow['fleet_resource_crystal']), + $_Lang['Deuterium'], prettyNumber($FleetRow['fleet_resource_deuterium']) + ); + $Message = json_encode($Message); + Cache_Message($FleetRow['fleet_owner'], 0, $FleetRow['fleet_end_time'], 5, '003', '003', $Message); + + RestoreFleetToPlanet($FleetRow, true, $_FleetCache); + $DoFleetDelete = true; + $LandingTime = $FleetRow['fleet_end_time']; + } + + if($DoFleetDelete === true) + { + $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; + // Check Task + if($FleetRow['fleet_start_type'] == 3 AND $FleetRow['fleet_end_type'] == 3 AND ($LandingTime - $FleetRow['fleet_send_time']) > 21600) + { + if($_User['id'] == $FleetRow['fleet_owner']) + { + $CurrentUser = $_User; + } + else + { + if(empty($GlobalParsedTasks[$FleetRow['fleet_owner']]['tasks_done_parsed'])) + { + $GetUserTasksDone['tasks_done'] = $_FleetCache['userTasks'][$FleetRow['fleet_owner']]; + Tasks_CheckUservar($GetUserTasksDone); + $GlobalParsedTasks[$FleetRow['fleet_owner']] = $GetUserTasksDone; + } + $CurrentUser = $GlobalParsedTasks[$FleetRow['fleet_owner']]; + $CurrentUser['id'] = $FleetRow['fleet_owner']; + } + Tasks_TriggerTask($CurrentUser, 'INTRODUCTION_FLEETSAVE_END'); + } + } + + return $Return; +} + +?> diff --git a/includes/functions/MissionCaseStayAlly.php b/includes/functions/MissionCaseStayAlly.php index 22fab41a8..991db51be 100644 --- a/includes/functions/MissionCaseStayAlly.php +++ b/includes/functions/MissionCaseStayAlly.php @@ -1,119 +1,119 @@ - $Value) - { - $FleetRow[$Key] = $Value; - } - } - } - if($FleetRow['calcType'] != 3) - { - $_FleetCache['updateFleets'][$FleetRow['fleet_id']]['fleet_mess'] = $FleetRow['fleet_mess']; - } - } - - return $Return; -} - -?> \ No newline at end of file + $Value) + { + $FleetRow[$Key] = $Value; + } + } + } + if($FleetRow['calcType'] != 3) + { + $_FleetCache['updateFleets'][$FleetRow['fleet_id']]['fleet_mess'] = $FleetRow['fleet_mess']; + } + } + + return $Return; +} + +?> diff --git a/includes/functions/MissionCaseTransport.php b/includes/functions/MissionCaseTransport.php index 1f6613865..28148dfe8 100644 --- a/includes/functions/MissionCaseTransport.php +++ b/includes/functions/MissionCaseTransport.php @@ -1,141 +1,141 @@ - $FleetRow['fleet_owner'], 'PlanetID' => $FleetRow['fleet_end_id'], 'Date' => $FleetRow['fleet_start_time'], 'Place' => 19, 'Code' => '1', 'ElementID' => '0', 'AdditionalData' => "M,{$FleetRow['fleet_resource_metal']};C,{$FleetRow['fleet_resource_crystal']};D,{$FleetRow['fleet_resource_deuterium']}"); - if($FleetRow['fleet_owner'] != $TargetOwner) - { - $UserDev_Log[] = array('UserID' => $TargetOwner, 'PlanetID' => $FleetRow['fleet_end_id'], 'Date' => $FleetRow['fleet_start_time'], 'Place' => 19, 'Code' => '2', 'ElementID' => '0', 'AdditionalData' => "M,{$FleetRow['fleet_resource_metal']};C,{$FleetRow['fleet_resource_crystal']};D,{$FleetRow['fleet_resource_deuterium']}"); - } - - if($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['calcCount'] == 1) - { - $CachePointer = &$_FleetCache['updateFleets'][$FleetRow['fleet_id']]; - $CachePointer['fleet_mess'] = 1; - $CachePointer['fleet_resource_metal'] = -$FleetRow['fleet_resource_metal']; - $CachePointer['fleet_resource_crystal'] = -$FleetRow['fleet_resource_crystal']; - $CachePointer['fleet_resource_deuterium'] = -$FleetRow['fleet_resource_deuterium']; - } - else - { - $_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']] = array - ( - 'fleet_resource_metal' => 0, - 'fleet_resource_crystal' => 0, - 'fleet_resource_deuterium' => 0, - ); - $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['needUpdate'] = false; - } - } - - if($FleetRow['calcType'] == 3) - { - if(!empty($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']])) - { - foreach($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']] as $Key => $Value) - { - $FleetRow[$Key] = $Value; - } - } - - $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack'] = true; - $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack_Time'] = $Now; - - $Message = false; - if($FleetRow['fleet_resource_metal'] == 0 AND $FleetRow['fleet_resource_crystal'] == 0 AND $FleetRow['fleet_resource_deuterium'] == 0) - { - $Message['msg_id'] = '035'; - $Message['args'] = array - ( - ($FleetRow['fleet_start_type'] == 1) ? $_Lang['to_planet'] : $_Lang['to_moon'], $StartName, - $FleetRow['fleet_start_galaxy'], $FleetRow['fleet_start_system'], - $FleetRow['fleet_start_galaxy'], $FleetRow['fleet_start_system'], $FleetRow['fleet_start_planet'] - ); - } - else - { - $Message['msg_id'] = '034'; - $Message['args'] = array - ( - ($FleetRow['fleet_start_type'] == 1) ? $_Lang['to_planet'] : $_Lang['to_moon'], $StartName, - $FleetRow['fleet_start_galaxy'], $FleetRow['fleet_start_system'], - $FleetRow['fleet_start_galaxy'], $FleetRow['fleet_start_system'], $FleetRow['fleet_start_planet'], - prettyNumber($FleetRow['fleet_resource_metal']), - prettyNumber($FleetRow['fleet_resource_crystal']), - prettyNumber($FleetRow['fleet_resource_deuterium']) - ); - } - $Message = json_encode($Message); - Cache_Message($StartOwner, 0, $FleetRow['fleet_end_time'], 5, '002', '003', $Message); - - RestoreFleetToPlanet($FleetRow, true, $_FleetCache); - } - - return $Return; -} - -?> \ No newline at end of file + $FleetRow['fleet_owner'], 'PlanetID' => $FleetRow['fleet_end_id'], 'Date' => $FleetRow['fleet_start_time'], 'Place' => 19, 'Code' => '1', 'ElementID' => '0', 'AdditionalData' => "M,{$FleetRow['fleet_resource_metal']};C,{$FleetRow['fleet_resource_crystal']};D,{$FleetRow['fleet_resource_deuterium']}"); + if($FleetRow['fleet_owner'] != $TargetOwner) + { + $UserDev_Log[] = array('UserID' => $TargetOwner, 'PlanetID' => $FleetRow['fleet_end_id'], 'Date' => $FleetRow['fleet_start_time'], 'Place' => 19, 'Code' => '2', 'ElementID' => '0', 'AdditionalData' => "M,{$FleetRow['fleet_resource_metal']};C,{$FleetRow['fleet_resource_crystal']};D,{$FleetRow['fleet_resource_deuterium']}"); + } + + if($_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['calcCount'] == 1) + { + $CachePointer = &$_FleetCache['updateFleets'][$FleetRow['fleet_id']]; + $CachePointer['fleet_mess'] = 1; + $CachePointer['fleet_resource_metal'] = -$FleetRow['fleet_resource_metal']; + $CachePointer['fleet_resource_crystal'] = -$FleetRow['fleet_resource_crystal']; + $CachePointer['fleet_resource_deuterium'] = -$FleetRow['fleet_resource_deuterium']; + } + else + { + $_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']] = array + ( + 'fleet_resource_metal' => 0, + 'fleet_resource_crystal' => 0, + 'fleet_resource_deuterium' => 0, + ); + $_FleetCache['fleetRowStatus'][$FleetRow['fleet_id']]['needUpdate'] = false; + } + } + + if($FleetRow['calcType'] == 3) + { + if(!empty($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']])) + { + foreach($_FleetCache['fleetRowUpdate'][$FleetRow['fleet_id']] as $Key => $Value) + { + $FleetRow[$Key] = $Value; + } + } + + $Return['FleetsToDelete'][] = $FleetRow['fleet_id']; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack'] = true; + $Return['FleetArchive'][$FleetRow['fleet_id']]['Fleet_Calculated_ComeBack_Time'] = $Now; + + $Message = false; + if($FleetRow['fleet_resource_metal'] == 0 AND $FleetRow['fleet_resource_crystal'] == 0 AND $FleetRow['fleet_resource_deuterium'] == 0) + { + $Message['msg_id'] = '035'; + $Message['args'] = array + ( + ($FleetRow['fleet_start_type'] == 1) ? $_Lang['to_planet'] : $_Lang['to_moon'], $StartName, + $FleetRow['fleet_start_galaxy'], $FleetRow['fleet_start_system'], + $FleetRow['fleet_start_galaxy'], $FleetRow['fleet_start_system'], $FleetRow['fleet_start_planet'] + ); + } + else + { + $Message['msg_id'] = '034'; + $Message['args'] = array + ( + ($FleetRow['fleet_start_type'] == 1) ? $_Lang['to_planet'] : $_Lang['to_moon'], $StartName, + $FleetRow['fleet_start_galaxy'], $FleetRow['fleet_start_system'], + $FleetRow['fleet_start_galaxy'], $FleetRow['fleet_start_system'], $FleetRow['fleet_start_planet'], + prettyNumber($FleetRow['fleet_resource_metal']), + prettyNumber($FleetRow['fleet_resource_crystal']), + prettyNumber($FleetRow['fleet_resource_deuterium']) + ); + } + $Message = json_encode($Message); + Cache_Message($StartOwner, 0, $FleetRow['fleet_end_time'], 5, '002', '003', $Message); + + RestoreFleetToPlanet($FleetRow, true, $_FleetCache); + } + + return $Return; +} + +?> diff --git a/includes/functions/MissionCheckCalculation.php b/includes/functions/MissionCheckCalculation.php index 0f4d42728..94486864c 100644 --- a/includes/functions/MissionCheckCalculation.php +++ b/includes/functions/MissionCheckCalculation.php @@ -1,68 +1,68 @@ - 0) - { - $Return['users'] = $FleetRow['fleet_target_owner']; - } - if($FleetRow['fleet_mission'] == 9) - { - // Get Additional Planets, just in case, if Moon will be destroyed - $Return['addPlanets'] = $FleetRow['fleet_end_id']; - } - if($FleetRow['fleet_mission'] != 10) - { - // Get DefendingFleets - $Return['defFleets'] = $FleetRow['fleet_end_id']; - } - } - if(in_array($FleetRow['fleet_mission'], array(1, 5, 6, 7, 8, 9))) - { - // Get UserTasksData - $Return['taskData'][] = $FleetRow['fleet_owner']; - if($FleetRow['fleet_mission'] == 9 && $FleetRow['fleet_target_owner'] > 0) - { - $Return['taskData'][] = $FleetRow['fleet_target_owner']; - } - } - if($FleetRow['fleet_mission'] == 1 && $FleetRow['fleets_count'] > 0) - { - $Temp = explode(',', str_replace('|', '', $FleetRow['fleets_id'])); - $Return['acsFleets'][$FleetRow['fleet_id']] = $Temp; - // Get FleetsFromACS - } - if($FleetRow['fleet_mission'] == 8) - { - // Get GalaxyRow - $Return['galaxy'] = $FleetRow['fleet_end_id_galaxy']; - } - } - if($FleetRow['fleet_end_stay'] > 0 && $FleetRow['fleet_end_stay'] <= $Now && $FleetRow['fleet_mess'] != 2) - { - $Return['timeSort'][$FleetRow['fleet_end_stay'].str_pad($FleetRow['fleet_id'], 20, '0', STR_PAD_LEFT).'02'] = 2; - } - if($FleetRow['fleet_end_time'] <= $Now) - { - if(($FleetRow['fleet_mission'] == 4 && !empty($Return['timeSort'])) || $FleetRow['fleet_mission'] == 10) - { - // If this Fleet's order is to "Stay" or it's Missile Attack, don't force to recalculate it - } - else - { - $Return['timeSort'][$FleetRow['fleet_end_time'].str_pad($FleetRow['fleet_id'], 20, '0', STR_PAD_LEFT).'03'] = 3; - } - } - return $Return; -} - -?> \ No newline at end of file + 0) + { + $Return['users'] = $FleetRow['fleet_target_owner']; + } + if($FleetRow['fleet_mission'] == 9) + { + // Get Additional Planets, just in case, if Moon will be destroyed + $Return['addPlanets'] = $FleetRow['fleet_end_id']; + } + if($FleetRow['fleet_mission'] != 10) + { + // Get DefendingFleets + $Return['defFleets'] = $FleetRow['fleet_end_id']; + } + } + if(in_array($FleetRow['fleet_mission'], array(1, 5, 6, 7, 8, 9))) + { + // Get UserTasksData + $Return['taskData'][] = $FleetRow['fleet_owner']; + if($FleetRow['fleet_mission'] == 9 && $FleetRow['fleet_target_owner'] > 0) + { + $Return['taskData'][] = $FleetRow['fleet_target_owner']; + } + } + if($FleetRow['fleet_mission'] == 1 && $FleetRow['fleets_count'] > 0) + { + $Temp = explode(',', str_replace('|', '', $FleetRow['fleets_id'])); + $Return['acsFleets'][$FleetRow['fleet_id']] = $Temp; + // Get FleetsFromACS + } + if($FleetRow['fleet_mission'] == 8) + { + // Get GalaxyRow + $Return['galaxy'] = $FleetRow['fleet_end_id_galaxy']; + } + } + if($FleetRow['fleet_end_stay'] > 0 && $FleetRow['fleet_end_stay'] <= $Now && $FleetRow['fleet_mess'] != 2) + { + $Return['timeSort'][$FleetRow['fleet_end_stay'].str_pad($FleetRow['fleet_id'], 20, '0', STR_PAD_LEFT).'02'] = 2; + } + if($FleetRow['fleet_end_time'] <= $Now) + { + if(($FleetRow['fleet_mission'] == 4 && !empty($Return['timeSort'])) || $FleetRow['fleet_mission'] == 10) + { + // If this Fleet's order is to "Stay" or it's Missile Attack, don't force to recalculate it + } + else + { + $Return['timeSort'][$FleetRow['fleet_end_time'].str_pad($FleetRow['fleet_id'], 20, '0', STR_PAD_LEFT).'03'] = 3; + } + } + return $Return; +} + +?> diff --git a/includes/functions/Pagination.php b/includes/functions/Pagination.php index 7b97be14c..2152549bf 100644 --- a/includes/functions/Pagination.php +++ b/includes/functions/Pagination.php @@ -1,195 +1,195 @@ -= $LastPage) - { - $ThisPage = $LastPage; - $Return['hasNext'] = false; - $IsOnEdge = true; - } - if($MaxPages < 3) - { - // We have to show at least 3 pages - $MaxPages = 3; - } - - $ToShow = $MaxPages - 3; - if(($ToShow % 2) == 1 AND $ToShow > 0) - { - // If $ToShow is even number, cut one down - $ToShow -= 1; - $AddToOneSide = true; - } - - $LeftSide = $RightSide = ($ToShow / 2); - if($AddToOneSide) - { - if($ThisPage > (($LastPage + 1) / 2)) - { - $LeftSide += 1; - } - else - { - $RightSide += 1; - } - } - $LeftMost = ($ThisPage - $LeftSide); - $RightMost = ($ThisPage + $RightSide); - $StartToLeftMostDistance = $LeftMost - 1; - $EndToRightMostDistance = $LastPage - $RightMost; - if($StartToLeftMostDistance <= 1) - { - $Return['hasLeftMostBreak'] = false; - if($StartToLeftMostDistance < 1) - { - $Value = (($StartToLeftMostDistance - 1) * -1); - $RightSide += (($StartToLeftMostDistance - 1) * -1); - $RightMost += $Value; - } - } - if($EndToRightMostDistance <= 1) - { - $Return['hasRightMostBreak'] = false; - if($EndToRightMostDistance < 1) - { - $Value = (($EndToRightMostDistance - 1) * -1); - $LeftSide += $Value; - $LeftMost -= $Value; - } - } - - // Generate Elements Array - $Return['pages'][] = 1; - if($Return['hasLeftMostBreak'] AND $MaxPages < $LastPage) - { - $Return['pages'][] = '_'; - } - for($i = $LeftMost; $i < $ThisPage; $i += 1) - { - if($LeftSide <= 0) - { - break; - } - if($i <= 1) - { - $i = 1; - continue; - } - $Return['pages'][] = $i; - $LeftSide -= 1; - } - if($IsOnEdge === false) - { - $Return['pages'][] = $ThisPage; - } - for($i = ($ThisPage + 1); $i < $LastPage; $i += 1) - { - if($RightSide <= 0) - { - break; - } - $Return['pages'][] = $i; - $RightSide -= 1; - } - if($Return['hasRightMostBreak'] AND $MaxPages < $LastPage) - { - $Return['pages'][] = '_'; - } - if($LastPage != 1) - { - $Return['pages'][] = $LastPage; - } - - return $Return; -} - -function ParsePaginationArray($PaginationArray, $Page, $ElementTemplate, $ViewOptions = array()) -{ - if(empty($ElementTemplate)) - { - return array(); - } - - if(!empty($PaginationArray['pages'])) - { - // Initialization - global $_Lang; - if(!isset($_Lang['Pagination_Prev'])) - { - $_Lang['Pagination_Prev'] = '«'; - } - if(!isset($_Lang['Pagination_Next'])) - { - $_Lang['Pagination_Next'] = '»'; - } - $ReplaceFind = array('{$Classes}', '{$Value}', '{$ShowValue}'); - $Return = array(); - - if(isset($ViewOptions['OffsetValues']) && $ViewOptions['OffsetValues'] === true) - { - $ValuesAsOffset = true; - } - else - { - $ValuesAsOffset = false; - } - - // Parsing - if(isset($PaginationArray['hasPrev']) && $PaginationArray['hasPrev']) - { - $Return[] = str_replace($ReplaceFind, array('', ($ValuesAsOffset ? -1 : ($Page - 1)), $_Lang['Pagination_Prev']), $ElementTemplate); - } - foreach($PaginationArray['pages'] as $PageNo) - { - if($PageNo != '_') - { - $Return[] = str_replace - ( - $ReplaceFind, - array - ( - (($PageNo == $Page) ? $ViewOptions['CurrentPage_Classes'] : ''), - ($ValuesAsOffset ? ($PageNo - $Page) : $PageNo), - $PageNo - ), - $ElementTemplate - ); - } - else - { - $Return[] = $ViewOptions['Breaker_View']; - } - } - if(isset($PaginationArray['hasNext']) && $PaginationArray['hasNext']) - { - $Return[] = str_replace($ReplaceFind, array('', ($ValuesAsOffset ? 1 : ($Page + 1)), $_Lang['Pagination_Next']), $ElementTemplate); - } - - return $Return; - } - return array(); -} - -?> \ No newline at end of file += $LastPage) + { + $ThisPage = $LastPage; + $Return['hasNext'] = false; + $IsOnEdge = true; + } + if($MaxPages < 3) + { + // We have to show at least 3 pages + $MaxPages = 3; + } + + $ToShow = $MaxPages - 3; + if(($ToShow % 2) == 1 AND $ToShow > 0) + { + // If $ToShow is even number, cut one down + $ToShow -= 1; + $AddToOneSide = true; + } + + $LeftSide = $RightSide = ($ToShow / 2); + if($AddToOneSide) + { + if($ThisPage > (($LastPage + 1) / 2)) + { + $LeftSide += 1; + } + else + { + $RightSide += 1; + } + } + $LeftMost = ($ThisPage - $LeftSide); + $RightMost = ($ThisPage + $RightSide); + $StartToLeftMostDistance = $LeftMost - 1; + $EndToRightMostDistance = $LastPage - $RightMost; + if($StartToLeftMostDistance <= 1) + { + $Return['hasLeftMostBreak'] = false; + if($StartToLeftMostDistance < 1) + { + $Value = (($StartToLeftMostDistance - 1) * -1); + $RightSide += (($StartToLeftMostDistance - 1) * -1); + $RightMost += $Value; + } + } + if($EndToRightMostDistance <= 1) + { + $Return['hasRightMostBreak'] = false; + if($EndToRightMostDistance < 1) + { + $Value = (($EndToRightMostDistance - 1) * -1); + $LeftSide += $Value; + $LeftMost -= $Value; + } + } + + // Generate Elements Array + $Return['pages'][] = 1; + if($Return['hasLeftMostBreak'] AND $MaxPages < $LastPage) + { + $Return['pages'][] = '_'; + } + for($i = $LeftMost; $i < $ThisPage; $i += 1) + { + if($LeftSide <= 0) + { + break; + } + if($i <= 1) + { + $i = 1; + continue; + } + $Return['pages'][] = $i; + $LeftSide -= 1; + } + if($IsOnEdge === false) + { + $Return['pages'][] = $ThisPage; + } + for($i = ($ThisPage + 1); $i < $LastPage; $i += 1) + { + if($RightSide <= 0) + { + break; + } + $Return['pages'][] = $i; + $RightSide -= 1; + } + if($Return['hasRightMostBreak'] AND $MaxPages < $LastPage) + { + $Return['pages'][] = '_'; + } + if($LastPage != 1) + { + $Return['pages'][] = $LastPage; + } + + return $Return; +} + +function ParsePaginationArray($PaginationArray, $Page, $ElementTemplate, $ViewOptions = array()) +{ + if(empty($ElementTemplate)) + { + return array(); + } + + if(!empty($PaginationArray['pages'])) + { + // Initialization + global $_Lang; + if(!isset($_Lang['Pagination_Prev'])) + { + $_Lang['Pagination_Prev'] = '«'; + } + if(!isset($_Lang['Pagination_Next'])) + { + $_Lang['Pagination_Next'] = '»'; + } + $ReplaceFind = array('{$Classes}', '{$Value}', '{$ShowValue}'); + $Return = array(); + + if(isset($ViewOptions['OffsetValues']) && $ViewOptions['OffsetValues'] === true) + { + $ValuesAsOffset = true; + } + else + { + $ValuesAsOffset = false; + } + + // Parsing + if(isset($PaginationArray['hasPrev']) && $PaginationArray['hasPrev']) + { + $Return[] = str_replace($ReplaceFind, array('', ($ValuesAsOffset ? -1 : ($Page - 1)), $_Lang['Pagination_Prev']), $ElementTemplate); + } + foreach($PaginationArray['pages'] as $PageNo) + { + if($PageNo != '_') + { + $Return[] = str_replace + ( + $ReplaceFind, + array + ( + (($PageNo == $Page) ? $ViewOptions['CurrentPage_Classes'] : ''), + ($ValuesAsOffset ? ($PageNo - $Page) : $PageNo), + $PageNo + ), + $ElementTemplate + ); + } + else + { + $Return[] = $ViewOptions['Breaker_View']; + } + } + if(isset($PaginationArray['hasNext']) && $PaginationArray['hasNext']) + { + $Return[] = str_replace($ReplaceFind, array('', ($ValuesAsOffset ? 1 : ($Page + 1)), $_Lang['Pagination_Next']), $ElementTemplate); + } + + return $Return; + } + return array(); +} + +?> diff --git a/includes/functions/PlanetResourceUpdate.php b/includes/functions/PlanetResourceUpdate.php index 51186a7ba..32fb62b9b 100644 --- a/includes/functions/PlanetResourceUpdate.php +++ b/includes/functions/PlanetResourceUpdate.php @@ -1,503 +1,503 @@ - $Value) - { - $CurrentPlanet[$Key] = $Value['old']; - } - } - - $ProductionTime = ($UpdateTime - $CurrentPlanet['last_update']); - - // Update place for resources - $CurrentPlanet['metal_max'] = (floor(BASE_STORAGE_SIZE * pow(1.7, $CurrentPlanet[$_Vars_GameElements[22]]))); - $CurrentPlanet['crystal_max'] = (floor(BASE_STORAGE_SIZE * pow(1.7, $CurrentPlanet[$_Vars_GameElements[23]]))); - $CurrentPlanet['deuterium_max'] = (floor(BASE_STORAGE_SIZE * pow(1.7, $CurrentPlanet[$_Vars_GameElements[24]]))); - - // Start ResourceUpdating - if($CurrentPlanet['planet_type'] == 1) - { - // Calculate Officers Income Bonus - // - Geologist: Resource Bonus - if($ProductionTime > 0) - { - $Multiplier_Resources = 1; - $Add_Multiplier_Resources = 0; - if($CurrentUser['geologist_time'] > $CurrentPlanet['last_update']) - { - if($CurrentUser['geologist_time'] >= $UpdateTime) - { - $Add_Multiplier_Resources = $ProductionTime; - } - else - { - $Add_Multiplier_Resources = ($CurrentUser['geologist_time'] - $CurrentPlanet['last_update']); - } - $Multiplier_Resources += (0.15 * ($Add_Multiplier_Resources / $ProductionTime)); - } - // - Engineed: Energy Bonus - $Multiplier_Energy = 1; - $Add_Multiplier_Energy = 0; - if($CurrentUser['engineer_time'] > $CurrentPlanet['last_update']) - { - if($CurrentUser['engineer_time'] >= $UpdateTime) - { - $Add_Multiplier_Energy = $ProductionTime; - } - else - { - $Add_Multiplier_Energy = ($CurrentUser['engineer_time'] - $CurrentPlanet['last_update']); - } - $Multiplier_Energy += (0.10 * ($Add_Multiplier_Energy / $ProductionTime)); - } - } - else - { - if($CurrentUser['geologist_time'] >= $CurrentPlanet['last_update']) - { - $Multiplier_Resources = 1.15; - } - else - { - $Multiplier_Resources = 1; - } - if($CurrentUser['engineer_time'] >= $CurrentPlanet['last_update']) - { - $Multiplier_Energy = 1.10; - } - else - { - $Multiplier_Energy = 1; - } - } - - // Calculate Storage for Resources (with Overflow) - $MaxMetalStorage = $CurrentPlanet['metal_max'] * MAX_OVERFLOW; - $MaxCrystalStorage = $CurrentPlanet['crystal_max'] * MAX_OVERFLOW; - $MaxDeuteriumStorage = $CurrentPlanet['deuterium_max'] * MAX_OVERFLOW; - - // Calculate Income from Mines, Power Plants, Extractors etc. - $Caps = array - ( - 'metal_perhour' => 0, - 'crystal_perhour' => 0, - 'deuterium_perhour' => 0, - 'energy_used' => 0, - 'energy_max' => 0 - ); - $BuildTemp = $CurrentPlanet['temp_max']; - $TextIfEmpty = 'return "0";'; - foreach($_Vars_ElementCategories['prod'] as $ElementID) - { - $BuildLevelFactor = $CurrentPlanet[$_Vars_GameElements[$ElementID].'_workpercent']; - $BuildLevel = $CurrentPlanet[$_Vars_GameElements[$ElementID]]; - - if($BuildLevel <= 0) - { - continue; - } - - if($_Vars_ResProduction[$ElementID]['formule']['metal'] != $TextIfEmpty) - { - $Caps['metal_perhour'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['metal']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); - } - if($_Vars_ResProduction[$ElementID]['formule']['crystal'] != $TextIfEmpty) - { - $Caps['crystal_perhour'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['crystal']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); - } - if($ElementID != 12) - { - if($_Vars_ResProduction[$ElementID]['formule']['deuterium'] != $TextIfEmpty) - { - $Caps['deuterium_perhour'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); - } - } - else - { - $Caps['deuterium_perhour'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']); - } - - if($ElementID < 4) - { - $Caps['energy_used'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy'])); - } - else - { - if($ElementID != 12) - { - $Caps['energy_max'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $Multiplier_Energy); - } - else - { - $MineDeuteriumUse = floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']) * (-1); - if($MineDeuteriumUse > 0) - { - if($CurrentPlanet['deuterium'] <= 0) - { - if($Caps['deuterium_perhour'] == ($MineDeuteriumUse * (-1))) - { - // If no enough + production of deuterium - } - else - { - // If there is still some deuterium in + production to use - $FusionReactorMulti = ($Caps['deuterium_perhour'] + $MineDeuteriumUse) / $MineDeuteriumUse; - if($FusionReactorMulti > 1) - { - $FusionReactorMulti = 1; - } - $Caps['energy_max'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $FusionReactorMulti * $Multiplier_Energy); - } - } - else - { - if($Caps['deuterium_perhour'] >= 0) - { - $Caps['energy_max'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $Multiplier_Energy); - } - else - { - $FusionReactorMulti = $CurrentPlanet['deuterium'] / ($MineDeuteriumUse / 3600); - if($FusionReactorMulti > 1) - { - $FusionReactorMulti = 1; - } - $Caps['energy_max'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $FusionReactorMulti * $Multiplier_Energy); - } - } - } - } - } - } - - // Set current IncomeLevels - $CurrentPlanet['metal_perhour'] = $Caps['metal_perhour']; - $CurrentPlanet['crystal_perhour'] = $Caps['crystal_perhour']; - $CurrentPlanet['deuterium_perhour'] = $Caps['deuterium_perhour']; - $CurrentPlanet['energy_used'] = $Caps['energy_used']; - $CurrentPlanet['energy_max'] = $Caps['energy_max']; - - if($ProductionTime > 0) - { - // Calculate ProductionLevel - if(!isOnVacation($CurrentUser)) - { - if($Caps['energy_max'] == 0 AND abs($Caps['energy_used']) > 0) - { - $production_level = 0; - } - elseif($Caps['energy_max'] > 0 AND abs($Caps['energy_used']) > $Caps['energy_max']) - { - $production_level = floor(($Caps['energy_max'] * 100) / abs($Caps['energy_used'])); - } - else - { - $production_level = 100; - } - if($production_level > 100) - { - $production_level = 100; - } - } - else - { - // Protect against VacationMode - $production_level = 0; - } - - // Calculate TotalIncome - if($CurrentPlanet['metal'] < $MaxMetalStorage) - { - $Metal_BuildIncome= ($ProductionTime * ($Caps['metal_perhour'] / 3600)) * (0.01 * $production_level); - $Metal_BaseIncome = $ProductionTime * (($_GameConfig['metal_basic_income'] * $_GameConfig['resource_multiplier']) / 3600); - $Metal_TotalIncome = $Metal_BuildIncome + $Metal_BaseIncome; - $Metal_Theoretical = $CurrentPlanet['metal'] + $Metal_TotalIncome; - - if($Metal_Theoretical < 0) - { - $Metal_Theoretical = 0; - } - if($Metal_Theoretical < $MaxMetalStorage) - { - $CurrentPlanet['metal'] = $Metal_Theoretical; - } - else - { - $CurrentPlanet['metal'] = $MaxMetalStorage; - $Metal_TotalIncome -= ($Metal_Theoretical - $MaxMetalStorage); - } - } - if($CurrentPlanet['crystal'] < $MaxCrystalStorage) - { - $Crystal_BuildIncome= ($ProductionTime * ($Caps['crystal_perhour'] / 3600)) * (0.01 * $production_level); - $Crystal_BaseIncome = $ProductionTime * (($_GameConfig['crystal_basic_income'] * $_GameConfig['resource_multiplier']) / 3600); - $Crystal_TotalIncome = $Crystal_BuildIncome + $Crystal_BaseIncome; - $Crystal_Theoretical = $CurrentPlanet['crystal'] + $Crystal_TotalIncome; - - if($Crystal_Theoretical < 0) - { - $Crystal_Theoretical = 0; - } - if($Crystal_Theoretical < $MaxCrystalStorage) - { - $CurrentPlanet['crystal'] = $Crystal_Theoretical; - } - else - { - $CurrentPlanet['crystal'] = $MaxCrystalStorage; - $Crystal_TotalIncome -= ($Crystal_Theoretical - $MaxCrystalStorage); - } - } - if($CurrentPlanet['deuterium'] < $MaxDeuteriumStorage) - { - $Deuterium_BuildIncome= ($ProductionTime * ($Caps['deuterium_perhour'] / 3600)) * (0.01 * $production_level); - $Deuterium_BaseIncome = $ProductionTime * (($_GameConfig['deuterium_basic_income'] * $_GameConfig['resource_multiplier']) / 3600); - $Deuterium_TotalIncome = $Deuterium_BuildIncome + $Deuterium_BaseIncome; - $Deuterium_Theoretical = $CurrentPlanet['deuterium'] + $Deuterium_TotalIncome; - - if($Deuterium_Theoretical < 0) - { - $Deuterium_Theoretical = 0; - } - if($Deuterium_Theoretical < $MaxDeuteriumStorage) - { - $CurrentPlanet['deuterium'] = $Deuterium_Theoretical; - } - else - { - $CurrentPlanet['deuterium'] = $MaxDeuteriumStorage; - $Deuterium_TotalIncome -= ($Deuterium_Theoretical - $MaxDeuteriumStorage); - } - } - $NeedUpdate = true; - } - } - - // End of ResourceUpdate - $CurrentPlanet['last_update'] = $UpdateTime; - - if($Simul === false) - { - // Management of eventual shipyard Queue - $Builded = HandleShipyardQueue($CurrentUser, $CurrentPlanet, $ProductionTime, $UpdateTime); - - // Update planet - $QryUpdatePlanet = ''; - $QryUpdatePlanet .= "UPDATE {{table}} SET "; - $QryUpdatePlanet .= "`metal` = '{$CurrentPlanet['metal']}', "; - $QryUpdatePlanet .= "`crystal` = '{$CurrentPlanet['crystal']}', "; - $QryUpdatePlanet .= "`deuterium` = '{$CurrentPlanet['deuterium']}', "; - $QryUpdatePlanet .= "`last_update` = '{$CurrentPlanet['last_update']}', "; - $QryUpdatePlanet .= "`shipyardQueue` = '{$CurrentPlanet['shipyardQueue']}', "; - $QryUpdatePlanet .= "`metal_perhour` = '{$CurrentPlanet['metal_perhour']}', "; - $QryUpdatePlanet .= "`crystal_perhour` = '{$CurrentPlanet['crystal_perhour']}', "; - $QryUpdatePlanet .= "`deuterium_perhour` = '{$CurrentPlanet['deuterium_perhour']}', "; - $QryUpdatePlanet .= "`energy_used` = '{$CurrentPlanet['energy_used']}', "; - $QryUpdatePlanet .= "`energy_max` = '{$CurrentPlanet['energy_max']}', "; - // Check if something has been built in Shipyard - if(!empty($Builded)) - { - $NeedUpdate = true; - foreach($Builded as $Element => $Count) - { - if(!empty($_Vars_GameElements[$Element])) - { - $QryUpdatePlanet .= "`{$_Vars_GameElements[$Element]}` = `{$_Vars_GameElements[$Element]}` + {$Count}, "; - } - } - } - $QryUpdatePlanet .= "`shipyardQueue_additionalWorkTime` = '{$CurrentPlanet['shipyardQueue_additionalWorkTime']}' "; - $QryUpdatePlanet .= "WHERE "; - $QryUpdatePlanet .= "`id` = {$CurrentPlanet['id']};"; - - doquery('LOCK TABLE {{table}} WRITE, {{prefix}}errors WRITE', 'planets'); - $Last_DontShowMenus = $_DontShowMenus; - $_DontShowMenus= true; - doquery($QryUpdatePlanet, 'planets'); - doquery('UNLOCK TABLES', ''); - $_DontShowMenus = $Last_DontShowMenus; - } - - if(!empty($SetPercents[$CurrentPlanet['id']]) AND $CurrentPlanet['planet_type'] == 1) - { - foreach($SetPercents[$CurrentPlanet['id']] as $Key => $Value) - { - foreach($_Vars_ElementCategories['prod'] as $ProdID) - { - if($_Vars_GameElements[$ProdID].'_workpercent' == $Key) - { - $CalcDiff = array(); - - $BuildLevelFactor = $CurrentPlanet[$_Vars_GameElements[$ProdID].'_workpercent']; - $BuildLevel = $CurrentPlanet[$_Vars_GameElements[$ProdID]]; - - if($BuildLevel <= 0) - { - // Don't waste time to calculate 0 production... - continue; - } - - if($_Vars_ResProduction[$ProdID]['formule']['metal'] != $TextIfEmpty) - { - $BuildLevelFactor = $Value['old']; - $CalcDiff['metal_perhour']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['metal']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); - $BuildLevelFactor = $Value['new']; - $CalcDiff['metal_perhour']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['metal']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); - } - if($_Vars_ResProduction[$ProdID]['formule']['crystal'] != $TextIfEmpty) - { - $BuildLevelFactor = $Value['old']; - $CalcDiff['crystal_perhour']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['crystal']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); - $BuildLevelFactor = $Value['new']; - $CalcDiff['crystal_perhour']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['crystal']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); - } - if($ProdID != 12) - { - if($_Vars_ResProduction[$ProdID]['formule']['deuterium'] != $TextIfEmpty) - { - $BuildLevelFactor = $Value['old']; - $CalcDiff['deuterium_perhour']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['deuterium']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); - $BuildLevelFactor = $Value['new']; - $CalcDiff['deuterium_perhour']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['deuterium']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); - } - } - else - { - $BuildLevelFactor = $Value['old']; - $CalcDiff['deuterium_perhour']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']); - $BuildLevelFactor = $Value['new']; - $CalcDiff['deuterium_perhour']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']); - } - - if($ProdID < 4) - { - $BuildLevelFactor = $Value['old']; - $CalcDiff['energy_used']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy'])); - $BuildLevelFactor = $Value['new']; - $CalcDiff['energy_used']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy'])); - } - elseif($ProdID >= 4 ) - { - if($ProdID != 12) - { - $BuildLevelFactor = $Value['old']; - $CalcDiff['energy_max']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $Multiplier_Energy); - $BuildLevelFactor = $Value['new']; - $CalcDiff['energy_max']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $Multiplier_Energy); - } - else - { - $BuildLevelFactor = $Value['old']; - $MineDeuteriumUse = floor(eval($_Vars_ResProduction[$ProdID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']) * (-1); - if($MineDeuteriumUse > 0) - { - if($CurrentPlanet['deuterium'] <= 0) - { - if($CurrentPlanet['deuterium_perhour'] <= ($MineDeuteriumUse * (-1))) - { - // If no enough + production of deuterium - $CalcDiff['energy_max']['old'] = 0; - } - else - { - // If there is still some deuterium in + production to use - $FusionReactorMulti = ($CurrentPlanet['deuterium_perhour'] + $MineDeuteriumUse) / $MineDeuteriumUse; - if($FusionReactorMulti > 1) - { - $FusionReactorMulti = 1; - } - $CalcDiff['energy_max']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $FusionReactorMulti * $Multiplier_Energy); - } - } - else - { - if($CurrentPlanet['deuterium_perhour'] >= 0) - { - $CalcDiff['energy_max']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $Multiplier_Energy); - } - else - { - $FusionReactorMulti = $CurrentPlanet['deuterium'] / ($MineDeuteriumUse / 3600); - if($FusionReactorMulti > 1) - { - $FusionReactorMulti = 1; - } - $CalcDiff['energy_max']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $FusionReactorMulti * $Multiplier_Energy); - } - } - } - else - { - $CalcDiff['energy_max']['old'] = 0; - } - - $CurrentPlanet['deuterium_perhour'] += $CalcDiff['deuterium_perhour']['new'] - $CalcDiff['deuterium_perhour']['old']; - unset($CalcDiff['deuterium_perhour']); - - $BuildLevelFactor = $Value['new']; - $MineDeuteriumUse = floor(eval($_Vars_ResProduction[$ProdID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']) * (-1); - if($MineDeuteriumUse > 0) - { - if($CurrentPlanet['deuterium'] <= 0) - { - if($CurrentPlanet['deuterium_perhour'] <= ($MineDeuteriumUse * (-1))) - { - // If no enough + production of deuterium - $CalcDiff['energy_max']['new'] = 0; - } - else - { - // If there is still some deuterium in + production to use - $FusionReactorMulti = ($CurrentPlanet['deuterium_perhour'] + $MineDeuteriumUse) / $MineDeuteriumUse; - if($FusionReactorMulti > 1) - { - $FusionReactorMulti = 1; - } - $CalcDiff['energy_max']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $FusionReactorMulti * $Multiplier_Energy); - } - } - else - { - if($CurrentPlanet['deuterium_perhour'] >= 0) - { - $CalcDiff['energy_max']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $Multiplier_Energy); - } - else - { - $FusionReactorMulti = $CurrentPlanet['deuterium'] / ($MineDeuteriumUse / 3600); - if($FusionReactorMulti > 1) - { - $FusionReactorMulti = 1; - } - $CalcDiff['energy_max']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $FusionReactorMulti * $Multiplier_Energy); - } - } - } - else - { - $CalcDiff['energy_max']['new'] = 0; - } - } - } - - foreach($CalcDiff as $Key => $Values) - { - $CalcThatDiff = $Values['new'] - $Values['old']; - $CurrentPlanet[$Key] += $CalcThatDiff; - } - } - } - } - } - - return $NeedUpdate; -} - -?> \ No newline at end of file + $Value) + { + $CurrentPlanet[$Key] = $Value['old']; + } + } + + $ProductionTime = ($UpdateTime - $CurrentPlanet['last_update']); + + // Update place for resources + $CurrentPlanet['metal_max'] = (floor(BASE_STORAGE_SIZE * pow(1.7, $CurrentPlanet[$_Vars_GameElements[22]]))); + $CurrentPlanet['crystal_max'] = (floor(BASE_STORAGE_SIZE * pow(1.7, $CurrentPlanet[$_Vars_GameElements[23]]))); + $CurrentPlanet['deuterium_max'] = (floor(BASE_STORAGE_SIZE * pow(1.7, $CurrentPlanet[$_Vars_GameElements[24]]))); + + // Start ResourceUpdating + if($CurrentPlanet['planet_type'] == 1) + { + // Calculate Officers Income Bonus + // - Geologist: Resource Bonus + if($ProductionTime > 0) + { + $Multiplier_Resources = 1; + $Add_Multiplier_Resources = 0; + if($CurrentUser['geologist_time'] > $CurrentPlanet['last_update']) + { + if($CurrentUser['geologist_time'] >= $UpdateTime) + { + $Add_Multiplier_Resources = $ProductionTime; + } + else + { + $Add_Multiplier_Resources = ($CurrentUser['geologist_time'] - $CurrentPlanet['last_update']); + } + $Multiplier_Resources += (0.15 * ($Add_Multiplier_Resources / $ProductionTime)); + } + // - Engineed: Energy Bonus + $Multiplier_Energy = 1; + $Add_Multiplier_Energy = 0; + if($CurrentUser['engineer_time'] > $CurrentPlanet['last_update']) + { + if($CurrentUser['engineer_time'] >= $UpdateTime) + { + $Add_Multiplier_Energy = $ProductionTime; + } + else + { + $Add_Multiplier_Energy = ($CurrentUser['engineer_time'] - $CurrentPlanet['last_update']); + } + $Multiplier_Energy += (0.10 * ($Add_Multiplier_Energy / $ProductionTime)); + } + } + else + { + if($CurrentUser['geologist_time'] >= $CurrentPlanet['last_update']) + { + $Multiplier_Resources = 1.15; + } + else + { + $Multiplier_Resources = 1; + } + if($CurrentUser['engineer_time'] >= $CurrentPlanet['last_update']) + { + $Multiplier_Energy = 1.10; + } + else + { + $Multiplier_Energy = 1; + } + } + + // Calculate Storage for Resources (with Overflow) + $MaxMetalStorage = $CurrentPlanet['metal_max'] * MAX_OVERFLOW; + $MaxCrystalStorage = $CurrentPlanet['crystal_max'] * MAX_OVERFLOW; + $MaxDeuteriumStorage = $CurrentPlanet['deuterium_max'] * MAX_OVERFLOW; + + // Calculate Income from Mines, Power Plants, Extractors etc. + $Caps = array + ( + 'metal_perhour' => 0, + 'crystal_perhour' => 0, + 'deuterium_perhour' => 0, + 'energy_used' => 0, + 'energy_max' => 0 + ); + $BuildTemp = $CurrentPlanet['temp_max']; + $TextIfEmpty = 'return "0";'; + foreach($_Vars_ElementCategories['prod'] as $ElementID) + { + $BuildLevelFactor = $CurrentPlanet[$_Vars_GameElements[$ElementID].'_workpercent']; + $BuildLevel = $CurrentPlanet[$_Vars_GameElements[$ElementID]]; + + if($BuildLevel <= 0) + { + continue; + } + + if($_Vars_ResProduction[$ElementID]['formule']['metal'] != $TextIfEmpty) + { + $Caps['metal_perhour'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['metal']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); + } + if($_Vars_ResProduction[$ElementID]['formule']['crystal'] != $TextIfEmpty) + { + $Caps['crystal_perhour'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['crystal']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); + } + if($ElementID != 12) + { + if($_Vars_ResProduction[$ElementID]['formule']['deuterium'] != $TextIfEmpty) + { + $Caps['deuterium_perhour'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); + } + } + else + { + $Caps['deuterium_perhour'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']); + } + + if($ElementID < 4) + { + $Caps['energy_used'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy'])); + } + else + { + if($ElementID != 12) + { + $Caps['energy_max'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $Multiplier_Energy); + } + else + { + $MineDeuteriumUse = floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']) * (-1); + if($MineDeuteriumUse > 0) + { + if($CurrentPlanet['deuterium'] <= 0) + { + if($Caps['deuterium_perhour'] == ($MineDeuteriumUse * (-1))) + { + // If no enough + production of deuterium + } + else + { + // If there is still some deuterium in + production to use + $FusionReactorMulti = ($Caps['deuterium_perhour'] + $MineDeuteriumUse) / $MineDeuteriumUse; + if($FusionReactorMulti > 1) + { + $FusionReactorMulti = 1; + } + $Caps['energy_max'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $FusionReactorMulti * $Multiplier_Energy); + } + } + else + { + if($Caps['deuterium_perhour'] >= 0) + { + $Caps['energy_max'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $Multiplier_Energy); + } + else + { + $FusionReactorMulti = $CurrentPlanet['deuterium'] / ($MineDeuteriumUse / 3600); + if($FusionReactorMulti > 1) + { + $FusionReactorMulti = 1; + } + $Caps['energy_max'] += floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $FusionReactorMulti * $Multiplier_Energy); + } + } + } + } + } + } + + // Set current IncomeLevels + $CurrentPlanet['metal_perhour'] = $Caps['metal_perhour']; + $CurrentPlanet['crystal_perhour'] = $Caps['crystal_perhour']; + $CurrentPlanet['deuterium_perhour'] = $Caps['deuterium_perhour']; + $CurrentPlanet['energy_used'] = $Caps['energy_used']; + $CurrentPlanet['energy_max'] = $Caps['energy_max']; + + if($ProductionTime > 0) + { + // Calculate ProductionLevel + if(!isOnVacation($CurrentUser)) + { + if($Caps['energy_max'] == 0 AND abs($Caps['energy_used']) > 0) + { + $production_level = 0; + } + elseif($Caps['energy_max'] > 0 AND abs($Caps['energy_used']) > $Caps['energy_max']) + { + $production_level = floor(($Caps['energy_max'] * 100) / abs($Caps['energy_used'])); + } + else + { + $production_level = 100; + } + if($production_level > 100) + { + $production_level = 100; + } + } + else + { + // Protect against VacationMode + $production_level = 0; + } + + // Calculate TotalIncome + if($CurrentPlanet['metal'] < $MaxMetalStorage) + { + $Metal_BuildIncome= ($ProductionTime * ($Caps['metal_perhour'] / 3600)) * (0.01 * $production_level); + $Metal_BaseIncome = $ProductionTime * (($_GameConfig['metal_basic_income'] * $_GameConfig['resource_multiplier']) / 3600); + $Metal_TotalIncome = $Metal_BuildIncome + $Metal_BaseIncome; + $Metal_Theoretical = $CurrentPlanet['metal'] + $Metal_TotalIncome; + + if($Metal_Theoretical < 0) + { + $Metal_Theoretical = 0; + } + if($Metal_Theoretical < $MaxMetalStorage) + { + $CurrentPlanet['metal'] = $Metal_Theoretical; + } + else + { + $CurrentPlanet['metal'] = $MaxMetalStorage; + $Metal_TotalIncome -= ($Metal_Theoretical - $MaxMetalStorage); + } + } + if($CurrentPlanet['crystal'] < $MaxCrystalStorage) + { + $Crystal_BuildIncome= ($ProductionTime * ($Caps['crystal_perhour'] / 3600)) * (0.01 * $production_level); + $Crystal_BaseIncome = $ProductionTime * (($_GameConfig['crystal_basic_income'] * $_GameConfig['resource_multiplier']) / 3600); + $Crystal_TotalIncome = $Crystal_BuildIncome + $Crystal_BaseIncome; + $Crystal_Theoretical = $CurrentPlanet['crystal'] + $Crystal_TotalIncome; + + if($Crystal_Theoretical < 0) + { + $Crystal_Theoretical = 0; + } + if($Crystal_Theoretical < $MaxCrystalStorage) + { + $CurrentPlanet['crystal'] = $Crystal_Theoretical; + } + else + { + $CurrentPlanet['crystal'] = $MaxCrystalStorage; + $Crystal_TotalIncome -= ($Crystal_Theoretical - $MaxCrystalStorage); + } + } + if($CurrentPlanet['deuterium'] < $MaxDeuteriumStorage) + { + $Deuterium_BuildIncome= ($ProductionTime * ($Caps['deuterium_perhour'] / 3600)) * (0.01 * $production_level); + $Deuterium_BaseIncome = $ProductionTime * (($_GameConfig['deuterium_basic_income'] * $_GameConfig['resource_multiplier']) / 3600); + $Deuterium_TotalIncome = $Deuterium_BuildIncome + $Deuterium_BaseIncome; + $Deuterium_Theoretical = $CurrentPlanet['deuterium'] + $Deuterium_TotalIncome; + + if($Deuterium_Theoretical < 0) + { + $Deuterium_Theoretical = 0; + } + if($Deuterium_Theoretical < $MaxDeuteriumStorage) + { + $CurrentPlanet['deuterium'] = $Deuterium_Theoretical; + } + else + { + $CurrentPlanet['deuterium'] = $MaxDeuteriumStorage; + $Deuterium_TotalIncome -= ($Deuterium_Theoretical - $MaxDeuteriumStorage); + } + } + $NeedUpdate = true; + } + } + + // End of ResourceUpdate + $CurrentPlanet['last_update'] = $UpdateTime; + + if($Simul === false) + { + // Management of eventual shipyard Queue + $Builded = HandleShipyardQueue($CurrentUser, $CurrentPlanet, $ProductionTime, $UpdateTime); + + // Update planet + $QryUpdatePlanet = ''; + $QryUpdatePlanet .= "UPDATE {{table}} SET "; + $QryUpdatePlanet .= "`metal` = '{$CurrentPlanet['metal']}', "; + $QryUpdatePlanet .= "`crystal` = '{$CurrentPlanet['crystal']}', "; + $QryUpdatePlanet .= "`deuterium` = '{$CurrentPlanet['deuterium']}', "; + $QryUpdatePlanet .= "`last_update` = '{$CurrentPlanet['last_update']}', "; + $QryUpdatePlanet .= "`shipyardQueue` = '{$CurrentPlanet['shipyardQueue']}', "; + $QryUpdatePlanet .= "`metal_perhour` = '{$CurrentPlanet['metal_perhour']}', "; + $QryUpdatePlanet .= "`crystal_perhour` = '{$CurrentPlanet['crystal_perhour']}', "; + $QryUpdatePlanet .= "`deuterium_perhour` = '{$CurrentPlanet['deuterium_perhour']}', "; + $QryUpdatePlanet .= "`energy_used` = '{$CurrentPlanet['energy_used']}', "; + $QryUpdatePlanet .= "`energy_max` = '{$CurrentPlanet['energy_max']}', "; + // Check if something has been built in Shipyard + if(!empty($Builded)) + { + $NeedUpdate = true; + foreach($Builded as $Element => $Count) + { + if(!empty($_Vars_GameElements[$Element])) + { + $QryUpdatePlanet .= "`{$_Vars_GameElements[$Element]}` = `{$_Vars_GameElements[$Element]}` + {$Count}, "; + } + } + } + $QryUpdatePlanet .= "`shipyardQueue_additionalWorkTime` = '{$CurrentPlanet['shipyardQueue_additionalWorkTime']}' "; + $QryUpdatePlanet .= "WHERE "; + $QryUpdatePlanet .= "`id` = {$CurrentPlanet['id']};"; + + doquery('LOCK TABLE {{table}} WRITE, {{prefix}}errors WRITE', 'planets'); + $Last_DontShowMenus = $_DontShowMenus; + $_DontShowMenus= true; + doquery($QryUpdatePlanet, 'planets'); + doquery('UNLOCK TABLES', ''); + $_DontShowMenus = $Last_DontShowMenus; + } + + if(!empty($SetPercents[$CurrentPlanet['id']]) AND $CurrentPlanet['planet_type'] == 1) + { + foreach($SetPercents[$CurrentPlanet['id']] as $Key => $Value) + { + foreach($_Vars_ElementCategories['prod'] as $ProdID) + { + if($_Vars_GameElements[$ProdID].'_workpercent' == $Key) + { + $CalcDiff = array(); + + $BuildLevelFactor = $CurrentPlanet[$_Vars_GameElements[$ProdID].'_workpercent']; + $BuildLevel = $CurrentPlanet[$_Vars_GameElements[$ProdID]]; + + if($BuildLevel <= 0) + { + // Don't waste time to calculate 0 production... + continue; + } + + if($_Vars_ResProduction[$ProdID]['formule']['metal'] != $TextIfEmpty) + { + $BuildLevelFactor = $Value['old']; + $CalcDiff['metal_perhour']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['metal']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); + $BuildLevelFactor = $Value['new']; + $CalcDiff['metal_perhour']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['metal']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); + } + if($_Vars_ResProduction[$ProdID]['formule']['crystal'] != $TextIfEmpty) + { + $BuildLevelFactor = $Value['old']; + $CalcDiff['crystal_perhour']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['crystal']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); + $BuildLevelFactor = $Value['new']; + $CalcDiff['crystal_perhour']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['crystal']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); + } + if($ProdID != 12) + { + if($_Vars_ResProduction[$ProdID]['formule']['deuterium'] != $TextIfEmpty) + { + $BuildLevelFactor = $Value['old']; + $CalcDiff['deuterium_perhour']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['deuterium']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); + $BuildLevelFactor = $Value['new']; + $CalcDiff['deuterium_perhour']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['deuterium']) * $_GameConfig['resource_multiplier'] * $Multiplier_Resources); + } + } + else + { + $BuildLevelFactor = $Value['old']; + $CalcDiff['deuterium_perhour']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']); + $BuildLevelFactor = $Value['new']; + $CalcDiff['deuterium_perhour']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']); + } + + if($ProdID < 4) + { + $BuildLevelFactor = $Value['old']; + $CalcDiff['energy_used']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy'])); + $BuildLevelFactor = $Value['new']; + $CalcDiff['energy_used']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy'])); + } + elseif($ProdID >= 4 ) + { + if($ProdID != 12) + { + $BuildLevelFactor = $Value['old']; + $CalcDiff['energy_max']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $Multiplier_Energy); + $BuildLevelFactor = $Value['new']; + $CalcDiff['energy_max']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $Multiplier_Energy); + } + else + { + $BuildLevelFactor = $Value['old']; + $MineDeuteriumUse = floor(eval($_Vars_ResProduction[$ProdID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']) * (-1); + if($MineDeuteriumUse > 0) + { + if($CurrentPlanet['deuterium'] <= 0) + { + if($CurrentPlanet['deuterium_perhour'] <= ($MineDeuteriumUse * (-1))) + { + // If no enough + production of deuterium + $CalcDiff['energy_max']['old'] = 0; + } + else + { + // If there is still some deuterium in + production to use + $FusionReactorMulti = ($CurrentPlanet['deuterium_perhour'] + $MineDeuteriumUse) / $MineDeuteriumUse; + if($FusionReactorMulti > 1) + { + $FusionReactorMulti = 1; + } + $CalcDiff['energy_max']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $FusionReactorMulti * $Multiplier_Energy); + } + } + else + { + if($CurrentPlanet['deuterium_perhour'] >= 0) + { + $CalcDiff['energy_max']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $Multiplier_Energy); + } + else + { + $FusionReactorMulti = $CurrentPlanet['deuterium'] / ($MineDeuteriumUse / 3600); + if($FusionReactorMulti > 1) + { + $FusionReactorMulti = 1; + } + $CalcDiff['energy_max']['old'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $FusionReactorMulti * $Multiplier_Energy); + } + } + } + else + { + $CalcDiff['energy_max']['old'] = 0; + } + + $CurrentPlanet['deuterium_perhour'] += $CalcDiff['deuterium_perhour']['new'] - $CalcDiff['deuterium_perhour']['old']; + unset($CalcDiff['deuterium_perhour']); + + $BuildLevelFactor = $Value['new']; + $MineDeuteriumUse = floor(eval($_Vars_ResProduction[$ProdID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']) * (-1); + if($MineDeuteriumUse > 0) + { + if($CurrentPlanet['deuterium'] <= 0) + { + if($CurrentPlanet['deuterium_perhour'] <= ($MineDeuteriumUse * (-1))) + { + // If no enough + production of deuterium + $CalcDiff['energy_max']['new'] = 0; + } + else + { + // If there is still some deuterium in + production to use + $FusionReactorMulti = ($CurrentPlanet['deuterium_perhour'] + $MineDeuteriumUse) / $MineDeuteriumUse; + if($FusionReactorMulti > 1) + { + $FusionReactorMulti = 1; + } + $CalcDiff['energy_max']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $FusionReactorMulti * $Multiplier_Energy); + } + } + else + { + if($CurrentPlanet['deuterium_perhour'] >= 0) + { + $CalcDiff['energy_max']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $Multiplier_Energy); + } + else + { + $FusionReactorMulti = $CurrentPlanet['deuterium'] / ($MineDeuteriumUse / 3600); + if($FusionReactorMulti > 1) + { + $FusionReactorMulti = 1; + } + $CalcDiff['energy_max']['new'] = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $FusionReactorMulti * $Multiplier_Energy); + } + } + } + else + { + $CalcDiff['energy_max']['new'] = 0; + } + } + } + + foreach($CalcDiff as $Key => $Values) + { + $CalcThatDiff = $Values['new'] - $Values['old']; + $CurrentPlanet[$Key] += $CalcThatDiff; + } + } + } + } + } + + return $NeedUpdate; +} + +?> diff --git a/includes/functions/PostResearchSaveChanges.php b/includes/functions/PostResearchSaveChanges.php index e8cff289e..fb1bffc95 100644 --- a/includes/functions/PostResearchSaveChanges.php +++ b/includes/functions/PostResearchSaveChanges.php @@ -1,24 +1,24 @@ - 0) - { - $QryUpdateUser = "UPDATE {{table}} SET "; - $QryUpdateUser .= "`techQueue_Planet` = '0', `techQueue_EndTime` = '0' "; - $QryUpdateUser .= "WHERE `id` = {$UpdateUser['id']};"; - doquery($QryUpdateUser, 'users'); - } -} - -?> \ No newline at end of file + 0) + { + $QryUpdateUser = "UPDATE {{table}} SET "; + $QryUpdateUser .= "`techQueue_Planet` = '0', `techQueue_EndTime` = '0' "; + $QryUpdateUser .= "WHERE `id` = {$UpdateUser['id']};"; + doquery($QryUpdateUser, 'users'); + } +} + +?> diff --git a/includes/functions/ReadBattleReport.php b/includes/functions/ReadBattleReport.php index 07548b1be..05543e60c 100644 --- a/includes/functions/ReadBattleReport.php +++ b/includes/functions/ReadBattleReport.php @@ -1,423 +1,423 @@ -{$_Lang['sys_mess_attacker_lost_in_1_round']}"; - } - $ReportData = json_decode($Report['report'], true); - - $Every1FromTeamDestroyed = false; - // End of Temp variables - - // All Rounds - $Rounds = $ReportData['rounds']; - // Battle Result - $Result = $ReportData['init']['result']; - $Stolen['met'] = $ReportData['init']['met']; - $Stolen['cry'] = $ReportData['init']['cry']; - $Stolen['deu'] = $ReportData['init']['deu']; - $Debris['met'] = $ReportData['init']['deb_met']; - $Debris['cry'] = $ReportData['init']['deb_cry']; - $MoonChance = $ReportData['init']['moon_chance']; - $TotalMoonChance = $ReportData['init']['total_moon_chance']; - $CreatedMoon = $ReportData['init']['moon_created']; - $MoonDestroyed = $ReportData['init']['moon_destroyed']; - $DestroyMoonChance = $ReportData['init']['moon_des_chance']; - $FleetDestroyed = $ReportData['init']['fleet_destroyed']; - $DestroyFleetChance = $ReportData['init']['fleet_des_chance']; - $PlanetName = $ReportData['init']['planet_name']; - $IsOnMoon = $ReportData['init']['onMoon']; - $LostUnits['atk'] = $ReportData['init']['atk_lost']; - $LostUnits['def'] = $ReportData['init']['def_lost']; - // Misc. - $GenerateTime = $ReportData['init']['time']; - // UsersData - $UsersData['atk'] = $ReportData['init']['usr']['atk']; - $UsersData['def'] = $ReportData['init']['usr']['def']; - $AddedUsernames = array('atk' => array(), 'def' => array()); - foreach($UsersData as $TypeKey => $AllUsers) - { - foreach($AllUsers as $UserKey => $UserVal) - { - if(empty($UserVal['username'])) - { - $UserVal['username'] = '-'; - } - if(!in_array($UserVal['username'], $AddedUsernames[$TypeKey])) - { - $AddedUsernames[$TypeKey][] = $UserVal['username']; - $Usernames[$TypeKey][] = "{$UserVal['username']}"; - } - } - } - - $Title = sprintf($_Lang['sys_attack_title'], prettyDate('(d m Y - H:i:s)', $ReportData['init']['date'], 1)); - $UsersFighting = implode(', ', $Usernames['atk']).' '.$_Lang['sys_battle_versus'].' '.implode(', ', $Usernames['def']); - $ReportCode = ''; - $ReportCode .= ""; - - if($Rounds === (array)$Rounds) - { - // General Templates - $GeneralTPL['ships'] = array - ( - "", - "", - "", - "", - "", - ); - - // Parse UsersData - $Users = array(); - foreach($UsersData as $TypeKey => $AllUsers) - { - foreach($AllUsers as $UserKey => $UserVal) - { - if(empty($UserVal['username'])) - { - $UserVal['username'] = $_Lang['sys_attack_defender_abandoned_'.($IsOnMoon ? '3' : '1')]; - } - $Pointer = &$Users[$TypeKey][$UserKey]; - $Temp = explode(':', $UserVal['pos']); - $Pointer['pos'] = array('g' => $Temp[0], 's' => $Temp[1], 'p' => $Temp[2]); - $Pointer['techs'] = String2Array($UserVal['techs']); - $Pointer['name'] = sprintf(($TypeKey == 'atk' ? $_Lang['sys_attack_attacker_pos'] : $_Lang['sys_attack_defender_pos']), $UserVal['username'], (empty($UserVal['ally']) ? '' : "[{$UserVal['ally']}]"), $Temp[0], $Temp[1], $Temp[2], $Temp[0], $Temp[1], $Temp[2]); - $Pointer['tech'] = sprintf($_Lang['sys_attack_techologies'], 100 + ($Pointer['techs'][109] * 10), 100 + ($Pointer['techs'][110] * 10), 100 + ($Pointer['techs'][111] * 10)); - $Pointer['techval'] = array('atk' => 1 + (0.1 * $Pointer['techs'][109]), 'shield' => 1 + (0.1 * $Pointer['techs'][110]), 'def' => 1 + (0.1 * $Pointer['techs'][111])); - $Pointer['TotalForceFactor'] = 1; - $Pointer['TotalShieldFactor'] = 1; - - $Pointer['morale'] = null; - if(isset($UserVal['morale']) && $UserVal['morale'] !== null) - { - // Bonuses - if($UserVal['morale'] >= MORALE_BONUS_FLEETPOWERUP1) - { - $Pointer['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; - } - if($UserVal['morale'] >= MORALE_BONUS_FLEETSHIELDUP1) - { - $Pointer['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; - } - // Penalties - if($UserVal['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN1) - { - $Pointer['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; - } - if($UserVal['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN2) - { - $Pointer['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; - } - if($UserVal['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) - { - $Pointer['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; - } - if($UserVal['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) - { - $Pointer['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; - } - - $Pointer['morale'] = sprintf($_Lang['sys_attack_morale'], $UserVal['morale']); - $UserMap[$UserVal['id']] = &$UsersData[$TypeKey][$UserKey]; - } - $Pointer['header'] = "
    {$Pointer['name']}
    {$Pointer['tech']}{$Pointer['morale']}"; - } - } - - foreach($Rounds as $Number => $Data) - { - foreach($Data as $TypeKey => $InnerData) - { - if((array)$InnerData['ships'] === $InnerData['ships']) - { - // If ShipsArray is OK (has some ships) - foreach($Users[$TypeKey] as $UserID => $UserData) - { - if(isset($Destroyed[$TypeKey][$UserID])) - { - continue; - } - - $ThisRoundCode = "'; - $ThisRoundArray[] = $ThisRoundCode; - $ThisRoundArray[] = ''; - } - } - else - { - // ShipArray is empty (no ships at all) - foreach($Users[$TypeKey] as $UserID => $UserData) - { - if(isset($Destroyed[$TypeKey][$UserID])) - { - continue; - } - - $ThisRoundCode = ''; - $ThisRoundCode .= ""; - $ThisRoundArray[] = $ThisRoundCode; - $ThisRoundArray[] = ''; - } - $Every1FromTeamDestroyed = true; - } - array_pop($ThisRoundArray); - $ThisRoundArray[] = ''; - } - if($Every1FromTeamDestroyed === false AND $Number <= BATTLE_MAX_ROUNDS) - { - $AttackWaveStat = sprintf($_Lang['sys_attack_wave'], ((count($Data['atk']['ships']) > 1) ? $_Lang['sys_msg_atk_fleets'] : $_Lang['sys_msg_atk_fleet']), prettyNumber($Data['atk']['count']), (($Data['atk']['count'] > 1) ? $_Lang['sys_x_times'] : ''),prettyNumber (floor($Data['atk']['force'])), ((count($Data['def']['ships']) > 1) ? $_Lang['sys_msg_into_defs'] : $_Lang['sys_msg_into_def']), ((count($Data['def']['ships']) > 1) ? $_Lang['sys_msg_into_defs'] : $_Lang['sys_msg_into_def_shield']), prettyNumber(floor($Data['def']['shield']))); - $DefendWavaStat = sprintf($_Lang['sys_attack_wave'], ((count($Data['def']['ships']) > 1) ? $_Lang['sys_msg_def_fleets'] : $_Lang['sys_msg_def_fleet']), prettyNumber($Data['def']['count']), (($Data['def']['count'] > 1) ? $_Lang['sys_x_times'] : ''),prettyNumber (floor($Data['def']['force'])), ((count($Data['atk']['ships']) > 1) ? $_Lang['sys_msg_into_atks'] : $_Lang['sys_msg_into_atk']), ((count($Data['atk']['ships']) > 1) ? $_Lang['sys_msg_into_atks'] : $_Lang['sys_msg_into_atk']), prettyNumber(floor($Data['atk']['shield']))); - - $ThisRoundArray[] = ""; - $ThisRoundArray[] = ''; - } - } - array_pop($ThisRoundArray); - $ReportCode .= implode('', $ThisRoundArray); - } - else - { - $ReportCode .= ''; - } - - $ReportCode .= ''; - - if(!empty($MoonDestroyText)) - { - $ReportCode .= ''; - $ReportCode .= ''; - } - - if(!empty($ReportData['morale'])) - { - $ReportCode .= ''; - foreach($ReportData['morale'] as $ThisUserID => $ThisData) - { - if($ThisData['usertype'] == 'atk') - { - if($ThisData['type'] === MORALE_POSITIVE) - { - $ThisMessage = $_Lang['BattleReport_Morale_Attacker_Positive']; - } - else - { - $ThisMessage = $_Lang['BattleReport_Morale_Attacker_Negative']; - } - } - else - { - $ThisMessage = $_Lang['BattleReport_Morale_Defender_Positive']; - } - - $ReportCode .= ''; - } - } - - $ReportCode .= '
    {$Title}
    {$UsersFighting}
    {$_Lang['sys_ship_type']}
    {$_Lang['sys_ship_count']}
    {$_Lang['sys_ship_weapon']}
    {$_Lang['sys_ship_shield']}
    {$_Lang['sys_ship_armour']}
    {$UserData['header']}"; - if(!empty($InnerData['ships'][$UserID])) - { - // If User has Ships (not destroyed) - $ThisRoundCode .= ''; - $ShipsLoop = 0; - - $TableRow = $GeneralTPL['ships']; - - $InnerData['ships'][$UserID] = String2Array($InnerData['ships'][$UserID]); - $ShipsCount = count($InnerData['ships'][$UserID]); - foreach($InnerData['ships'][$UserID] as $ShipID => $ShipCount) - { - $ShipsLoop += 1; - $ShipsCount -= 1; - if(!isset($ShipCalculations[$TypeKey][$UserID][$ShipID])) - { - // Calculate ShipValues if it's our first time here - $ForceUpgrade = 0; - if(!empty($_Vars_CombatUpgrades[$ShipID])) - { - foreach($_Vars_CombatUpgrades[$ShipID] as $UpTech => $ReqLevel) - { - $TechAvailable = $UserData['techs'][$UpTech]; - if($TechAvailable > $ReqLevel) - { - $ForceUpgrade += ($TechAvailable - $ReqLevel) * 0.05; - } - } - } - $ShipCalculations[$TypeKey][$UserID][$ShipID] = array - ( - 'name'=> $_Lang['tech'][$ShipID], - 'force' => floor($_Vars_CombatData[$ShipID]['attack'] * ($UserData['techval']['atk'] + $ForceUpgrade) * $UserData['TotalForceFactor']), - 'shield'=> floor($_Vars_CombatData[$ShipID]['shield'] * $UserData['techval']['shield'] * $UserData['TotalShieldFactor']), - 'hull'=> floor((($_Vars_Prices[$ShipID]['metal'] + $_Vars_Prices[$ShipID]['crystal']) / 10) * $UserData['techval']['def']) - ); - } - - $TableRow[0] .= ""; - $TableRow[1] .= ''; - $TableRow[2] .= ''; - $TableRow[3] .= ''; - $TableRow[4] .= ''; - - if($ShipsLoop == $_User['rw_breakline'] AND $ShipsCount > 0) - { - // Do inTable lineBreak - $ShipsLoop = 0; - foreach($TableRow as &$TableRowData) - { - $ThisRoundCode .= $TableRowData.''; - } - $ThisRoundCode .= ""; - $TableRow = $GeneralTPL['ships']; - } - } - foreach($TableRow as &$TableRowData) - { - $ThisRoundCode .= $TableRowData.''; - } - $ThisRoundCode .= '
    {$ShipCalculations[$TypeKey][$UserID][$ShipID]['name']}'.prettyNumber($ShipCount).''.prettyNumber($ShipCalculations[$TypeKey][$UserID][$ShipID]['force'] * $ShipCount).''.prettyNumber($ShipCalculations[$TypeKey][$UserID][$ShipID]['shield'] * $ShipCount).''.prettyNumber($ShipCalculations[$TypeKey][$UserID][$ShipID]['hull'] * $ShipCount).'
    '; - } - else - { - // If User has no ships (is destroyed) - $ThisRoundCode .= "

    {$_Lang['sys_destroyed']}
    "; - $Destroyed[$TypeKey][$UserID] = true; - } - $ThisRoundCode .= '
    {$UserData['header']}"; - $ThisRoundCode .= "

    {$_Lang['sys_destroyed']}

    {$AttackWaveStat}
    {$DefendWavaStat}
    '.$_Lang['BattleReportReader_FatalError'].'
    '; - - $StrAttackerUnits = sprintf($_Lang['sys_attacker_lostunits'], prettyNumber ($LostUnits['atk'])); - $StrDefenderUnits = sprintf($_Lang['sys_defender_lostunits'], prettyNumber ($LostUnits['def'])); - $StrRuins = sprintf($_Lang['sys_gcdrunits'], prettyNumber($Debris['met']), $_Lang['Metal_rec'], prettyNumber($Debris['cry']), $_Lang['Crystal_rec']); - $DebrisField = "{$StrAttackerUnits}
    {$StrDefenderUnits}
    {$StrRuins}"; - - if($MoonChance !== false) - { - if($TotalMoonChance > $MoonChance) - { - $ChanceMoon = sprintf($_Lang['sys_moonproba_total'], $MoonChance, prettyNumber($TotalMoonChance)); - } - else - { - $ChanceMoon = sprintf($_Lang['sys_moonproba'], $MoonChance); - } - } - else - { - $ChanceMoon = false; - } - - if($CreatedMoon === true) - { - $GottenMoon = sprintf($_Lang['sys_moonbuilt'], $PlanetName, $Users['def'][0]['pos']['g'], $Users['def'][0]['pos']['s'], $Users['def'][0]['pos']['p'], $Users['def'][0]['pos']['g'], $Users['def'][0]['pos']['s'], $Users['def'][0]['pos']['p']); - } - else - { - $GottenMoon = false; - } - - switch($Result) - { - case COMBAT_ATK: // Attacker won the battle - $Pillage = sprintf($_Lang['sys_stealed_ressources'], prettyNumber($Stolen['met']), $_Lang['Metal_rec'], prettyNumber($Stolen['cry']), $_Lang['Crystal_rec'], prettyNumber($Stolen['deu']), $_Lang['Deuterium_rec']); - $ReportCode .= "{$_Lang['sys_attacker_won']}
    {$Pillage}
    "; - $ReportCode .= "{$DebrisField}
    "; - if($MoonDestroyed !== false) - { - if($MoonDestroyed !== -1) - { - if($MoonDestroyed === 1 AND $FleetDestroyed !== true) - { - $MoonDestroyText = $_Lang['sys_destruction_onlymoon']; - } - elseif($MoonDestroyed === 1 AND $FleetDestroyed == true) - { - $MoonDestroyText = $_Lang['sys_destruction_both']; - } - elseif($MoonDestroyed === 0 AND $FleetDestroyed == true) - { - $MoonDestroyText = $_Lang['sys_destruction_onlyfleet']; - } - else - { - $MoonDestroyText = $_Lang['sys_destruction_nothing']; - } - - $MoonDestroyText .= '

    '; - $MoonDestroyText .= sprintf($_Lang['sys_destruc_lune'], $DestroyMoonChance).'
    '; - $MoonDestroyText .= sprintf($_Lang['sys_destruc_rip'], $DestroyFleetChance).'
    '; - } - else - { - $MoonDestroyText = $_Lang['sys_destruction_nothappened']; - } - } - if($ChanceMoon) - { - $ReportCode .= "{$ChanceMoon}
    "; - } - if($GottenMoon) - { - $ReportCode .= "{$GottenMoon}
    "; - } - break; - case COMBAT_DEF: // Defender won the battle - $ReportCode .= "{$_Lang['sys_defender_won']}
    "; - $ReportCode .= "{$DebrisField}
    "; - if($ChanceMoon) - { - $ReportCode .= "{$ChanceMoon}
    "; - } - if($GottenMoon) - { - $ReportCode .= "{$GottenMoon}
    "; - } - break; - case COMBAT_DRAW; // It's a draw! - $ReportCode .= "{$_Lang['sys_both_won']}
    "; - $ReportCode .= "{$DebrisField}
    "; - if($ChanceMoon) - { - $ReportCode .= "{$ChanceMoon}
    "; - } - if($GottenMoon) - { - $ReportCode .= "{$GottenMoon}
    "; - } - break; - } - if($IsOnMoon) - { - $ReportCode .= $_Lang['sys_battle_onMoon'].'
    '; - } - - $ReportCode .= '
    '; - $ReportCode .= $MoonDestroyText; - $ReportCode .= '
    '; - $ReportCode .= sprintf($ThisMessage, $UserMap[$ThisUserID]['username'], sprintf('%0.2f', $ThisData['factor']), $ThisData['level']); - $ReportCode .= '
    '; - $ReportCode .= sprintf($_Lang['sys_rapport_build_time'], $GenerateTime); - $ReportCode .= '
    '.$_Lang['sys_raport_build_engine'].'
    '; - - return "{$ReportCode}"; -} - -?> \ No newline at end of file +{$_Lang['sys_mess_attacker_lost_in_1_round']}"; + } + $ReportData = json_decode($Report['report'], true); + + $Every1FromTeamDestroyed = false; + // End of Temp variables + + // All Rounds + $Rounds = $ReportData['rounds']; + // Battle Result + $Result = $ReportData['init']['result']; + $Stolen['met'] = $ReportData['init']['met']; + $Stolen['cry'] = $ReportData['init']['cry']; + $Stolen['deu'] = $ReportData['init']['deu']; + $Debris['met'] = $ReportData['init']['deb_met']; + $Debris['cry'] = $ReportData['init']['deb_cry']; + $MoonChance = $ReportData['init']['moon_chance']; + $TotalMoonChance = $ReportData['init']['total_moon_chance']; + $CreatedMoon = $ReportData['init']['moon_created']; + $MoonDestroyed = $ReportData['init']['moon_destroyed']; + $DestroyMoonChance = $ReportData['init']['moon_des_chance']; + $FleetDestroyed = $ReportData['init']['fleet_destroyed']; + $DestroyFleetChance = $ReportData['init']['fleet_des_chance']; + $PlanetName = $ReportData['init']['planet_name']; + $IsOnMoon = $ReportData['init']['onMoon']; + $LostUnits['atk'] = $ReportData['init']['atk_lost']; + $LostUnits['def'] = $ReportData['init']['def_lost']; + // Misc. + $GenerateTime = $ReportData['init']['time']; + // UsersData + $UsersData['atk'] = $ReportData['init']['usr']['atk']; + $UsersData['def'] = $ReportData['init']['usr']['def']; + $AddedUsernames = array('atk' => array(), 'def' => array()); + foreach($UsersData as $TypeKey => $AllUsers) + { + foreach($AllUsers as $UserKey => $UserVal) + { + if(empty($UserVal['username'])) + { + $UserVal['username'] = '-'; + } + if(!in_array($UserVal['username'], $AddedUsernames[$TypeKey])) + { + $AddedUsernames[$TypeKey][] = $UserVal['username']; + $Usernames[$TypeKey][] = "{$UserVal['username']}"; + } + } + } + + $Title = sprintf($_Lang['sys_attack_title'], prettyDate('(d m Y - H:i:s)', $ReportData['init']['date'], 1)); + $UsersFighting = implode(', ', $Usernames['atk']).' '.$_Lang['sys_battle_versus'].' '.implode(', ', $Usernames['def']); + $ReportCode = ''; + $ReportCode .= ""; + + if($Rounds === (array)$Rounds) + { + // General Templates + $GeneralTPL['ships'] = array + ( + "", + "", + "", + "", + "", + ); + + // Parse UsersData + $Users = array(); + foreach($UsersData as $TypeKey => $AllUsers) + { + foreach($AllUsers as $UserKey => $UserVal) + { + if(empty($UserVal['username'])) + { + $UserVal['username'] = $_Lang['sys_attack_defender_abandoned_'.($IsOnMoon ? '3' : '1')]; + } + $Pointer = &$Users[$TypeKey][$UserKey]; + $Temp = explode(':', $UserVal['pos']); + $Pointer['pos'] = array('g' => $Temp[0], 's' => $Temp[1], 'p' => $Temp[2]); + $Pointer['techs'] = String2Array($UserVal['techs']); + $Pointer['name'] = sprintf(($TypeKey == 'atk' ? $_Lang['sys_attack_attacker_pos'] : $_Lang['sys_attack_defender_pos']), $UserVal['username'], (empty($UserVal['ally']) ? '' : "[{$UserVal['ally']}]"), $Temp[0], $Temp[1], $Temp[2], $Temp[0], $Temp[1], $Temp[2]); + $Pointer['tech'] = sprintf($_Lang['sys_attack_techologies'], 100 + ($Pointer['techs'][109] * 10), 100 + ($Pointer['techs'][110] * 10), 100 + ($Pointer['techs'][111] * 10)); + $Pointer['techval'] = array('atk' => 1 + (0.1 * $Pointer['techs'][109]), 'shield' => 1 + (0.1 * $Pointer['techs'][110]), 'def' => 1 + (0.1 * $Pointer['techs'][111])); + $Pointer['TotalForceFactor'] = 1; + $Pointer['TotalShieldFactor'] = 1; + + $Pointer['morale'] = null; + if(isset($UserVal['morale']) && $UserVal['morale'] !== null) + { + // Bonuses + if($UserVal['morale'] >= MORALE_BONUS_FLEETPOWERUP1) + { + $Pointer['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; + } + if($UserVal['morale'] >= MORALE_BONUS_FLEETSHIELDUP1) + { + $Pointer['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; + } + // Penalties + if($UserVal['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN1) + { + $Pointer['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; + } + if($UserVal['morale'] <= MORALE_PENALTY_FLEETPOWERDOWN2) + { + $Pointer['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; + } + if($UserVal['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN1) + { + $Pointer['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; + } + if($UserVal['morale'] <= MORALE_PENALTY_FLEETSHIELDDOWN2) + { + $Pointer['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; + } + + $Pointer['morale'] = sprintf($_Lang['sys_attack_morale'], $UserVal['morale']); + $UserMap[$UserVal['id']] = &$UsersData[$TypeKey][$UserKey]; + } + $Pointer['header'] = "
    {$Pointer['name']}
    {$Pointer['tech']}{$Pointer['morale']}"; + } + } + + foreach($Rounds as $Number => $Data) + { + foreach($Data as $TypeKey => $InnerData) + { + if((array)$InnerData['ships'] === $InnerData['ships']) + { + // If ShipsArray is OK (has some ships) + foreach($Users[$TypeKey] as $UserID => $UserData) + { + if(isset($Destroyed[$TypeKey][$UserID])) + { + continue; + } + + $ThisRoundCode = "'; + $ThisRoundArray[] = $ThisRoundCode; + $ThisRoundArray[] = ''; + } + } + else + { + // ShipArray is empty (no ships at all) + foreach($Users[$TypeKey] as $UserID => $UserData) + { + if(isset($Destroyed[$TypeKey][$UserID])) + { + continue; + } + + $ThisRoundCode = ''; + $ThisRoundCode .= ""; + $ThisRoundArray[] = $ThisRoundCode; + $ThisRoundArray[] = ''; + } + $Every1FromTeamDestroyed = true; + } + array_pop($ThisRoundArray); + $ThisRoundArray[] = ''; + } + if($Every1FromTeamDestroyed === false AND $Number <= BATTLE_MAX_ROUNDS) + { + $AttackWaveStat = sprintf($_Lang['sys_attack_wave'], ((count($Data['atk']['ships']) > 1) ? $_Lang['sys_msg_atk_fleets'] : $_Lang['sys_msg_atk_fleet']), prettyNumber($Data['atk']['count']), (($Data['atk']['count'] > 1) ? $_Lang['sys_x_times'] : ''),prettyNumber (floor($Data['atk']['force'])), ((count($Data['def']['ships']) > 1) ? $_Lang['sys_msg_into_defs'] : $_Lang['sys_msg_into_def']), ((count($Data['def']['ships']) > 1) ? $_Lang['sys_msg_into_defs'] : $_Lang['sys_msg_into_def_shield']), prettyNumber(floor($Data['def']['shield']))); + $DefendWavaStat = sprintf($_Lang['sys_attack_wave'], ((count($Data['def']['ships']) > 1) ? $_Lang['sys_msg_def_fleets'] : $_Lang['sys_msg_def_fleet']), prettyNumber($Data['def']['count']), (($Data['def']['count'] > 1) ? $_Lang['sys_x_times'] : ''),prettyNumber (floor($Data['def']['force'])), ((count($Data['atk']['ships']) > 1) ? $_Lang['sys_msg_into_atks'] : $_Lang['sys_msg_into_atk']), ((count($Data['atk']['ships']) > 1) ? $_Lang['sys_msg_into_atks'] : $_Lang['sys_msg_into_atk']), prettyNumber(floor($Data['atk']['shield']))); + + $ThisRoundArray[] = ""; + $ThisRoundArray[] = ''; + } + } + array_pop($ThisRoundArray); + $ReportCode .= implode('', $ThisRoundArray); + } + else + { + $ReportCode .= ''; + } + + $ReportCode .= ''; + + if(!empty($MoonDestroyText)) + { + $ReportCode .= ''; + $ReportCode .= ''; + } + + if(!empty($ReportData['morale'])) + { + $ReportCode .= ''; + foreach($ReportData['morale'] as $ThisUserID => $ThisData) + { + if($ThisData['usertype'] == 'atk') + { + if($ThisData['type'] === MORALE_POSITIVE) + { + $ThisMessage = $_Lang['BattleReport_Morale_Attacker_Positive']; + } + else + { + $ThisMessage = $_Lang['BattleReport_Morale_Attacker_Negative']; + } + } + else + { + $ThisMessage = $_Lang['BattleReport_Morale_Defender_Positive']; + } + + $ReportCode .= ''; + } + } + + $ReportCode .= '
    {$Title}
    {$UsersFighting}
    {$_Lang['sys_ship_type']}
    {$_Lang['sys_ship_count']}
    {$_Lang['sys_ship_weapon']}
    {$_Lang['sys_ship_shield']}
    {$_Lang['sys_ship_armour']}
    {$UserData['header']}"; + if(!empty($InnerData['ships'][$UserID])) + { + // If User has Ships (not destroyed) + $ThisRoundCode .= ''; + $ShipsLoop = 0; + + $TableRow = $GeneralTPL['ships']; + + $InnerData['ships'][$UserID] = String2Array($InnerData['ships'][$UserID]); + $ShipsCount = count($InnerData['ships'][$UserID]); + foreach($InnerData['ships'][$UserID] as $ShipID => $ShipCount) + { + $ShipsLoop += 1; + $ShipsCount -= 1; + if(!isset($ShipCalculations[$TypeKey][$UserID][$ShipID])) + { + // Calculate ShipValues if it's our first time here + $ForceUpgrade = 0; + if(!empty($_Vars_CombatUpgrades[$ShipID])) + { + foreach($_Vars_CombatUpgrades[$ShipID] as $UpTech => $ReqLevel) + { + $TechAvailable = $UserData['techs'][$UpTech]; + if($TechAvailable > $ReqLevel) + { + $ForceUpgrade += ($TechAvailable - $ReqLevel) * 0.05; + } + } + } + $ShipCalculations[$TypeKey][$UserID][$ShipID] = array + ( + 'name'=> $_Lang['tech'][$ShipID], + 'force' => floor($_Vars_CombatData[$ShipID]['attack'] * ($UserData['techval']['atk'] + $ForceUpgrade) * $UserData['TotalForceFactor']), + 'shield'=> floor($_Vars_CombatData[$ShipID]['shield'] * $UserData['techval']['shield'] * $UserData['TotalShieldFactor']), + 'hull'=> floor((($_Vars_Prices[$ShipID]['metal'] + $_Vars_Prices[$ShipID]['crystal']) / 10) * $UserData['techval']['def']) + ); + } + + $TableRow[0] .= ""; + $TableRow[1] .= ''; + $TableRow[2] .= ''; + $TableRow[3] .= ''; + $TableRow[4] .= ''; + + if($ShipsLoop == $_User['rw_breakline'] AND $ShipsCount > 0) + { + // Do inTable lineBreak + $ShipsLoop = 0; + foreach($TableRow as &$TableRowData) + { + $ThisRoundCode .= $TableRowData.''; + } + $ThisRoundCode .= ""; + $TableRow = $GeneralTPL['ships']; + } + } + foreach($TableRow as &$TableRowData) + { + $ThisRoundCode .= $TableRowData.''; + } + $ThisRoundCode .= '
    {$ShipCalculations[$TypeKey][$UserID][$ShipID]['name']}'.prettyNumber($ShipCount).''.prettyNumber($ShipCalculations[$TypeKey][$UserID][$ShipID]['force'] * $ShipCount).''.prettyNumber($ShipCalculations[$TypeKey][$UserID][$ShipID]['shield'] * $ShipCount).''.prettyNumber($ShipCalculations[$TypeKey][$UserID][$ShipID]['hull'] * $ShipCount).'
    '; + } + else + { + // If User has no ships (is destroyed) + $ThisRoundCode .= "

    {$_Lang['sys_destroyed']}
    "; + $Destroyed[$TypeKey][$UserID] = true; + } + $ThisRoundCode .= '
    {$UserData['header']}"; + $ThisRoundCode .= "

    {$_Lang['sys_destroyed']}

    {$AttackWaveStat}
    {$DefendWavaStat}
    '.$_Lang['BattleReportReader_FatalError'].'
    '; + + $StrAttackerUnits = sprintf($_Lang['sys_attacker_lostunits'], prettyNumber ($LostUnits['atk'])); + $StrDefenderUnits = sprintf($_Lang['sys_defender_lostunits'], prettyNumber ($LostUnits['def'])); + $StrRuins = sprintf($_Lang['sys_gcdrunits'], prettyNumber($Debris['met']), $_Lang['Metal_rec'], prettyNumber($Debris['cry']), $_Lang['Crystal_rec']); + $DebrisField = "{$StrAttackerUnits}
    {$StrDefenderUnits}
    {$StrRuins}"; + + if($MoonChance !== false) + { + if($TotalMoonChance > $MoonChance) + { + $ChanceMoon = sprintf($_Lang['sys_moonproba_total'], $MoonChance, prettyNumber($TotalMoonChance)); + } + else + { + $ChanceMoon = sprintf($_Lang['sys_moonproba'], $MoonChance); + } + } + else + { + $ChanceMoon = false; + } + + if($CreatedMoon === true) + { + $GottenMoon = sprintf($_Lang['sys_moonbuilt'], $PlanetName, $Users['def'][0]['pos']['g'], $Users['def'][0]['pos']['s'], $Users['def'][0]['pos']['p'], $Users['def'][0]['pos']['g'], $Users['def'][0]['pos']['s'], $Users['def'][0]['pos']['p']); + } + else + { + $GottenMoon = false; + } + + switch($Result) + { + case COMBAT_ATK: // Attacker won the battle + $Pillage = sprintf($_Lang['sys_stealed_ressources'], prettyNumber($Stolen['met']), $_Lang['Metal_rec'], prettyNumber($Stolen['cry']), $_Lang['Crystal_rec'], prettyNumber($Stolen['deu']), $_Lang['Deuterium_rec']); + $ReportCode .= "{$_Lang['sys_attacker_won']}
    {$Pillage}
    "; + $ReportCode .= "{$DebrisField}
    "; + if($MoonDestroyed !== false) + { + if($MoonDestroyed !== -1) + { + if($MoonDestroyed === 1 AND $FleetDestroyed !== true) + { + $MoonDestroyText = $_Lang['sys_destruction_onlymoon']; + } + elseif($MoonDestroyed === 1 AND $FleetDestroyed == true) + { + $MoonDestroyText = $_Lang['sys_destruction_both']; + } + elseif($MoonDestroyed === 0 AND $FleetDestroyed == true) + { + $MoonDestroyText = $_Lang['sys_destruction_onlyfleet']; + } + else + { + $MoonDestroyText = $_Lang['sys_destruction_nothing']; + } + + $MoonDestroyText .= '

    '; + $MoonDestroyText .= sprintf($_Lang['sys_destruc_lune'], $DestroyMoonChance).'
    '; + $MoonDestroyText .= sprintf($_Lang['sys_destruc_rip'], $DestroyFleetChance).'
    '; + } + else + { + $MoonDestroyText = $_Lang['sys_destruction_nothappened']; + } + } + if($ChanceMoon) + { + $ReportCode .= "{$ChanceMoon}
    "; + } + if($GottenMoon) + { + $ReportCode .= "{$GottenMoon}
    "; + } + break; + case COMBAT_DEF: // Defender won the battle + $ReportCode .= "{$_Lang['sys_defender_won']}
    "; + $ReportCode .= "{$DebrisField}
    "; + if($ChanceMoon) + { + $ReportCode .= "{$ChanceMoon}
    "; + } + if($GottenMoon) + { + $ReportCode .= "{$GottenMoon}
    "; + } + break; + case COMBAT_DRAW; // It's a draw! + $ReportCode .= "{$_Lang['sys_both_won']}
    "; + $ReportCode .= "{$DebrisField}
    "; + if($ChanceMoon) + { + $ReportCode .= "{$ChanceMoon}
    "; + } + if($GottenMoon) + { + $ReportCode .= "{$GottenMoon}
    "; + } + break; + } + if($IsOnMoon) + { + $ReportCode .= $_Lang['sys_battle_onMoon'].'
    '; + } + + $ReportCode .= '
    '; + $ReportCode .= $MoonDestroyText; + $ReportCode .= '
    '; + $ReportCode .= sprintf($ThisMessage, $UserMap[$ThisUserID]['username'], sprintf('%0.2f', $ThisData['factor']), $ThisData['level']); + $ReportCode .= '
    '; + $ReportCode .= sprintf($_Lang['sys_rapport_build_time'], $GenerateTime); + $ReportCode .= '
    '.$_Lang['sys_raport_build_engine'].'
    '; + + return "{$ReportCode}"; +} + +?> diff --git a/includes/functions/RemoveBuildingFromQueue.php b/includes/functions/RemoveBuildingFromQueue.php index 94987f0aa..eba0130ca 100644 --- a/includes/functions/RemoveBuildingFromQueue.php +++ b/includes/functions/RemoveBuildingFromQueue.php @@ -1,90 +1,90 @@ - 1) - { - $CurrentQueue = $CurrentPlanet['buildQueue']; - if($CurrentQueue != 0) - { - $Queue = explode(';', $CurrentQueue); - foreach($Queue as $ID => $Data) - { - if(!empty($Data)) - { - $Data = explode(',', $Data); - $QueueArray[] = $Data; - } - } - $ElementCount = count($QueueArray); - if($QueueID <= $ElementCount) - { - if($QueueID == $ElementCount) - { - $RemovedQID = $QueueID - 1; - $ReturnID = $QueueArray[$RemovedQID][0]; - unset($QueueArray[$RemovedQID]); - foreach($QueueArray as &$Data) - { - $Data = implode(',', $Data); - } - $NewQueue = implode(';', $QueueArray); - } - else - { - $RemovedQID = $QueueID - 1; - $RemovedTime = $QueueArray[$RemovedQID][2]; - $RemovedID = $QueueArray[$RemovedQID][0]; - $ReturnID = $RemovedID; - - $TempPlanet = $CurrentPlanet; - foreach($QueueArray as $ID => &$Data) - { - if($ID < $RemovedQID) - { - if($Data[4] == 'build') - { - $TempPlanet[$_Vars_GameElements[$Data[0]]] += 1; - } - else - { - $TempPlanet[$_Vars_GameElements[$Data[0]]] -= 1; - } - continue; - } - elseif($ID > $RemovedQID) - { - $TempTime = GetBuildingTime($CurrentUser, $TempPlanet, $Data[0]); - if($Data[4] == 'build') - { - $TempPlanet[$_Vars_GameElements[$Data[0]]] += 1; - } - else - { - $TempTime /= 2; - $TempPlanet[$_Vars_GameElements[$Data[0]]] -= 1; - } - $RemovedTime += ($Data[2] - $TempTime); - $Data[1] = $TempPlanet[$_Vars_GameElements[$Data[0]]]; - $Data[2] = $TempTime; - $Data[3] -= $RemovedTime; - } - } - unset($QueueArray[$RemovedQID]); - foreach($QueueArray as &$Data) - { - $Data = implode(',', $Data); - } - $NewQueue = implode(';', $QueueArray); - } - $CurrentPlanet['buildQueue'] = $NewQueue; - } - } - } - - return $ReturnID; -} - -?> \ No newline at end of file + 1) + { + $CurrentQueue = $CurrentPlanet['buildQueue']; + if($CurrentQueue != 0) + { + $Queue = explode(';', $CurrentQueue); + foreach($Queue as $ID => $Data) + { + if(!empty($Data)) + { + $Data = explode(',', $Data); + $QueueArray[] = $Data; + } + } + $ElementCount = count($QueueArray); + if($QueueID <= $ElementCount) + { + if($QueueID == $ElementCount) + { + $RemovedQID = $QueueID - 1; + $ReturnID = $QueueArray[$RemovedQID][0]; + unset($QueueArray[$RemovedQID]); + foreach($QueueArray as &$Data) + { + $Data = implode(',', $Data); + } + $NewQueue = implode(';', $QueueArray); + } + else + { + $RemovedQID = $QueueID - 1; + $RemovedTime = $QueueArray[$RemovedQID][2]; + $RemovedID = $QueueArray[$RemovedQID][0]; + $ReturnID = $RemovedID; + + $TempPlanet = $CurrentPlanet; + foreach($QueueArray as $ID => &$Data) + { + if($ID < $RemovedQID) + { + if($Data[4] == 'build') + { + $TempPlanet[$_Vars_GameElements[$Data[0]]] += 1; + } + else + { + $TempPlanet[$_Vars_GameElements[$Data[0]]] -= 1; + } + continue; + } + elseif($ID > $RemovedQID) + { + $TempTime = GetBuildingTime($CurrentUser, $TempPlanet, $Data[0]); + if($Data[4] == 'build') + { + $TempPlanet[$_Vars_GameElements[$Data[0]]] += 1; + } + else + { + $TempTime /= 2; + $TempPlanet[$_Vars_GameElements[$Data[0]]] -= 1; + } + $RemovedTime += ($Data[2] - $TempTime); + $Data[1] = $TempPlanet[$_Vars_GameElements[$Data[0]]]; + $Data[2] = $TempTime; + $Data[3] -= $RemovedTime; + } + } + unset($QueueArray[$RemovedQID]); + foreach($QueueArray as &$Data) + { + $Data = implode(',', $Data); + } + $NewQueue = implode(';', $QueueArray); + } + $CurrentPlanet['buildQueue'] = $NewQueue; + } + } + } + + return $ReturnID; +} + +?> diff --git a/includes/functions/ResearchBuildingPage.php b/includes/functions/ResearchBuildingPage.php index f75faa59a..1f5282edb 100644 --- a/includes/functions/ResearchBuildingPage.php +++ b/includes/functions/ResearchBuildingPage.php @@ -1,251 +1,251 @@ - 0) - { - include($_EnginePath.'/includes/functions/CheckLabInQueue.php'); - - $Results['planets'] = array(); - while($PlanetsData = mysql_fetch_assoc($CheckOtherPlanets)) - { - // Update Planet - Building Queue - $CheckLab = CheckLabInQueue($PlanetsData); - if($CheckLab !== false) - { - if($CheckLab <= $Now) - { - if(HandlePlanetQueue($PlanetsData, $CurrentUser, $Now, true) === true) - { - $Results['planets'][] = $PlanetsData; - } - } - else - { - $LabInQueueAt[] = "{$PlanetsData['name']} [{$PlanetsData['galaxy']}:{$PlanetsData['system']}:{$PlanetsData['planet']}]"; - $LabInQueue = true; - } - } - } - HandlePlanetUpdate_MultiUpdate($Results, $CurrentUser); - } - } - if(!$LabInQueue) - { - $_Lang['Input_HideNoResearch'] = 'display: none;'; - } - else - { - $_Lang['labo_on_update'] = sprintf($_Lang['labo_on_update'], implode(', ', $LabInQueueAt)); - } - - PlanetResourceUpdate($CurrentUser, $CurrentPlanet, $Now); - - if(is_array($ThePlanet)) - { - $ResearchPlanet = &$ThePlanet; - } - else - { - $ResearchPlanet = &$CurrentPlanet; - } - - // Execute Commands - if(!isOnVacation($CurrentUser)) - { - if(isset($_GET['cmd'])) - { - if($LabInQueue === false) - { - $TheCommand = $_GET['cmd']; - $TechID = isset($_GET['tech']) ? intval($_GET['tech']) : 0; - $QueueElementID = isset($_GET['el']) ? intval($_GET['el']) : 0; - - if((in_array($TechID, $_Vars_ElementCategories['tech']) AND $TheCommand == 'search') OR ($TheCommand == 'cancel' AND $QueueElementID >= 0)) - { - // Parse Commands - $UpdateUser = null; - if($TheCommand == 'cancel') - { - // User requested cancel Action - include($_EnginePath.'includes/functions/TechQueue_Remove.php'); - $ShowElementID = TechQueue_Remove($ResearchPlanet, $CurrentUser, $QueueElementID, $Now); - if($ShowElementID !== false AND $CurrentUser['techQueue_Planet'] == '0') - { - $UpdateUser = &$CurrentUser; - } - else - { - $UpdateUser = false; - } - $CommandDone = true; - } - else if($TheCommand == 'search') - { - // User requested do the research - include($_EnginePath.'includes/functions/TechQueue_Add.php'); - TechQueue_Add($ResearchPlanet, $CurrentUser, $TechID); - $ShowElementID = $TechID; - $CommandDone = true; - } - - if($CommandDone === true) - { - if(HandlePlanetQueue_TechnologySetNext($ResearchPlanet, $CurrentUser, $Now, true) === false) - { - include($_EnginePath.'includes/functions/PostResearchSaveChanges.php'); - PostResearchSaveChanges($ResearchPlanet, ($ResearchPlanet['id'] == $CurrentPlanet['id'] ? true : false), $UpdateUser); - } - } - } - } - } - } - - $TechRowTPL = gettemplate('buildings_research_row'); - $TechScrTPL = gettemplate('buildings_research_script'); - - if(!empty($ResearchPlanet['techQueue'])) - { - $ExplodeQueue = explode(';', $ResearchPlanet['techQueue']); - $FirstElement = explode(',', $ExplodeQueue[0]); - $FirstElementID = $FirstElement[0]; - $InResearch = true; - } - else - { - $InResearch = false; - } - - $TechnoList = ''; - foreach($_Vars_ElementCategories['tech'] as $Tech) - { - $RowParse = $_Lang; - $RowParse['skinpath'] = $_SkinPath; - $RowParse['tech_id'] = $Tech; - $building_level = $CurrentUser[$_Vars_GameElements[$Tech]]; - $RowParse['tech_level'] = ($building_level == 0) ? '' : "({$_Lang['level']} {$building_level})"; - $RowParse['tech_name'] = $_Lang['tech'][$Tech]; - $RowParse['tech_descr'] = $_Lang['res']['descriptions'][$Tech]; - - if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $Tech)) - { - $RowParse['tech_price'] = GetElementPrice($CurrentUser, $CurrentPlanet, $Tech); - $SearchTime = GetBuildingTime($CurrentUser, $CurrentPlanet, $Tech); - $RowParse['search_time'] = ShowBuildTime($SearchTime); - $RowParse['tech_restp'] = GetRestPrice ($CurrentUser, $CurrentPlanet, $Tech, true); - $CanBeDone = IsElementBuyable($CurrentUser, $CurrentPlanet, $Tech); - - // Check if user can do the research (TechQueue is empty) - if(!isOnVacation($CurrentUser)) - { - if(!$InResearch) - { - // Yes! We can do the science! - $LevelToDo = 1 + $CurrentUser[$_Vars_GameElements[$Tech]]; - // Check if is "buyable" & Lab is not in BuildQueue - if($CanBeDone AND !$LabInQueue) - { - $TechnoLink = ""; - if($LevelToDo == 1) - { - $TechnoLink .= "{$_Lang['Rechercher']}"; - } - else - { - $TechnoLink .= "{$_Lang['Rechercher']}
    {$_Lang['level']} {$LevelToDo}
    "; - } - $TechnoLink .= '
    '; - } - else - { - if($LevelToDo == 1) - { - $TechnoLink = "{$_Lang['Rechercher']}"; - } - else - { - $TechnoLink = "{$_Lang['Rechercher']}
    {$_Lang['level']} {$LevelToDo}
    "; - } - } - } - else - { - // Research - underway - if($FirstElementID == $Tech) - { - // Include ChronoApplet - include($_EnginePath.'includes/functions/InsertJavaScriptChronoApplet.php'); - $bloc = $_Lang; - $bloc['Script'] = InsertJavaScriptChronoApplet('res', '', $ResearchPlanet['techQueue_firstEndTime'], true, false, 'function() { SetTimer = \"'.$_Lang['completed'].'\"; window.setTimeout(\'document.location.href=\"buildings.php?mode=research\";\', 500); }'); - $bloc['SetStartTime'] = pretty_time($ResearchPlanet['techQueue_firstEndTime'] - $Now, true); - $bloc['tech_home'] = $ResearchPlanet['id']; - $bloc['tech_id']= $FirstElementID; - if($ResearchPlanet['id'] != $CurrentPlanet['id']) - { - // Research is not on this planet - $bloc['tech_name']= " {$_Lang['on']}
    {$ResearchPlanet['name']}
    [{$ResearchPlanet['galaxy']}:{$ResearchPlanet['system']}:{$ResearchPlanet['planet']}]"; - } - else - { - // Research is on this planet - $bloc['tech_name']= ''; - } - $TechnoLink = parsetemplate($TechScrTPL, $bloc); - } - else - { - $TechnoLink= '-'; - } - } - } - else - { - $TechnoLink = "{$_Lang['ListBox_Disallow_VacationMode']}"; - } - $RowParse['tech_link']= $TechnoLink; - } - else - { - if($CurrentUser['settings_ExpandedBuildView'] == 0) - { - continue; - } - $RowParse['tech_link'] = ' '; - $RowParse['TechRequirementsPlace'] = GetElementTechReq($CurrentUser, $CurrentPlanet, $Tech); - } - - $TechnoList .= parsetemplate($TechRowTPL, $RowParse); - } - - $PageParse = $_Lang; - $PageParse['technolist'] = $TechnoList; - - if($InResearch) - { - $PageParse['Insert_QueueInfo'] = parsetemplate(gettemplate('_singleRow'), array('Classes' => 'pad5 red', 'Colspan' => 3, 'Text' => $_Lang['Queue_ListView_Info'])); - } - - display(parsetemplate(gettemplate('buildings_research'), $PageParse), $_Lang['Research']); -} - -?> \ No newline at end of file + 0) + { + include($_EnginePath.'/includes/functions/CheckLabInQueue.php'); + + $Results['planets'] = array(); + while($PlanetsData = mysql_fetch_assoc($CheckOtherPlanets)) + { + // Update Planet - Building Queue + $CheckLab = CheckLabInQueue($PlanetsData); + if($CheckLab !== false) + { + if($CheckLab <= $Now) + { + if(HandlePlanetQueue($PlanetsData, $CurrentUser, $Now, true) === true) + { + $Results['planets'][] = $PlanetsData; + } + } + else + { + $LabInQueueAt[] = "{$PlanetsData['name']} [{$PlanetsData['galaxy']}:{$PlanetsData['system']}:{$PlanetsData['planet']}]"; + $LabInQueue = true; + } + } + } + HandlePlanetUpdate_MultiUpdate($Results, $CurrentUser); + } + } + if(!$LabInQueue) + { + $_Lang['Input_HideNoResearch'] = 'display: none;'; + } + else + { + $_Lang['labo_on_update'] = sprintf($_Lang['labo_on_update'], implode(', ', $LabInQueueAt)); + } + + PlanetResourceUpdate($CurrentUser, $CurrentPlanet, $Now); + + if(is_array($ThePlanet)) + { + $ResearchPlanet = &$ThePlanet; + } + else + { + $ResearchPlanet = &$CurrentPlanet; + } + + // Execute Commands + if(!isOnVacation($CurrentUser)) + { + if(isset($_GET['cmd'])) + { + if($LabInQueue === false) + { + $TheCommand = $_GET['cmd']; + $TechID = isset($_GET['tech']) ? intval($_GET['tech']) : 0; + $QueueElementID = isset($_GET['el']) ? intval($_GET['el']) : 0; + + if((in_array($TechID, $_Vars_ElementCategories['tech']) AND $TheCommand == 'search') OR ($TheCommand == 'cancel' AND $QueueElementID >= 0)) + { + // Parse Commands + $UpdateUser = null; + if($TheCommand == 'cancel') + { + // User requested cancel Action + include($_EnginePath.'includes/functions/TechQueue_Remove.php'); + $ShowElementID = TechQueue_Remove($ResearchPlanet, $CurrentUser, $QueueElementID, $Now); + if($ShowElementID !== false AND $CurrentUser['techQueue_Planet'] == '0') + { + $UpdateUser = &$CurrentUser; + } + else + { + $UpdateUser = false; + } + $CommandDone = true; + } + else if($TheCommand == 'search') + { + // User requested do the research + include($_EnginePath.'includes/functions/TechQueue_Add.php'); + TechQueue_Add($ResearchPlanet, $CurrentUser, $TechID); + $ShowElementID = $TechID; + $CommandDone = true; + } + + if($CommandDone === true) + { + if(HandlePlanetQueue_TechnologySetNext($ResearchPlanet, $CurrentUser, $Now, true) === false) + { + include($_EnginePath.'includes/functions/PostResearchSaveChanges.php'); + PostResearchSaveChanges($ResearchPlanet, ($ResearchPlanet['id'] == $CurrentPlanet['id'] ? true : false), $UpdateUser); + } + } + } + } + } + } + + $TechRowTPL = gettemplate('buildings_research_row'); + $TechScrTPL = gettemplate('buildings_research_script'); + + if(!empty($ResearchPlanet['techQueue'])) + { + $ExplodeQueue = explode(';', $ResearchPlanet['techQueue']); + $FirstElement = explode(',', $ExplodeQueue[0]); + $FirstElementID = $FirstElement[0]; + $InResearch = true; + } + else + { + $InResearch = false; + } + + $TechnoList = ''; + foreach($_Vars_ElementCategories['tech'] as $Tech) + { + $RowParse = $_Lang; + $RowParse['skinpath'] = $_SkinPath; + $RowParse['tech_id'] = $Tech; + $building_level = $CurrentUser[$_Vars_GameElements[$Tech]]; + $RowParse['tech_level'] = ($building_level == 0) ? '' : "({$_Lang['level']} {$building_level})"; + $RowParse['tech_name'] = $_Lang['tech'][$Tech]; + $RowParse['tech_descr'] = $_Lang['res']['descriptions'][$Tech]; + + if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $Tech)) + { + $RowParse['tech_price'] = GetElementPrice($CurrentUser, $CurrentPlanet, $Tech); + $SearchTime = GetBuildingTime($CurrentUser, $CurrentPlanet, $Tech); + $RowParse['search_time'] = ShowBuildTime($SearchTime); + $RowParse['tech_restp'] = GetRestPrice ($CurrentUser, $CurrentPlanet, $Tech, true); + $CanBeDone = IsElementBuyable($CurrentUser, $CurrentPlanet, $Tech); + + // Check if user can do the research (TechQueue is empty) + if(!isOnVacation($CurrentUser)) + { + if(!$InResearch) + { + // Yes! We can do the science! + $LevelToDo = 1 + $CurrentUser[$_Vars_GameElements[$Tech]]; + // Check if is "buyable" & Lab is not in BuildQueue + if($CanBeDone AND !$LabInQueue) + { + $TechnoLink = ""; + if($LevelToDo == 1) + { + $TechnoLink .= "{$_Lang['Rechercher']}"; + } + else + { + $TechnoLink .= "{$_Lang['Rechercher']}
    {$_Lang['level']} {$LevelToDo}
    "; + } + $TechnoLink .= '
    '; + } + else + { + if($LevelToDo == 1) + { + $TechnoLink = "{$_Lang['Rechercher']}"; + } + else + { + $TechnoLink = "{$_Lang['Rechercher']}
    {$_Lang['level']} {$LevelToDo}
    "; + } + } + } + else + { + // Research - underway + if($FirstElementID == $Tech) + { + // Include ChronoApplet + include($_EnginePath.'includes/functions/InsertJavaScriptChronoApplet.php'); + $bloc = $_Lang; + $bloc['Script'] = InsertJavaScriptChronoApplet('res', '', $ResearchPlanet['techQueue_firstEndTime'], true, false, 'function() { SetTimer = \"'.$_Lang['completed'].'\"; window.setTimeout(\'document.location.href=\"buildings.php?mode=research\";\', 500); }'); + $bloc['SetStartTime'] = pretty_time($ResearchPlanet['techQueue_firstEndTime'] - $Now, true); + $bloc['tech_home'] = $ResearchPlanet['id']; + $bloc['tech_id']= $FirstElementID; + if($ResearchPlanet['id'] != $CurrentPlanet['id']) + { + // Research is not on this planet + $bloc['tech_name']= " {$_Lang['on']}
    {$ResearchPlanet['name']}
    [{$ResearchPlanet['galaxy']}:{$ResearchPlanet['system']}:{$ResearchPlanet['planet']}]"; + } + else + { + // Research is on this planet + $bloc['tech_name']= ''; + } + $TechnoLink = parsetemplate($TechScrTPL, $bloc); + } + else + { + $TechnoLink= '-'; + } + } + } + else + { + $TechnoLink = "{$_Lang['ListBox_Disallow_VacationMode']}"; + } + $RowParse['tech_link']= $TechnoLink; + } + else + { + if($CurrentUser['settings_ExpandedBuildView'] == 0) + { + continue; + } + $RowParse['tech_link'] = ' '; + $RowParse['TechRequirementsPlace'] = GetElementTechReq($CurrentUser, $CurrentPlanet, $Tech); + } + + $TechnoList .= parsetemplate($TechRowTPL, $RowParse); + } + + $PageParse = $_Lang; + $PageParse['technolist'] = $TechnoList; + + if($InResearch) + { + $PageParse['Insert_QueueInfo'] = parsetemplate(gettemplate('_singleRow'), array('Classes' => 'pad5 red', 'Colspan' => 3, 'Text' => $_Lang['Queue_ListView_Info'])); + } + + display(parsetemplate(gettemplate('buildings_research'), $PageParse), $_Lang['Research']); +} + +?> diff --git a/includes/functions/RestoreFleetToPlanet.php b/includes/functions/RestoreFleetToPlanet.php index 8c6748628..fdaec0655 100644 --- a/includes/functions/RestoreFleetToPlanet.php +++ b/includes/functions/RestoreFleetToPlanet.php @@ -1,86 +1,86 @@ - 0) - { - $UpdatePlanet[$_Vars_GameElements[$ThisShip[0]]] = $ThisShip[1]; - $DevArray[] = "{$ThisShip[0]},{$ThisShip[1]}"; - } - } - - if($FleetRow['fleet_resource_metal'] > 0) - { - $DevArray[] = 'M,'.$FleetRow['fleet_resource_metal']; - $UpdatePlanet['metal'] = $FleetRow['fleet_resource_metal']; - } - if($FleetRow['fleet_resource_crystal'] > 0) - { - $DevArray[] = 'C,'.$FleetRow['fleet_resource_crystal']; - $UpdatePlanet['crystal'] = $FleetRow['fleet_resource_crystal']; - } - if($FleetRow['fleet_resource_deuterium'] > 0) - { - $DevArray[] = 'D,'.$FleetRow['fleet_resource_deuterium']; - $UpdatePlanet['deuterium'] = $FleetRow['fleet_resource_deuterium']; - } - - if(!empty($UpdatePlanet)) - { - if($Start === true) - { - $PlanetID = $FleetRow['fleet_start_id']; - $DevLogTime = $FleetRow['fleet_end_time']; - $SetCode = '1'; - } - else - { - $PlanetID = $FleetRow['fleet_end_id']; - $DevLogTime = $FleetRow['fleet_start_time']; - $SetCode = '2'; - } - if(!empty($_FleetCache['planets'][$PlanetID])) - { - global $HPQ_PlanetUpdatedFields; - $_FleetCache['updatePlanets'][$PlanetID] = true; - foreach($UpdatePlanet as $Key => $Value) - { - $HPQ_PlanetUpdatedFields[] = $Key; - $_FleetCache['planets'][$PlanetID][$Key] += $Value; - } - } - else - { - foreach($UpdatePlanet as $Key => $Value) - { - if(empty($_FleetCache['addToPlanets']['fields']) OR !in_array($Key, $_FleetCache['addToPlanets']['fields'])) - { - $_FleetCache['addToPlanets']['fields'][] = $Key; - } - if(!isset($_FleetCache['addToPlanets']['data'][$PlanetID][$Key])) - { - $_FleetCache['addToPlanets']['data'][$PlanetID][$Key] = 0; - } - $_FleetCache['addToPlanets']['data'][$PlanetID][$Key] += $Value; - } - } - - $UserDev_Log[] = array - ( - 'UserID' => $FleetRow['fleet_owner'], 'PlanetID' => $PlanetID, 'Date' => $DevLogTime, 'Place' => 21, - 'Code' => $SetCode, 'ElementID' => $FleetRow['fleet_id'], 'AdditionalData' => implode(';', $DevArray) - ); - - return true; - } - return false; -} - -?> \ No newline at end of file + 0) + { + $UpdatePlanet[$_Vars_GameElements[$ThisShip[0]]] = $ThisShip[1]; + $DevArray[] = "{$ThisShip[0]},{$ThisShip[1]}"; + } + } + + if($FleetRow['fleet_resource_metal'] > 0) + { + $DevArray[] = 'M,'.$FleetRow['fleet_resource_metal']; + $UpdatePlanet['metal'] = $FleetRow['fleet_resource_metal']; + } + if($FleetRow['fleet_resource_crystal'] > 0) + { + $DevArray[] = 'C,'.$FleetRow['fleet_resource_crystal']; + $UpdatePlanet['crystal'] = $FleetRow['fleet_resource_crystal']; + } + if($FleetRow['fleet_resource_deuterium'] > 0) + { + $DevArray[] = 'D,'.$FleetRow['fleet_resource_deuterium']; + $UpdatePlanet['deuterium'] = $FleetRow['fleet_resource_deuterium']; + } + + if(!empty($UpdatePlanet)) + { + if($Start === true) + { + $PlanetID = $FleetRow['fleet_start_id']; + $DevLogTime = $FleetRow['fleet_end_time']; + $SetCode = '1'; + } + else + { + $PlanetID = $FleetRow['fleet_end_id']; + $DevLogTime = $FleetRow['fleet_start_time']; + $SetCode = '2'; + } + if(!empty($_FleetCache['planets'][$PlanetID])) + { + global $HPQ_PlanetUpdatedFields; + $_FleetCache['updatePlanets'][$PlanetID] = true; + foreach($UpdatePlanet as $Key => $Value) + { + $HPQ_PlanetUpdatedFields[] = $Key; + $_FleetCache['planets'][$PlanetID][$Key] += $Value; + } + } + else + { + foreach($UpdatePlanet as $Key => $Value) + { + if(empty($_FleetCache['addToPlanets']['fields']) OR !in_array($Key, $_FleetCache['addToPlanets']['fields'])) + { + $_FleetCache['addToPlanets']['fields'][] = $Key; + } + if(!isset($_FleetCache['addToPlanets']['data'][$PlanetID][$Key])) + { + $_FleetCache['addToPlanets']['data'][$PlanetID][$Key] = 0; + } + $_FleetCache['addToPlanets']['data'][$PlanetID][$Key] += $Value; + } + } + + $UserDev_Log[] = array + ( + 'UserID' => $FleetRow['fleet_owner'], 'PlanetID' => $PlanetID, 'Date' => $DevLogTime, 'Place' => 21, + 'Code' => $SetCode, 'ElementID' => $FleetRow['fleet_id'], 'AdditionalData' => implode(';', $DevArray) + ); + + return true; + } + return false; +} + +?> diff --git a/includes/functions/SendMail.php b/includes/functions/SendMail.php index c2ab930fb..1de0b3d59 100644 --- a/includes/functions/SendMail.php +++ b/includes/functions/SendMail.php @@ -1,151 +1,151 @@ -SmtpClose(); - return true; - } - else - { - return false; - } - } - - if($__MailerInc !== TRUE) - { - require "{$_EnginePath}includes/phpmailer/class.phpmailer.php"; - $__MailerInc = TRUE; - } - - try - { - $From = trim($From); - if(!$From) - { - $From = MAILER_MSGFIELDS_FROM; - $FromName = MAILER_MSGFIELDS_FROM_NAME; - } - else - { - $FromName = $From; - } - - if(empty($Object)) - { - $Object = new PHPMailer(true); - - if(MAILER_SMTP_USE) - { - $Object->IsSMTP(); - $Object->SMTPAuth = true; - $Object->SMTPSecure = 'ssl'; - $Object->Host = MAILER_SMTP_HOST; - $Object->Port = MAILER_SMTP_PORT; - $Object->Username = MAILER_SMTP_USER; - $Object->Password = MAILER_SMTP_PASSWORD; - } - - $Object->AltBody = 'HTML Compat needed'; - $Object->WordWrap = 80; - $Object->IsHTML(true); - - if($MoreThanOne === true && MAILER_SMTP_USE) - { - $Object->SMTPKeepAlive = true; - } - } - - $body = preg_replace('/\\\\/','', $body); - - $Object->AddReplyTo($From, $FromName); - $Object->From = $From; - $Object->FromName = $FromName; - $Object->AddAddress($to); - $Object->Subject = $title; - $Object->MsgHTML($body); - - $Object->Send(); - - $Object->RemoveToAddress($to); - - return true; - } - catch(phpmailerException $e) - { - return $e->errorMessage(); - } -} - -function SendMassMail($to, $title, $body, $From = '') -{ - global $_EnginePath, $__MailerInc; - - if($__MailerInc !== TRUE) - { - require "{$_EnginePath}includes/phpmailer/class.phpmailer.php"; - $__MailerInc = TRUE; - } - - try - { - $From = trim($From); - if(!$From) - { - $From = MAILER_MSGFIELDS_FROM; - $FromName = MAILER_MSGFIELDS_FROM_NAME; - } - else - { - $FromName = $From; - } - - $Object = new PHPMailer(true); - - if(MAILER_SMTP_USE) - { - $Object->IsSMTP(); - $Object->SMTPAuth = true; - $Object->SMTPSecure = 'ssl'; - $Object->Host = MAILER_SMTP_HOST; - $Object->Port = MAILER_SMTP_PORT; - $Object->Username = MAILER_SMTP_USER; - $Object->Password = MAILER_SMTP_PASSWORD; - } - - $Object->AltBody = 'HTML Compat needed'; - $Object->WordWrap = 80; - $Object->IsHTML(true); - - $body = preg_replace('/\\\\/','', $body); //Strip backslashes - - $Object->AddReplyTo($From, $FromName); - $Object->From = $From; - $Object->FromName = $FromName; - $Object->AddAddress($From); - $Object->Subject = $title; - $Object->MsgHTML($body); - $Object->AddCustomHeader('Bcc: '.implode(', ', $to)); - - $Object->Send(); - - return true; - } - catch(phpmailerException $e) - { - return $e->errorMessage(); - } -} - -function CloseMailConnection() -{ - return SendMail('', '', '', '', '', true); -} - -?> \ No newline at end of file +SmtpClose(); + return true; + } + else + { + return false; + } + } + + if($__MailerInc !== TRUE) + { + require "{$_EnginePath}includes/phpmailer/class.phpmailer.php"; + $__MailerInc = TRUE; + } + + try + { + $From = trim($From); + if(!$From) + { + $From = MAILER_MSGFIELDS_FROM; + $FromName = MAILER_MSGFIELDS_FROM_NAME; + } + else + { + $FromName = $From; + } + + if(empty($Object)) + { + $Object = new PHPMailer(true); + + if(MAILER_SMTP_USE) + { + $Object->IsSMTP(); + $Object->SMTPAuth = true; + $Object->SMTPSecure = 'ssl'; + $Object->Host = MAILER_SMTP_HOST; + $Object->Port = MAILER_SMTP_PORT; + $Object->Username = MAILER_SMTP_USER; + $Object->Password = MAILER_SMTP_PASSWORD; + } + + $Object->AltBody = 'HTML Compat needed'; + $Object->WordWrap = 80; + $Object->IsHTML(true); + + if($MoreThanOne === true && MAILER_SMTP_USE) + { + $Object->SMTPKeepAlive = true; + } + } + + $body = preg_replace('/\\\\/','', $body); + + $Object->AddReplyTo($From, $FromName); + $Object->From = $From; + $Object->FromName = $FromName; + $Object->AddAddress($to); + $Object->Subject = $title; + $Object->MsgHTML($body); + + $Object->Send(); + + $Object->RemoveToAddress($to); + + return true; + } + catch(phpmailerException $e) + { + return $e->errorMessage(); + } +} + +function SendMassMail($to, $title, $body, $From = '') +{ + global $_EnginePath, $__MailerInc; + + if($__MailerInc !== TRUE) + { + require "{$_EnginePath}includes/phpmailer/class.phpmailer.php"; + $__MailerInc = TRUE; + } + + try + { + $From = trim($From); + if(!$From) + { + $From = MAILER_MSGFIELDS_FROM; + $FromName = MAILER_MSGFIELDS_FROM_NAME; + } + else + { + $FromName = $From; + } + + $Object = new PHPMailer(true); + + if(MAILER_SMTP_USE) + { + $Object->IsSMTP(); + $Object->SMTPAuth = true; + $Object->SMTPSecure = 'ssl'; + $Object->Host = MAILER_SMTP_HOST; + $Object->Port = MAILER_SMTP_PORT; + $Object->Username = MAILER_SMTP_USER; + $Object->Password = MAILER_SMTP_PASSWORD; + } + + $Object->AltBody = 'HTML Compat needed'; + $Object->WordWrap = 80; + $Object->IsHTML(true); + + $body = preg_replace('/\\\\/','', $body); //Strip backslashes + + $Object->AddReplyTo($From, $FromName); + $Object->From = $From; + $Object->FromName = $FromName; + $Object->AddAddress($From); + $Object->Subject = $title; + $Object->MsgHTML($body); + $Object->AddCustomHeader('Bcc: '.implode(', ', $to)); + + $Object->Send(); + + return true; + } + catch(phpmailerException $e) + { + return $e->errorMessage(); + } +} + +function CloseMailConnection() +{ + return SendMail('', '', '', '', '', true); +} + +?> diff --git a/includes/functions/SendSimpleMassMessage.php b/includes/functions/SendSimpleMassMessage.php index 93988ca16..2d1c5ba4d 100644 --- a/includes/functions/SendSimpleMassMessage.php +++ b/includes/functions/SendSimpleMassMessage.php @@ -1,21 +1,21 @@ - \ No newline at end of file + diff --git a/includes/functions/SendSimpleMessage.php b/includes/functions/SendSimpleMessage.php index 98724fcbb..9add69246 100644 --- a/includes/functions/SendSimpleMessage.php +++ b/includes/functions/SendSimpleMessage.php @@ -1,31 +1,31 @@ - \ No newline at end of file + diff --git a/includes/functions/SendSimpleMultipleMessages.php b/includes/functions/SendSimpleMultipleMessages.php index b75afbed0..598a6df3d 100644 --- a/includes/functions/SendSimpleMultipleMessages.php +++ b/includes/functions/SendSimpleMultipleMessages.php @@ -1,28 +1,28 @@ - \ No newline at end of file + diff --git a/includes/functions/SetSelectedPlanet.php b/includes/functions/SetSelectedPlanet.php index ee8275c70..fad453da2 100644 --- a/includes/functions/SetSelectedPlanet.php +++ b/includes/functions/SetSelectedPlanet.php @@ -1,28 +1,28 @@ - 0) - { - $IsPlanetMine = doquery("SELECT `id` FROM {{table}} WHERE `id` = {$SelectPlanet} AND `id_owner` = {$CurrentUser['id']} LIMIT 1;", 'planets', true); - if($IsPlanetMine['id'] == $SelectPlanet) - { - $CurrentUser['current_planet'] = $SelectPlanet; - doquery("UPDATE {{table}} SET `current_planet` = {$SelectPlanet} WHERE `id` = {$CurrentUser['id']} LIMIT 1;", 'users'); - } - } -} - -?> \ No newline at end of file + 0) + { + $IsPlanetMine = doquery("SELECT `id` FROM {{table}} WHERE `id` = {$SelectPlanet} AND `id_owner` = {$CurrentUser['id']} LIMIT 1;", 'planets', true); + if($IsPlanetMine['id'] == $SelectPlanet) + { + $CurrentUser['current_planet'] = $SelectPlanet; + doquery("UPDATE {{table}} SET `current_planet` = {$SelectPlanet} WHERE `id` = {$CurrentUser['id']} LIMIT 1;", 'users'); + } + } +} + +?> diff --git a/includes/functions/ShipyardPage.php b/includes/functions/ShipyardPage.php index 474a921ca..d5b645877 100644 --- a/includes/functions/ShipyardPage.php +++ b/includes/functions/ShipyardPage.php @@ -1,574 +1,574 @@ - '')); - $TPL['queue_topinfo'] = gettemplate('buildings_compact_queue_topinfo'); - $TPL['infobox_body'] = gettemplate('buildings_compact_infobox_body_shipyard'); - $TPL['infobox_req_res'] = gettemplate('buildings_compact_infobox_req_res'); - $TPL['infobox_additionalnfo'] = gettemplate('buildings_compact_infobox_additionalnfo'); - $TPL['infobox_additionalnfo_single'] = gettemplate('buildings_compact_infobox_additionalnfo_single'); - $TPL['infobox_req_selector_single'] = gettemplate('buildings_compact_infobox_req_selector_single'); - $TPL['infobox_req_selector_dual'] = gettemplate('buildings_compact_infobox_req_selector_dual'); - - if($CurrentPlanet[$_Vars_GameElements[21]] > 0) - { - $HasShipyard = true; - } - else - { - $HasShipyard = false; - } - - PlanetResourceUpdate($CurrentUser, $CurrentPlanet, $Now); - - if($IsInDefense) - { - $MissileSizes = array(502 => 1, 503 => 2); - $Missiles[502] = $CurrentPlanet[$_Vars_GameElements[502]]; - $Missiles[503] = $CurrentPlanet[$_Vars_GameElements[503]]; - $Shields[407] = $CurrentPlanet[$_Vars_GameElements[407]]; - $Shields[408] = $CurrentPlanet[$_Vars_GameElements[408]]; - $SiloSize = $CurrentPlanet[$_Vars_GameElements[44]]; - $MaxMissiles = $SiloSize * SILO_PERLEVELPLACE; - $SiloFreeSpace = $MaxMissiles; - - $CurrentQueue = $CurrentPlanet['shipyardQueue']; - if(!empty($CurrentQueue)) - { - $CurrentQueue = explode(';', $CurrentQueue); - foreach($CurrentQueue as $QueueData) - { - if(empty($QueueData)) - { - continue; - } - $QueueData = explode(',', $QueueData); - $ElementID = $QueueData[0]; - $ElementCount = $QueueData[1]; - if($ElementCount > 0) - { - if($ElementID == 502 OR $ElementID == 503) - { - $Missiles[$ElementID] += $ElementCount; - } - else if($ElementID == 407 OR $ElementID == 408) - { - $Shields[$ElementID] += $ElementCount; - } - } - } - } - - foreach($Missiles as $MissileKey => $MissileCount) - { - if($MissileCount > 0) - { - $SiloFreeSpace -= $MissileCount * $MissileSizes[$MissileKey]; - } - } - } - - // Execute Commands - if(!isOnVacation($CurrentUser)) - { - if(isset($_POST['cmd']) && $_POST['cmd'] == 'exec') - { - $AddedInQueue = false; - $AddedSomething = false; - - if($CurrentPlanet['shipyardQueue'] == '0') - { - $CurrentPlanet['shipyardQueue'] = ''; - } - - if($CurrentPlanet) - { - include($_EnginePath.'includes/functions/GetElementRessources.php'); - foreach($_POST['elem'] as $ElementID => $Count) - { - $Element = intval($ElementID); - $Count = floor(floatval(str_replace('.', '', $Count))); - if(in_array($ElementID, $_Vars_ElementCategories[$PageType])) - { - if($Count > 0) - { - if($Count > $QueueSize) - { - $Count = $QueueSize; - } - - if($IsInDefense) - { - if($ElementID == 407 OR $ElementID == 408) - { - if($Shields[$ElementID] >= 1) - { - continue; - } - else if($Count > 1) - { - $Count = 1; - } - } - else if($ElementID == 502 OR $ElementID == 503) - { - $ThisNeededSpace = $Count * $MissileSizes[$ElementID]; - if($ThisNeededSpace > $SiloFreeSpace) - { - $Count = floor($SiloFreeSpace/$MissileSizes[$ElementID]); - if($Count <= 0) - { - continue; - } - } - } - } - - if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $ElementID)) - { - $MaxElements = GetMaxConstructibleElements($ElementID, $CurrentPlanet); - if($Count > $MaxElements) - { - $Count = $MaxElements; - } - - if($Count > 0) - { - if($ElementID == 407 OR $ElementID == 408) - { - $Shields[$ElementID] += $Count; - } - else if($ElementID == 502 OR $ElementID == 503) - { - $Missiles[$ElementID] += $Count; - $SiloFreeSpace -= $Count * $MissileSizes[$ElementID]; - } - - $Ressource = GetElementRessources($ElementID, $Count); - $AddedSomething = true; - - if(!isset($UpdateAchievements[$ElementID])) - { - $UpdateAchievements[$ElementID] = 0; - } - $UpdateAchievements[$ElementID] += $Count; - $addToBHangar = "{$ElementID},{$Count};"; - $CurrentPlanet['metal'] -= $Ressource['metal']; - $CurrentPlanet['crystal'] -= $Ressource['crystal']; - $CurrentPlanet['deuterium'] -= $Ressource['deuterium']; - $CurrentPlanet['shipyardQueue'] .= $addToBHangar; - - $DevLog_Array[] = "{$ElementID},{$Count}"; - } - } - } - } - } - - if($AddedSomething) - { - // Update Achievements - foreach($UpdateAchievements as $Key => $Value) - { - $QryAchievementsKey[] = "`build_{$Key}`"; - $QryAchievementsArr[] = "`build_{$Key}` = `build_{$Key}` + VALUES(`build_{$Key}`)"; - } - $QryAchievements = ''; - $QryAchievements .= "INSERT INTO {{table}} (`A_UserID`, ".implode(', ', $QryAchievementsKey).") VALUES ({$CurrentUser['id']}, ".implode(', ', $UpdateAchievements).")"; - $QryAchievements .= " ON DUPLICATE KEY UPDATE "; - $QryAchievements .= implode(', ', $QryAchievementsArr); - $QryAchievements .= ';'; - doquery($QryAchievements, 'achievements_stats'); - - // Update DevLog - $UserDev_Log[] = array('PlanetID' => $CurrentPlanet['id'], 'Date' => $Now, 'Place' => ($IsInFleet ? 6 : 7), 'Code' => '0', 'ElementID' => '0', 'AdditionalData' => implode(';', $DevLog_Array)); - } - } - } - } - // End of - Execute Commands - - // Parse Queue - $CurrentQueue = $CurrentPlanet['shipyardQueue']; - $QueueIndex = 0; - $TotalTime = 0; - if(!empty($CurrentQueue)) - { - $CurrentQueue = explode(';', $CurrentQueue); - foreach($CurrentQueue as $QueueID => $QueueData) - { - if(empty($QueueData)) - { - continue; - } - $QueueData = explode(',', $QueueData); - $ListID = $QueueIndex + 1; - $ElementID = $QueueData[0]; - $ElementCount = $QueueData[1]; - $ElementName = $_Lang['tech'][$ElementID]; - $ElementTime = GetBuildingTime($CurrentUser, $CurrentPlanet, $ElementID); - $ElementTotalTime = $ElementTime * $ElementCount; - $TotalTime += $ElementTotalTime; - if($ElementTime > 0) - { - $RemoveCount = 0.1 / $ElementTime; - } - else - { - $RemoveCount = $ElementCount; - } - - $QueueParser[] = array - ( - 'ElementNo' => $ListID, - 'ElementID' => $ElementID, - 'Name' => $ElementName, - 'Count' => prettyNumber($ElementCount), - ); - $QueueJSArray[$ListID] = array('No' => $ListID, 'Remove' => $RemoveCount, 'Count' => $ElementCount); - - $QueueIndex += 1; - } - - if(!empty($QueueParser)) - { - $TotalTime -= $CurrentPlanet['shipyardQueue_additionalWorkTime']; - $QueueJSArray[1]['Count'] -= ($QueueJSArray[1]['Remove'] * (10 + ($CurrentPlanet['shipyardQueue_additionalWorkTime'] * 10))); - - include($_EnginePath.'/includes/functions/InsertJavaScriptChronoApplet.php'); - $QueueParser[0]['ChronoAppletScript'] = InsertJavaScriptChronoApplet('QueueFirstTimer', '', $TotalTime, false, false, 'function() { SetTimer = \"'.$_Lang['completed'].'\"; window.setTimeout(\'document.location.href=\"buildings.php?mode='.$PageType.'\";\', 1000); }'); - $QueueParser[0]['EndTimer'] = pretty_time($TotalTime, true); - $Parse['Create_RunQueueJSHandler'] = 'true'; - - foreach($QueueParser as $QueueID => $QueueData) - { - if($QueueID == 0) - { - $ThisTPL = gettemplate('buildings_compact_queue_firstel_shipyard'); - } - else if($QueueID == 1) - { - $ThisTPL = gettemplate('buildings_compact_queue_nextel_shipyard'); - } - $Parse['Create_Queue'] .= parsetemplate($ThisTPL, $QueueData); - } - } - } - else - { - $Parse['Create_Queue'] = parsetemplate($TPL['queue_topinfo'], array('InfoText' => $_Lang['Queue_Empty'])); - } - // End of - Parse Queue - - $ResImages = array - ( - 'metal' => 'metall', - 'crystal' => 'kristall', - 'deuterium' => 'deuterium', - 'energy_max' => 'energie', - 'darkEnergy' => 'darkenergy' - ); - $ResLangs = array - ( - 'metal' => $_Lang['Metal'], - 'crystal' => $_Lang['Crystal'], - 'deuterium' => $_Lang['Deuterium'], - 'energy_max' => $_Lang['Energy'], - 'darkEnergy' => $_Lang['DarkEnergy'] - ); - - $ElementParserDefault = array - ( - 'SkinPath' => $_SkinPath, - 'InfoBox_Count' => $_Lang['InfoBox_Count'], - 'InfoBox_Build' => $_Lang['InfoBox_DoResearch'], - 'InfoBox_RequirementsFor' => $_Lang['InfoBox_RequirementsForShip'], - 'InfoBox_ResRequirements' => $_Lang['InfoBox_ResRequirementsShip'], - 'InfoBox_TechRequirements' => $_Lang['InfoBox_TechRequirements'], - 'InfoBox_Requirements_Res' => $_Lang['InfoBox_Requirements_Res'], - 'InfoBox_Requirements_Tech' => $_Lang['InfoBox_Requirements_Tech'], - 'InfoBox_BuildTime' => $_Lang['InfoBox_ConstructionTime'], - 'InfoBox_MaxConstructible' => $_Lang['InfoBox_MaxConstructible'], - 'InfoBox_ShowTechReq' => $_Lang['InfoBox_ShowTechReq'], - 'InfoBox_ShowResReq' => $_Lang['InfoBox_ShowResReq'], - 'ElementPriceDiv' => '' - ); - - $TabIndex = 1; - - foreach($_Vars_ElementCategories[$PageType] as $ElementID) - { - $ElementParser = $ElementParserDefault; - - $HasResources = true; - $TechLevelOK = false; - $BlockShield = false; - $BlockMissile = false; - - $ElementParser['ElementCount'] = prettyNumber($CurrentPlanet[$_Vars_GameElements[$ElementID]]); - if(strlen($ElementParser['ElementCount']) > 10) - { - $ElementParser['IsBigNum'] = 'bignum'; - } - $ElementParser['MaxConstructible'] = GetMaxConstructibleElements($ElementID, $CurrentPlanet); - if($IsInDefense) - { - if($ElementID == 407 OR $ElementID == 408) - { - if($Shields[$ElementID] >= 1) - { - $ElementParser['MaxConstructible'] = 0; - $BlockShield = true; - } - else - { - $ElementParser['MaxConstructible'] = 1; - } - } - else if($ElementID == 502 OR $ElementID == 503) - { - $MaxMissilesSpace = floor($SiloFreeSpace / $MissileSizes[$ElementID]); - if($MaxMissilesSpace > 0) - { - if($MaxMissilesSpace < $ElementParser['MaxConstructible']) - { - $ElementParser['MaxConstructible'] = $MaxMissilesSpace; - } - } - else - { - $BlockMissile = true; - $ElementParser['MaxConstructible'] = 0; - } - } - } - $ElementParser['MaxConstructible'] = prettyNumber($ElementParser['MaxConstructible']); - $ElementParser['ElementName'] = $_Lang['tech'][$ElementID]; - $ElementParser['ElementID'] = $ElementID; - $ElementParser['Desc'] = $_Lang['res']['descriptions'][$ElementID]; - - $ElementParser['ElementPrice'] = GetBuildingPrice($CurrentUser, $CurrentPlanet, $ElementID, true, false, true); - foreach($ElementParser['ElementPrice'] as $Key => $Value) - { - if($Value > 0) - { - $ResColor = ''; - $ResMinusColor = ''; - $MinusValue = ' '; - - if($Key != 'darkEnergy') - { - $UseVar = &$CurrentPlanet; - } - else - { - $UseVar = &$CurrentUser; - } - if($UseVar[$Key] < $Value) - { - $ResMinusColor = 'red'; - $MinusValue = '('.prettyNumber($UseVar[$Key] - $Value).')'; - $ResColor = 'red'; - } - - $ElementParser['ElementPrices'] = array - ( - 'SkinPath' => $_SkinPath, - 'ResName' => $Key, - 'ResImg' => $ResImages[$Key], - 'ResColor' => $ResColor, - 'Value' => prettyNumber($Value), - 'ResMinusColor' => $ResMinusColor, - 'MinusValue' => $MinusValue - ); - $ElementParser['ElementPriceDiv'] .= parsetemplate($TPL['infobox_req_res'], $ElementParser['ElementPrices']); - $ElementPriceArray[$ElementID][$Key] = $Value; - } - } - $ElementParser['BuildTime'] = GetBuildingTime($CurrentUser, $CurrentPlanet, $ElementID); - $ElementTimeArray[$ElementID] = $ElementParser['BuildTime']; - $ElementParser['BuildTime'] = pretty_time($ElementParser['BuildTime']); - if($ElementID == 212) - { - $BuildLevelFactor = 10; - $BuildLevel = 1; - $BuildTemp= $CurrentPlanet['temp_max']; - $ElementParser['AdditionalNfo'][] = parsetemplate($TPL['infobox_additionalnfo'], array - ( - 'Label' => $_Lang['Energy'], - 'ValueClasses' => 'lime', - 'Value' => '+'.prettyNumber(floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']))) - )); - } - - if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $ElementID)) - { - $TechLevelOK = true; - $ElementParser['ElementRequirementsHeadline'] = $TPL['infobox_req_selector_single']; - } - else - { - $ElementParser['ElementRequirementsHeadline'] = $TPL['infobox_req_selector_dual']; - $ElementParser['ElementTechDiv'] = GetElementTechReq($CurrentUser, $CurrentPlanet, $ElementID, true); - $ElementParser['HideResReqDiv'] = 'hide'; - } - $HasResources = IsElementBuyable($CurrentUser, $CurrentPlanet, $ElementID, true, false, true); - - $BlockReason = array(); - - if(!$HasResources) - { - $BlockReason[] = $_Lang['ListBox_Disallow_NoResources']; - } - if(!$TechLevelOK) - { - $BlockReason[] = $_Lang['ListBox_Disallow_NoTech']; - } - if($BlockShield) - { - $BlockReason[] = $_Lang['ListBox_Disallow_ShieldBlock']; - $ElementParser['AdditionalNfo'][] = parsetemplate($TPL['infobox_additionalnfo_single'], array('ValueClasses' => 'red', 'Value' => $_Lang['ListBox_Disallow_ShieldBlock'])); - } - if($BlockMissile) - { - $BlockReason[] = $_Lang['ListBox_Disallow_MissileBlock']; - $ElementParser['AdditionalNfo'][] = parsetemplate($TPL['infobox_additionalnfo_single'], array('ValueClasses' => 'red', 'Value' => $_Lang['ListBox_Disallow_MissileBlock'])); - } - if(!$HasShipyard) - { - $BlockReason[] = $_Lang['ListBox_Disallow_NoShipyard']; - } - if(isOnVacation($CurrentUser)) - { - $BlockReason[] = $_Lang['ListBox_Disallow_VacationMode']; - } - - if(!empty($BlockReason)) - { - $ElementParser['ElementDisabled'] = $TPL['list_disabled']; - $ElementParser['ElementDisableInv'] = 'inv'; - $ElementParser['ElementDisableReason'] = end($BlockReason); - } - else - { - $ElementParser['TabIndex'] = $TabIndex; - $TabIndex += 1; - } - - if(!empty($ElementParser['AdditionalNfo'])) - { - $ElementParser['AdditionalNfo'] = implode('', $ElementParser['AdditionalNfo']); - } - $ElementParser['ElementRequirementsHeadline'] = parsetemplate($ElementParser['ElementRequirementsHeadline'], $ElementParser); - $StructuresList[] = parsetemplate($TPL['list_element'], $ElementParser); - $InfoBoxes[] = parsetemplate($TPL['infobox_body'], $ElementParser); - } - - // Create List - $ThisRowIndex = 0; - $InRowCount = 0; - foreach($StructuresList as $ParsedData) - { - if($InRowCount == $ElementsPerRow) - { - $ParsedRows[($ThisRowIndex + 1)] = $TPL['list_breakrow']; - $ThisRowIndex += 2; - $InRowCount = 0; - } - - if(!isset($StructureRows[$ThisRowIndex]['Elements'])) - { - $StructureRows[$ThisRowIndex]['Elements'] = ''; - } - $StructureRows[$ThisRowIndex]['Elements'] .= $ParsedData; - $InRowCount += 1; - } - if($InRowCount < $ElementsPerRow) - { - $StructureRows[$ThisRowIndex]['Elements'] .= str_repeat($TPL['list_hidden'], ($ElementsPerRow - $InRowCount)); - } - foreach($StructureRows as $Index => $Data) - { - $ParsedRows[$Index] = parsetemplate($TPL['list_row'], $Data); - } - ksort($ParsedRows, SORT_ASC); - $Parse['Create_StructuresList'] = implode('', $ParsedRows); - $Parse['Create_ElementsInfoBoxes'] = implode('', $InfoBoxes); - $Parse['Create_PrettyTimeZero'] = pretty_time(0); - $Parse['Create_InsertPrices'] = json_encode($ElementPriceArray); - $Parse['Create_InsertTimes'] = json_encode($ElementTimeArray); - if($CurrentUser['settings_useprettyinputbox'] == 1) - { - $Parse['P_AllowPrettyInputBox'] = 'true'; - } - else - { - $Parse['P_AllowPrettyInputBox'] = 'false'; - } - $Parse['Create_QueueJSArray'] = json_encode(isset($QueueJSArray) ? $QueueJSArray : null); - $Parse['Create_LastJSQueueID'] = ($QueueIndex > 0 ? $QueueIndex : '0'); - $Parse['Create_MetalMax'] = floor($CurrentPlanet['metal']); - $Parse['Create_CrystalMax'] = floor($CurrentPlanet['crystal']); - $Parse['Create_DeuteriumMax'] = floor($CurrentPlanet['deuterium']); - // End of - Parse all available ships - - $Parse['Insert_SkinPath'] = $_SkinPath; - $Parse['Insert_PlanetImg'] = $CurrentPlanet['image']; - $Parse['Insert_PlanetType'] = $_Lang['PlanetType_'.$CurrentPlanet['planet_type']]; - $Parse['Insert_PlanetName'] = $CurrentPlanet['name']; - $Parse['Insert_PlanetPos_Galaxy'] = $CurrentPlanet['galaxy']; - $Parse['Insert_PlanetPos_System'] = $CurrentPlanet['system']; - $Parse['Insert_PlanetPos_Planet'] = $CurrentPlanet['planet']; - $Parse['Insert_Overview_ShipyardLevel'] = $CurrentPlanet[$_Vars_GameElements[21]]; - $Parse['Insert_Overview_NanoFactoryLevel'] = $CurrentPlanet[$_Vars_GameElements[15]]; - $Parse['Insert_Overview_Temperature'] = sprintf($_Lang['Overview_Form_Temperature'], $CurrentPlanet['temp_min'], $CurrentPlanet['temp_max']); - - $BuildLevelFactor = 10; - $BuildLevel = 1; - $BuildTemp = $CurrentPlanet['temp_max']; - $Parse['Insert_Overview_SolarSateliteEnergy'] = prettyNumber(floor(eval($_Vars_ResProduction[212]['formule']['energy']))); - - $Page = parsetemplate(gettemplate('buildings_compact_body_shipyard'), $Parse); - - display($Page, $_Lang['Title_Shipyard']); -} - -?> \ No newline at end of file + '')); + $TPL['queue_topinfo'] = gettemplate('buildings_compact_queue_topinfo'); + $TPL['infobox_body'] = gettemplate('buildings_compact_infobox_body_shipyard'); + $TPL['infobox_req_res'] = gettemplate('buildings_compact_infobox_req_res'); + $TPL['infobox_additionalnfo'] = gettemplate('buildings_compact_infobox_additionalnfo'); + $TPL['infobox_additionalnfo_single'] = gettemplate('buildings_compact_infobox_additionalnfo_single'); + $TPL['infobox_req_selector_single'] = gettemplate('buildings_compact_infobox_req_selector_single'); + $TPL['infobox_req_selector_dual'] = gettemplate('buildings_compact_infobox_req_selector_dual'); + + if($CurrentPlanet[$_Vars_GameElements[21]] > 0) + { + $HasShipyard = true; + } + else + { + $HasShipyard = false; + } + + PlanetResourceUpdate($CurrentUser, $CurrentPlanet, $Now); + + if($IsInDefense) + { + $MissileSizes = array(502 => 1, 503 => 2); + $Missiles[502] = $CurrentPlanet[$_Vars_GameElements[502]]; + $Missiles[503] = $CurrentPlanet[$_Vars_GameElements[503]]; + $Shields[407] = $CurrentPlanet[$_Vars_GameElements[407]]; + $Shields[408] = $CurrentPlanet[$_Vars_GameElements[408]]; + $SiloSize = $CurrentPlanet[$_Vars_GameElements[44]]; + $MaxMissiles = $SiloSize * SILO_PERLEVELPLACE; + $SiloFreeSpace = $MaxMissiles; + + $CurrentQueue = $CurrentPlanet['shipyardQueue']; + if(!empty($CurrentQueue)) + { + $CurrentQueue = explode(';', $CurrentQueue); + foreach($CurrentQueue as $QueueData) + { + if(empty($QueueData)) + { + continue; + } + $QueueData = explode(',', $QueueData); + $ElementID = $QueueData[0]; + $ElementCount = $QueueData[1]; + if($ElementCount > 0) + { + if($ElementID == 502 OR $ElementID == 503) + { + $Missiles[$ElementID] += $ElementCount; + } + else if($ElementID == 407 OR $ElementID == 408) + { + $Shields[$ElementID] += $ElementCount; + } + } + } + } + + foreach($Missiles as $MissileKey => $MissileCount) + { + if($MissileCount > 0) + { + $SiloFreeSpace -= $MissileCount * $MissileSizes[$MissileKey]; + } + } + } + + // Execute Commands + if(!isOnVacation($CurrentUser)) + { + if(isset($_POST['cmd']) && $_POST['cmd'] == 'exec') + { + $AddedInQueue = false; + $AddedSomething = false; + + if($CurrentPlanet['shipyardQueue'] == '0') + { + $CurrentPlanet['shipyardQueue'] = ''; + } + + if($CurrentPlanet) + { + include($_EnginePath.'includes/functions/GetElementRessources.php'); + foreach($_POST['elem'] as $ElementID => $Count) + { + $Element = intval($ElementID); + $Count = floor(floatval(str_replace('.', '', $Count))); + if(in_array($ElementID, $_Vars_ElementCategories[$PageType])) + { + if($Count > 0) + { + if($Count > $QueueSize) + { + $Count = $QueueSize; + } + + if($IsInDefense) + { + if($ElementID == 407 OR $ElementID == 408) + { + if($Shields[$ElementID] >= 1) + { + continue; + } + else if($Count > 1) + { + $Count = 1; + } + } + else if($ElementID == 502 OR $ElementID == 503) + { + $ThisNeededSpace = $Count * $MissileSizes[$ElementID]; + if($ThisNeededSpace > $SiloFreeSpace) + { + $Count = floor($SiloFreeSpace/$MissileSizes[$ElementID]); + if($Count <= 0) + { + continue; + } + } + } + } + + if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $ElementID)) + { + $MaxElements = GetMaxConstructibleElements($ElementID, $CurrentPlanet); + if($Count > $MaxElements) + { + $Count = $MaxElements; + } + + if($Count > 0) + { + if($ElementID == 407 OR $ElementID == 408) + { + $Shields[$ElementID] += $Count; + } + else if($ElementID == 502 OR $ElementID == 503) + { + $Missiles[$ElementID] += $Count; + $SiloFreeSpace -= $Count * $MissileSizes[$ElementID]; + } + + $Ressource = GetElementRessources($ElementID, $Count); + $AddedSomething = true; + + if(!isset($UpdateAchievements[$ElementID])) + { + $UpdateAchievements[$ElementID] = 0; + } + $UpdateAchievements[$ElementID] += $Count; + $addToBHangar = "{$ElementID},{$Count};"; + $CurrentPlanet['metal'] -= $Ressource['metal']; + $CurrentPlanet['crystal'] -= $Ressource['crystal']; + $CurrentPlanet['deuterium'] -= $Ressource['deuterium']; + $CurrentPlanet['shipyardQueue'] .= $addToBHangar; + + $DevLog_Array[] = "{$ElementID},{$Count}"; + } + } + } + } + } + + if($AddedSomething) + { + // Update Achievements + foreach($UpdateAchievements as $Key => $Value) + { + $QryAchievementsKey[] = "`build_{$Key}`"; + $QryAchievementsArr[] = "`build_{$Key}` = `build_{$Key}` + VALUES(`build_{$Key}`)"; + } + $QryAchievements = ''; + $QryAchievements .= "INSERT INTO {{table}} (`A_UserID`, ".implode(', ', $QryAchievementsKey).") VALUES ({$CurrentUser['id']}, ".implode(', ', $UpdateAchievements).")"; + $QryAchievements .= " ON DUPLICATE KEY UPDATE "; + $QryAchievements .= implode(', ', $QryAchievementsArr); + $QryAchievements .= ';'; + doquery($QryAchievements, 'achievements_stats'); + + // Update DevLog + $UserDev_Log[] = array('PlanetID' => $CurrentPlanet['id'], 'Date' => $Now, 'Place' => ($IsInFleet ? 6 : 7), 'Code' => '0', 'ElementID' => '0', 'AdditionalData' => implode(';', $DevLog_Array)); + } + } + } + } + // End of - Execute Commands + + // Parse Queue + $CurrentQueue = $CurrentPlanet['shipyardQueue']; + $QueueIndex = 0; + $TotalTime = 0; + if(!empty($CurrentQueue)) + { + $CurrentQueue = explode(';', $CurrentQueue); + foreach($CurrentQueue as $QueueID => $QueueData) + { + if(empty($QueueData)) + { + continue; + } + $QueueData = explode(',', $QueueData); + $ListID = $QueueIndex + 1; + $ElementID = $QueueData[0]; + $ElementCount = $QueueData[1]; + $ElementName = $_Lang['tech'][$ElementID]; + $ElementTime = GetBuildingTime($CurrentUser, $CurrentPlanet, $ElementID); + $ElementTotalTime = $ElementTime * $ElementCount; + $TotalTime += $ElementTotalTime; + if($ElementTime > 0) + { + $RemoveCount = 0.1 / $ElementTime; + } + else + { + $RemoveCount = $ElementCount; + } + + $QueueParser[] = array + ( + 'ElementNo' => $ListID, + 'ElementID' => $ElementID, + 'Name' => $ElementName, + 'Count' => prettyNumber($ElementCount), + ); + $QueueJSArray[$ListID] = array('No' => $ListID, 'Remove' => $RemoveCount, 'Count' => $ElementCount); + + $QueueIndex += 1; + } + + if(!empty($QueueParser)) + { + $TotalTime -= $CurrentPlanet['shipyardQueue_additionalWorkTime']; + $QueueJSArray[1]['Count'] -= ($QueueJSArray[1]['Remove'] * (10 + ($CurrentPlanet['shipyardQueue_additionalWorkTime'] * 10))); + + include($_EnginePath.'/includes/functions/InsertJavaScriptChronoApplet.php'); + $QueueParser[0]['ChronoAppletScript'] = InsertJavaScriptChronoApplet('QueueFirstTimer', '', $TotalTime, false, false, 'function() { SetTimer = \"'.$_Lang['completed'].'\"; window.setTimeout(\'document.location.href=\"buildings.php?mode='.$PageType.'\";\', 1000); }'); + $QueueParser[0]['EndTimer'] = pretty_time($TotalTime, true); + $Parse['Create_RunQueueJSHandler'] = 'true'; + + foreach($QueueParser as $QueueID => $QueueData) + { + if($QueueID == 0) + { + $ThisTPL = gettemplate('buildings_compact_queue_firstel_shipyard'); + } + else if($QueueID == 1) + { + $ThisTPL = gettemplate('buildings_compact_queue_nextel_shipyard'); + } + $Parse['Create_Queue'] .= parsetemplate($ThisTPL, $QueueData); + } + } + } + else + { + $Parse['Create_Queue'] = parsetemplate($TPL['queue_topinfo'], array('InfoText' => $_Lang['Queue_Empty'])); + } + // End of - Parse Queue + + $ResImages = array + ( + 'metal' => 'metall', + 'crystal' => 'kristall', + 'deuterium' => 'deuterium', + 'energy_max' => 'energie', + 'darkEnergy' => 'darkenergy' + ); + $ResLangs = array + ( + 'metal' => $_Lang['Metal'], + 'crystal' => $_Lang['Crystal'], + 'deuterium' => $_Lang['Deuterium'], + 'energy_max' => $_Lang['Energy'], + 'darkEnergy' => $_Lang['DarkEnergy'] + ); + + $ElementParserDefault = array + ( + 'SkinPath' => $_SkinPath, + 'InfoBox_Count' => $_Lang['InfoBox_Count'], + 'InfoBox_Build' => $_Lang['InfoBox_DoResearch'], + 'InfoBox_RequirementsFor' => $_Lang['InfoBox_RequirementsForShip'], + 'InfoBox_ResRequirements' => $_Lang['InfoBox_ResRequirementsShip'], + 'InfoBox_TechRequirements' => $_Lang['InfoBox_TechRequirements'], + 'InfoBox_Requirements_Res' => $_Lang['InfoBox_Requirements_Res'], + 'InfoBox_Requirements_Tech' => $_Lang['InfoBox_Requirements_Tech'], + 'InfoBox_BuildTime' => $_Lang['InfoBox_ConstructionTime'], + 'InfoBox_MaxConstructible' => $_Lang['InfoBox_MaxConstructible'], + 'InfoBox_ShowTechReq' => $_Lang['InfoBox_ShowTechReq'], + 'InfoBox_ShowResReq' => $_Lang['InfoBox_ShowResReq'], + 'ElementPriceDiv' => '' + ); + + $TabIndex = 1; + + foreach($_Vars_ElementCategories[$PageType] as $ElementID) + { + $ElementParser = $ElementParserDefault; + + $HasResources = true; + $TechLevelOK = false; + $BlockShield = false; + $BlockMissile = false; + + $ElementParser['ElementCount'] = prettyNumber($CurrentPlanet[$_Vars_GameElements[$ElementID]]); + if(strlen($ElementParser['ElementCount']) > 10) + { + $ElementParser['IsBigNum'] = 'bignum'; + } + $ElementParser['MaxConstructible'] = GetMaxConstructibleElements($ElementID, $CurrentPlanet); + if($IsInDefense) + { + if($ElementID == 407 OR $ElementID == 408) + { + if($Shields[$ElementID] >= 1) + { + $ElementParser['MaxConstructible'] = 0; + $BlockShield = true; + } + else + { + $ElementParser['MaxConstructible'] = 1; + } + } + else if($ElementID == 502 OR $ElementID == 503) + { + $MaxMissilesSpace = floor($SiloFreeSpace / $MissileSizes[$ElementID]); + if($MaxMissilesSpace > 0) + { + if($MaxMissilesSpace < $ElementParser['MaxConstructible']) + { + $ElementParser['MaxConstructible'] = $MaxMissilesSpace; + } + } + else + { + $BlockMissile = true; + $ElementParser['MaxConstructible'] = 0; + } + } + } + $ElementParser['MaxConstructible'] = prettyNumber($ElementParser['MaxConstructible']); + $ElementParser['ElementName'] = $_Lang['tech'][$ElementID]; + $ElementParser['ElementID'] = $ElementID; + $ElementParser['Desc'] = $_Lang['res']['descriptions'][$ElementID]; + + $ElementParser['ElementPrice'] = GetBuildingPrice($CurrentUser, $CurrentPlanet, $ElementID, true, false, true); + foreach($ElementParser['ElementPrice'] as $Key => $Value) + { + if($Value > 0) + { + $ResColor = ''; + $ResMinusColor = ''; + $MinusValue = ' '; + + if($Key != 'darkEnergy') + { + $UseVar = &$CurrentPlanet; + } + else + { + $UseVar = &$CurrentUser; + } + if($UseVar[$Key] < $Value) + { + $ResMinusColor = 'red'; + $MinusValue = '('.prettyNumber($UseVar[$Key] - $Value).')'; + $ResColor = 'red'; + } + + $ElementParser['ElementPrices'] = array + ( + 'SkinPath' => $_SkinPath, + 'ResName' => $Key, + 'ResImg' => $ResImages[$Key], + 'ResColor' => $ResColor, + 'Value' => prettyNumber($Value), + 'ResMinusColor' => $ResMinusColor, + 'MinusValue' => $MinusValue + ); + $ElementParser['ElementPriceDiv'] .= parsetemplate($TPL['infobox_req_res'], $ElementParser['ElementPrices']); + $ElementPriceArray[$ElementID][$Key] = $Value; + } + } + $ElementParser['BuildTime'] = GetBuildingTime($CurrentUser, $CurrentPlanet, $ElementID); + $ElementTimeArray[$ElementID] = $ElementParser['BuildTime']; + $ElementParser['BuildTime'] = pretty_time($ElementParser['BuildTime']); + if($ElementID == 212) + { + $BuildLevelFactor = 10; + $BuildLevel = 1; + $BuildTemp= $CurrentPlanet['temp_max']; + $ElementParser['AdditionalNfo'][] = parsetemplate($TPL['infobox_additionalnfo'], array + ( + 'Label' => $_Lang['Energy'], + 'ValueClasses' => 'lime', + 'Value' => '+'.prettyNumber(floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']))) + )); + } + + if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $ElementID)) + { + $TechLevelOK = true; + $ElementParser['ElementRequirementsHeadline'] = $TPL['infobox_req_selector_single']; + } + else + { + $ElementParser['ElementRequirementsHeadline'] = $TPL['infobox_req_selector_dual']; + $ElementParser['ElementTechDiv'] = GetElementTechReq($CurrentUser, $CurrentPlanet, $ElementID, true); + $ElementParser['HideResReqDiv'] = 'hide'; + } + $HasResources = IsElementBuyable($CurrentUser, $CurrentPlanet, $ElementID, true, false, true); + + $BlockReason = array(); + + if(!$HasResources) + { + $BlockReason[] = $_Lang['ListBox_Disallow_NoResources']; + } + if(!$TechLevelOK) + { + $BlockReason[] = $_Lang['ListBox_Disallow_NoTech']; + } + if($BlockShield) + { + $BlockReason[] = $_Lang['ListBox_Disallow_ShieldBlock']; + $ElementParser['AdditionalNfo'][] = parsetemplate($TPL['infobox_additionalnfo_single'], array('ValueClasses' => 'red', 'Value' => $_Lang['ListBox_Disallow_ShieldBlock'])); + } + if($BlockMissile) + { + $BlockReason[] = $_Lang['ListBox_Disallow_MissileBlock']; + $ElementParser['AdditionalNfo'][] = parsetemplate($TPL['infobox_additionalnfo_single'], array('ValueClasses' => 'red', 'Value' => $_Lang['ListBox_Disallow_MissileBlock'])); + } + if(!$HasShipyard) + { + $BlockReason[] = $_Lang['ListBox_Disallow_NoShipyard']; + } + if(isOnVacation($CurrentUser)) + { + $BlockReason[] = $_Lang['ListBox_Disallow_VacationMode']; + } + + if(!empty($BlockReason)) + { + $ElementParser['ElementDisabled'] = $TPL['list_disabled']; + $ElementParser['ElementDisableInv'] = 'inv'; + $ElementParser['ElementDisableReason'] = end($BlockReason); + } + else + { + $ElementParser['TabIndex'] = $TabIndex; + $TabIndex += 1; + } + + if(!empty($ElementParser['AdditionalNfo'])) + { + $ElementParser['AdditionalNfo'] = implode('', $ElementParser['AdditionalNfo']); + } + $ElementParser['ElementRequirementsHeadline'] = parsetemplate($ElementParser['ElementRequirementsHeadline'], $ElementParser); + $StructuresList[] = parsetemplate($TPL['list_element'], $ElementParser); + $InfoBoxes[] = parsetemplate($TPL['infobox_body'], $ElementParser); + } + + // Create List + $ThisRowIndex = 0; + $InRowCount = 0; + foreach($StructuresList as $ParsedData) + { + if($InRowCount == $ElementsPerRow) + { + $ParsedRows[($ThisRowIndex + 1)] = $TPL['list_breakrow']; + $ThisRowIndex += 2; + $InRowCount = 0; + } + + if(!isset($StructureRows[$ThisRowIndex]['Elements'])) + { + $StructureRows[$ThisRowIndex]['Elements'] = ''; + } + $StructureRows[$ThisRowIndex]['Elements'] .= $ParsedData; + $InRowCount += 1; + } + if($InRowCount < $ElementsPerRow) + { + $StructureRows[$ThisRowIndex]['Elements'] .= str_repeat($TPL['list_hidden'], ($ElementsPerRow - $InRowCount)); + } + foreach($StructureRows as $Index => $Data) + { + $ParsedRows[$Index] = parsetemplate($TPL['list_row'], $Data); + } + ksort($ParsedRows, SORT_ASC); + $Parse['Create_StructuresList'] = implode('', $ParsedRows); + $Parse['Create_ElementsInfoBoxes'] = implode('', $InfoBoxes); + $Parse['Create_PrettyTimeZero'] = pretty_time(0); + $Parse['Create_InsertPrices'] = json_encode($ElementPriceArray); + $Parse['Create_InsertTimes'] = json_encode($ElementTimeArray); + if($CurrentUser['settings_useprettyinputbox'] == 1) + { + $Parse['P_AllowPrettyInputBox'] = 'true'; + } + else + { + $Parse['P_AllowPrettyInputBox'] = 'false'; + } + $Parse['Create_QueueJSArray'] = json_encode(isset($QueueJSArray) ? $QueueJSArray : null); + $Parse['Create_LastJSQueueID'] = ($QueueIndex > 0 ? $QueueIndex : '0'); + $Parse['Create_MetalMax'] = floor($CurrentPlanet['metal']); + $Parse['Create_CrystalMax'] = floor($CurrentPlanet['crystal']); + $Parse['Create_DeuteriumMax'] = floor($CurrentPlanet['deuterium']); + // End of - Parse all available ships + + $Parse['Insert_SkinPath'] = $_SkinPath; + $Parse['Insert_PlanetImg'] = $CurrentPlanet['image']; + $Parse['Insert_PlanetType'] = $_Lang['PlanetType_'.$CurrentPlanet['planet_type']]; + $Parse['Insert_PlanetName'] = $CurrentPlanet['name']; + $Parse['Insert_PlanetPos_Galaxy'] = $CurrentPlanet['galaxy']; + $Parse['Insert_PlanetPos_System'] = $CurrentPlanet['system']; + $Parse['Insert_PlanetPos_Planet'] = $CurrentPlanet['planet']; + $Parse['Insert_Overview_ShipyardLevel'] = $CurrentPlanet[$_Vars_GameElements[21]]; + $Parse['Insert_Overview_NanoFactoryLevel'] = $CurrentPlanet[$_Vars_GameElements[15]]; + $Parse['Insert_Overview_Temperature'] = sprintf($_Lang['Overview_Form_Temperature'], $CurrentPlanet['temp_min'], $CurrentPlanet['temp_max']); + + $BuildLevelFactor = 10; + $BuildLevel = 1; + $BuildTemp = $CurrentPlanet['temp_max']; + $Parse['Insert_Overview_SolarSateliteEnergy'] = prettyNumber(floor(eval($_Vars_ResProduction[212]['formule']['energy']))); + + $Page = parsetemplate(gettemplate('buildings_compact_body_shipyard'), $Parse); + + display($Page, $_Lang['Title_Shipyard']); +} + +?> diff --git a/includes/functions/ShowBuildingQueue.php b/includes/functions/ShowBuildingQueue.php index 3b46c659b..8194e94b7 100644 --- a/includes/functions/ShowBuildingQueue.php +++ b/includes/functions/ShowBuildingQueue.php @@ -1,96 +1,96 @@ -.lime { color: lime; }'; - $PlanetID = $CurrentPlanet['id']; - $CurrentTime = time(); - for($QueueID = 0; $QueueID < $ActualCount; $QueueID += 1) - { - // Each BuildingRecord is created in array: - // [0] -> Building ID - // [1] -> Level of Building - // [2] -> Time of Construction - // [3] -> End Time of Construction - // [4] -> Action (build/destroy) - $BuildArray = explode (',', $QueueArray[$QueueID]); - $BuildEndTime = floor($BuildArray[3]); - if($BuildEndTime >= $CurrentTime) - { - $ListID = $QueueID + 1; - $Element = $BuildArray[0]; - $BuildLevel = $BuildArray[1]; - $BuildMode = $BuildArray[4]; - $BuildTime = $BuildEndTime - $CurrentTime; - $ElementTitle = $_Lang['tech'][$Element]; - - $BuildLevelShow = $BuildLevel; - if($BuildMode != 'build') - { - $BuildLevelShow += 1; - $ShowDestroy = " ({$_Lang['destroy']})"; - } - else - { - $ShowDestroy = ''; - } - - $CreateRow = "{$ListID}. {$ElementTitle} ({$_Lang['level']} {$BuildLevelShow}){$ShowDestroy}"; - $CreateRow .= ''; - if($ListID == 1) - { - if(isset($_Vars_PremiumBuildings[$Element]) && $_Vars_PremiumBuildings[$Element] == 1) - { - $LinkHref = '#'; - $LinkOnClick = "alert('{$_Lang['CannotDeletePremiumBuilding_Warning']}'); return false;"; - $LinkClass = ' style="cursor: pointer; color: red;"'; - } - else - { - $LinkHref = "buildings.php?listid={$ListID}&cmd=cancel&planet={$PlanetID}"; - $LinkOnClick = "return confirm('{$_Lang['AreYouSure']}');"; - $LinkClass = ''; - } - $CreateRow .= "
    {$BuildTime}
    "; - $CreateRow .= '
    '.date('d/m H:i:s', $BuildEndTime).'
    '; - $CreateRow .= ""; - } - else - { - $CreateRow .= "{$_Lang['DelFromQueue']}"; - $CreateRow .= '

    '.date('d/m H:i:s', $BuildEndTime).'
    '; - } - $CreateRow .= ''; - - $ListIDRow .= $CreateRow; - } - } - } - - $RetValue['lenght'] = $ActualCount; - $RetValue['buildlist'] = $ListIDRow; - - return $RetValue; -} - -?> \ No newline at end of file +.lime { color: lime; }'; + $PlanetID = $CurrentPlanet['id']; + $CurrentTime = time(); + for($QueueID = 0; $QueueID < $ActualCount; $QueueID += 1) + { + // Each BuildingRecord is created in array: + // [0] -> Building ID + // [1] -> Level of Building + // [2] -> Time of Construction + // [3] -> End Time of Construction + // [4] -> Action (build/destroy) + $BuildArray = explode (',', $QueueArray[$QueueID]); + $BuildEndTime = floor($BuildArray[3]); + if($BuildEndTime >= $CurrentTime) + { + $ListID = $QueueID + 1; + $Element = $BuildArray[0]; + $BuildLevel = $BuildArray[1]; + $BuildMode = $BuildArray[4]; + $BuildTime = $BuildEndTime - $CurrentTime; + $ElementTitle = $_Lang['tech'][$Element]; + + $BuildLevelShow = $BuildLevel; + if($BuildMode != 'build') + { + $BuildLevelShow += 1; + $ShowDestroy = " ({$_Lang['destroy']})"; + } + else + { + $ShowDestroy = ''; + } + + $CreateRow = "{$ListID}. {$ElementTitle} ({$_Lang['level']} {$BuildLevelShow}){$ShowDestroy}"; + $CreateRow .= ''; + if($ListID == 1) + { + if(isset($_Vars_PremiumBuildings[$Element]) && $_Vars_PremiumBuildings[$Element] == 1) + { + $LinkHref = '#'; + $LinkOnClick = "alert('{$_Lang['CannotDeletePremiumBuilding_Warning']}'); return false;"; + $LinkClass = ' style="cursor: pointer; color: red;"'; + } + else + { + $LinkHref = "buildings.php?listid={$ListID}&cmd=cancel&planet={$PlanetID}"; + $LinkOnClick = "return confirm('{$_Lang['AreYouSure']}');"; + $LinkClass = ''; + } + $CreateRow .= "
    {$BuildTime}
    "; + $CreateRow .= '
    '.date('d/m H:i:s', $BuildEndTime).'
    '; + $CreateRow .= ""; + } + else + { + $CreateRow .= "{$_Lang['DelFromQueue']}"; + $CreateRow .= '

    '.date('d/m H:i:s', $BuildEndTime).'
    '; + } + $CreateRow .= ''; + + $ListIDRow .= $CreateRow; + } + } + } + + $RetValue['lenght'] = $ActualCount; + $RetValue['buildlist'] = $ListIDRow; + + return $RetValue; +} + +?> diff --git a/includes/functions/ShowGalaxyFooter.php b/includes/functions/ShowGalaxyFooter.php index bc845b37f..d7f3c02ee 100644 --- a/includes/functions/ShowGalaxyFooter.php +++ b/includes/functions/ShowGalaxyFooter.php @@ -1,36 +1,36 @@ - $Galaxy, - 'System' => $System, - 'Footer_Expedition' => $_Lang['Footer_Expedition'], - 'Footer_ColonizedPlanets' => $_Lang['Footer_ColonizedPlanets'], - 'Footer_Missiles' => $_Lang['Footer_Missiles'], - 'Footer_MissilesTitle' => $_Lang['Footer_MissilesTitle'], - 'Footer_MissilesDestroy' => $_Lang['Footer_MissilesDestroy'], - 'Footer_Ships' => $_Lang['Footer_Ships'], - 'Footer_Ship_Recyclers' => $_Lang['Footer_Ship_Recyclers'], - 'Footer_Ship_SpyProbes' => $_Lang['Footer_Ship_SpyProbes'], - 'Footer_Ship_Colonizators' => $_Lang['Footer_Ship_Colonizators'], - 'Footer_FlyingFleets' => $_Lang['Footer_FlyingFleets'], - 'Input_ColonizedPlanets' => prettyNumber($planetcount), - 'Input_LegendPopup' => GalaxyLegendPopup(), - 'Input_Missiles' => prettyNumber($CurrentMIP), - 'Input_Missiles_NoDisplay' => ($CurrentMIP > 0 ? '' : 'display: none;'), - 'Input_Recyclers' => prettyNumber($CurrentRC), - 'Input_SpyProbes' => prettyNumber($CurrentSP), - 'Input_Colonizers' => prettyNumber($CurrentCS), - 'Input_FlyingFleets' => prettyNumber($maxfleet_count), - 'Input_MaxFleets' => prettyNumber($fleetmax), - ); - - return parsetemplate($TPL, $Parse); -} - -?> \ No newline at end of file + $Galaxy, + 'System' => $System, + 'Footer_Expedition' => $_Lang['Footer_Expedition'], + 'Footer_ColonizedPlanets' => $_Lang['Footer_ColonizedPlanets'], + 'Footer_Missiles' => $_Lang['Footer_Missiles'], + 'Footer_MissilesTitle' => $_Lang['Footer_MissilesTitle'], + 'Footer_MissilesDestroy' => $_Lang['Footer_MissilesDestroy'], + 'Footer_Ships' => $_Lang['Footer_Ships'], + 'Footer_Ship_Recyclers' => $_Lang['Footer_Ship_Recyclers'], + 'Footer_Ship_SpyProbes' => $_Lang['Footer_Ship_SpyProbes'], + 'Footer_Ship_Colonizators' => $_Lang['Footer_Ship_Colonizators'], + 'Footer_FlyingFleets' => $_Lang['Footer_FlyingFleets'], + 'Input_ColonizedPlanets' => prettyNumber($planetcount), + 'Input_LegendPopup' => GalaxyLegendPopup(), + 'Input_Missiles' => prettyNumber($CurrentMIP), + 'Input_Missiles_NoDisplay' => ($CurrentMIP > 0 ? '' : 'display: none;'), + 'Input_Recyclers' => prettyNumber($CurrentRC), + 'Input_SpyProbes' => prettyNumber($CurrentSP), + 'Input_Colonizers' => prettyNumber($CurrentCS), + 'Input_FlyingFleets' => prettyNumber($maxfleet_count), + 'Input_MaxFleets' => prettyNumber($fleetmax), + ); + + return parsetemplate($TPL, $Parse); +} + +?> diff --git a/includes/functions/ShowGalaxyMISelector.php b/includes/functions/ShowGalaxyMISelector.php index 553af27b4..fcdffe08d 100644 --- a/includes/functions/ShowGalaxyMISelector.php +++ b/includes/functions/ShowGalaxyMISelector.php @@ -1,37 +1,37 @@ - $Galaxy, - 'System' => $System, - 'Planet' => $Planet, - 'ThisPos' => "{$Galaxy}:{$System}:{$Planet}", - 'MSelector_Title' => $_Lang['MSelector_Title'], - 'MSelector_MCount' => $_Lang['MSelector_MCount'], - 'MSelector_Target' => $_Lang['MSelector_Target'], - 'MSelector_TargetAll' => $_Lang['MSelector_TargetAll'], - 'MSelector_AvailableM' => $_Lang['MSelector_AvailableM'], - 'MSelector_Submit' => $_Lang['MSelector_Submit'], - 'MSelector_Close' => $_Lang['MSelector_Close'], - 'Input_MissileCount' => prettyNumber($AvailableMissiles), - 'Input_HideMissileForm' => ($HideSelector === true ? 'class="hide"' : ''), - 'Input_Targets' => '' - ); - foreach($_Vars_ElementCategories['defense'] as $ElementID) - { - if(in_array($ElementID, $_Vars_ElementCategories['rockets'])) - { - continue; - } - $Parse['Input_Targets'] .= ""; - } - - return parsetemplate($TPL, $Parse); -} - -?> \ No newline at end of file + $Galaxy, + 'System' => $System, + 'Planet' => $Planet, + 'ThisPos' => "{$Galaxy}:{$System}:{$Planet}", + 'MSelector_Title' => $_Lang['MSelector_Title'], + 'MSelector_MCount' => $_Lang['MSelector_MCount'], + 'MSelector_Target' => $_Lang['MSelector_Target'], + 'MSelector_TargetAll' => $_Lang['MSelector_TargetAll'], + 'MSelector_AvailableM' => $_Lang['MSelector_AvailableM'], + 'MSelector_Submit' => $_Lang['MSelector_Submit'], + 'MSelector_Close' => $_Lang['MSelector_Close'], + 'Input_MissileCount' => prettyNumber($AvailableMissiles), + 'Input_HideMissileForm' => ($HideSelector === true ? 'class="hide"' : ''), + 'Input_Targets' => '' + ); + foreach($_Vars_ElementCategories['defense'] as $ElementID) + { + if(in_array($ElementID, $_Vars_ElementCategories['rockets'])) + { + continue; + } + $Parse['Input_Targets'] .= ""; + } + + return parsetemplate($TPL, $Parse); +} + +?> diff --git a/includes/functions/ShowGalaxyRows.php b/includes/functions/ShowGalaxyRows.php index c1ad62209..0bde9a408 100644 --- a/includes/functions/ShowGalaxyRows.php +++ b/includes/functions/ShowGalaxyRows.php @@ -1,175 +1,175 @@ - UNIX_TIMESTAMP() "; - $Query_SFB .= "ORDER BY `EndTime` DESC LIMIT 1;"; - $Query_Buddy = ''; - $Query_Buddy .= "SELECT `sender`, `owner` FROM {{table}} "; - $Query_Buddy .= "WHERE `active` = 1 AND (`sender` = {$_User['id']} OR `owner` = {$_User['id']});"; - $Query_AllyPacts = ''; - $Query_AllyPacts .= "SELECT IF(`AllyID_Sender` = {$_User['ally_id']}, `AllyID_Owner`, `AllyID_Sender`) AS `AllyID`, `Type` "; - $Query_AllyPacts .= "FROM {{table}} WHERE (`AllyID_Sender` = {$_User['ally_id']} OR `AllyID_Owner` = {$_User['ally_id']}) AND `Active` = 1;"; - - $GalaxyResult = doquery($Query_Galaxies, 'galaxy'); - $PlanetsResult = doquery($Query_Planets, 'planets'); - $MoonsResult = doquery($Query_Moons, 'planets'); - $SFBStatus = doquery($Query_SFB, 'smart_fleet_blockade', true); - $MyBuddyList = doquery($Query_Buddy, 'buddy'); - - $MyAllyPacts = array(); - if($_User['ally_id'] > 0) - { - $Result_MyAllyPacts = doquery($Query_AllyPacts, 'ally_pacts'); - if(mysql_num_rows($Result_MyAllyPacts) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_MyAllyPacts)) - { - $MyAllyPacts[$FetchData['AllyID']] = $FetchData['Type']; - } - } - } - - $MyBuddies = array(); - if(mysql_num_rows($MyBuddyList) > 0) - { - while($MyBuddyData = mysql_fetch_assoc($MyBuddyList)) - { - if($MyBuddyData['sender'] != $_User['id']) - { - if(!in_array($MyBuddyData['sender'], $MyBuddies)) - { - $MyBuddies[] = $MyBuddyData['sender']; - } - continue; - } - if($MyBuddyData['owner'] != $_User['id']) - { - if(!in_array($MyBuddyData['owner'], $MyBuddies)) - { - $MyBuddies[] = $MyBuddyData['owner']; - } - } - } - } - - $Planet = 1; - $RowTPL = gettemplate('galaxy_row_body'); - - while($GalaxyRow = mysql_fetch_assoc($GalaxyResult) OR $Planet <= MAX_PLANET_IN_SYSTEM) - { - if($Planet <= MAX_PLANET_IN_SYSTEM) - { - if($GalaxyRow['planet'] > 0 AND $GalaxyRow['planet'] < $Planet) - { - $GalaxyRow = mysql_fetch_assoc($GalaxyResult); - } - - while($GalaxyRow['planet'] != $Planet) - { - if($Planet <= MAX_PLANET_IN_SYSTEM) - { - $RowData = ''; - $RowData .= GalaxyRowPos($Galaxy, $System, $Planet); - $RowData .= GalaxyRowPlanet(false, array(), array(), $Galaxy, $System, $Planet, 1, $MyBuddies, $MyAllyPacts); - $RowData .= GalaxyRowPlanetName(false, array(), array(), $Galaxy, $System, $Planet, 1, $MyBuddies); - $RowData .= GalaxyRowMoon(false, array(), array(), $Galaxy, $System, $Planet, 3, $MyBuddies, $MyAllyPacts); - $RowData .= GalaxyRowDebris(false, $Galaxy, $System, $Planet, 2); - $RowData .= GalaxyRowUser(array(), array(), $MyBuddies, $SFBStatus); - $RowData .= GalaxyRowAlly(array(), $MyAllyPacts); - $RowData .= GalaxyRowActions(array(), array(), $Galaxy, $System, $Planet, $MyBuddies); - - $Result .= parsetemplate($RowTPL, array('Data' => $RowData, 'SetHighlight' => ($Planet == $HighlightPlanet ? ' class="rowHighlight"' : ''))); - - $Planet += 1; - } - else - { - break; - } - } - - if($GalaxyRow['planet'] == $Planet) - { - $RowData = ''; - - $GalaxyRowMoon = array(); - if($GalaxyRow['id_planet'] != 0) - { - $GalaxyRowPlanet = mysql_fetch_assoc($PlanetsResult); - if($GalaxyRow['hide_planet'] == 0 OR CheckAuth('supportadmin') OR $_User['id'] == $GalaxyRowPlanet['id_owner']) - { - $planetcount += 1; - $GalaxyRowPlayer = $GalaxyRowPlanet; - $GalaxyRowPlayer['id'] = $GalaxyRowPlayer['user_id']; - if($GalaxyRow['id_moon'] != 0) - { - $GalaxyRowMoon = mysql_fetch_assoc($MoonsResult); - } - } - else - { - unset($GalaxyRowPlanet); - unset($GalaxyRow); - } - } - - $RowData .= GalaxyRowPos($Galaxy, $System, $Planet); - $RowData .= GalaxyRowPlanet($GalaxyRow, $GalaxyRowPlanet, $GalaxyRowPlayer, $Galaxy, $System, $Planet, 1 , $MyBuddies, $MyAllyPacts); - $RowData .= GalaxyRowPlanetName($GalaxyRow, $GalaxyRowPlanet, $GalaxyRowPlayer, $Galaxy, $System, $Planet, 1, $MyBuddies); - $RowData .= GalaxyRowMoon($GalaxyRow, $GalaxyRowMoon, $GalaxyRowPlayer, $Galaxy, $System, $Planet, 3, $MyBuddies, $MyAllyPacts); - $RowData .= GalaxyRowDebris($GalaxyRow, $Galaxy, $System, $Planet, 2); - $RowData .= GalaxyRowUser($GalaxyRowPlanet, $GalaxyRowPlayer, $MyBuddies, $SFBStatus); - $RowData .= GalaxyRowAlly($GalaxyRowPlayer, $MyAllyPacts); - $RowData .= GalaxyRowActions($GalaxyRowPlanet, $GalaxyRowPlayer, $Galaxy, $System, $Planet, $MyBuddies); - - $Result .= parsetemplate($RowTPL, array('Data' => $RowData, 'SetHighlight' => ($Planet == $HighlightPlanet ? ' class="rowHighlight"' : ''))); - - unset($GalaxyRowPlanet); - unset($GalaxyRowMoon); - unset($GalaxyRowPlayer); - } - - $Planet += 1; - } - else - { - break; - } - } - - return $Result; -} - -?> \ No newline at end of file + UNIX_TIMESTAMP() "; + $Query_SFB .= "ORDER BY `EndTime` DESC LIMIT 1;"; + $Query_Buddy = ''; + $Query_Buddy .= "SELECT `sender`, `owner` FROM {{table}} "; + $Query_Buddy .= "WHERE `active` = 1 AND (`sender` = {$_User['id']} OR `owner` = {$_User['id']});"; + $Query_AllyPacts = ''; + $Query_AllyPacts .= "SELECT IF(`AllyID_Sender` = {$_User['ally_id']}, `AllyID_Owner`, `AllyID_Sender`) AS `AllyID`, `Type` "; + $Query_AllyPacts .= "FROM {{table}} WHERE (`AllyID_Sender` = {$_User['ally_id']} OR `AllyID_Owner` = {$_User['ally_id']}) AND `Active` = 1;"; + + $GalaxyResult = doquery($Query_Galaxies, 'galaxy'); + $PlanetsResult = doquery($Query_Planets, 'planets'); + $MoonsResult = doquery($Query_Moons, 'planets'); + $SFBStatus = doquery($Query_SFB, 'smart_fleet_blockade', true); + $MyBuddyList = doquery($Query_Buddy, 'buddy'); + + $MyAllyPacts = array(); + if($_User['ally_id'] > 0) + { + $Result_MyAllyPacts = doquery($Query_AllyPacts, 'ally_pacts'); + if(mysql_num_rows($Result_MyAllyPacts) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_MyAllyPacts)) + { + $MyAllyPacts[$FetchData['AllyID']] = $FetchData['Type']; + } + } + } + + $MyBuddies = array(); + if(mysql_num_rows($MyBuddyList) > 0) + { + while($MyBuddyData = mysql_fetch_assoc($MyBuddyList)) + { + if($MyBuddyData['sender'] != $_User['id']) + { + if(!in_array($MyBuddyData['sender'], $MyBuddies)) + { + $MyBuddies[] = $MyBuddyData['sender']; + } + continue; + } + if($MyBuddyData['owner'] != $_User['id']) + { + if(!in_array($MyBuddyData['owner'], $MyBuddies)) + { + $MyBuddies[] = $MyBuddyData['owner']; + } + } + } + } + + $Planet = 1; + $RowTPL = gettemplate('galaxy_row_body'); + + while($GalaxyRow = mysql_fetch_assoc($GalaxyResult) OR $Planet <= MAX_PLANET_IN_SYSTEM) + { + if($Planet <= MAX_PLANET_IN_SYSTEM) + { + if($GalaxyRow['planet'] > 0 AND $GalaxyRow['planet'] < $Planet) + { + $GalaxyRow = mysql_fetch_assoc($GalaxyResult); + } + + while($GalaxyRow['planet'] != $Planet) + { + if($Planet <= MAX_PLANET_IN_SYSTEM) + { + $RowData = ''; + $RowData .= GalaxyRowPos($Galaxy, $System, $Planet); + $RowData .= GalaxyRowPlanet(false, array(), array(), $Galaxy, $System, $Planet, 1, $MyBuddies, $MyAllyPacts); + $RowData .= GalaxyRowPlanetName(false, array(), array(), $Galaxy, $System, $Planet, 1, $MyBuddies); + $RowData .= GalaxyRowMoon(false, array(), array(), $Galaxy, $System, $Planet, 3, $MyBuddies, $MyAllyPacts); + $RowData .= GalaxyRowDebris(false, $Galaxy, $System, $Planet, 2); + $RowData .= GalaxyRowUser(array(), array(), $MyBuddies, $SFBStatus); + $RowData .= GalaxyRowAlly(array(), $MyAllyPacts); + $RowData .= GalaxyRowActions(array(), array(), $Galaxy, $System, $Planet, $MyBuddies); + + $Result .= parsetemplate($RowTPL, array('Data' => $RowData, 'SetHighlight' => ($Planet == $HighlightPlanet ? ' class="rowHighlight"' : ''))); + + $Planet += 1; + } + else + { + break; + } + } + + if($GalaxyRow['planet'] == $Planet) + { + $RowData = ''; + + $GalaxyRowMoon = array(); + if($GalaxyRow['id_planet'] != 0) + { + $GalaxyRowPlanet = mysql_fetch_assoc($PlanetsResult); + if($GalaxyRow['hide_planet'] == 0 OR CheckAuth('supportadmin') OR $_User['id'] == $GalaxyRowPlanet['id_owner']) + { + $planetcount += 1; + $GalaxyRowPlayer = $GalaxyRowPlanet; + $GalaxyRowPlayer['id'] = $GalaxyRowPlayer['user_id']; + if($GalaxyRow['id_moon'] != 0) + { + $GalaxyRowMoon = mysql_fetch_assoc($MoonsResult); + } + } + else + { + unset($GalaxyRowPlanet); + unset($GalaxyRow); + } + } + + $RowData .= GalaxyRowPos($Galaxy, $System, $Planet); + $RowData .= GalaxyRowPlanet($GalaxyRow, $GalaxyRowPlanet, $GalaxyRowPlayer, $Galaxy, $System, $Planet, 1 , $MyBuddies, $MyAllyPacts); + $RowData .= GalaxyRowPlanetName($GalaxyRow, $GalaxyRowPlanet, $GalaxyRowPlayer, $Galaxy, $System, $Planet, 1, $MyBuddies); + $RowData .= GalaxyRowMoon($GalaxyRow, $GalaxyRowMoon, $GalaxyRowPlayer, $Galaxy, $System, $Planet, 3, $MyBuddies, $MyAllyPacts); + $RowData .= GalaxyRowDebris($GalaxyRow, $Galaxy, $System, $Planet, 2); + $RowData .= GalaxyRowUser($GalaxyRowPlanet, $GalaxyRowPlayer, $MyBuddies, $SFBStatus); + $RowData .= GalaxyRowAlly($GalaxyRowPlayer, $MyAllyPacts); + $RowData .= GalaxyRowActions($GalaxyRowPlanet, $GalaxyRowPlayer, $Galaxy, $System, $Planet, $MyBuddies); + + $Result .= parsetemplate($RowTPL, array('Data' => $RowData, 'SetHighlight' => ($Planet == $HighlightPlanet ? ' class="rowHighlight"' : ''))); + + unset($GalaxyRowPlanet); + unset($GalaxyRowMoon); + unset($GalaxyRowPlayer); + } + + $Planet += 1; + } + else + { + break; + } + } + + return $Result; +} + +?> diff --git a/includes/functions/ShowGalaxySelector.php b/includes/functions/ShowGalaxySelector.php index 8fcfad658..5d71e91e8 100644 --- a/includes/functions/ShowGalaxySelector.php +++ b/includes/functions/ShowGalaxySelector.php @@ -1,36 +1,36 @@ - MAX_GALAXY_IN_WORLD) - { - $Galaxy = MAX_GALAXY_IN_WORLD; - } - else if($Galaxy < 1) - { - $Galaxy = 1; - } - if($System > MAX_SYSTEM_IN_GALAXY) - { - $System = MAX_SYSTEM_IN_GALAXY; - } - else if($System < 1) - { - $System = 1; - } - - $TPL = gettemplate('galaxy_selector'); - $Parse = array - ( - 'Lang_Galaxy' => $_Lang['Galaxy'], - 'Lang_System' => $_Lang['Solar_system'], - 'Lang_Submit' => $_Lang['Afficher'], - 'Input_Galaxy' => $Galaxy, - 'Input_System' => $System - ); - return parsetemplate($TPL, $Parse); -} - -?> \ No newline at end of file + MAX_GALAXY_IN_WORLD) + { + $Galaxy = MAX_GALAXY_IN_WORLD; + } + else if($Galaxy < 1) + { + $Galaxy = 1; + } + if($System > MAX_SYSTEM_IN_GALAXY) + { + $System = MAX_SYSTEM_IN_GALAXY; + } + else if($System < 1) + { + $System = 1; + } + + $TPL = gettemplate('galaxy_selector'); + $Parse = array + ( + 'Lang_Galaxy' => $_Lang['Galaxy'], + 'Lang_System' => $_Lang['Solar_system'], + 'Lang_Submit' => $_Lang['Afficher'], + 'Input_Galaxy' => $Galaxy, + 'Input_System' => $System + ); + return parsetemplate($TPL, $Parse); +} + +?> diff --git a/includes/functions/ShowGalaxyTitles.php b/includes/functions/ShowGalaxyTitles.php index 159269927..37d4c0d7e 100644 --- a/includes/functions/ShowGalaxyTitles.php +++ b/includes/functions/ShowGalaxyTitles.php @@ -1,25 +1,25 @@ - $_Lang['Pos'], - 'Planet' => $_Lang['Planet'], - 'Name' => $_Lang['Name'], - 'Moon' => $_Lang['Moon'], - 'gl_debris' => $_Lang['gl_debris'], - 'Player' => $_Lang['Player'], - 'PlayerPos' => $_Lang['PlayerPos'], - 'PlayerPosTitle' => $_Lang['PlayerPosTitle'], - 'Alliance' => $_Lang['Alliance'], - 'Actions' => $_Lang['Actions'], - ); - - return parsetemplate($TPL, $Parse); -} - -?> \ No newline at end of file + $_Lang['Pos'], + 'Planet' => $_Lang['Planet'], + 'Name' => $_Lang['Name'], + 'Moon' => $_Lang['Moon'], + 'gl_debris' => $_Lang['gl_debris'], + 'Player' => $_Lang['Player'], + 'PlayerPos' => $_Lang['PlayerPos'], + 'PlayerPosTitle' => $_Lang['PlayerPosTitle'], + 'Alliance' => $_Lang['Alliance'], + 'Actions' => $_Lang['Actions'], + ); + + return parsetemplate($TPL, $Parse); +} + +?> diff --git a/includes/functions/ShowTopNavigationBar.php b/includes/functions/ShowTopNavigationBar.php index 6a1562aba..7fafcc329 100644 --- a/includes/functions/ShowTopNavigationBar.php +++ b/includes/functions/ShowTopNavigationBar.php @@ -1,425 +1,425 @@ -{$CurPlanet['name']} [{$CurPlanet['galaxy']}:{$CurPlanet['system']}:{$CurPlanet['planet']}]  "; - } - } - if($CurrentUser['planet_sort_moons'] == 1) - { - if(!empty($PlanetListArray)) - { - foreach($PlanetListArray as $Pos => $Planet) - { - $ParsedPlanetList[] = $Planet; - if(!empty($MoonListArray[$Pos])) - { - $ParsedPlanetList[] = $MoonListArray[$Pos]; - } - } - unset($PlanetListArray); - unset($MoonListArray); - foreach($ParsedPlanetList as $CurPlanet) - { - if($CurPlanet['id'] == $CurrentUser['current_planet']) - { - $ThisPlanetSelected = ' selected'; - } - else - { - $ThisPlanetSelected = ''; - } - if($CurPlanet['planet_type'] == 1) - { - $ThisPlanetPos = "{$CurPlanet['galaxy']}:{$CurPlanet['system']}:{$CurPlanet['planet']}"; - } - else - { - if($ThisPlanetSelected != '') - { - $ThisPlanetPos = "{$CurPlanet['galaxy']}:{$CurPlanet['system']}:{$CurPlanet['planet']}] [{$_Lang['PlanetList_MoonChar']}"; - } - else - { - $ThisPlanetPos = $_Lang['PlanetList_MoonSign']; - } - } - $parse['planetlist'] .= "\n"; - } - unset($ParsedPlanetList); - } - } - if($OtherType_ID > 0) - { - $parse['Insert_TypeChange_ID'] = $OtherType_ID; - if($CurrentPlanet['planet_type'] == 1) - { - $parse['Insert_TypeChange_Sign'] = $_Lang['PlanetList_TypeChange_Sign_M']; - $parse['Insert_TypeChange_Title'] = $_Lang['PlanetList_TypeChange_Title_M']; - } - else - { - $parse['Insert_TypeChange_Sign'] = $_Lang['PlanetList_TypeChange_Sign_P']; - $parse['Insert_TypeChange_Title'] = $_Lang['PlanetList_TypeChange_Title_P']; - } - } - else - { - $parse['Insert_TypeChange_Hide'] = 'hide'; - } - - // Calculate resources for JS RealTime Counters - - // > Energy - $EnergyFree = $CurrentPlanet['energy_max'] + $CurrentPlanet['energy_used']; - $EnergyPretty = prettyNumber($EnergyFree); - if($EnergyFree < 0) - { - $parse['Energy_free'] = colorRed($EnergyPretty); - } - else - { - $parse['Energy_free'] = colorGreen($EnergyPretty); - } - $parse['Energy_used'] = prettyNumber($CurrentPlanet['energy_max'] - $EnergyFree); - $parse['Energy_total'] = prettyNumber($CurrentPlanet['energy_max']); - - // > Metal - if($CurrentPlanet['metal'] >= $CurrentPlanet['metal_max']) - { - $parse['ShowCount_Metal'] = colorRed(prettyNumber($CurrentPlanet['metal'])); - $parse['ShowStore_Metal'] = colorRed(prettyNumber($CurrentPlanet['metal_max'])); - } - else - { - $parse['ShowCount_Metal'] = colorGreen(prettyNumber($CurrentPlanet['metal'])); - $parse['ShowStore_Metal'] = colorGreen(prettyNumber($CurrentPlanet['metal_max'])); - } - - // > Crystal - if($CurrentPlanet['crystal'] >= $CurrentPlanet['crystal_max']) - { - $parse['ShowCount_Crystal'] = colorRed(prettyNumber($CurrentPlanet['crystal'])); - $parse['ShowStore_Crystal'] = colorRed(prettyNumber($CurrentPlanet['crystal_max'])); - } - else - { - $parse['ShowCount_Crystal'] = colorGreen(prettyNumber($CurrentPlanet['crystal'])); - $parse['ShowStore_Crystal'] = colorGreen(prettyNumber($CurrentPlanet['crystal_max'])); - } - - // > Deuterium - if($CurrentPlanet['deuterium'] >= $CurrentPlanet['deuterium_max']) - { - $parse['ShowCount_Deuterium'] = colorRed(prettyNumber($CurrentPlanet['deuterium'])); - $parse['ShowStore_Deuterium'] = colorRed(prettyNumber($CurrentPlanet['deuterium_max'])); - } - else - { - $parse['ShowCount_Deuterium'] = colorGreen(prettyNumber($CurrentPlanet['deuterium'])); - $parse['ShowStore_Deuterium'] = colorGreen(prettyNumber($CurrentPlanet['deuterium_max'])); - } - - // > JS Vars - $parse['JSCount_Metal'] = $CurrentPlanet['metal']; - $parse['JSCount_Crystal'] = $CurrentPlanet['crystal']; - $parse['JSCount_Deuterium'] = $CurrentPlanet['deuterium']; - $parse['JSStore_Metal'] = $CurrentPlanet['metal_max']; - $parse['JSStore_Crystal'] = $CurrentPlanet['crystal_max']; - $parse['JSStore_Deuterium'] = $CurrentPlanet['deuterium_max']; - $parse['JSStoreOverflow_Metal'] = $CurrentPlanet['metal_max'] * MAX_OVERFLOW; - $parse['JSStoreOverflow_Crystal'] = $CurrentPlanet['crystal_max'] * MAX_OVERFLOW; - $parse['JSStoreOverflow_Deuterium'] = $CurrentPlanet['deuterium_max'] * MAX_OVERFLOW; - - // > Production Level - if(!$IsOnVacation) - { - if($CurrentPlanet['energy_max'] == 0 AND abs($CurrentPlanet['energy_used']) > 0) - { - $production_level = 0; - $CurrentPlanet['metal_perhour'] = $_GameConfig['metal_basic_income']; - $CurrentPlanet['crystal_perhour'] = $_GameConfig['crystal_basic_income']; - $CurrentPlanet['deuterium_perhour'] = $_GameConfig['deuterium_basic_income']; - } - else if($CurrentPlanet['energy_max'] > 0 AND abs($CurrentPlanet['energy_used']) > $CurrentPlanet['energy_max']) - { - $production_level = floor(($CurrentPlanet['energy_max'] * 100) / abs($CurrentPlanet['energy_used'])); - } - else - { - $production_level = 100; - } - if($production_level > 100) - { - $production_level = 100; - } - } - else - { - $production_level = 0; - } - - // > Income - $parse['JSPerHour_Metal'] = ($CurrentPlanet['metal_perhour'] * 0.01 * $production_level) + (($CurrentPlanet['planet_type'] == 1) ? ($_GameConfig['metal_basic_income'] * $_GameConfig['resource_multiplier']) : 0); - $parse['JSPerHour_Crystal'] = ($CurrentPlanet['crystal_perhour'] * 0.01 * $production_level) + (($CurrentPlanet['planet_type'] == 1) ? ($_GameConfig['crystal_basic_income'] * $_GameConfig['resource_multiplier']) : 0); - $parse['JSPerHour_Deuterium'] = ($CurrentPlanet['deuterium_perhour'] * 0.01 * $production_level) + (($CurrentPlanet['planet_type'] == 1) ? ($_GameConfig['deuterium_basic_income'] * $_GameConfig['resource_multiplier']) : 0); - - // > Create ToolTip Infos - $parse['TipIncome_Metal'] = '('.(($parse['JSPerHour_Metal'] >= 0) ? '+' : '-').prettyNumber(abs(round($parse['JSPerHour_Metal']))).'/h)'; - $parse['TipIncome_Crystal'] = '('.(($parse['JSPerHour_Crystal'] >= 0) ? '+' : '-').prettyNumber(abs(round($parse['JSPerHour_Crystal']))).'/h)'; - $parse['TipIncome_Deuterium'] = '('.(($parse['JSPerHour_Deuterium'] >= 0) ? '+' : '-').prettyNumber(abs(round($parse['JSPerHour_Deuterium']))).'/h)'; - - $IncomePerSecond['met'] = $parse['JSPerHour_Metal'] / 3600; - $IncomePerSecond['cry'] = $parse['JSPerHour_Crystal'] / 3600; - $IncomePerSecond['deu'] = $parse['JSPerHour_Deuterium'] / 3600; - - if($IncomePerSecond['met'] > 0) - { - $parse['Metal_full_time'] = (round($parse['JSStoreOverflow_Metal']) - round($CurrentPlanet['metal'])) / $IncomePerSecond['met']; - if($parse['Metal_full_time'] > 0) - { - $parse['Metal_full_time'] = $parse['full_in'].' '.pretty_time($parse['Metal_full_time']).''; - } - else - { - $parse['Metal_full_time'] = ''.$parse['full'].''; - } - } - else - { - $parse['Metal_full_time'] = $_Lang['income_no_mine']; - } - if($IsOnVacation) - { - $parse['Metal_full_time'] = $_Lang['income_vacation']; - } - - if($IncomePerSecond['cry'] > 0) - { - $parse['Crystal_full_time'] = (round($parse['JSStoreOverflow_Crystal']) - round($CurrentPlanet['crystal'])) / $IncomePerSecond['cry']; - if($parse['Crystal_full_time'] > 0) - { - $parse['Crystal_full_time'] = $parse['full_in'].' '.pretty_time($parse['Crystal_full_time']).''; - } - else - { - $parse['Crystal_full_time'] = ''.$parse['full'].''; - } - } - else - { - $parse['Crystal_full_time'] = $_Lang['income_no_mine']; - } - if($IsOnVacation) - { - $parse['Crystal_full_time'] = $_Lang['income_vacation']; - } - - if($IncomePerSecond['deu'] > 0) - { - $parse['Deuterium_full_time'] = (round($parse['JSStoreOverflow_Deuterium']) - round($CurrentPlanet['deuterium'])) / $IncomePerSecond['deu']; - if($parse['Deuterium_full_time'] > 0) - { - $parse['Deuterium_full_time'] = $parse['full_in'].' '.pretty_time($parse['Deuterium_full_time']).''; - } - else - { - $parse['Deuterium_full_time'] = ''.$parse['full'].''; - } - } - elseif($IncomePerSecond['deu'] < 0) - { - $parse['Deuterium_full_time'] = $_Lang['income_minus']; - } - else - { - $parse['Deuterium_full_time'] = $_Lang['income_no_mine']; - } - if($IsOnVacation) - { - $parse['Deuterium_full_time'] = $_Lang['income_vacation']; - } - - // > Create ToolTip Storage Status - if($CurrentPlanet['metal'] > $CurrentPlanet['metal_max']) - { - if($CurrentPlanet['metal'] == $parse['JSStoreOverflow_Metal']) - { - $parse['Metal_store_status'] = $parse['Store_status_Full']; - } - else - { - $parse['Metal_store_status'] = $parse['Store_status_Overload']; - } - } - else - { - if($CurrentPlanet['metal'] > 0) - { - if($CurrentPlanet['metal'] >= ($CurrentPlanet['metal_max'] * 0.8)) - { - $parse['Metal_store_status'] = $parse['Store_status_NearFull']; - } - else - { - $parse['Metal_store_status'] = $parse['Store_status_OK']; - } - } - else - { - $parse['Metal_store_status'] = $parse['Store_status_Empty']; - } - } - - if($CurrentPlanet['crystal'] > $CurrentPlanet['crystal_max']) - { - if($CurrentPlanet['crystal'] == $parse['JSStoreOverflow_Crystal']) - { - $parse['Crystal_store_status'] = $parse['Store_status_Full']; - } - else - { - $parse['Crystal_store_status'] = $parse['Store_status_Overload']; - } - } - else - { - if($CurrentPlanet['crystal'] > 0) - { - if($CurrentPlanet['crystal'] >= ($CurrentPlanet['crystal_max'] * 0.8)) - { - $parse['Crystal_store_status'] = $parse['Store_status_NearFull']; - } - else - { - $parse['Crystal_store_status'] = $parse['Store_status_OK']; - } - } - else - { - $parse['Crystal_store_status'] = $parse['Store_status_Empty']; - } - } - - if($CurrentPlanet['deuterium'] > $CurrentPlanet['deuterium_max']) - { - if($CurrentPlanet['deuterium'] == $parse['JSStoreOverflow_Deuterium']) - { - $parse['Deuterium_store_status'] = $parse['Store_status_Full']; - } - else - { - $parse['Deuterium_store_status'] = $parse['Store_status_Overload']; - } - } - else - { - if($CurrentPlanet['metal'] > 0) - { - if($CurrentPlanet['deuterium'] >= ($CurrentPlanet['deuterium_max'] * 0.8)) - { - $parse['Deuterium_store_status'] = $parse['Store_status_NearFull']; - } - else - { - $parse['Deuterium_store_status'] = $parse['Store_status_OK']; - } - } - else - { - $parse['Deuterium_store_status'] = $parse['Store_status_Empty']; - } - } - - // Dark Energy - if($_User['darkEnergy'] > 0) - { - $parse['ShowCount_DarkEnergy'] = ''.prettyNumber($_User['darkEnergy']).''; - } - else - { - $parse['ShowCount_DarkEnergy'] = ''.$_User['darkEnergy'].''; - } - - // Messages Counter - $Query_MsgCount = ''; - $Query_MsgCount .= "SELECT COUNT(*) AS `Count` FROM {{table}} WHERE "; - $Query_MsgCount .= "`id_owner` = {$CurrentUser['id']} AND "; - $Query_MsgCount .= "`deleted` = false AND "; - $Query_MsgCount .= "`read` = false "; - $Query_MsgCount .= "LIMIT 1;"; - $Result_MsgCount = doquery($Query_MsgCount, 'messages', true); - if($Result_MsgCount['Count'] > 0) - { - $parse['ShowCount_Messages'] = '[ '.prettyNumber($Result_MsgCount['Count']).' ]'; - $NewMSGCount = $Result_MsgCount['Count']; - } - else - { - $parse['ShowCount_Messages'] = '0'; - } - - $TopBar = parsetemplate(gettemplate('topnav'), $parse); - - return $TopBar; - } -} - -?> +{$CurPlanet['name']} [{$CurPlanet['galaxy']}:{$CurPlanet['system']}:{$CurPlanet['planet']}]  "; + } + } + if($CurrentUser['planet_sort_moons'] == 1) + { + if(!empty($PlanetListArray)) + { + foreach($PlanetListArray as $Pos => $Planet) + { + $ParsedPlanetList[] = $Planet; + if(!empty($MoonListArray[$Pos])) + { + $ParsedPlanetList[] = $MoonListArray[$Pos]; + } + } + unset($PlanetListArray); + unset($MoonListArray); + foreach($ParsedPlanetList as $CurPlanet) + { + if($CurPlanet['id'] == $CurrentUser['current_planet']) + { + $ThisPlanetSelected = ' selected'; + } + else + { + $ThisPlanetSelected = ''; + } + if($CurPlanet['planet_type'] == 1) + { + $ThisPlanetPos = "{$CurPlanet['galaxy']}:{$CurPlanet['system']}:{$CurPlanet['planet']}"; + } + else + { + if($ThisPlanetSelected != '') + { + $ThisPlanetPos = "{$CurPlanet['galaxy']}:{$CurPlanet['system']}:{$CurPlanet['planet']}] [{$_Lang['PlanetList_MoonChar']}"; + } + else + { + $ThisPlanetPos = $_Lang['PlanetList_MoonSign']; + } + } + $parse['planetlist'] .= "\n"; + } + unset($ParsedPlanetList); + } + } + if($OtherType_ID > 0) + { + $parse['Insert_TypeChange_ID'] = $OtherType_ID; + if($CurrentPlanet['planet_type'] == 1) + { + $parse['Insert_TypeChange_Sign'] = $_Lang['PlanetList_TypeChange_Sign_M']; + $parse['Insert_TypeChange_Title'] = $_Lang['PlanetList_TypeChange_Title_M']; + } + else + { + $parse['Insert_TypeChange_Sign'] = $_Lang['PlanetList_TypeChange_Sign_P']; + $parse['Insert_TypeChange_Title'] = $_Lang['PlanetList_TypeChange_Title_P']; + } + } + else + { + $parse['Insert_TypeChange_Hide'] = 'hide'; + } + + // Calculate resources for JS RealTime Counters + + // > Energy + $EnergyFree = $CurrentPlanet['energy_max'] + $CurrentPlanet['energy_used']; + $EnergyPretty = prettyNumber($EnergyFree); + if($EnergyFree < 0) + { + $parse['Energy_free'] = colorRed($EnergyPretty); + } + else + { + $parse['Energy_free'] = colorGreen($EnergyPretty); + } + $parse['Energy_used'] = prettyNumber($CurrentPlanet['energy_max'] - $EnergyFree); + $parse['Energy_total'] = prettyNumber($CurrentPlanet['energy_max']); + + // > Metal + if($CurrentPlanet['metal'] >= $CurrentPlanet['metal_max']) + { + $parse['ShowCount_Metal'] = colorRed(prettyNumber($CurrentPlanet['metal'])); + $parse['ShowStore_Metal'] = colorRed(prettyNumber($CurrentPlanet['metal_max'])); + } + else + { + $parse['ShowCount_Metal'] = colorGreen(prettyNumber($CurrentPlanet['metal'])); + $parse['ShowStore_Metal'] = colorGreen(prettyNumber($CurrentPlanet['metal_max'])); + } + + // > Crystal + if($CurrentPlanet['crystal'] >= $CurrentPlanet['crystal_max']) + { + $parse['ShowCount_Crystal'] = colorRed(prettyNumber($CurrentPlanet['crystal'])); + $parse['ShowStore_Crystal'] = colorRed(prettyNumber($CurrentPlanet['crystal_max'])); + } + else + { + $parse['ShowCount_Crystal'] = colorGreen(prettyNumber($CurrentPlanet['crystal'])); + $parse['ShowStore_Crystal'] = colorGreen(prettyNumber($CurrentPlanet['crystal_max'])); + } + + // > Deuterium + if($CurrentPlanet['deuterium'] >= $CurrentPlanet['deuterium_max']) + { + $parse['ShowCount_Deuterium'] = colorRed(prettyNumber($CurrentPlanet['deuterium'])); + $parse['ShowStore_Deuterium'] = colorRed(prettyNumber($CurrentPlanet['deuterium_max'])); + } + else + { + $parse['ShowCount_Deuterium'] = colorGreen(prettyNumber($CurrentPlanet['deuterium'])); + $parse['ShowStore_Deuterium'] = colorGreen(prettyNumber($CurrentPlanet['deuterium_max'])); + } + + // > JS Vars + $parse['JSCount_Metal'] = $CurrentPlanet['metal']; + $parse['JSCount_Crystal'] = $CurrentPlanet['crystal']; + $parse['JSCount_Deuterium'] = $CurrentPlanet['deuterium']; + $parse['JSStore_Metal'] = $CurrentPlanet['metal_max']; + $parse['JSStore_Crystal'] = $CurrentPlanet['crystal_max']; + $parse['JSStore_Deuterium'] = $CurrentPlanet['deuterium_max']; + $parse['JSStoreOverflow_Metal'] = $CurrentPlanet['metal_max'] * MAX_OVERFLOW; + $parse['JSStoreOverflow_Crystal'] = $CurrentPlanet['crystal_max'] * MAX_OVERFLOW; + $parse['JSStoreOverflow_Deuterium'] = $CurrentPlanet['deuterium_max'] * MAX_OVERFLOW; + + // > Production Level + if(!$IsOnVacation) + { + if($CurrentPlanet['energy_max'] == 0 AND abs($CurrentPlanet['energy_used']) > 0) + { + $production_level = 0; + $CurrentPlanet['metal_perhour'] = $_GameConfig['metal_basic_income']; + $CurrentPlanet['crystal_perhour'] = $_GameConfig['crystal_basic_income']; + $CurrentPlanet['deuterium_perhour'] = $_GameConfig['deuterium_basic_income']; + } + else if($CurrentPlanet['energy_max'] > 0 AND abs($CurrentPlanet['energy_used']) > $CurrentPlanet['energy_max']) + { + $production_level = floor(($CurrentPlanet['energy_max'] * 100) / abs($CurrentPlanet['energy_used'])); + } + else + { + $production_level = 100; + } + if($production_level > 100) + { + $production_level = 100; + } + } + else + { + $production_level = 0; + } + + // > Income + $parse['JSPerHour_Metal'] = ($CurrentPlanet['metal_perhour'] * 0.01 * $production_level) + (($CurrentPlanet['planet_type'] == 1) ? ($_GameConfig['metal_basic_income'] * $_GameConfig['resource_multiplier']) : 0); + $parse['JSPerHour_Crystal'] = ($CurrentPlanet['crystal_perhour'] * 0.01 * $production_level) + (($CurrentPlanet['planet_type'] == 1) ? ($_GameConfig['crystal_basic_income'] * $_GameConfig['resource_multiplier']) : 0); + $parse['JSPerHour_Deuterium'] = ($CurrentPlanet['deuterium_perhour'] * 0.01 * $production_level) + (($CurrentPlanet['planet_type'] == 1) ? ($_GameConfig['deuterium_basic_income'] * $_GameConfig['resource_multiplier']) : 0); + + // > Create ToolTip Infos + $parse['TipIncome_Metal'] = '('.(($parse['JSPerHour_Metal'] >= 0) ? '+' : '-').prettyNumber(abs(round($parse['JSPerHour_Metal']))).'/h)'; + $parse['TipIncome_Crystal'] = '('.(($parse['JSPerHour_Crystal'] >= 0) ? '+' : '-').prettyNumber(abs(round($parse['JSPerHour_Crystal']))).'/h)'; + $parse['TipIncome_Deuterium'] = '('.(($parse['JSPerHour_Deuterium'] >= 0) ? '+' : '-').prettyNumber(abs(round($parse['JSPerHour_Deuterium']))).'/h)'; + + $IncomePerSecond['met'] = $parse['JSPerHour_Metal'] / 3600; + $IncomePerSecond['cry'] = $parse['JSPerHour_Crystal'] / 3600; + $IncomePerSecond['deu'] = $parse['JSPerHour_Deuterium'] / 3600; + + if($IncomePerSecond['met'] > 0) + { + $parse['Metal_full_time'] = (round($parse['JSStoreOverflow_Metal']) - round($CurrentPlanet['metal'])) / $IncomePerSecond['met']; + if($parse['Metal_full_time'] > 0) + { + $parse['Metal_full_time'] = $parse['full_in'].' '.pretty_time($parse['Metal_full_time']).''; + } + else + { + $parse['Metal_full_time'] = ''.$parse['full'].''; + } + } + else + { + $parse['Metal_full_time'] = $_Lang['income_no_mine']; + } + if($IsOnVacation) + { + $parse['Metal_full_time'] = $_Lang['income_vacation']; + } + + if($IncomePerSecond['cry'] > 0) + { + $parse['Crystal_full_time'] = (round($parse['JSStoreOverflow_Crystal']) - round($CurrentPlanet['crystal'])) / $IncomePerSecond['cry']; + if($parse['Crystal_full_time'] > 0) + { + $parse['Crystal_full_time'] = $parse['full_in'].' '.pretty_time($parse['Crystal_full_time']).''; + } + else + { + $parse['Crystal_full_time'] = ''.$parse['full'].''; + } + } + else + { + $parse['Crystal_full_time'] = $_Lang['income_no_mine']; + } + if($IsOnVacation) + { + $parse['Crystal_full_time'] = $_Lang['income_vacation']; + } + + if($IncomePerSecond['deu'] > 0) + { + $parse['Deuterium_full_time'] = (round($parse['JSStoreOverflow_Deuterium']) - round($CurrentPlanet['deuterium'])) / $IncomePerSecond['deu']; + if($parse['Deuterium_full_time'] > 0) + { + $parse['Deuterium_full_time'] = $parse['full_in'].' '.pretty_time($parse['Deuterium_full_time']).''; + } + else + { + $parse['Deuterium_full_time'] = ''.$parse['full'].''; + } + } + elseif($IncomePerSecond['deu'] < 0) + { + $parse['Deuterium_full_time'] = $_Lang['income_minus']; + } + else + { + $parse['Deuterium_full_time'] = $_Lang['income_no_mine']; + } + if($IsOnVacation) + { + $parse['Deuterium_full_time'] = $_Lang['income_vacation']; + } + + // > Create ToolTip Storage Status + if($CurrentPlanet['metal'] > $CurrentPlanet['metal_max']) + { + if($CurrentPlanet['metal'] == $parse['JSStoreOverflow_Metal']) + { + $parse['Metal_store_status'] = $parse['Store_status_Full']; + } + else + { + $parse['Metal_store_status'] = $parse['Store_status_Overload']; + } + } + else + { + if($CurrentPlanet['metal'] > 0) + { + if($CurrentPlanet['metal'] >= ($CurrentPlanet['metal_max'] * 0.8)) + { + $parse['Metal_store_status'] = $parse['Store_status_NearFull']; + } + else + { + $parse['Metal_store_status'] = $parse['Store_status_OK']; + } + } + else + { + $parse['Metal_store_status'] = $parse['Store_status_Empty']; + } + } + + if($CurrentPlanet['crystal'] > $CurrentPlanet['crystal_max']) + { + if($CurrentPlanet['crystal'] == $parse['JSStoreOverflow_Crystal']) + { + $parse['Crystal_store_status'] = $parse['Store_status_Full']; + } + else + { + $parse['Crystal_store_status'] = $parse['Store_status_Overload']; + } + } + else + { + if($CurrentPlanet['crystal'] > 0) + { + if($CurrentPlanet['crystal'] >= ($CurrentPlanet['crystal_max'] * 0.8)) + { + $parse['Crystal_store_status'] = $parse['Store_status_NearFull']; + } + else + { + $parse['Crystal_store_status'] = $parse['Store_status_OK']; + } + } + else + { + $parse['Crystal_store_status'] = $parse['Store_status_Empty']; + } + } + + if($CurrentPlanet['deuterium'] > $CurrentPlanet['deuterium_max']) + { + if($CurrentPlanet['deuterium'] == $parse['JSStoreOverflow_Deuterium']) + { + $parse['Deuterium_store_status'] = $parse['Store_status_Full']; + } + else + { + $parse['Deuterium_store_status'] = $parse['Store_status_Overload']; + } + } + else + { + if($CurrentPlanet['metal'] > 0) + { + if($CurrentPlanet['deuterium'] >= ($CurrentPlanet['deuterium_max'] * 0.8)) + { + $parse['Deuterium_store_status'] = $parse['Store_status_NearFull']; + } + else + { + $parse['Deuterium_store_status'] = $parse['Store_status_OK']; + } + } + else + { + $parse['Deuterium_store_status'] = $parse['Store_status_Empty']; + } + } + + // Dark Energy + if($_User['darkEnergy'] > 0) + { + $parse['ShowCount_DarkEnergy'] = ''.prettyNumber($_User['darkEnergy']).''; + } + else + { + $parse['ShowCount_DarkEnergy'] = ''.$_User['darkEnergy'].''; + } + + // Messages Counter + $Query_MsgCount = ''; + $Query_MsgCount .= "SELECT COUNT(*) AS `Count` FROM {{table}} WHERE "; + $Query_MsgCount .= "`id_owner` = {$CurrentUser['id']} AND "; + $Query_MsgCount .= "`deleted` = false AND "; + $Query_MsgCount .= "`read` = false "; + $Query_MsgCount .= "LIMIT 1;"; + $Result_MsgCount = doquery($Query_MsgCount, 'messages', true); + if($Result_MsgCount['Count'] > 0) + { + $parse['ShowCount_Messages'] = '[ '.prettyNumber($Result_MsgCount['Count']).' ]'; + $NewMSGCount = $Result_MsgCount['Count']; + } + else + { + $parse['ShowCount_Messages'] = '0'; + } + + $TopBar = parsetemplate(gettemplate('topnav'), $parse); + + return $TopBar; + } +} + +?> diff --git a/includes/functions/SortUserPlanets.php b/includes/functions/SortUserPlanets.php index 258eb168f..c3f616b02 100644 --- a/includes/functions/SortUserPlanets.php +++ b/includes/functions/SortUserPlanets.php @@ -1,33 +1,33 @@ - \ No newline at end of file + diff --git a/includes/functions/SpyTarget.php b/includes/functions/SpyTarget.php index e579ab7fc..72cdf2fb1 100644 --- a/includes/functions/SpyTarget.php +++ b/includes/functions/SpyTarget.php @@ -1,183 +1,183 @@ - 0) - { - $ReturnData[] = '{SpyRes_Msg_empty}'; - } - else - { - $ReturnData[] = '{SpyRes_Msg_ab_empty}'; - } - } - else - { - if($UserInfo['uid'] > 0) - { - $ReturnData[] = '{SpyRes_Msg}'; - } - else - { - $ReturnData[] = '{SpyRes_Msg_ab}'; - } - } - $ReturnData[] = ($TargetArray['planet_type'] == 1 ? $_Lang['Spy_OnPlanet'] : $_Lang['Spy_OnMoon']); - $ReturnData[] = $TargetArray['name']; - $ReturnData[] = $TargetArray['galaxy']; - $ReturnData[] = $TargetArray['system']; - $ReturnData[] = $TargetArray['galaxy']; - $ReturnData[] = $TargetArray['system']; - $ReturnData[] = $TargetArray['planet']; - if($UserInfo['uid'] > 0) - { - $ReturnData[] = $UserInfo['uid']; - $ReturnData[] = $UserInfo['username']; - } - else - { - $ReturnData[] = $_Lang['Spy_Abandoned_'.$TargetArray['planet_type']]; - } - if($UserInfo['isEmptyReport'] === true) - { - $ReturnData[] = $_Lang['Spy_Morale_EmptyReport']; - } - else - { - $ReturnData[] = prettyNumber($TargetArray['metal']); - $ReturnData[] = prettyNumber($TargetArray['crystal']); - $ReturnData[] = prettyNumber($TargetArray['deuterium']); - $ReturnData[] = prettyNumber($TargetArray['energy_max']); - } - $ReturnArray[] = $ReturnData; - $LookAtLoop = false; - } - else if($Mode == 1) - { - // Show Ships - $ElementArrays[] = $_Vars_ElementCategories['fleet']; - $AddToSim = true; - } - else if($Mode == 2) - { - $ElementArrays[] = $_Vars_ElementCategories['defense']; - $AddToSim = true; - } - else if($Mode == 3) - { - $ElementArrays[] = $_Vars_ElementCategories['build']; - } - else if($Mode == 4) - { - $ElementArrays[] = $_Vars_ElementCategories['tech']; - $AddToSim = array(109, 110, 111, 120, 121, 122, 125, 126, 199); - } - else if($Mode == 5) - { - // Show Morale Info - if(MORALE_ENABLED) - { - Morale_ReCalculate($TargetArray, $UserInfo['SpyTime']); - $TargetMorale = $TargetArray['morale_level']; - $TargetMoraleStatus = $_Lang['SpyRes_Morale_Mood_Neutral']; - if($TargetArray['morale_droptime'] > $UserInfo['SpyTime']) - { - if($TargetMorale > 0) - { - $TargetMoraleStatus = $_Lang['SpyRes_Morale_Mood_Positive']; - } - else if($TargetMorale < 0) - { - $TargetMoraleStatus = $_Lang['SpyRes_Morale_Mood_Negative']; - } - } - - $ReturnArray[] = array('{SpyRes_Mor}', $TargetMorale, $TargetMoraleStatus, prettyNumber($TargetArray['morale_points'])); - } - else - { - $ReturnArray[] = array('{SpyRes_Emp}'); - } - $LookAtLoop = false; - } - - $Count = 0; - if($LookAtLoop == true) - { - $ReturnArray[] = array('{SpyRes_Oth}', ((2 * SPY_REPORT_ROW) + (SPY_REPORT_ROW - 1)), $TitleString); - - $ArrayString = null; - if(!empty($ElementArrays)) - { - foreach($ElementArrays as $ThisArray) - { - $row = 0; - foreach($ThisArray as $ElementID) - { - if(isset($TargetArray[$_Vars_GameElements[$ElementID]]) && $TargetArray[$_Vars_GameElements[$ElementID]] > 0) - { - if($row == 0) - { - $ArrayString .= ''; - } - $ArrayString .= '{s_tdl}{tech}['.$ElementID.']{s_tdr}'.prettyNumber($TargetArray[$_Vars_GameElements[$ElementID]]).''; - if($row < SPY_REPORT_ROW - 1) - { - $ArrayString .= '{s_tdn}'; - } - $Count += $TargetArray[$_Vars_GameElements[$ElementID]]; - $row += 1; - if($row == SPY_REPORT_ROW) - { - $ArrayString .= ''; - $row = 0; - } - if($AddToSim === TRUE OR ((array)$AddToSim === $AddToSim AND in_array($ElementID, $AddToSim, true))) - { - $SimData[$ElementID] = $TargetArray[$_Vars_GameElements[$ElementID]]; - } - } - } - while($row != 0) - { - $ArrayString .= '{s_tdn}{s_tdn}'; - $row += 1; - if($row == SPY_REPORT_ROW) - { - $ArrayString .= ''; - $row= 0; - } - } - } - } - - $ReturnArray[] = $ArrayString; - } - $ReturnArray[] = ''; - - $return['Array'] = $ReturnArray; - $return['Count'] = $Count; - $return['Sim'] = $SimData; - return $return; -} - -?> \ No newline at end of file + 0) + { + $ReturnData[] = '{SpyRes_Msg_empty}'; + } + else + { + $ReturnData[] = '{SpyRes_Msg_ab_empty}'; + } + } + else + { + if($UserInfo['uid'] > 0) + { + $ReturnData[] = '{SpyRes_Msg}'; + } + else + { + $ReturnData[] = '{SpyRes_Msg_ab}'; + } + } + $ReturnData[] = ($TargetArray['planet_type'] == 1 ? $_Lang['Spy_OnPlanet'] : $_Lang['Spy_OnMoon']); + $ReturnData[] = $TargetArray['name']; + $ReturnData[] = $TargetArray['galaxy']; + $ReturnData[] = $TargetArray['system']; + $ReturnData[] = $TargetArray['galaxy']; + $ReturnData[] = $TargetArray['system']; + $ReturnData[] = $TargetArray['planet']; + if($UserInfo['uid'] > 0) + { + $ReturnData[] = $UserInfo['uid']; + $ReturnData[] = $UserInfo['username']; + } + else + { + $ReturnData[] = $_Lang['Spy_Abandoned_'.$TargetArray['planet_type']]; + } + if($UserInfo['isEmptyReport'] === true) + { + $ReturnData[] = $_Lang['Spy_Morale_EmptyReport']; + } + else + { + $ReturnData[] = prettyNumber($TargetArray['metal']); + $ReturnData[] = prettyNumber($TargetArray['crystal']); + $ReturnData[] = prettyNumber($TargetArray['deuterium']); + $ReturnData[] = prettyNumber($TargetArray['energy_max']); + } + $ReturnArray[] = $ReturnData; + $LookAtLoop = false; + } + else if($Mode == 1) + { + // Show Ships + $ElementArrays[] = $_Vars_ElementCategories['fleet']; + $AddToSim = true; + } + else if($Mode == 2) + { + $ElementArrays[] = $_Vars_ElementCategories['defense']; + $AddToSim = true; + } + else if($Mode == 3) + { + $ElementArrays[] = $_Vars_ElementCategories['build']; + } + else if($Mode == 4) + { + $ElementArrays[] = $_Vars_ElementCategories['tech']; + $AddToSim = array(109, 110, 111, 120, 121, 122, 125, 126, 199); + } + else if($Mode == 5) + { + // Show Morale Info + if(MORALE_ENABLED) + { + Morale_ReCalculate($TargetArray, $UserInfo['SpyTime']); + $TargetMorale = $TargetArray['morale_level']; + $TargetMoraleStatus = $_Lang['SpyRes_Morale_Mood_Neutral']; + if($TargetArray['morale_droptime'] > $UserInfo['SpyTime']) + { + if($TargetMorale > 0) + { + $TargetMoraleStatus = $_Lang['SpyRes_Morale_Mood_Positive']; + } + else if($TargetMorale < 0) + { + $TargetMoraleStatus = $_Lang['SpyRes_Morale_Mood_Negative']; + } + } + + $ReturnArray[] = array('{SpyRes_Mor}', $TargetMorale, $TargetMoraleStatus, prettyNumber($TargetArray['morale_points'])); + } + else + { + $ReturnArray[] = array('{SpyRes_Emp}'); + } + $LookAtLoop = false; + } + + $Count = 0; + if($LookAtLoop == true) + { + $ReturnArray[] = array('{SpyRes_Oth}', ((2 * SPY_REPORT_ROW) + (SPY_REPORT_ROW - 1)), $TitleString); + + $ArrayString = null; + if(!empty($ElementArrays)) + { + foreach($ElementArrays as $ThisArray) + { + $row = 0; + foreach($ThisArray as $ElementID) + { + if(isset($TargetArray[$_Vars_GameElements[$ElementID]]) && $TargetArray[$_Vars_GameElements[$ElementID]] > 0) + { + if($row == 0) + { + $ArrayString .= ''; + } + $ArrayString .= '{s_tdl}{tech}['.$ElementID.']{s_tdr}'.prettyNumber($TargetArray[$_Vars_GameElements[$ElementID]]).''; + if($row < SPY_REPORT_ROW - 1) + { + $ArrayString .= '{s_tdn}'; + } + $Count += $TargetArray[$_Vars_GameElements[$ElementID]]; + $row += 1; + if($row == SPY_REPORT_ROW) + { + $ArrayString .= ''; + $row = 0; + } + if($AddToSim === TRUE OR ((array)$AddToSim === $AddToSim AND in_array($ElementID, $AddToSim, true))) + { + $SimData[$ElementID] = $TargetArray[$_Vars_GameElements[$ElementID]]; + } + } + } + while($row != 0) + { + $ArrayString .= '{s_tdn}{s_tdn}'; + $row += 1; + if($row == SPY_REPORT_ROW) + { + $ArrayString .= ''; + $row= 0; + } + } + } + } + + $ReturnArray[] = $ArrayString; + } + $ReturnArray[] = ''; + + $return['Array'] = $ReturnArray; + $return['Count'] = $Count; + $return['Sim'] = $SimData; + return $return; +} + +?> diff --git a/includes/functions/StoreGoodsToPlanet.php b/includes/functions/StoreGoodsToPlanet.php index 8c16cb285..39ef75ada 100644 --- a/includes/functions/StoreGoodsToPlanet.php +++ b/includes/functions/StoreGoodsToPlanet.php @@ -1,61 +1,61 @@ - 0) - { - $UpdatePlanet['metal'] = $FleetRow['fleet_resource_metal']; - } - if($FleetRow['fleet_resource_crystal'] > 0) - { - $UpdatePlanet['crystal'] = $FleetRow['fleet_resource_crystal']; - } - if($FleetRow['fleet_resource_deuterium'] > 0) - { - $UpdatePlanet['deuterium'] = $FleetRow['fleet_resource_deuterium']; - } - - if(!empty($UpdatePlanet)) - { - if($Start === true) - { - $PlanetID = $FleetRow['fleet_start_id']; - } - else - { - $PlanetID = $FleetRow['fleet_end_id']; - } - - if(!empty($_FleetCache['planets'][$PlanetID])) - { - global $HPQ_PlanetUpdatedFields; - $_FleetCache['updatePlanets'][$PlanetID] = true; - foreach($UpdatePlanet as $Key => $Value) - { - $HPQ_PlanetUpdatedFields[] = $Key; - $_FleetCache['planets'][$PlanetID][$Key] += $Value; - } - } - else - { - foreach($UpdatePlanet as $Key => $Value) - { - if(empty($_FleetCache['addToPlanets']['fields']) OR !in_array($Key, $_FleetCache['addToPlanets']['fields'])) - { - $_FleetCache['addToPlanets']['fields'][] = $Key; - } - if(!isset($_FleetCache['addToPlanets']['data'][$PlanetID][$Key])) - { - $_FleetCache['addToPlanets']['data'][$PlanetID][$Key] = 0; - } - $_FleetCache['addToPlanets']['data'][$PlanetID][$Key] += $Value; - } - } - - return true; - } - return false; -} - -?> \ No newline at end of file + 0) + { + $UpdatePlanet['metal'] = $FleetRow['fleet_resource_metal']; + } + if($FleetRow['fleet_resource_crystal'] > 0) + { + $UpdatePlanet['crystal'] = $FleetRow['fleet_resource_crystal']; + } + if($FleetRow['fleet_resource_deuterium'] > 0) + { + $UpdatePlanet['deuterium'] = $FleetRow['fleet_resource_deuterium']; + } + + if(!empty($UpdatePlanet)) + { + if($Start === true) + { + $PlanetID = $FleetRow['fleet_start_id']; + } + else + { + $PlanetID = $FleetRow['fleet_end_id']; + } + + if(!empty($_FleetCache['planets'][$PlanetID])) + { + global $HPQ_PlanetUpdatedFields; + $_FleetCache['updatePlanets'][$PlanetID] = true; + foreach($UpdatePlanet as $Key => $Value) + { + $HPQ_PlanetUpdatedFields[] = $Key; + $_FleetCache['planets'][$PlanetID][$Key] += $Value; + } + } + else + { + foreach($UpdatePlanet as $Key => $Value) + { + if(empty($_FleetCache['addToPlanets']['fields']) OR !in_array($Key, $_FleetCache['addToPlanets']['fields'])) + { + $_FleetCache['addToPlanets']['fields'][] = $Key; + } + if(!isset($_FleetCache['addToPlanets']['data'][$PlanetID][$Key])) + { + $_FleetCache['addToPlanets']['data'][$PlanetID][$Key] = 0; + } + $_FleetCache['addToPlanets']['data'][$PlanetID][$Key] += $Value; + } + } + + return true; + } + return false; +} + +?> diff --git a/includes/functions/StructuresBuildingPage.php b/includes/functions/StructuresBuildingPage.php index 23fcf512f..743716cf2 100644 --- a/includes/functions/StructuresBuildingPage.php +++ b/includes/functions/StructuresBuildingPage.php @@ -1,775 +1,775 @@ - 'dPart')); - $TPL['list_disabled'] = parsetemplate($TPL['list_disabled'], array('AddOpacity' => '')); - $TPL['queue_topinfo'] = gettemplate('buildings_compact_queue_topinfo'); - $TPL['infobox_body'] = gettemplate('buildings_compact_infobox_body_structures'); - $TPL['infobox_levelmodif'] = gettemplate('buildings_compact_infobox_levelmodif'); - $TPL['infobox_req_res'] = gettemplate('buildings_compact_infobox_req_res'); - $TPL['infobox_req_desttable'] = gettemplate('buildings_compact_infobox_req_desttable'); - $TPL['infobox_req_destres'] = gettemplate('buildings_compact_infobox_req_destres'); - $TPL['infobox_additionalnfo'] = gettemplate('buildings_compact_infobox_additionalnfo'); - $TPL['infobox_req_selector_single'] = gettemplate('buildings_compact_infobox_req_selector_single'); - $TPL['infobox_req_selector_dual'] = gettemplate('buildings_compact_infobox_req_selector_dual'); - - // Handle Commands - if(!isOnVacation($CurrentUser)) - { - if(!empty($_GET['cmd'])) - { - $TheCommand = $_GET['cmd']; - if($TheCommand == 'cancel') - { - include($_EnginePath.'includes/functions/CancelBuildingFromQueue.php'); - $ShowID = CancelBuildingFromQueue($CurrentPlanet, $CurrentUser); - $CommandDone = true; - } - else if($TheCommand == 'remove') - { - if(!empty($_GET['listid'])) - { - include($_EnginePath.'includes/functions/RemoveBuildingFromQueue.php'); - $ShowID = RemoveBuildingFromQueue($CurrentPlanet, $CurrentUser, intval($_GET['listid'])); - $CommandDone = true; - } - } - else if($TheCommand == 'insert' OR $TheCommand == 'destroy') - { - if(!empty($_GET['building'])) - { - $ElementID = intval($_GET['building']); - if(in_array($ElementID, $_Vars_ElementCategories['buildOn'][$CurrentPlanet['planet_type']])) - { - if($TheCommand == 'insert') - { - $AddMode = true; - } - else - { - $AddMode = false; - } - if($ElementID == 31 AND $CurrentUser['techQueue_Planet'] > 0 AND $CurrentUser['techQueue_EndTime'] > 0 AND $_GameConfig['BuildLabWhileRun'] != 1) - { - $BlockCommand = true; - } - else - { - $BlockCommand = false; - } - if($BlockCommand !== true) - { - include($_EnginePath.'includes/functions/AddBuildingToQueue.php'); - AddBuildingToQueue($CurrentPlanet, $CurrentUser, $ElementID, $AddMode); - $CommandDone = true; - } - - $ShowID = $ElementID; - } - } - } - - if($ShowID > 0) - { - $ShowElementID = $ShowID; - } - - if($CommandDone === true) - { - if(HandlePlanetQueue_StructuresSetNext($CurrentPlanet, $CurrentUser, $Now, true) === false) - { - include($_EnginePath.'includes/functions/BuildingSavePlanetRecord.php'); - BuildingSavePlanetRecord($CurrentPlanet); - } - } - } - } - // End of - Handle Commands - - // Parse Queue - $CurrentQueue = $CurrentPlanet['buildQueue']; - if(!empty($CurrentQueue)) - { - $LockResources['metal'] = 0; - $LockResources['crystal'] = 0; - $LockResources['deuterium'] = 0; - - $CurrentQueue = explode(';', $CurrentQueue); - $QueueIndex = 0; - foreach($CurrentQueue as $QueueID => $QueueData) - { - $QueueData = explode(',', $QueueData); - $BuildEndTime = $QueueData[3]; - if($BuildEndTime >= $Now) - { - $ListID = $QueueIndex + 1; - $ElementID = $QueueData[0]; - $ElementLevel = $QueueData[1]; - $ElementMode = $QueueData[4]; - $ElementBuildtime = $BuildEndTime - $Now; - $ElementName = $_Lang['tech'][$ElementID]; - if($ElementMode != 'build') - { - $ElementLevel += 1; - $ElementModeColor = 'red'; - $ThisForDestroy = true; - } - else - { - $ElementModeColor = 'lime'; - $ThisForDestroy = false; - } - if($QueueIndex == 0) - { - include($_EnginePath.'/includes/functions/InsertJavaScriptChronoApplet.php'); - - $QueueParser[] = array - ( - 'ChronoAppletScript' => InsertJavaScriptChronoApplet('QueueFirstTimer', '', $BuildEndTime, true, false, 'function() { $(\"#QueueCancel\").html(\"'.$_Lang['Queue_Cancel_Go'].'\").attr(\"href\", \"buildings.php\").removeClass(\"cancelQueue\").addClass(\"lime\"); SetTimer = \"'.$_Lang['completed'].'\"; window.setTimeout(\'document.location.href=\"buildings.php\";\', 1000); }'), - 'EndTimer' => pretty_time($ElementBuildtime, true), - 'SkinPath' => $_SkinPath, - 'ElementID' => $ElementID, - 'Name' => $ElementName, - 'LevelText' => $_Lang['level'], - 'Level' => $ElementLevel, - 'ModeText' => ($ThisForDestroy ? $_Lang['Queue_Mode_Destroy_1'] : $_Lang['Queue_Mode_Build_1']), - 'ModeColor' => $ElementModeColor, - 'EndText' => $_Lang['Queue_EndTime'], - 'EndDate' => date('d/m | H:i:s', $BuildEndTime), - 'EndTitleBeg' => $_Lang['Queue_EndTitleBeg'], - 'EndTitleHour' => $_Lang['Queue_EndTitleHour'], - 'EndDateExpand' => prettyDate('d m Y', $BuildEndTime, 1), - 'EndTimeExpand' => date('H:i:s', $BuildEndTime), - 'PremBlock' => (isset($_Vars_PremiumBuildings[$ElementID]) && $_Vars_PremiumBuildings[$ElementID] == 1 ? 'premblock' : ''), - 'ListID' => $ListID, - 'PlanetID' => $CurrentPlanet['id'], - 'CancelText' => (isset($_Vars_PremiumBuildings[$ElementID]) && $_Vars_PremiumBuildings[$ElementID] == 1 ? $_Lang['Queue_Cancel_CantCancel'] : ($ThisForDestroy ? $_Lang['Queue_Cancel_Destroy'] : $_Lang['Queue_Cancel_Build'])) - ); - } - else - { - $QueueParser[] = array - ( - 'ElementNo' => $ListID, - 'ElementID' => $ElementID, - 'Name' => $ElementName, - 'LevelText' => $_Lang['level'], - 'Level' => $ElementLevel, - 'ModeText' => ($ThisForDestroy ? $_Lang['Queue_Mode_Destroy_1+'] : $_Lang['Queue_Mode_Build_1+']), - 'ModeColor' => $ElementModeColor, - 'EndDate' => date('d/m H:i:s', $BuildEndTime), - 'EndTitleBeg' => $_Lang['Queue_EndTitleBeg'], - 'EndTitleHour' => $_Lang['Queue_EndTitleHour'], - 'EndDateExpand' => prettyDate('d m Y', $BuildEndTime, 1), - 'EndTimeExpand' => date('H:i:s', $BuildEndTime), - 'InfoBox_BuildTime' => ($ThisForDestroy ? $_Lang['InfoBox_DestroyTime'] : $_Lang['InfoBox_BuildTime']), - 'BuildTime' => pretty_time($BuildEndTime - $PreviousBuildEndTime), - 'ListID' => $ListID, - 'PlanetID' => $CurrentPlanet['id'], - 'RemoveText' => $_Lang['Queue_Cancel_Remove'] - ); - - $GetResourcesToLock = GetBuildingPrice($CurrentUser, $CurrentPlanet, $ElementID, true, $ThisForDestroy); - $LockResources['metal'] += $GetResourcesToLock['metal']; - $LockResources['crystal'] += $GetResourcesToLock['crystal']; - $LockResources['deuterium'] += $GetResourcesToLock['deuterium']; - } - - if(!isset($LevelModifiers[$ElementID])) - { - $LevelModifiers[$ElementID] = 0; - } - if($ThisForDestroy) - { - $LevelModifiers[$ElementID] += 1; - $CurrentPlanet[$_Vars_GameElements[$ElementID]] -= 1; - $FieldsModifier += 2; - } - else - { - $LevelModifiers[$ElementID] -= 1; - $CurrentPlanet[$_Vars_GameElements[$ElementID]] += 1; - } - - $QueueIndex += 1; - } - $PreviousBuildEndTime = $BuildEndTime; - } - $CurrentPlanet['metal'] -= (isset($LockResources['metal']) ? $LockResources['metal'] : 0); - $CurrentPlanet['crystal'] -= (isset($LockResources['crystal']) ? $LockResources['crystal'] : 0); - $CurrentPlanet['deuterium'] -= (isset($LockResources['deuterium']) ? $LockResources['deuterium'] : 0); - - $Queue['lenght'] = $QueueIndex; - if(!empty($QueueParser)) - { - $Parse['Create_Queue'] = ''; - foreach($QueueParser as $QueueID => $QueueData) - { - if($QueueID == 0) - { - $ThisTPL = gettemplate('buildings_compact_queue_firstel'); - } - else if($QueueID == 1) - { - $ThisTPL = gettemplate('buildings_compact_queue_nextel'); - } - $Parse['Create_Queue'] .= parsetemplate($ThisTPL, $QueueData); - } - } - } - else - { - $Queue['lenght'] = 0; - $Parse['Create_Queue'] = parsetemplate($TPL['queue_topinfo'], array('InfoText' => $_Lang['Queue_Empty'])); - } - // End of - Parse Queue - - // Parse all available buildings - if(($CurrentPlanet['field_current'] + $Queue['lenght'] - $FieldsModifier) < CalculateMaxPlanetFields($CurrentPlanet)) - { - $HasLeftFields = true; - } - else - { - $HasLeftFields = false; - } - if($Queue['lenght'] < ((isPro($CurrentUser)) ? MAX_BUILDING_QUEUE_SIZE_PRO : MAX_BUILDING_QUEUE_SIZE)) - { - $CanAddToQueue = true; - } - else - { - $CanAddToQueue = false; - $Parse['Create_Queue'] = parsetemplate($TPL['queue_topinfo'], array('InfoColor' => 'red', 'InfoText' => $_Lang['Queue_Full'])).$Parse['Create_Queue']; - } - if($CurrentUser['engineer_time'] > $Now) - { - $EnergyMulti = 1.10; - } - else - { - $EnergyMulti = 1; - } - if($CurrentUser['geologist_time'] > $Now) - { - $ResourceMulti = 1.15; - } - else - { - $ResourceMulti = 1; - } - $ResImages = array - ( - 'metal' => 'metall', - 'crystal' => 'kristall', - 'deuterium' => 'deuterium', - 'energy_max' => 'energie', - 'darkEnergy' => 'darkenergy' - ); - $ResLangs = array - ( - 'metal' => $_Lang['Metal'], - 'crystal' => $_Lang['Crystal'], - 'deuterium' => $_Lang['Deuterium'], - 'energy_max' => $_Lang['Energy'], - 'darkEnergy' => $_Lang['DarkEnergy'] - ); - - $ElementParserDefault = array - ( - 'SkinPath' => $_SkinPath, - 'InfoBox_Level' => $_Lang['InfoBox_Level'], - 'InfoBox_Build' => $_Lang['InfoBox_Build'], - 'InfoBox_Destroy' => $_Lang['InfoBox_Destroy'], - 'InfoBox_RequirementsFor' => $_Lang['InfoBox_RequirementsFor'], - 'InfoBox_ResRequirements' => $_Lang['InfoBox_ResRequirements'], - 'InfoBox_TechRequirements' => $_Lang['InfoBox_TechRequirements'], - 'InfoBox_Requirements_Res' => $_Lang['InfoBox_Requirements_Res'], - 'InfoBox_Requirements_Tech' => $_Lang['InfoBox_Requirements_Tech'], - 'InfoBox_BuildTime' => $_Lang['InfoBox_BuildTime'], - 'InfoBox_ShowTechReq' => $_Lang['InfoBox_ShowTechReq'], - 'InfoBox_ShowResReq' => $_Lang['InfoBox_ShowResReq'], - ); - - foreach($_Vars_ElementCategories['build'] as $ElementID) - { - if(in_array($ElementID, $_Vars_ElementCategories['buildOn'][$CurrentPlanet['planet_type']])) - { - $ElementParser = $ElementParserDefault; - - $CurrentLevel = $CurrentPlanet[$_Vars_GameElements[$ElementID]]; - $NextLevel = $CurrentPlanet[$_Vars_GameElements[$ElementID]] + 1; - $MaxLevelReached = false; - $TechLevelOK = false; - $HasResources = true; - - $HideButton_Build = false; - $HideButton_Destroy = false; - $HideButton_QuickBuild = false; - - $ElementParser['HideBuildWarn'] = 'hide'; - $ElementParser['ElementName'] = $_Lang['tech'][$ElementID]; - $ElementParser['ElementID'] = $ElementID; - $ElementParser['ElementLevel'] = prettyNumber($CurrentPlanet[$_Vars_GameElements[$ElementID]]); - $ElementParser['ElementRealLevel'] = prettyNumber($CurrentPlanet[$_Vars_GameElements[$ElementID]] + (isset($LevelModifiers[$ElementID]) ? $LevelModifiers[$ElementID] : 0)); - $ElementParser['BuildLevel'] = prettyNumber($CurrentPlanet[$_Vars_GameElements[$ElementID]] + 1); - $ElementParser['DestroyLevel'] = prettyNumber($CurrentPlanet[$_Vars_GameElements[$ElementID]] - 1); - $ElementParser['Desc'] = $_Lang['res']['descriptions'][$ElementID]; - $ElementParser['BuildButtonColor'] = 'buildDo_Green'; - $ElementParser['DestroyButtonColor'] = 'buildDo_Red'; - - if(isset($LevelModifiers[$ElementID])) - { - if($LevelModifiers[$ElementID] > 0) - { - $ElementParser['levelmodif']['modColor'] = 'red'; - $ElementParser['levelmodif']['modText'] = prettyNumber($LevelModifiers[$ElementID] * (-1)); - } - else if($LevelModifiers[$ElementID] == 0) - { - $ElementParser['levelmodif']['modColor'] = 'orange'; - $ElementParser['levelmodif']['modText'] = '0'; - } - else - { - $ElementParser['levelmodif']['modColor'] = 'lime'; - $ElementParser['levelmodif']['modText'] = '+'.prettyNumber($LevelModifiers[$ElementID] * (-1)); - } - $ElementParser['LevelModifier'] = parsetemplate($TPL['infobox_levelmodif'], $ElementParser['levelmodif']); - $ElementParser['ElementLevelModif'] = parsetemplate($TPL['list_levelmodif'], $ElementParser['levelmodif']); - unset($ElementParser['levelmodif']); - } - - if(!(isset($_Vars_MaxElementLevel[$ElementID]) && $_Vars_MaxElementLevel[$ElementID] > 0 && $NextLevel > $_Vars_MaxElementLevel[$ElementID])) - { - $ElementParser['ElementPrice'] = GetBuildingPrice($CurrentUser, $CurrentPlanet, $ElementID, true, false, true); - foreach($ElementParser['ElementPrice'] as $Key => $Value) - { - if($Value > 0) - { - $ResColor = ''; - $ResMinusColor = ''; - $MinusValue = ' '; - - if($Key != 'darkEnergy') - { - $UseVar = &$CurrentPlanet; - } - else - { - $UseVar = &$CurrentUser; - } - if($UseVar[$Key] < $Value) - { - $ResMinusColor = 'red'; - $MinusValue = '('.prettyNumber($UseVar[$Key] - $Value).')'; - if($Queue['lenght'] > 0) - { - $ResColor = 'orange'; - } - else - { - $ResColor = 'red'; - } - } - - $ElementParser['ElementPrices'] = array - ( - 'SkinPath' => $_SkinPath, - 'ResName' => $Key, - 'ResImg' => $ResImages[$Key], - 'ResColor' => $ResColor, - 'Value' => prettyNumber($Value), - 'ResMinusColor' => $ResMinusColor, - 'MinusValue' => $MinusValue, - ); - if(!isset($ElementParser['ElementPriceDiv'])) - { - $ElementParser['ElementPriceDiv'] = ''; - } - $ElementParser['ElementPriceDiv'] .= parsetemplate($TPL['infobox_req_res'], $ElementParser['ElementPrices']); - } - } - $ElementParser['BuildTime'] = pretty_time(GetBuildingTime($CurrentUser, $CurrentPlanet, $ElementID)); - } - else - { - $MaxLevelReached = true; - $ElementParser['HideBuildInfo'] = 'hide'; - $ElementParser['HideBuildWarn'] = ''; - $HideButton_Build = true; - $ElementParser['BuildWarn_Color'] = 'red'; - $ElementParser['BuildWarn_Text'] = $_Lang['ListBox_Disallow_MaxLevelReached']; - } - if($CurrentLevel == 0 || (isset($_Vars_IndestructibleBuildings[$ElementID]) && $_Vars_IndestructibleBuildings[$ElementID])) - { - $HideButton_Destroy = true; - } - if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $ElementID)) - { - $TechLevelOK = true; - $ElementParser['ElementRequirementsHeadline'] = $TPL['infobox_req_selector_single']; - } - else - { - $ElementParser['ElementRequirementsHeadline'] = $TPL['infobox_req_selector_dual']; - $ElementParser['ElementTechDiv'] = GetElementTechReq($CurrentUser, $CurrentPlanet, $ElementID, true); - $ElementParser['HideResReqDiv'] = 'hide'; - } - if(IsElementBuyable($CurrentUser, $CurrentPlanet, $ElementID, true, false, true) === false) - { - $HasResources = false; - if($Queue['lenght'] == 0) - { - $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; - $HideButton_QuickBuild = true; - } - else - { - $ElementParser['BuildButtonColor'] = 'buildDo_Orange'; - } - } - if(IsElementBuyable($CurrentUser, $CurrentPlanet, $ElementID, true, true) === false) - { - if($Queue['lenght'] == 0) - { - $ElementParser['DestroyButtonColor'] = 'destroyDo_Gray'; - } - } - - $BlockReason = array(); - - if($MaxLevelReached) - { - $BlockReason[] = $_Lang['ListBox_Disallow_MaxLevelReached']; - } - else if(!$HasResources) - { - $BlockReason[] = $_Lang['ListBox_Disallow_NoResources']; - } - if(!$TechLevelOK) - { - $BlockReason[] = $_Lang['ListBox_Disallow_NoTech']; - $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; - $HideButton_QuickBuild = true; - $HideButton_Destroy = true; - } - if($ElementID == 31 AND $CurrentUser['techQueue_Planet'] > 0 AND $CurrentUser['techQueue_EndTime'] > 0 AND $_GameConfig['BuildLabWhileRun'] != 1) - { - $BlockReason[] = $_Lang['ListBox_Disallow_LabResearch']; - $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; - $ElementParser['DestroyButtonColor'] = 'destroyDo_Gray'; - $HideButton_QuickBuild = true; - } - if($HasLeftFields === false) - { - $BlockReason[] = $_Lang['ListBox_Disallow_NoFreeFields']; - $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; - $HideButton_QuickBuild = true; - } - if($CanAddToQueue === false) - { - $BlockReason[] = $_Lang['ListBox_Disallow_QueueIsFull']; - $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; - $HideButton_QuickBuild = true; - } - if(isOnVacation($CurrentUser)) - { - $BlockReason[] = $_Lang['ListBox_Disallow_VacationMode']; - $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; - $ElementParser['DestroyButtonColor'] = 'destroyDo_Gray'; - $HideButton_QuickBuild = true; - } - - if(!empty($BlockReason)) - { - if($ElementParser['BuildButtonColor'] == 'buildDo_Orange') - { - $ElementParser['ElementDisabled'] = $TPL['list_partdisabled']; - } - else - { - $ElementParser['ElementDisabled'] = $TPL['list_disabled']; - } - $ElementParser['ElementDisableReason'] = end($BlockReason); - } - - if($HideButton_Build) - { - $ElementParser['HideBuildButton'] = 'hide'; - } - if($HideButton_Build OR $HideButton_QuickBuild) - { - $ElementParser['HideQuickBuildButton'] = 'hide'; - } - if($HideButton_Destroy) - { - $ElementParser['HideDestroyButton'] = 'hide'; - } - else - { - $ElementDestroyCost = GetBuildingPrice($CurrentUser, $CurrentPlanet, $ElementID, true, true, true); - $ElementParser['Create_DestroyTips_Res'] = ''; - foreach($ElementDestroyCost as $Key => $Value) - { - if($Value > 0) - { - $ResColor = ''; - if($Key != 'darkEnergy') - { - if($CurrentPlanet[$Key] < $Value) - { - if($Queue['lenght'] > 0) - { - $ResColor = 'orange'; - } - else - { - $ResColor = 'red'; - } - } - } - else - { - if($CurrentUser[$Key] < $Value) - { - if($Queue['lenght'] > 0) - { - $ResColor = 'orange'; - } - else - { - $ResColor = 'red'; - } - } - } - $ElementParser['ElementPrices'] = array('Name' => $ResLangs[$Key], 'Color' => $ResColor, 'Value' => prettyNumber($Value)); - $ElementParser['Create_DestroyTips_Res'] .= parsetemplate($TPL['infobox_req_destres'], $ElementParser['ElementPrices']); - } - } - if(!isset($Parse['Create_DestroyTips'])) - { - $Parse['Create_DestroyTips'] = ''; - } - $Parse['Create_DestroyTips'] .= parsetemplate($TPL['infobox_req_desttable'], array - ( - 'ElementID' => $ElementID, - 'InfoBox_DestroyCost' => $_Lang['InfoBox_DestroyCost'], - 'InfoBox_DestroyTime' => $_Lang['InfoBox_DestroyTime'], - 'Resources' => $ElementParser['Create_DestroyTips_Res'], - 'DestroyTime' => pretty_time(GetBuildingTime($CurrentUser, $CurrentPlanet, $ElementID) / 2) - )); - } - - if(in_array($ElementID, $_Vars_ElementCategories['prod'])) - { - // Show energy on BuildingPage - $BuildLevelFactor = 10; - $BuildTemp = $CurrentPlanet['temp_max']; - $CurrentBuildtLvl = $CurrentLevel; - $BuildLevel = ($CurrentBuildtLvl > 0) ? $CurrentBuildtLvl : 0; - $Production = array(); - $Needs = array(); - $ThisResource = ''; - - // Calculate ThisLevel Income - if($ElementID <= 3) - { - if($ElementID == 1) - { - $ThisResource = $_Lang['Metal']; - $Production[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['metal']) * $_GameConfig['resource_multiplier'] * $ResourceMulti); - } - else if($ElementID == 2) - { - $ThisResource = $_Lang['Crystal']; - $Production[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['crystal']) * $_GameConfig['resource_multiplier'] * $ResourceMulti); - } - else if($ElementID == 3) - { - $ThisResource = $_Lang['Deuterium']; - $Production[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * $_GameConfig['resource_multiplier'] * $ResourceMulti); - } - $Needs[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy'])); - } - else - { - if($ElementID == 12) - { - $Needs[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']); - } - $Production[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $EnergyMulti); - } - // Calculate NextLevel Income - $BuildLevel += 1; - if($ElementID <= 3) - { - if($ElementID == 1) - { - $Production[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['metal']) * $_GameConfig['resource_multiplier'] * $ResourceMulti); - } - else if($ElementID == 2) - { - $Production[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['crystal']) * $_GameConfig['resource_multiplier'] * $ResourceMulti); - } - else if($ElementID == 3) - { - $Production[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * $_GameConfig['resource_multiplier'] * $ResourceMulti); - } - $Needs[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy'])); - } - else - { - if($ElementID == 12) - { - $Needs[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']); - } - $Production[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $EnergyMulti); - } - // Calculate Difference - $Production = prettyNumber($Production[1] - $Production[0]); - if(!isset($Needs[1])) - { - $Needs[1] = 0; - } - if(!isset($Needs[0])) - { - $Needs[0] = 0; - } - $Needs = prettyNumber($Needs[1] - $Needs[0]); - - if($ElementID >= 1 AND $ElementID <= 3) - { - $ElementParser['AdditionalNfo'][] = parsetemplate($TPL['infobox_additionalnfo'], array('Label' => $_Lang['Energy'], 'ValueClasses' => 'red', 'Value' => $Needs)); - $ElementParser['AdditionalNfo'][] = parsetemplate($TPL['infobox_additionalnfo'], array('Label' => $ThisResource, 'ValueClasses' => 'lime', 'Value' => '+'.$Production)); - } - else if($ElementID == 4 OR $ElementID == 12) - { - if($ElementID != 12) - { - $ElementParser['AdditionalNfo'][] = parsetemplate($TPL['infobox_additionalnfo'], array('Label' => $_Lang['Energy'], 'ValueClasses' => 'lime', 'Value' => '+'.$Production)); - } - else - { - $ElementParser['AdditionalNfo'][] = parsetemplate($TPL['infobox_additionalnfo'], array('Label' => $_Lang['Energy'], 'ValueClasses' => 'lime', 'Value' => '+'.$Production)); - $ElementParser['AdditionalNfo'][] = parsetemplate($TPL['infobox_additionalnfo'], array('Label' => $_Lang['Deuterium'], 'ValueClasses' => 'red', 'Value' => $Needs)); - } - } - } - - if(!empty($ElementParser['AdditionalNfo'])) - { - $ElementParser['AdditionalNfo'] = implode('', $ElementParser['AdditionalNfo']); - } - $ElementParser['ElementRequirementsHeadline'] = parsetemplate($ElementParser['ElementRequirementsHeadline'], $ElementParser); - $StructuresList[] = parsetemplate($TPL['list_element'], $ElementParser); - $InfoBoxes[] = parsetemplate($TPL['infobox_body'], $ElementParser); - } - } - - if(!empty($LevelModifiers)) - { - foreach($LevelModifiers as $ElementID => $Modifier) - { - $CurrentPlanet[$_Vars_GameElements[$ElementID]] += $Modifier; - } - } - $CurrentPlanet['metal'] += (isset($LockResources['metal']) ? $LockResources['metal'] : 0); - $CurrentPlanet['crystal'] += (isset($LockResources['crystal']) ? $LockResources['crystal'] : 0); - $CurrentPlanet['deuterium'] += (isset($LockResources['deuterium']) ? $LockResources['deuterium'] : 0); - - // Create Structures List - $ThisRowIndex = 0; - $InRowCount = 0; - foreach($StructuresList as $ParsedData) - { - if($InRowCount == $ElementsPerRow) - { - $ParsedRows[($ThisRowIndex + 1)] = $TPL['list_breakrow']; - $ThisRowIndex += 2; - $InRowCount = 0; - } - - if(!isset($StructureRows[$ThisRowIndex]['Elements'])) - { - $StructureRows[$ThisRowIndex]['Elements'] = ''; - } - $StructureRows[$ThisRowIndex]['Elements'] .= $ParsedData; - $InRowCount += 1; - } - if($InRowCount < $ElementsPerRow) - { - if(!isset($StructureRows[$ThisRowIndex]['Elements'])) - { - $StructureRows[$ThisRowIndex]['Elements'] = ''; - } - $StructureRows[$ThisRowIndex]['Elements'] .= str_repeat($TPL['list_hidden'], ($ElementsPerRow - $InRowCount)); - } - foreach($StructureRows as $Index => $Data) - { - $ParsedRows[$Index] = parsetemplate($TPL['list_row'], $Data); - } - ksort($ParsedRows, SORT_ASC); - $Parse['Create_StructuresList'] = implode('', $ParsedRows); - $Parse['Create_ElementsInfoBoxes'] = implode('', $InfoBoxes); - if($ShowElementID > 0) - { - $Parse['Create_ShowElementOnStartup'] = $ShowElementID; - } - $MaxFields = CalculateMaxPlanetFields($CurrentPlanet); - if($CurrentPlanet['field_current'] == $MaxFields) - { - $Parse['Insert_Overview_Fields_Used_Color'] = 'red'; - } - else if($CurrentPlanet['field_current'] >= ($MaxFields * 0.9)) - { - $Parse['Insert_Overview_Fields_Used_Color'] = 'orange'; - } - else - { - $Parse['Insert_Overview_Fields_Used_Color'] = 'lime'; - } - // End of - Parse all available buildings - - $Parse['Insert_SkinPath'] = $_SkinPath; - $Parse['Insert_PlanetImg'] = $CurrentPlanet['image']; - $Parse['Insert_PlanetType'] = $_Lang['PlanetType_'.$CurrentPlanet['planet_type']]; - $Parse['Insert_PlanetName'] = $CurrentPlanet['name']; - $Parse['Insert_PlanetPos_Galaxy'] = $CurrentPlanet['galaxy']; - $Parse['Insert_PlanetPos_System'] = $CurrentPlanet['system']; - $Parse['Insert_PlanetPos_Planet'] = $CurrentPlanet['planet']; - $Parse['Insert_Overview_Diameter'] = prettyNumber($CurrentPlanet['diameter']); - $Parse['Insert_Overview_Fields_Used'] = prettyNumber($CurrentPlanet['field_current']); - $Parse['Insert_Overview_Fields_Max'] = prettyNumber($MaxFields); - $Parse['Insert_Overview_Fields_Percent'] = sprintf('%0.2f', ($CurrentPlanet['field_current'] / $MaxFields) * 100); - $Parse['Insert_Overview_Temperature'] = sprintf($_Lang['Overview_Form_Temperature'], $CurrentPlanet['temp_min'], $CurrentPlanet['temp_max']); - - $Page = parsetemplate(gettemplate('buildings_compact_body_structures'), $Parse); - - display($Page, $_Lang['Builds']); -} - -?> \ No newline at end of file + 'dPart')); + $TPL['list_disabled'] = parsetemplate($TPL['list_disabled'], array('AddOpacity' => '')); + $TPL['queue_topinfo'] = gettemplate('buildings_compact_queue_topinfo'); + $TPL['infobox_body'] = gettemplate('buildings_compact_infobox_body_structures'); + $TPL['infobox_levelmodif'] = gettemplate('buildings_compact_infobox_levelmodif'); + $TPL['infobox_req_res'] = gettemplate('buildings_compact_infobox_req_res'); + $TPL['infobox_req_desttable'] = gettemplate('buildings_compact_infobox_req_desttable'); + $TPL['infobox_req_destres'] = gettemplate('buildings_compact_infobox_req_destres'); + $TPL['infobox_additionalnfo'] = gettemplate('buildings_compact_infobox_additionalnfo'); + $TPL['infobox_req_selector_single'] = gettemplate('buildings_compact_infobox_req_selector_single'); + $TPL['infobox_req_selector_dual'] = gettemplate('buildings_compact_infobox_req_selector_dual'); + + // Handle Commands + if(!isOnVacation($CurrentUser)) + { + if(!empty($_GET['cmd'])) + { + $TheCommand = $_GET['cmd']; + if($TheCommand == 'cancel') + { + include($_EnginePath.'includes/functions/CancelBuildingFromQueue.php'); + $ShowID = CancelBuildingFromQueue($CurrentPlanet, $CurrentUser); + $CommandDone = true; + } + else if($TheCommand == 'remove') + { + if(!empty($_GET['listid'])) + { + include($_EnginePath.'includes/functions/RemoveBuildingFromQueue.php'); + $ShowID = RemoveBuildingFromQueue($CurrentPlanet, $CurrentUser, intval($_GET['listid'])); + $CommandDone = true; + } + } + else if($TheCommand == 'insert' OR $TheCommand == 'destroy') + { + if(!empty($_GET['building'])) + { + $ElementID = intval($_GET['building']); + if(in_array($ElementID, $_Vars_ElementCategories['buildOn'][$CurrentPlanet['planet_type']])) + { + if($TheCommand == 'insert') + { + $AddMode = true; + } + else + { + $AddMode = false; + } + if($ElementID == 31 AND $CurrentUser['techQueue_Planet'] > 0 AND $CurrentUser['techQueue_EndTime'] > 0 AND $_GameConfig['BuildLabWhileRun'] != 1) + { + $BlockCommand = true; + } + else + { + $BlockCommand = false; + } + if($BlockCommand !== true) + { + include($_EnginePath.'includes/functions/AddBuildingToQueue.php'); + AddBuildingToQueue($CurrentPlanet, $CurrentUser, $ElementID, $AddMode); + $CommandDone = true; + } + + $ShowID = $ElementID; + } + } + } + + if($ShowID > 0) + { + $ShowElementID = $ShowID; + } + + if($CommandDone === true) + { + if(HandlePlanetQueue_StructuresSetNext($CurrentPlanet, $CurrentUser, $Now, true) === false) + { + include($_EnginePath.'includes/functions/BuildingSavePlanetRecord.php'); + BuildingSavePlanetRecord($CurrentPlanet); + } + } + } + } + // End of - Handle Commands + + // Parse Queue + $CurrentQueue = $CurrentPlanet['buildQueue']; + if(!empty($CurrentQueue)) + { + $LockResources['metal'] = 0; + $LockResources['crystal'] = 0; + $LockResources['deuterium'] = 0; + + $CurrentQueue = explode(';', $CurrentQueue); + $QueueIndex = 0; + foreach($CurrentQueue as $QueueID => $QueueData) + { + $QueueData = explode(',', $QueueData); + $BuildEndTime = $QueueData[3]; + if($BuildEndTime >= $Now) + { + $ListID = $QueueIndex + 1; + $ElementID = $QueueData[0]; + $ElementLevel = $QueueData[1]; + $ElementMode = $QueueData[4]; + $ElementBuildtime = $BuildEndTime - $Now; + $ElementName = $_Lang['tech'][$ElementID]; + if($ElementMode != 'build') + { + $ElementLevel += 1; + $ElementModeColor = 'red'; + $ThisForDestroy = true; + } + else + { + $ElementModeColor = 'lime'; + $ThisForDestroy = false; + } + if($QueueIndex == 0) + { + include($_EnginePath.'/includes/functions/InsertJavaScriptChronoApplet.php'); + + $QueueParser[] = array + ( + 'ChronoAppletScript' => InsertJavaScriptChronoApplet('QueueFirstTimer', '', $BuildEndTime, true, false, 'function() { $(\"#QueueCancel\").html(\"'.$_Lang['Queue_Cancel_Go'].'\").attr(\"href\", \"buildings.php\").removeClass(\"cancelQueue\").addClass(\"lime\"); SetTimer = \"'.$_Lang['completed'].'\"; window.setTimeout(\'document.location.href=\"buildings.php\";\', 1000); }'), + 'EndTimer' => pretty_time($ElementBuildtime, true), + 'SkinPath' => $_SkinPath, + 'ElementID' => $ElementID, + 'Name' => $ElementName, + 'LevelText' => $_Lang['level'], + 'Level' => $ElementLevel, + 'ModeText' => ($ThisForDestroy ? $_Lang['Queue_Mode_Destroy_1'] : $_Lang['Queue_Mode_Build_1']), + 'ModeColor' => $ElementModeColor, + 'EndText' => $_Lang['Queue_EndTime'], + 'EndDate' => date('d/m | H:i:s', $BuildEndTime), + 'EndTitleBeg' => $_Lang['Queue_EndTitleBeg'], + 'EndTitleHour' => $_Lang['Queue_EndTitleHour'], + 'EndDateExpand' => prettyDate('d m Y', $BuildEndTime, 1), + 'EndTimeExpand' => date('H:i:s', $BuildEndTime), + 'PremBlock' => (isset($_Vars_PremiumBuildings[$ElementID]) && $_Vars_PremiumBuildings[$ElementID] == 1 ? 'premblock' : ''), + 'ListID' => $ListID, + 'PlanetID' => $CurrentPlanet['id'], + 'CancelText' => (isset($_Vars_PremiumBuildings[$ElementID]) && $_Vars_PremiumBuildings[$ElementID] == 1 ? $_Lang['Queue_Cancel_CantCancel'] : ($ThisForDestroy ? $_Lang['Queue_Cancel_Destroy'] : $_Lang['Queue_Cancel_Build'])) + ); + } + else + { + $QueueParser[] = array + ( + 'ElementNo' => $ListID, + 'ElementID' => $ElementID, + 'Name' => $ElementName, + 'LevelText' => $_Lang['level'], + 'Level' => $ElementLevel, + 'ModeText' => ($ThisForDestroy ? $_Lang['Queue_Mode_Destroy_1+'] : $_Lang['Queue_Mode_Build_1+']), + 'ModeColor' => $ElementModeColor, + 'EndDate' => date('d/m H:i:s', $BuildEndTime), + 'EndTitleBeg' => $_Lang['Queue_EndTitleBeg'], + 'EndTitleHour' => $_Lang['Queue_EndTitleHour'], + 'EndDateExpand' => prettyDate('d m Y', $BuildEndTime, 1), + 'EndTimeExpand' => date('H:i:s', $BuildEndTime), + 'InfoBox_BuildTime' => ($ThisForDestroy ? $_Lang['InfoBox_DestroyTime'] : $_Lang['InfoBox_BuildTime']), + 'BuildTime' => pretty_time($BuildEndTime - $PreviousBuildEndTime), + 'ListID' => $ListID, + 'PlanetID' => $CurrentPlanet['id'], + 'RemoveText' => $_Lang['Queue_Cancel_Remove'] + ); + + $GetResourcesToLock = GetBuildingPrice($CurrentUser, $CurrentPlanet, $ElementID, true, $ThisForDestroy); + $LockResources['metal'] += $GetResourcesToLock['metal']; + $LockResources['crystal'] += $GetResourcesToLock['crystal']; + $LockResources['deuterium'] += $GetResourcesToLock['deuterium']; + } + + if(!isset($LevelModifiers[$ElementID])) + { + $LevelModifiers[$ElementID] = 0; + } + if($ThisForDestroy) + { + $LevelModifiers[$ElementID] += 1; + $CurrentPlanet[$_Vars_GameElements[$ElementID]] -= 1; + $FieldsModifier += 2; + } + else + { + $LevelModifiers[$ElementID] -= 1; + $CurrentPlanet[$_Vars_GameElements[$ElementID]] += 1; + } + + $QueueIndex += 1; + } + $PreviousBuildEndTime = $BuildEndTime; + } + $CurrentPlanet['metal'] -= (isset($LockResources['metal']) ? $LockResources['metal'] : 0); + $CurrentPlanet['crystal'] -= (isset($LockResources['crystal']) ? $LockResources['crystal'] : 0); + $CurrentPlanet['deuterium'] -= (isset($LockResources['deuterium']) ? $LockResources['deuterium'] : 0); + + $Queue['lenght'] = $QueueIndex; + if(!empty($QueueParser)) + { + $Parse['Create_Queue'] = ''; + foreach($QueueParser as $QueueID => $QueueData) + { + if($QueueID == 0) + { + $ThisTPL = gettemplate('buildings_compact_queue_firstel'); + } + else if($QueueID == 1) + { + $ThisTPL = gettemplate('buildings_compact_queue_nextel'); + } + $Parse['Create_Queue'] .= parsetemplate($ThisTPL, $QueueData); + } + } + } + else + { + $Queue['lenght'] = 0; + $Parse['Create_Queue'] = parsetemplate($TPL['queue_topinfo'], array('InfoText' => $_Lang['Queue_Empty'])); + } + // End of - Parse Queue + + // Parse all available buildings + if(($CurrentPlanet['field_current'] + $Queue['lenght'] - $FieldsModifier) < CalculateMaxPlanetFields($CurrentPlanet)) + { + $HasLeftFields = true; + } + else + { + $HasLeftFields = false; + } + if($Queue['lenght'] < ((isPro($CurrentUser)) ? MAX_BUILDING_QUEUE_SIZE_PRO : MAX_BUILDING_QUEUE_SIZE)) + { + $CanAddToQueue = true; + } + else + { + $CanAddToQueue = false; + $Parse['Create_Queue'] = parsetemplate($TPL['queue_topinfo'], array('InfoColor' => 'red', 'InfoText' => $_Lang['Queue_Full'])).$Parse['Create_Queue']; + } + if($CurrentUser['engineer_time'] > $Now) + { + $EnergyMulti = 1.10; + } + else + { + $EnergyMulti = 1; + } + if($CurrentUser['geologist_time'] > $Now) + { + $ResourceMulti = 1.15; + } + else + { + $ResourceMulti = 1; + } + $ResImages = array + ( + 'metal' => 'metall', + 'crystal' => 'kristall', + 'deuterium' => 'deuterium', + 'energy_max' => 'energie', + 'darkEnergy' => 'darkenergy' + ); + $ResLangs = array + ( + 'metal' => $_Lang['Metal'], + 'crystal' => $_Lang['Crystal'], + 'deuterium' => $_Lang['Deuterium'], + 'energy_max' => $_Lang['Energy'], + 'darkEnergy' => $_Lang['DarkEnergy'] + ); + + $ElementParserDefault = array + ( + 'SkinPath' => $_SkinPath, + 'InfoBox_Level' => $_Lang['InfoBox_Level'], + 'InfoBox_Build' => $_Lang['InfoBox_Build'], + 'InfoBox_Destroy' => $_Lang['InfoBox_Destroy'], + 'InfoBox_RequirementsFor' => $_Lang['InfoBox_RequirementsFor'], + 'InfoBox_ResRequirements' => $_Lang['InfoBox_ResRequirements'], + 'InfoBox_TechRequirements' => $_Lang['InfoBox_TechRequirements'], + 'InfoBox_Requirements_Res' => $_Lang['InfoBox_Requirements_Res'], + 'InfoBox_Requirements_Tech' => $_Lang['InfoBox_Requirements_Tech'], + 'InfoBox_BuildTime' => $_Lang['InfoBox_BuildTime'], + 'InfoBox_ShowTechReq' => $_Lang['InfoBox_ShowTechReq'], + 'InfoBox_ShowResReq' => $_Lang['InfoBox_ShowResReq'], + ); + + foreach($_Vars_ElementCategories['build'] as $ElementID) + { + if(in_array($ElementID, $_Vars_ElementCategories['buildOn'][$CurrentPlanet['planet_type']])) + { + $ElementParser = $ElementParserDefault; + + $CurrentLevel = $CurrentPlanet[$_Vars_GameElements[$ElementID]]; + $NextLevel = $CurrentPlanet[$_Vars_GameElements[$ElementID]] + 1; + $MaxLevelReached = false; + $TechLevelOK = false; + $HasResources = true; + + $HideButton_Build = false; + $HideButton_Destroy = false; + $HideButton_QuickBuild = false; + + $ElementParser['HideBuildWarn'] = 'hide'; + $ElementParser['ElementName'] = $_Lang['tech'][$ElementID]; + $ElementParser['ElementID'] = $ElementID; + $ElementParser['ElementLevel'] = prettyNumber($CurrentPlanet[$_Vars_GameElements[$ElementID]]); + $ElementParser['ElementRealLevel'] = prettyNumber($CurrentPlanet[$_Vars_GameElements[$ElementID]] + (isset($LevelModifiers[$ElementID]) ? $LevelModifiers[$ElementID] : 0)); + $ElementParser['BuildLevel'] = prettyNumber($CurrentPlanet[$_Vars_GameElements[$ElementID]] + 1); + $ElementParser['DestroyLevel'] = prettyNumber($CurrentPlanet[$_Vars_GameElements[$ElementID]] - 1); + $ElementParser['Desc'] = $_Lang['res']['descriptions'][$ElementID]; + $ElementParser['BuildButtonColor'] = 'buildDo_Green'; + $ElementParser['DestroyButtonColor'] = 'buildDo_Red'; + + if(isset($LevelModifiers[$ElementID])) + { + if($LevelModifiers[$ElementID] > 0) + { + $ElementParser['levelmodif']['modColor'] = 'red'; + $ElementParser['levelmodif']['modText'] = prettyNumber($LevelModifiers[$ElementID] * (-1)); + } + else if($LevelModifiers[$ElementID] == 0) + { + $ElementParser['levelmodif']['modColor'] = 'orange'; + $ElementParser['levelmodif']['modText'] = '0'; + } + else + { + $ElementParser['levelmodif']['modColor'] = 'lime'; + $ElementParser['levelmodif']['modText'] = '+'.prettyNumber($LevelModifiers[$ElementID] * (-1)); + } + $ElementParser['LevelModifier'] = parsetemplate($TPL['infobox_levelmodif'], $ElementParser['levelmodif']); + $ElementParser['ElementLevelModif'] = parsetemplate($TPL['list_levelmodif'], $ElementParser['levelmodif']); + unset($ElementParser['levelmodif']); + } + + if(!(isset($_Vars_MaxElementLevel[$ElementID]) && $_Vars_MaxElementLevel[$ElementID] > 0 && $NextLevel > $_Vars_MaxElementLevel[$ElementID])) + { + $ElementParser['ElementPrice'] = GetBuildingPrice($CurrentUser, $CurrentPlanet, $ElementID, true, false, true); + foreach($ElementParser['ElementPrice'] as $Key => $Value) + { + if($Value > 0) + { + $ResColor = ''; + $ResMinusColor = ''; + $MinusValue = ' '; + + if($Key != 'darkEnergy') + { + $UseVar = &$CurrentPlanet; + } + else + { + $UseVar = &$CurrentUser; + } + if($UseVar[$Key] < $Value) + { + $ResMinusColor = 'red'; + $MinusValue = '('.prettyNumber($UseVar[$Key] - $Value).')'; + if($Queue['lenght'] > 0) + { + $ResColor = 'orange'; + } + else + { + $ResColor = 'red'; + } + } + + $ElementParser['ElementPrices'] = array + ( + 'SkinPath' => $_SkinPath, + 'ResName' => $Key, + 'ResImg' => $ResImages[$Key], + 'ResColor' => $ResColor, + 'Value' => prettyNumber($Value), + 'ResMinusColor' => $ResMinusColor, + 'MinusValue' => $MinusValue, + ); + if(!isset($ElementParser['ElementPriceDiv'])) + { + $ElementParser['ElementPriceDiv'] = ''; + } + $ElementParser['ElementPriceDiv'] .= parsetemplate($TPL['infobox_req_res'], $ElementParser['ElementPrices']); + } + } + $ElementParser['BuildTime'] = pretty_time(GetBuildingTime($CurrentUser, $CurrentPlanet, $ElementID)); + } + else + { + $MaxLevelReached = true; + $ElementParser['HideBuildInfo'] = 'hide'; + $ElementParser['HideBuildWarn'] = ''; + $HideButton_Build = true; + $ElementParser['BuildWarn_Color'] = 'red'; + $ElementParser['BuildWarn_Text'] = $_Lang['ListBox_Disallow_MaxLevelReached']; + } + if($CurrentLevel == 0 || (isset($_Vars_IndestructibleBuildings[$ElementID]) && $_Vars_IndestructibleBuildings[$ElementID])) + { + $HideButton_Destroy = true; + } + if(IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $ElementID)) + { + $TechLevelOK = true; + $ElementParser['ElementRequirementsHeadline'] = $TPL['infobox_req_selector_single']; + } + else + { + $ElementParser['ElementRequirementsHeadline'] = $TPL['infobox_req_selector_dual']; + $ElementParser['ElementTechDiv'] = GetElementTechReq($CurrentUser, $CurrentPlanet, $ElementID, true); + $ElementParser['HideResReqDiv'] = 'hide'; + } + if(IsElementBuyable($CurrentUser, $CurrentPlanet, $ElementID, true, false, true) === false) + { + $HasResources = false; + if($Queue['lenght'] == 0) + { + $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; + $HideButton_QuickBuild = true; + } + else + { + $ElementParser['BuildButtonColor'] = 'buildDo_Orange'; + } + } + if(IsElementBuyable($CurrentUser, $CurrentPlanet, $ElementID, true, true) === false) + { + if($Queue['lenght'] == 0) + { + $ElementParser['DestroyButtonColor'] = 'destroyDo_Gray'; + } + } + + $BlockReason = array(); + + if($MaxLevelReached) + { + $BlockReason[] = $_Lang['ListBox_Disallow_MaxLevelReached']; + } + else if(!$HasResources) + { + $BlockReason[] = $_Lang['ListBox_Disallow_NoResources']; + } + if(!$TechLevelOK) + { + $BlockReason[] = $_Lang['ListBox_Disallow_NoTech']; + $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; + $HideButton_QuickBuild = true; + $HideButton_Destroy = true; + } + if($ElementID == 31 AND $CurrentUser['techQueue_Planet'] > 0 AND $CurrentUser['techQueue_EndTime'] > 0 AND $_GameConfig['BuildLabWhileRun'] != 1) + { + $BlockReason[] = $_Lang['ListBox_Disallow_LabResearch']; + $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; + $ElementParser['DestroyButtonColor'] = 'destroyDo_Gray'; + $HideButton_QuickBuild = true; + } + if($HasLeftFields === false) + { + $BlockReason[] = $_Lang['ListBox_Disallow_NoFreeFields']; + $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; + $HideButton_QuickBuild = true; + } + if($CanAddToQueue === false) + { + $BlockReason[] = $_Lang['ListBox_Disallow_QueueIsFull']; + $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; + $HideButton_QuickBuild = true; + } + if(isOnVacation($CurrentUser)) + { + $BlockReason[] = $_Lang['ListBox_Disallow_VacationMode']; + $ElementParser['BuildButtonColor'] = 'buildDo_Gray'; + $ElementParser['DestroyButtonColor'] = 'destroyDo_Gray'; + $HideButton_QuickBuild = true; + } + + if(!empty($BlockReason)) + { + if($ElementParser['BuildButtonColor'] == 'buildDo_Orange') + { + $ElementParser['ElementDisabled'] = $TPL['list_partdisabled']; + } + else + { + $ElementParser['ElementDisabled'] = $TPL['list_disabled']; + } + $ElementParser['ElementDisableReason'] = end($BlockReason); + } + + if($HideButton_Build) + { + $ElementParser['HideBuildButton'] = 'hide'; + } + if($HideButton_Build OR $HideButton_QuickBuild) + { + $ElementParser['HideQuickBuildButton'] = 'hide'; + } + if($HideButton_Destroy) + { + $ElementParser['HideDestroyButton'] = 'hide'; + } + else + { + $ElementDestroyCost = GetBuildingPrice($CurrentUser, $CurrentPlanet, $ElementID, true, true, true); + $ElementParser['Create_DestroyTips_Res'] = ''; + foreach($ElementDestroyCost as $Key => $Value) + { + if($Value > 0) + { + $ResColor = ''; + if($Key != 'darkEnergy') + { + if($CurrentPlanet[$Key] < $Value) + { + if($Queue['lenght'] > 0) + { + $ResColor = 'orange'; + } + else + { + $ResColor = 'red'; + } + } + } + else + { + if($CurrentUser[$Key] < $Value) + { + if($Queue['lenght'] > 0) + { + $ResColor = 'orange'; + } + else + { + $ResColor = 'red'; + } + } + } + $ElementParser['ElementPrices'] = array('Name' => $ResLangs[$Key], 'Color' => $ResColor, 'Value' => prettyNumber($Value)); + $ElementParser['Create_DestroyTips_Res'] .= parsetemplate($TPL['infobox_req_destres'], $ElementParser['ElementPrices']); + } + } + if(!isset($Parse['Create_DestroyTips'])) + { + $Parse['Create_DestroyTips'] = ''; + } + $Parse['Create_DestroyTips'] .= parsetemplate($TPL['infobox_req_desttable'], array + ( + 'ElementID' => $ElementID, + 'InfoBox_DestroyCost' => $_Lang['InfoBox_DestroyCost'], + 'InfoBox_DestroyTime' => $_Lang['InfoBox_DestroyTime'], + 'Resources' => $ElementParser['Create_DestroyTips_Res'], + 'DestroyTime' => pretty_time(GetBuildingTime($CurrentUser, $CurrentPlanet, $ElementID) / 2) + )); + } + + if(in_array($ElementID, $_Vars_ElementCategories['prod'])) + { + // Show energy on BuildingPage + $BuildLevelFactor = 10; + $BuildTemp = $CurrentPlanet['temp_max']; + $CurrentBuildtLvl = $CurrentLevel; + $BuildLevel = ($CurrentBuildtLvl > 0) ? $CurrentBuildtLvl : 0; + $Production = array(); + $Needs = array(); + $ThisResource = ''; + + // Calculate ThisLevel Income + if($ElementID <= 3) + { + if($ElementID == 1) + { + $ThisResource = $_Lang['Metal']; + $Production[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['metal']) * $_GameConfig['resource_multiplier'] * $ResourceMulti); + } + else if($ElementID == 2) + { + $ThisResource = $_Lang['Crystal']; + $Production[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['crystal']) * $_GameConfig['resource_multiplier'] * $ResourceMulti); + } + else if($ElementID == 3) + { + $ThisResource = $_Lang['Deuterium']; + $Production[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * $_GameConfig['resource_multiplier'] * $ResourceMulti); + } + $Needs[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy'])); + } + else + { + if($ElementID == 12) + { + $Needs[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']); + } + $Production[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $EnergyMulti); + } + // Calculate NextLevel Income + $BuildLevel += 1; + if($ElementID <= 3) + { + if($ElementID == 1) + { + $Production[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['metal']) * $_GameConfig['resource_multiplier'] * $ResourceMulti); + } + else if($ElementID == 2) + { + $Production[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['crystal']) * $_GameConfig['resource_multiplier'] * $ResourceMulti); + } + else if($ElementID == 3) + { + $Production[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * $_GameConfig['resource_multiplier'] * $ResourceMulti); + } + $Needs[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy'])); + } + else + { + if($ElementID == 12) + { + $Needs[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']); + } + $Production[] = floor(eval($_Vars_ResProduction[$ElementID]['formule']['energy']) * $EnergyMulti); + } + // Calculate Difference + $Production = prettyNumber($Production[1] - $Production[0]); + if(!isset($Needs[1])) + { + $Needs[1] = 0; + } + if(!isset($Needs[0])) + { + $Needs[0] = 0; + } + $Needs = prettyNumber($Needs[1] - $Needs[0]); + + if($ElementID >= 1 AND $ElementID <= 3) + { + $ElementParser['AdditionalNfo'][] = parsetemplate($TPL['infobox_additionalnfo'], array('Label' => $_Lang['Energy'], 'ValueClasses' => 'red', 'Value' => $Needs)); + $ElementParser['AdditionalNfo'][] = parsetemplate($TPL['infobox_additionalnfo'], array('Label' => $ThisResource, 'ValueClasses' => 'lime', 'Value' => '+'.$Production)); + } + else if($ElementID == 4 OR $ElementID == 12) + { + if($ElementID != 12) + { + $ElementParser['AdditionalNfo'][] = parsetemplate($TPL['infobox_additionalnfo'], array('Label' => $_Lang['Energy'], 'ValueClasses' => 'lime', 'Value' => '+'.$Production)); + } + else + { + $ElementParser['AdditionalNfo'][] = parsetemplate($TPL['infobox_additionalnfo'], array('Label' => $_Lang['Energy'], 'ValueClasses' => 'lime', 'Value' => '+'.$Production)); + $ElementParser['AdditionalNfo'][] = parsetemplate($TPL['infobox_additionalnfo'], array('Label' => $_Lang['Deuterium'], 'ValueClasses' => 'red', 'Value' => $Needs)); + } + } + } + + if(!empty($ElementParser['AdditionalNfo'])) + { + $ElementParser['AdditionalNfo'] = implode('', $ElementParser['AdditionalNfo']); + } + $ElementParser['ElementRequirementsHeadline'] = parsetemplate($ElementParser['ElementRequirementsHeadline'], $ElementParser); + $StructuresList[] = parsetemplate($TPL['list_element'], $ElementParser); + $InfoBoxes[] = parsetemplate($TPL['infobox_body'], $ElementParser); + } + } + + if(!empty($LevelModifiers)) + { + foreach($LevelModifiers as $ElementID => $Modifier) + { + $CurrentPlanet[$_Vars_GameElements[$ElementID]] += $Modifier; + } + } + $CurrentPlanet['metal'] += (isset($LockResources['metal']) ? $LockResources['metal'] : 0); + $CurrentPlanet['crystal'] += (isset($LockResources['crystal']) ? $LockResources['crystal'] : 0); + $CurrentPlanet['deuterium'] += (isset($LockResources['deuterium']) ? $LockResources['deuterium'] : 0); + + // Create Structures List + $ThisRowIndex = 0; + $InRowCount = 0; + foreach($StructuresList as $ParsedData) + { + if($InRowCount == $ElementsPerRow) + { + $ParsedRows[($ThisRowIndex + 1)] = $TPL['list_breakrow']; + $ThisRowIndex += 2; + $InRowCount = 0; + } + + if(!isset($StructureRows[$ThisRowIndex]['Elements'])) + { + $StructureRows[$ThisRowIndex]['Elements'] = ''; + } + $StructureRows[$ThisRowIndex]['Elements'] .= $ParsedData; + $InRowCount += 1; + } + if($InRowCount < $ElementsPerRow) + { + if(!isset($StructureRows[$ThisRowIndex]['Elements'])) + { + $StructureRows[$ThisRowIndex]['Elements'] = ''; + } + $StructureRows[$ThisRowIndex]['Elements'] .= str_repeat($TPL['list_hidden'], ($ElementsPerRow - $InRowCount)); + } + foreach($StructureRows as $Index => $Data) + { + $ParsedRows[$Index] = parsetemplate($TPL['list_row'], $Data); + } + ksort($ParsedRows, SORT_ASC); + $Parse['Create_StructuresList'] = implode('', $ParsedRows); + $Parse['Create_ElementsInfoBoxes'] = implode('', $InfoBoxes); + if($ShowElementID > 0) + { + $Parse['Create_ShowElementOnStartup'] = $ShowElementID; + } + $MaxFields = CalculateMaxPlanetFields($CurrentPlanet); + if($CurrentPlanet['field_current'] == $MaxFields) + { + $Parse['Insert_Overview_Fields_Used_Color'] = 'red'; + } + else if($CurrentPlanet['field_current'] >= ($MaxFields * 0.9)) + { + $Parse['Insert_Overview_Fields_Used_Color'] = 'orange'; + } + else + { + $Parse['Insert_Overview_Fields_Used_Color'] = 'lime'; + } + // End of - Parse all available buildings + + $Parse['Insert_SkinPath'] = $_SkinPath; + $Parse['Insert_PlanetImg'] = $CurrentPlanet['image']; + $Parse['Insert_PlanetType'] = $_Lang['PlanetType_'.$CurrentPlanet['planet_type']]; + $Parse['Insert_PlanetName'] = $CurrentPlanet['name']; + $Parse['Insert_PlanetPos_Galaxy'] = $CurrentPlanet['galaxy']; + $Parse['Insert_PlanetPos_System'] = $CurrentPlanet['system']; + $Parse['Insert_PlanetPos_Planet'] = $CurrentPlanet['planet']; + $Parse['Insert_Overview_Diameter'] = prettyNumber($CurrentPlanet['diameter']); + $Parse['Insert_Overview_Fields_Used'] = prettyNumber($CurrentPlanet['field_current']); + $Parse['Insert_Overview_Fields_Max'] = prettyNumber($MaxFields); + $Parse['Insert_Overview_Fields_Percent'] = sprintf('%0.2f', ($CurrentPlanet['field_current'] / $MaxFields) * 100); + $Parse['Insert_Overview_Temperature'] = sprintf($_Lang['Overview_Form_Temperature'], $CurrentPlanet['temp_min'], $CurrentPlanet['temp_max']); + + $Page = parsetemplate(gettemplate('buildings_compact_body_structures'), $Parse); + + display($Page, $_Lang['Builds']); +} + +?> diff --git a/includes/functions/TasksFunctions.php b/includes/functions/TasksFunctions.php index e1e858d43..d81e66c63 100644 --- a/includes/functions/TasksFunctions.php +++ b/includes/functions/TasksFunctions.php @@ -1,316 +1,316 @@ - $_Vars_TasksData) - { - if(strstr($CatID, 's')) - { - $CatID = str_replace('s', '', $CatID); - } - foreach($_Vars_TasksData as $TaskID) - { - $UserVar['tasks_done_parsed']['done'][$CatID][] = $TaskID; - } - } - } - } - } - - if(empty($UserVar['tasks_done_parsed']['done'])) - { - $UserVar['tasks_done_parsed']['done'] = array(0 => array(0)); - } - return true; - } - return false; -} - -function Tasks_GetTaskCatID($TaskID) -{ - global $_Vars_TasksData; - - foreach($_Vars_TasksData as $_Vars_TasksDataCatID => $_Vars_TasksDataList) - { - if(!empty($_Vars_TasksDataList['tasks'][$TaskID])) - { - return $_Vars_TasksDataCatID; - } - } -} - -function Tasks_GetAvailableTasks($UserVar, $CheckJobType = false) -{ - global $_Vars_TasksData; - - $Return = array('tasks' => array()); - - foreach($_Vars_TasksData as $CatID => $CatData) - { - if(Tasks_IsCatDone($CatID, $UserVar)) - { - continue; - } - if(!Tasks_CheckCatAvailable($CatID, $UserVar)) - { - continue; - } - foreach($CatData['tasks'] as $TaskID => $TaskData) - { - if(Tasks_IsDone($TaskID, $UserVar)) - { - continue; - } - if(!Tasks_CheckAvailable($TaskID, $UserVar, $CatID)) - { - continue; - } - if($CheckJobType !== false AND strstr($TaskData['jobtypes'], $CheckJobType) === false) - { - continue; - } - - $Return['tasks'][] = $TaskID; - $Return['cats'][$TaskID] = $CatID; - } - } - - return $Return; -} - -function Tasks_IsCatDone($CatID, $UserVar) -{ - global $_Vars_TasksData; - - if(empty($UserVar['tasks_done_parsed']['done'][$CatID])) - { - return false; - } - if(count($UserVar['tasks_done_parsed']['done'][$CatID]) != count($_Vars_TasksData[$CatID]['tasks'])) - { - return false; - } - return true; -} - -function Tasks_IsDone($TaskID, $UserVar) -{ - foreach($UserVar['tasks_done_parsed']['done'] as $CatDoneTasks) - { - if(in_array($TaskID, $CatDoneTasks)) - { - return true; - } - } - return false; -} - -function Tasks_CheckCatAvailable($CatID, $UserVar) -{ - global $_Vars_TasksData; - - if(!empty($_Vars_TasksData[$CatID]['requirements'])) - { - foreach($_Vars_TasksData[$CatID]['requirements'] as $TaskCatReq) - { - if($TaskCatReq['type'] == 'CATEGORY') - { - if(!Tasks_IsCatDone($TaskCatReq['elementID'], $UserVar)) - { - return false; - } - } - elseif($TaskCatReq['type'] == 'TASK') - { - if(!Tasks_IsDone($TaskCatReq['elementID'], $UserVar)) - { - return false; - } - } - } - } - return true; -} - -function Tasks_CheckAvailable($TaskID, $UserVar, $TaskCatID = false) -{ - global $_Vars_TasksData; - - if($TaskCatID === false) - { - $TaskCatID = Tasks_GetTaskCatID($TaskID); - } - $Pointer = &$_Vars_TasksData[$TaskCatID]['tasks'][$TaskID]; - if(!empty($Pointer['requirements'])) - { - foreach($Pointer['requirements'] as $TaskReq) - { - if($TaskReq['type'] == 'CATEGORY') - { - if(!Tasks_IsCatDone($TaskReq['elementID'], $UserVar)) - { - return false; - } - } - elseif($TaskReq['type'] == 'TASK') - { - if(!Tasks_IsDone($TaskReq['elementID'], $UserVar)) - { - return false; - } - } - } - } - return true; -} - -function Tasks_ParseRewards($RewardData, &$UpdateArray) -{ - global $_Vars_GameElements; - if($RewardData['type'] == 'RESOURCES') - { - // Add Resources - if(isset($RewardData['met'])) - { - if(!isset($UpdateArray['planet']['metal'])) - { - $UpdateArray['planet']['metal'] = 0; - } - if(!isset($UpdateArray['devlog']['M'])) - { - $UpdateArray['devlog']['M'] = 0; - } - $UpdateArray['planet']['metal'] += $RewardData['met']; - $UpdateArray['devlog']['M'] += $RewardData['met']; - } - if(isset($RewardData['cry'])) - { - if(!isset($UpdateArray['planet']['crystal'])) - { - $UpdateArray['planet']['crystal'] = 0; - } - if(!isset($UpdateArray['devlog']['C'])) - { - $UpdateArray['devlog']['C'] = 0; - } - $UpdateArray['planet']['crystal'] += $RewardData['cry']; - $UpdateArray['devlog']['C'] += $RewardData['cry']; - } - if(isset($RewardData['deu'])) - { - if(!isset($UpdateArray['planet']['deuterium'])) - { - $UpdateArray['planet']['deuterium'] = 0; - } - if(!isset($UpdateArray['devlog']['D'])) - { - $UpdateArray['devlog']['D'] = 0; - } - $UpdateArray['planet']['deuterium'] += $RewardData['deu']; - $UpdateArray['devlog']['D'] += $RewardData['deu']; - } - } - else if($RewardData['type'] == 'PLANET_ELEMENT') - { - // Add Ships or Defenses - if(!isset($UpdateArray['planet'][$_Vars_GameElements[$RewardData['elementID']]])) - { - $UpdateArray['planet'][$_Vars_GameElements[$RewardData['elementID']]] = 0; - } - if(!isset($UpdateArray['devlog'][$RewardData['elementID']])) - { - $UpdateArray['devlog'][$RewardData['elementID']] = 0; - } - $UpdateArray['planet'][$_Vars_GameElements[$RewardData['elementID']]] += $RewardData['count']; - $UpdateArray['devlog'][$RewardData['elementID']] += $RewardData['count']; - } - else if($RewardData['type'] == 'PREMIUM_ITEM') - { - // Add Free PremiumItem - $UpdateArray['free_premium'][] = $RewardData['elementID']; - } - else if($RewardData['type'] == 'PREMIUM_RESOURCE') - { - // Add Free Dark Energy - if(!isset($UpdateArray['devlog']['DE'])) - { - $UpdateArray['devlog']['DE'] = 0; - } - if(!isset($UpdateArray['user']['darkEnergy'])) - { - $UpdateArray['user']['darkEnergy'] = 0; - } - $UpdateArray['devlog']['DE'] += $RewardData['value']; - $UpdateArray['user']['darkEnergy'] += $RewardData['value']; - } -} - -function Tasks_TriggerTask($TheUser, $JobType, $Callbacks = array()) -{ - global $_Vars_TasksData, $UserTasksUpdate; - - $CheckTasks = Tasks_GetAvailableTasks($TheUser, $JobType); - foreach($CheckTasks['tasks'] as $TaskID) - { - $ThisCat = $CheckTasks['cats'][$TaskID]; - foreach($_Vars_TasksData[$ThisCat]['tasks'][$TaskID]['jobs'] as $JobID => $JobArray) - { - if($JobArray['type'] == $JobType) - { - if(!empty($Callbacks['preCheck']) AND $Callbacks['preCheck']($JobArray, $ThisCat, $TaskID, $JobID) === true) - { - continue; - } - if(!empty($TheUser['tasks_done_parsed']['jobs'][$ThisCat][$TaskID])) - { - if(in_array($JobID, $TheUser['tasks_done_parsed']['jobs'][$ThisCat][$TaskID])) - { - continue; - } - } - if(!empty($UserTasksUpdate[$TheUser['id']]['done'][$ThisCat][$TaskID])) - { - if(in_array($JobID, $UserTasksUpdate[$TheUser['id']]['done'][$ThisCat][$TaskID])) - { - continue; - } - } - if(!empty($Callbacks['mainCheck']) AND $Callbacks['mainCheck']($JobArray, $ThisCat, $TaskID, $JobID) === true) - { - continue; - } - $UserTasksUpdate[$TheUser['id']]['done'][$ThisCat][$TaskID][] = $JobID; - } - } - } -} - -function Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, &$ThisUser, $Value) -{ - global $UserTasksUpdate; - if(!empty($UserTasksUpdate[$ThisUser['id']]['status'][$ThisCat][$TaskID][$JobID])) - { - $ThisUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$ThisUser['id']]['status'][$ThisCat][$TaskID][$JobID]; - } - if(!isset($ThisUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID])) - { - $ThisUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = 0; - } - $ThisUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] += $Value; - if($ThisUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] < $JobArray[$JobArray['statusField']]) - { - $UserTasksUpdate[$ThisUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $ThisUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; - return true; - } -} - -?> \ No newline at end of file + $_Vars_TasksData) + { + if(strstr($CatID, 's')) + { + $CatID = str_replace('s', '', $CatID); + } + foreach($_Vars_TasksData as $TaskID) + { + $UserVar['tasks_done_parsed']['done'][$CatID][] = $TaskID; + } + } + } + } + } + + if(empty($UserVar['tasks_done_parsed']['done'])) + { + $UserVar['tasks_done_parsed']['done'] = array(0 => array(0)); + } + return true; + } + return false; +} + +function Tasks_GetTaskCatID($TaskID) +{ + global $_Vars_TasksData; + + foreach($_Vars_TasksData as $_Vars_TasksDataCatID => $_Vars_TasksDataList) + { + if(!empty($_Vars_TasksDataList['tasks'][$TaskID])) + { + return $_Vars_TasksDataCatID; + } + } +} + +function Tasks_GetAvailableTasks($UserVar, $CheckJobType = false) +{ + global $_Vars_TasksData; + + $Return = array('tasks' => array()); + + foreach($_Vars_TasksData as $CatID => $CatData) + { + if(Tasks_IsCatDone($CatID, $UserVar)) + { + continue; + } + if(!Tasks_CheckCatAvailable($CatID, $UserVar)) + { + continue; + } + foreach($CatData['tasks'] as $TaskID => $TaskData) + { + if(Tasks_IsDone($TaskID, $UserVar)) + { + continue; + } + if(!Tasks_CheckAvailable($TaskID, $UserVar, $CatID)) + { + continue; + } + if($CheckJobType !== false AND strstr($TaskData['jobtypes'], $CheckJobType) === false) + { + continue; + } + + $Return['tasks'][] = $TaskID; + $Return['cats'][$TaskID] = $CatID; + } + } + + return $Return; +} + +function Tasks_IsCatDone($CatID, $UserVar) +{ + global $_Vars_TasksData; + + if(empty($UserVar['tasks_done_parsed']['done'][$CatID])) + { + return false; + } + if(count($UserVar['tasks_done_parsed']['done'][$CatID]) != count($_Vars_TasksData[$CatID]['tasks'])) + { + return false; + } + return true; +} + +function Tasks_IsDone($TaskID, $UserVar) +{ + foreach($UserVar['tasks_done_parsed']['done'] as $CatDoneTasks) + { + if(in_array($TaskID, $CatDoneTasks)) + { + return true; + } + } + return false; +} + +function Tasks_CheckCatAvailable($CatID, $UserVar) +{ + global $_Vars_TasksData; + + if(!empty($_Vars_TasksData[$CatID]['requirements'])) + { + foreach($_Vars_TasksData[$CatID]['requirements'] as $TaskCatReq) + { + if($TaskCatReq['type'] == 'CATEGORY') + { + if(!Tasks_IsCatDone($TaskCatReq['elementID'], $UserVar)) + { + return false; + } + } + elseif($TaskCatReq['type'] == 'TASK') + { + if(!Tasks_IsDone($TaskCatReq['elementID'], $UserVar)) + { + return false; + } + } + } + } + return true; +} + +function Tasks_CheckAvailable($TaskID, $UserVar, $TaskCatID = false) +{ + global $_Vars_TasksData; + + if($TaskCatID === false) + { + $TaskCatID = Tasks_GetTaskCatID($TaskID); + } + $Pointer = &$_Vars_TasksData[$TaskCatID]['tasks'][$TaskID]; + if(!empty($Pointer['requirements'])) + { + foreach($Pointer['requirements'] as $TaskReq) + { + if($TaskReq['type'] == 'CATEGORY') + { + if(!Tasks_IsCatDone($TaskReq['elementID'], $UserVar)) + { + return false; + } + } + elseif($TaskReq['type'] == 'TASK') + { + if(!Tasks_IsDone($TaskReq['elementID'], $UserVar)) + { + return false; + } + } + } + } + return true; +} + +function Tasks_ParseRewards($RewardData, &$UpdateArray) +{ + global $_Vars_GameElements; + if($RewardData['type'] == 'RESOURCES') + { + // Add Resources + if(isset($RewardData['met'])) + { + if(!isset($UpdateArray['planet']['metal'])) + { + $UpdateArray['planet']['metal'] = 0; + } + if(!isset($UpdateArray['devlog']['M'])) + { + $UpdateArray['devlog']['M'] = 0; + } + $UpdateArray['planet']['metal'] += $RewardData['met']; + $UpdateArray['devlog']['M'] += $RewardData['met']; + } + if(isset($RewardData['cry'])) + { + if(!isset($UpdateArray['planet']['crystal'])) + { + $UpdateArray['planet']['crystal'] = 0; + } + if(!isset($UpdateArray['devlog']['C'])) + { + $UpdateArray['devlog']['C'] = 0; + } + $UpdateArray['planet']['crystal'] += $RewardData['cry']; + $UpdateArray['devlog']['C'] += $RewardData['cry']; + } + if(isset($RewardData['deu'])) + { + if(!isset($UpdateArray['planet']['deuterium'])) + { + $UpdateArray['planet']['deuterium'] = 0; + } + if(!isset($UpdateArray['devlog']['D'])) + { + $UpdateArray['devlog']['D'] = 0; + } + $UpdateArray['planet']['deuterium'] += $RewardData['deu']; + $UpdateArray['devlog']['D'] += $RewardData['deu']; + } + } + else if($RewardData['type'] == 'PLANET_ELEMENT') + { + // Add Ships or Defenses + if(!isset($UpdateArray['planet'][$_Vars_GameElements[$RewardData['elementID']]])) + { + $UpdateArray['planet'][$_Vars_GameElements[$RewardData['elementID']]] = 0; + } + if(!isset($UpdateArray['devlog'][$RewardData['elementID']])) + { + $UpdateArray['devlog'][$RewardData['elementID']] = 0; + } + $UpdateArray['planet'][$_Vars_GameElements[$RewardData['elementID']]] += $RewardData['count']; + $UpdateArray['devlog'][$RewardData['elementID']] += $RewardData['count']; + } + else if($RewardData['type'] == 'PREMIUM_ITEM') + { + // Add Free PremiumItem + $UpdateArray['free_premium'][] = $RewardData['elementID']; + } + else if($RewardData['type'] == 'PREMIUM_RESOURCE') + { + // Add Free Dark Energy + if(!isset($UpdateArray['devlog']['DE'])) + { + $UpdateArray['devlog']['DE'] = 0; + } + if(!isset($UpdateArray['user']['darkEnergy'])) + { + $UpdateArray['user']['darkEnergy'] = 0; + } + $UpdateArray['devlog']['DE'] += $RewardData['value']; + $UpdateArray['user']['darkEnergy'] += $RewardData['value']; + } +} + +function Tasks_TriggerTask($TheUser, $JobType, $Callbacks = array()) +{ + global $_Vars_TasksData, $UserTasksUpdate; + + $CheckTasks = Tasks_GetAvailableTasks($TheUser, $JobType); + foreach($CheckTasks['tasks'] as $TaskID) + { + $ThisCat = $CheckTasks['cats'][$TaskID]; + foreach($_Vars_TasksData[$ThisCat]['tasks'][$TaskID]['jobs'] as $JobID => $JobArray) + { + if($JobArray['type'] == $JobType) + { + if(!empty($Callbacks['preCheck']) AND $Callbacks['preCheck']($JobArray, $ThisCat, $TaskID, $JobID) === true) + { + continue; + } + if(!empty($TheUser['tasks_done_parsed']['jobs'][$ThisCat][$TaskID])) + { + if(in_array($JobID, $TheUser['tasks_done_parsed']['jobs'][$ThisCat][$TaskID])) + { + continue; + } + } + if(!empty($UserTasksUpdate[$TheUser['id']]['done'][$ThisCat][$TaskID])) + { + if(in_array($JobID, $UserTasksUpdate[$TheUser['id']]['done'][$ThisCat][$TaskID])) + { + continue; + } + } + if(!empty($Callbacks['mainCheck']) AND $Callbacks['mainCheck']($JobArray, $ThisCat, $TaskID, $JobID) === true) + { + continue; + } + $UserTasksUpdate[$TheUser['id']]['done'][$ThisCat][$TaskID][] = $JobID; + } + } + } +} + +function Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, &$ThisUser, $Value) +{ + global $UserTasksUpdate; + if(!empty($UserTasksUpdate[$ThisUser['id']]['status'][$ThisCat][$TaskID][$JobID])) + { + $ThisUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$ThisUser['id']]['status'][$ThisCat][$TaskID][$JobID]; + } + if(!isset($ThisUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID])) + { + $ThisUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = 0; + } + $ThisUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] += $Value; + if($ThisUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] < $JobArray[$JobArray['statusField']]) + { + $UserTasksUpdate[$ThisUser['id']]['status'][$ThisCat][$TaskID][$JobID] = $ThisUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; + return true; + } +} + +?> diff --git a/includes/functions/TechQueue_Add.php b/includes/functions/TechQueue_Add.php index 5bd58700b..6c2752b9c 100644 --- a/includes/functions/TechQueue_Add.php +++ b/includes/functions/TechQueue_Add.php @@ -1,69 +1,69 @@ - 0 AND $TheUser['techQueue_Planet'] != $ThePlanet['id']) - { - return false; - } - - if(!empty($ThePlanet['techQueue'])) - { - $Queue = explode(';', $ThePlanet['techQueue']); - $QueueLength = count($Queue); - } - else - { - $Queue = array(); - $QueueLength = 0; - } - - $MaxLength = (isPro($TheUser) ? MAX_TECH_QUEUE_LENGTH_PRO : MAX_TECH_QUEUE_LENGTH); - $Modifier = array(); - - if($QueueLength + 1 <= $MaxLength) - { - if($QueueLength > 0) - { - foreach($Queue as $QueueElement) - { - $QueueElement = explode(',', $QueueElement); - if(!isset($Modifier[$_Vars_GameElements[$QueueElement[0]]])) - { - $Modifier[$_Vars_GameElements[$QueueElement[0]]] = 0; - } - $Modifier[$_Vars_GameElements[$QueueElement[0]]] += 1; - $TheUser[$_Vars_GameElements[$QueueElement[0]]] += 1; - $StartTime = $QueueElement[3]; - } - } - else - { - $StartTime = 0; - } - if($StartTime <= 0) - { - $StartTime = time(); - } - $Time = GetBuildingTime($TheUser, $ThePlanet, $TechID); - $EndTime = $StartTime + $Time; - $NextLevel = $TheUser[$_Vars_GameElements[$TechID]] + 1; - - $Queue[] = "{$TechID},{$NextLevel},{$Time},{$EndTime}"; - - $ThePlanet['techQueue'] = implode(';', $Queue); - - foreach($Modifier as $ElementField => $Value) - { - $TheUser[$ElementField] -= $Value; - } - - return true; - } - - return false; -} - -?> \ No newline at end of file + 0 AND $TheUser['techQueue_Planet'] != $ThePlanet['id']) + { + return false; + } + + if(!empty($ThePlanet['techQueue'])) + { + $Queue = explode(';', $ThePlanet['techQueue']); + $QueueLength = count($Queue); + } + else + { + $Queue = array(); + $QueueLength = 0; + } + + $MaxLength = (isPro($TheUser) ? MAX_TECH_QUEUE_LENGTH_PRO : MAX_TECH_QUEUE_LENGTH); + $Modifier = array(); + + if($QueueLength + 1 <= $MaxLength) + { + if($QueueLength > 0) + { + foreach($Queue as $QueueElement) + { + $QueueElement = explode(',', $QueueElement); + if(!isset($Modifier[$_Vars_GameElements[$QueueElement[0]]])) + { + $Modifier[$_Vars_GameElements[$QueueElement[0]]] = 0; + } + $Modifier[$_Vars_GameElements[$QueueElement[0]]] += 1; + $TheUser[$_Vars_GameElements[$QueueElement[0]]] += 1; + $StartTime = $QueueElement[3]; + } + } + else + { + $StartTime = 0; + } + if($StartTime <= 0) + { + $StartTime = time(); + } + $Time = GetBuildingTime($TheUser, $ThePlanet, $TechID); + $EndTime = $StartTime + $Time; + $NextLevel = $TheUser[$_Vars_GameElements[$TechID]] + 1; + + $Queue[] = "{$TechID},{$NextLevel},{$Time},{$EndTime}"; + + $ThePlanet['techQueue'] = implode(';', $Queue); + + foreach($Modifier as $ElementField => $Value) + { + $TheUser[$ElementField] -= $Value; + } + + return true; + } + + return false; +} + +?> diff --git a/includes/functions/TechQueue_Remove.php b/includes/functions/TechQueue_Remove.php index ef07b325d..c5515b5b8 100644 --- a/includes/functions/TechQueue_Remove.php +++ b/includes/functions/TechQueue_Remove.php @@ -1,74 +1,74 @@ -= $ElementID) - { - $NewQueue = array(); - $TempUser = $TheUser; - $RemovedTime = 0; - foreach($Queue as $QueueID => $QueueElement) - { - $QueueElement = explode(',', $QueueElement); - if($ElementID > $QueueID) - { - $TempUser[$_Vars_GameElements[$QueueElement[0]]] += 1; - $NewQueue[] = implode(',', $QueueElement); - continue; - } - if($ElementID == $QueueID) - { - $RemovedID = $QueueElement[0]; - if($ElementID == 0) - { - $Needed = GetBuildingPrice($TempUser, $ThePlanet, $RemovedID); - $ThePlanet['metal'] += $Needed['metal']; - $ThePlanet['crystal'] += $Needed['crystal']; - $ThePlanet['deuterium'] += $Needed['deuterium']; - $UserDev_Log[] = array('PlanetID' => $ThePlanet['id'], 'Date' => $CurrentTime, 'Place' => 4, 'Code' => 2, 'ElementID' => $RemovedID); - $ThePlanet['techQueue_firstEndTime'] = 0; - if($QueueLength == 1) - { - $TheUser['techQueue_Planet'] = '0'; - $TheUser['techQueue_EndTime'] = '0'; - } - $RemovedTime = $QueueElement[3] - $CurrentTime; - } - else - { - $RemovedTime = $QueueElement[2]; - } - } - else - { - $TempTime = GetBuildingTime($TempUser, $ThePlanet, $QueueElement[0]); - $TempUser[$_Vars_GameElements[$QueueElement[0]]] += 1; - $RemovedTime += ($QueueElement[2] - $TempTime); - $QueueElement[1] = $TempUser[$_Vars_GameElements[$QueueElement[0]]]; - $QueueElement[2] = $TempTime; - $QueueElement[3] -= $RemovedTime; - $NewQueue[] = implode(',', $QueueElement); - } - } - $ThePlanet['techQueue'] = implode(';', $NewQueue); - - return isset($RemovedID) ? $RemovedID : null; - } - } - - return false; -} - -?> \ No newline at end of file += $ElementID) + { + $NewQueue = array(); + $TempUser = $TheUser; + $RemovedTime = 0; + foreach($Queue as $QueueID => $QueueElement) + { + $QueueElement = explode(',', $QueueElement); + if($ElementID > $QueueID) + { + $TempUser[$_Vars_GameElements[$QueueElement[0]]] += 1; + $NewQueue[] = implode(',', $QueueElement); + continue; + } + if($ElementID == $QueueID) + { + $RemovedID = $QueueElement[0]; + if($ElementID == 0) + { + $Needed = GetBuildingPrice($TempUser, $ThePlanet, $RemovedID); + $ThePlanet['metal'] += $Needed['metal']; + $ThePlanet['crystal'] += $Needed['crystal']; + $ThePlanet['deuterium'] += $Needed['deuterium']; + $UserDev_Log[] = array('PlanetID' => $ThePlanet['id'], 'Date' => $CurrentTime, 'Place' => 4, 'Code' => 2, 'ElementID' => $RemovedID); + $ThePlanet['techQueue_firstEndTime'] = 0; + if($QueueLength == 1) + { + $TheUser['techQueue_Planet'] = '0'; + $TheUser['techQueue_EndTime'] = '0'; + } + $RemovedTime = $QueueElement[3] - $CurrentTime; + } + else + { + $RemovedTime = $QueueElement[2]; + } + } + else + { + $TempTime = GetBuildingTime($TempUser, $ThePlanet, $QueueElement[0]); + $TempUser[$_Vars_GameElements[$QueueElement[0]]] += 1; + $RemovedTime += ($QueueElement[2] - $TempTime); + $QueueElement[1] = $TempUser[$_Vars_GameElements[$QueueElement[0]]]; + $QueueElement[2] = $TempTime; + $QueueElement[3] -= $RemovedTime; + $NewQueue[] = implode(',', $QueueElement); + } + } + $ThePlanet['techQueue'] = implode(';', $NewQueue); + + return isset($RemovedID) ? $RemovedID : null; + } + } + + return false; +} + +?> diff --git a/includes/functions/index.php b/includes/functions/index.php index 2c5d40047..bc99142d1 100644 --- a/includes/functions/index.php +++ b/includes/functions/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/includes/index.php b/includes/index.php index 2c5d40047..bc99142d1 100644 --- a/includes/index.php +++ b/includes/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/includes/ingamefunctions.php b/includes/ingamefunctions.php index d108dd3eb..3e2d33483 100644 --- a/includes/ingamefunctions.php +++ b/includes/ingamefunctions.php @@ -1,43 +1,43 @@ - \ No newline at end of file + diff --git a/includes/phpBench.php b/includes/phpBench.php index 10234fbcc..6c7104921 100644 --- a/includes/phpBench.php +++ b/includes/phpBench.php @@ -1,238 +1,238 @@ - 1048576) - { - $Unit = 1048576; - $UnitName = 'MB'; - } - else if($Mem > 1024) - { - $Unit = 1024; - $UnitName = 'KB'; - } - else - { - $Unit = 1; - $UnitName = 'B'; - } - return sprintf('%0.4f', ($Mem/$Unit)).' '.$UnitName; - } - - public function breakPoint() - { - $this->TimeArray[] = $this->getTime(); - $this->MemArray[] = $this->humanMemSize(memory_get_usage()); - } - - public function newStart() - { - $this->StartTime = microtime(true); - } - - public function simpleCountStart($ReturnKey = false, $SetName = '') - { - $this->SimpleCountArray[] = array('start' => microtime(true), 'startram' => $this->humanMemSize(memory_get_usage()), 'name' => $SetName); - $this->CountersStarted += 1; - if($ReturnKey) - { - $GetKeys = array_keys($this->SimpleCountArray); - return $GetKeys[(count($GetKeys) - 1)]; - } - } - - public function simpleCountStop($ReturnKey = false) - { - if($this->CountersStarted > 0) - { - $Temp = $this->SimpleCountArray; - krsort($Temp); - foreach($Temp as $Key => $Value) - { - if(empty($Value['result'])) - { - $this->SimpleCountArray[$Key]['result'] = microtime(true) - $this->SimpleCountArray[$Key]['start']; - $this->SimpleCountArray[$Key]['endram'] = $this->humanMemSize(memory_get_usage()); - $this->SimpleCountArray[$Key]['assocLevel'] = $this->CountersStarted; - if($this->CountersStarted > 1) - { - $this->SimpleCountArray[$Key]['assoc'] = true; - } - if($ReturnKey) - { - $StopedKey = $Key; - } - break; - } - } - $this->CountersStarted -= 1; - if($ReturnKey) - { - return $StopedKey; - } - } - return false; - } - - public function showSimpleCountSwitch() - { - if($this->ShowSimpleCount) - { - $this->ShowSimpleCount = false; - } - else - { - $this->ShowSimpleCount = true; - } - } - - public function echoTableSwitch() - { - if($this->echoTable) - { - $this->echoTable = false; - } - else - { - $this->echoTable = true; - } - } - - private function getTime() - { - return (microtime(true) - $this->StartTime); - } - - function __construct() - { - $this->InitMem = $this->humanMemSize(memory_get_usage()); - $this->StartTime = microtime(true); - } - - private function prepareResults() - { - if($this->echoTable) - { - $this->breakPoint(); - $endKey = count($this->TimeArray) - 1; - - $Echo = '

    '; - - $Echo .= ''; - - $TotalTime = 0; - foreach($this->TimeArray as $key => $val) - { - $TotalTime += $val; - $Echo .= ''; - } - - if(!empty($this->SimpleCountArray[0]['result']) AND $this->ShowSimpleCount) - { - $Echo .= ''; - foreach($this->SimpleCountArray as $Index => $Data) - { - if(!empty($Data['result'])) - { - if(empty($PreviousParentID)) - { - $PreviousParentID[] = $Index; - $PreviousAssocLevel = 1; - } - $Difference = $PreviousAssocLevel - $Data['assocLevel']; - if($Difference == -2) - { - $PreviousParentID[] = $PreviousKey; - $PreviousAssocLevel = $this->SimpleCountArray[end($PreviousParentID)]['assocLevel']; - } - else if($Difference >= 0) - { - for($i = 0; $i <= $Difference; $i += 1) - { - array_pop($PreviousParentID); - } - if(empty($PreviousParentID)) - { - $PreviousParentID[] = $Index; - $PreviousAssocLevel = 1; - } - else - { - $PreviousAssocLevel = $this->SimpleCountArray[end($PreviousParentID)]['assocLevel']; - } - } - $PreviousKey = $Index; - - if(isset($Data['assoc']) && $Data['assoc'] == true) - { - $ThisTime = $this->SimpleCountArray[end($PreviousParentID)]['result']; - } - else - { - $ThisTime = $TotalTime; - } - $Echo .= ''; - $Echo .= ''; - } - } - } - - $Echo .= '
    Wyniki pomiarów
    Nazwa pkt.Nr.PoziomCzas wykonywaniaZużycie pamięci
    Init Mem#0  '.$this->InitMem.'
    '; - if($key != $endKey) - { - $Echo .= 'BreakPoint#'.($key+1).''; - } - else - { - $Echo .= 'EndPoint#'.($endKey+1).''; - } - $Echo .= ' '.sprintf('%0.20f', $val).' s.'.$this->MemArray[$key].'
    Proste Pomiary Użytkownika
    Pomiar'.(!empty($Data['name']) ? '
    ['.$Data['name'].']' : '').'
    #'.($Index+1).'» '.$Data['assocLevel'].''.sprintf('%0.20f', $Data['result']).' s.
    ('.sprintf('%0.8f', ($Data['result']/$ThisTime) * 100).'%)
    '.$Data['startram'].' / '.$Data['endram'].'
    '; - - $this->Result = $Echo; - } - } - - public function ReturnResult() - { - if($this->Result === FALSE) - { - $this->prepareResults(); - } - return $this->Result; - } - - public function ReturnTimeArray() - { - return $this->TimeArray; - } - - public function ReturnSimpleCountArray() - { - return $this->SimpleCountArray; - } -} - -?> \ No newline at end of file + 1048576) + { + $Unit = 1048576; + $UnitName = 'MB'; + } + else if($Mem > 1024) + { + $Unit = 1024; + $UnitName = 'KB'; + } + else + { + $Unit = 1; + $UnitName = 'B'; + } + return sprintf('%0.4f', ($Mem/$Unit)).' '.$UnitName; + } + + public function breakPoint() + { + $this->TimeArray[] = $this->getTime(); + $this->MemArray[] = $this->humanMemSize(memory_get_usage()); + } + + public function newStart() + { + $this->StartTime = microtime(true); + } + + public function simpleCountStart($ReturnKey = false, $SetName = '') + { + $this->SimpleCountArray[] = array('start' => microtime(true), 'startram' => $this->humanMemSize(memory_get_usage()), 'name' => $SetName); + $this->CountersStarted += 1; + if($ReturnKey) + { + $GetKeys = array_keys($this->SimpleCountArray); + return $GetKeys[(count($GetKeys) - 1)]; + } + } + + public function simpleCountStop($ReturnKey = false) + { + if($this->CountersStarted > 0) + { + $Temp = $this->SimpleCountArray; + krsort($Temp); + foreach($Temp as $Key => $Value) + { + if(empty($Value['result'])) + { + $this->SimpleCountArray[$Key]['result'] = microtime(true) - $this->SimpleCountArray[$Key]['start']; + $this->SimpleCountArray[$Key]['endram'] = $this->humanMemSize(memory_get_usage()); + $this->SimpleCountArray[$Key]['assocLevel'] = $this->CountersStarted; + if($this->CountersStarted > 1) + { + $this->SimpleCountArray[$Key]['assoc'] = true; + } + if($ReturnKey) + { + $StopedKey = $Key; + } + break; + } + } + $this->CountersStarted -= 1; + if($ReturnKey) + { + return $StopedKey; + } + } + return false; + } + + public function showSimpleCountSwitch() + { + if($this->ShowSimpleCount) + { + $this->ShowSimpleCount = false; + } + else + { + $this->ShowSimpleCount = true; + } + } + + public function echoTableSwitch() + { + if($this->echoTable) + { + $this->echoTable = false; + } + else + { + $this->echoTable = true; + } + } + + private function getTime() + { + return (microtime(true) - $this->StartTime); + } + + function __construct() + { + $this->InitMem = $this->humanMemSize(memory_get_usage()); + $this->StartTime = microtime(true); + } + + private function prepareResults() + { + if($this->echoTable) + { + $this->breakPoint(); + $endKey = count($this->TimeArray) - 1; + + $Echo = '

    '; + + $Echo .= ''; + + $TotalTime = 0; + foreach($this->TimeArray as $key => $val) + { + $TotalTime += $val; + $Echo .= ''; + } + + if(!empty($this->SimpleCountArray[0]['result']) AND $this->ShowSimpleCount) + { + $Echo .= ''; + foreach($this->SimpleCountArray as $Index => $Data) + { + if(!empty($Data['result'])) + { + if(empty($PreviousParentID)) + { + $PreviousParentID[] = $Index; + $PreviousAssocLevel = 1; + } + $Difference = $PreviousAssocLevel - $Data['assocLevel']; + if($Difference == -2) + { + $PreviousParentID[] = $PreviousKey; + $PreviousAssocLevel = $this->SimpleCountArray[end($PreviousParentID)]['assocLevel']; + } + else if($Difference >= 0) + { + for($i = 0; $i <= $Difference; $i += 1) + { + array_pop($PreviousParentID); + } + if(empty($PreviousParentID)) + { + $PreviousParentID[] = $Index; + $PreviousAssocLevel = 1; + } + else + { + $PreviousAssocLevel = $this->SimpleCountArray[end($PreviousParentID)]['assocLevel']; + } + } + $PreviousKey = $Index; + + if(isset($Data['assoc']) && $Data['assoc'] == true) + { + $ThisTime = $this->SimpleCountArray[end($PreviousParentID)]['result']; + } + else + { + $ThisTime = $TotalTime; + } + $Echo .= ''; + $Echo .= ''; + } + } + } + + $Echo .= '
    Wyniki pomiarów
    Nazwa pkt.Nr.PoziomCzas wykonywaniaZużycie pamięci
    Init Mem#0  '.$this->InitMem.'
    '; + if($key != $endKey) + { + $Echo .= 'BreakPoint#'.($key+1).''; + } + else + { + $Echo .= 'EndPoint#'.($endKey+1).''; + } + $Echo .= ' '.sprintf('%0.20f', $val).' s.'.$this->MemArray[$key].'
    Proste Pomiary Użytkownika
    Pomiar'.(!empty($Data['name']) ? '
    ['.$Data['name'].']' : '').'
    #'.($Index+1).'» '.$Data['assocLevel'].''.sprintf('%0.20f', $Data['result']).' s.
    ('.sprintf('%0.8f', ($Data['result']/$ThisTime) * 100).'%)
    '.$Data['startram'].' / '.$Data['endram'].'
    '; + + $this->Result = $Echo; + } + } + + public function ReturnResult() + { + if($this->Result === FALSE) + { + $this->prepareResults(); + } + return $this->Result; + } + + public function ReturnTimeArray() + { + return $this->TimeArray; + } + + public function ReturnSimpleCountArray() + { + return $this->SimpleCountArray; + } +} + +?> diff --git a/includes/recaptchalib.php b/includes/recaptchalib.php index 32c4f4d75..a7677bc92 100644 --- a/includes/recaptchalib.php +++ b/includes/recaptchalib.php @@ -65,30 +65,29 @@ function _recaptcha_qsencode ($data) { * @return array response */ function _recaptcha_http_post($host, $path, $data, $port = 80) { + $req = _recaptcha_qsencode ($data); - $req = _recaptcha_qsencode ($data); + $http_request = "POST $path HTTP/1.0\r\n"; + $http_request .= "Host: $host\r\n"; + $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; + $http_request .= "Content-Length: " . strlen($req) . "\r\n"; + $http_request .= "User-Agent: reCAPTCHA/PHP\r\n"; + $http_request .= "\r\n"; + $http_request .= $req; - $http_request = "POST $path HTTP/1.0\r\n"; - $http_request .= "Host: $host\r\n"; - $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; - $http_request .= "Content-Length: " . strlen($req) . "\r\n"; - $http_request .= "User-Agent: reCAPTCHA/PHP\r\n"; - $http_request .= "\r\n"; - $http_request .= $req; + $response = ''; + if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) { + die ('Could not open socket'); + } - $response = ''; - if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) { - die ('Could not open socket'); - } + fwrite($fs, $http_request); - fwrite($fs, $http_request); + while ( !feof($fs) ) + $response .= fgets($fs, 1160); // One TCP-IP packet + fclose($fs); + $response = explode("\r\n\r\n", $response, 2); - while ( !feof($fs) ) - $response .= fgets($fs, 1160); // One TCP-IP packet - fclose($fs); - $response = explode("\r\n\r\n", $response, 2); - - return $response; + return $response; } @@ -105,27 +104,26 @@ function _recaptcha_http_post($host, $path, $data, $port = 80) { */ function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false) { - if ($pubkey == null || $pubkey == '') { - die ("To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create"); - } - - if ($use_ssl) { - $server = RECAPTCHA_API_SECURE_SERVER; - } else { - $server = RECAPTCHA_API_SERVER; - } - - $errorpart = ""; - if ($error) { - $errorpart = "&error=" . $error; - } - return ' - - '; + if ($pubkey == null || $pubkey == '') { + die ("To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create"); + } + + if ($use_ssl) { + $server = RECAPTCHA_API_SECURE_SERVER; + } else { + $server = RECAPTCHA_API_SERVER; + } + + $errorpart = ""; + if ($error) { + $errorpart = "&error=" . $error; + } + return ' + '; } @@ -151,44 +149,44 @@ class ReCaptchaResponse { */ function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array()) { - if ($privkey == null || $privkey == '') { - die ("To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create"); - } - - if ($remoteip == null || $remoteip == '') { - die ("For security reasons, you must pass the remote ip to reCAPTCHA"); - } - - - - //discard spam submissions - if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) { - $recaptcha_response = new ReCaptchaResponse(); - $recaptcha_response->is_valid = false; - $recaptcha_response->error = 'incorrect-captcha-sol'; - return $recaptcha_response; - } - - $response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify", - array ( - 'privatekey' => $privkey, - 'remoteip' => $remoteip, - 'challenge' => $challenge, - 'response' => $response - ) + $extra_params - ); - - $answers = explode ("\n", $response [1]); - $recaptcha_response = new ReCaptchaResponse(); + if ($privkey == null || $privkey == '') { + die ("To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create"); + } + + if ($remoteip == null || $remoteip == '') { + die ("For security reasons, you must pass the remote ip to reCAPTCHA"); + } + + - if (trim ($answers [0]) == 'true') { - $recaptcha_response->is_valid = true; - } - else { - $recaptcha_response->is_valid = false; - $recaptcha_response->error = $answers [1]; - } + //discard spam submissions + if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) { + $recaptcha_response = new ReCaptchaResponse(); + $recaptcha_response->is_valid = false; + $recaptcha_response->error = 'incorrect-captcha-sol'; return $recaptcha_response; + } + + $response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify", + array ( + 'privatekey' => $privkey, + 'remoteip' => $remoteip, + 'challenge' => $challenge, + 'response' => $response + ) + $extra_params + ); + + $answers = explode ("\n", $response [1]); + $recaptcha_response = new ReCaptchaResponse(); + + if (trim ($answers [0]) == 'true') { + $recaptcha_response->is_valid = true; + } + else { + $recaptcha_response->is_valid = false; + $recaptcha_response->error = $answers [1]; + } + return $recaptcha_response; } @@ -200,44 +198,44 @@ function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $ex * @param string $appname The name of your application */ function recaptcha_get_signup_url ($domain = null, $appname = null) { - return "https://www.google.com/recaptcha/admin/create?" . _recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname)); + return "https://www.google.com/recaptcha/admin/create?" . _recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname)); } function _recaptcha_aes_pad($val) { - $block_size = 16; - $numpad = $block_size - (strlen ($val) % $block_size); - return str_pad($val, strlen ($val) + $numpad, chr($numpad)); + $block_size = 16; + $numpad = $block_size - (strlen ($val) % $block_size); + return str_pad($val, strlen ($val) + $numpad, chr($numpad)); } /* Mailhide related code */ function _recaptcha_aes_encrypt($val,$ky) { - if (! function_exists ("mcrypt_encrypt")) { - die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed."); - } - $mode=MCRYPT_MODE_CBC; - $enc=MCRYPT_RIJNDAEL_128; - $val=_recaptcha_aes_pad($val); - return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"); + if (! function_exists ("mcrypt_encrypt")) { + die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed."); + } + $mode=MCRYPT_MODE_CBC; + $enc=MCRYPT_RIJNDAEL_128; + $val=_recaptcha_aes_pad($val); + return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"); } function _recaptcha_mailhide_urlbase64 ($x) { - return strtr(base64_encode ($x), '+/', '-_'); + return strtr(base64_encode ($x), '+/', '-_'); } /* gets the reCAPTCHA Mailhide url for a given email, public key and private key */ function recaptcha_mailhide_url($pubkey, $privkey, $email) { - if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) { - die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " . - "you can do so at http://www.google.com/recaptcha/mailhide/apikey"); - } - - - $ky = pack('H*', $privkey); - $cryptmail = _recaptcha_aes_encrypt ($email, $ky); - - return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail); + if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) { + die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " . + "you can do so at http://www.google.com/recaptcha/mailhide/apikey"); + } + + + $ky = pack('H*', $privkey); + $cryptmail = _recaptcha_aes_encrypt ($email, $ky); + + return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail); } /** @@ -246,16 +244,16 @@ function recaptcha_mailhide_url($pubkey, $privkey, $email) { * the email is then displayed as john...@example.com */ function _recaptcha_mailhide_email_parts ($email) { - $arr = preg_split("/@/", $email ); - - if (strlen ($arr[0]) <= 4) { - $arr[0] = substr ($arr[0], 0, 1); - } else if (strlen ($arr[0]) <= 6) { - $arr[0] = substr ($arr[0], 0, 3); - } else { - $arr[0] = substr ($arr[0], 0, 4); - } - return $arr; + $arr = preg_split("/@/", $email ); + + if (strlen ($arr[0]) <= 4) { + $arr[0] = substr ($arr[0], 0, 1); + } else if (strlen ($arr[0]) <= 6) { + $arr[0] = substr ($arr[0], 0, 3); + } else { + $arr[0] = substr ($arr[0], 0, 4); + } + return $arr; } /** @@ -265,11 +263,11 @@ function _recaptcha_mailhide_email_parts ($email) { * http://www.google.com/recaptcha/mailhide/apikey */ function recaptcha_mailhide_html($pubkey, $privkey, $email) { - $emailparts = _recaptcha_mailhide_email_parts ($email); - $url = recaptcha_mailhide_url ($pubkey, $privkey, $email); - - return htmlentities($emailparts[0]) . "...@" . htmlentities ($emailparts [1]); + $emailparts = _recaptcha_mailhide_email_parts ($email); + $url = recaptcha_mailhide_url ($pubkey, $privkey, $email); + + return htmlentities($emailparts[0]) . "...@" . htmlentities ($emailparts [1]); } diff --git a/includes/strings.php b/includes/strings.php index e4e99d1f5..a8b67ed1d 100644 --- a/includes/strings.php +++ b/includes/strings.php @@ -1,63 +1,63 @@ - 0) - { - return colorGreen($Number); - } - else if($Number < 0) - { - return colorRed($Number); - } - else - { - if($ZeroToOrange) - { - return colorOrange($Number); - } - return $Number; - } -} - -function prettyColorNumber($Number, $ZeroToOrange = false) -{ - if($Number > 0) - { - return colorGreen(prettyNumber($Number)); - } - else if($Number < 0) - { - return colorRed(prettyNumber($Number)); - } - else - { - if($ZeroToOrange) - { - return colorOrange(prettyNumber($Number)); - } - return prettyNumber($Number); - } -} - -function colorRed($Number) -{ - return "{$Number}"; -} - -function colorGreen($Number) -{ - return "{$Number}"; -} - -function colorOrange($Number) -{ - return "{$Number}"; -} - -?> \ No newline at end of file + 0) + { + return colorGreen($Number); + } + else if($Number < 0) + { + return colorRed($Number); + } + else + { + if($ZeroToOrange) + { + return colorOrange($Number); + } + return $Number; + } +} + +function prettyColorNumber($Number, $ZeroToOrange = false) +{ + if($Number > 0) + { + return colorGreen(prettyNumber($Number)); + } + else if($Number < 0) + { + return colorRed(prettyNumber($Number)); + } + else + { + if($ZeroToOrange) + { + return colorOrange(prettyNumber($Number)); + } + return prettyNumber($Number); + } +} + +function colorRed($Number) +{ + return "{$Number}"; +} + +function colorGreen($Number) +{ + return "{$Number}"; +} + +function colorOrange($Number) +{ + return "{$Number}"; +} + +?> diff --git a/includes/unlocalised.php b/includes/unlocalised.php index d80bf10ea..4c2311076 100644 --- a/includes/unlocalised.php +++ b/includes/unlocalised.php @@ -1,462 +1,462 @@ - 1); - } - - $Return = array(); - foreach($FleetArray as $Ship => $Count) - { - if(!empty($_Vars_Prices[$Ship]['engine'])) - { - foreach($_Vars_Prices[$Ship]['engine'] as $EngineID => $EngineData) - { - if(!isset($EngineData['tech'])) - { - $speedalls[$Ship] = $EngineData['speed']; - if($ReturnInfo === true) - { - $EngineData['engineID'] = $EngineID; - $Return[$Ship]['engine'] = $EngineData; - } - break; - } - - if($Player[$_Vars_GameElements[$EngineData['tech']]] >= $EngineData['minlevel']) - { - $speedalls[$Ship] = $EngineData['speed'] * (1 + ($_Vars_TechSpeedModifiers[$EngineData['tech']] * $Player[$_Vars_GameElements[$EngineData['tech']]])); - if($ReturnInfo === true) - { - $EngineData['engineID'] = $EngineID; - $Return[$Ship]['engine'] = $EngineData; - } - break; - } - } - } - else - { - $speedalls[$Ship] = 0; - } - } - if($Fleet != 0) - { - $speedalls = $speedalls[$Ship]; - } - - if($ReturnInfo === true) - { - return array('speed' => $speedalls, 'info' => $Return); - } - return $speedalls; -} - -function GetShipConsumption($Ship, $Player) -{ - global $_Vars_Prices, $_Vars_GameElements; - - if(!empty($_Vars_Prices[$Ship]['engine'])) - { - foreach($_Vars_Prices[$Ship]['engine'] as $EngineData) - { - if(!isset($EngineData['tech']) || $Player[$_Vars_GameElements[$EngineData['tech']]] >= $EngineData['minlevel']) - { - $Consumption = $EngineData['consumption']; - break; - } - } - } - else - { - $Consumption = 0; - } - - return $Consumption; -} - -function GetFleetConsumption($FleetArray, $SpeedFactor, $MissionDuration, $MissionDistance, $Player) -{ - $consumption = 0; - foreach($FleetArray as $Ship => $Count) - { - if($Ship > 0) - { - $ShipSpeed = GetFleetMaxSpeed('', $Ship, $Player); - $ShipConsumption = GetShipConsumption($Ship, $Player); - $spd = 35000 / ($MissionDuration * $SpeedFactor - 10) * sqrt($MissionDistance * 10 / $ShipSpeed); - $basicConsumption = $ShipConsumption * $Count; - $consumption += $basicConsumption * $MissionDistance / 35000 * (($spd / 10) + 1) * (($spd / 10) + 1); - } - } - - return (round($consumption) + 1); -} - -function GetStartAdressLink($FleetRow, $FleetType, $FromWindow = false) -{ - $Link = ''; - $Link .= ""; - $Link .= "[{$FleetRow['fleet_start_galaxy']}:{$FleetRow['fleet_start_system']}:{$FleetRow['fleet_start_planet']}]"; - return $Link; -} - -function GetTargetAdressLink($FleetRow, $FleetType, $FromWindow = false) -{ - $Link = ''; - $Link .= ""; - $Link .= "[{$FleetRow['fleet_end_galaxy']}:{$FleetRow['fleet_end_system']}:{$FleetRow['fleet_end_planet']}]"; - return $Link; -} - -function BuildHostileFleetPlayerLink($FleetRow, $FromWindow = false) -{ - global $_Lang, $_SkinPath; - - $Link = ''; - $Link .= $FleetRow['owner_name']." "; - $Link .= ""; - $Link .= "\"{$_Lang['ov_message']}\""; - return $Link; -} - -function CreatePlanetLink($Galaxy, $System, $Planet) -{ - $Link = ''; - $Link .= ""; - $Link .= "[{$Galaxy}:{$System}:{$Planet}]"; - return $Link; -} - -function GetNextJumpWaitTime($CurMoon) -{ - global $_Vars_GameElements; - - $JumpGateLevel = $CurMoon[$_Vars_GameElements[43]]; - $LastJumpTime = $CurMoon['last_jump_time']; - if($JumpGateLevel > 0) - { - $WaitBetweenJmp = 3600 * (1 / $JumpGateLevel); - $NextJumpTime = $LastJumpTime + $WaitBetweenJmp; - - $Now = time(); - if($NextJumpTime >= $Now) - { - $RestWait = $NextJumpTime - $Now; - $RestString = ' '.pretty_time($RestWait); - } - else - { - $RestWait = 0; - $RestString = ''; - } - } - else - { - $RestWait = 0; - $RestString = ''; - } - $RetValue['string'] = $RestString; - $RetValue['value'] = $RestWait; - - return $RetValue; -} - -function CreateFleetPopupedFleetLink($FleetRow, $Texte) -{ - global $_Lang; - - $FleetArray = String2Array($FleetRow['fleet_array']); - if(!empty($FleetArray)) - { - foreach($FleetArray as $ShipID => $ShipCount) - { - $CreateTitle[] = "{$_Lang['tech'][$ShipID]}:".prettyNumber($ShipCount).""; - } - } - if($FleetRow['fleet_resource_metal'] > 0 OR $FleetRow['fleet_resource_crystal'] > 0 OR $FleetRow['fleet_resource_deuterium'] > 0) - { - $CreateTitle[] = ' '; - if($FleetRow['fleet_resource_metal'] > 0) - { - $CreateTitle[] = "{$_Lang['Metal']}:".prettyNumber($FleetRow['fleet_resource_metal']).""; - } - if($FleetRow['fleet_resource_crystal'] > 0) - { - $CreateTitle[] = "{$_Lang['Crystal']}:".prettyNumber($FleetRow['fleet_resource_crystal']).""; - } - if($FleetRow['fleet_resource_deuterium'] > 0) - { - $CreateTitle[] = "{$_Lang['Deuterium']}:".prettyNumber($FleetRow['fleet_resource_deuterium']).""; - } - } - - return ''.$Texte.''; -} - -// String-related functions -function pretty_time($Seconds, $ChronoType = false, $Format = false) -{ - $Time = ''; - - $Seconds = floor($Seconds); - $Days = floor($Seconds / TIME_DAY); - $Seconds -= $Days * TIME_DAY; - $Hours = floor($Seconds / 3600); - $Seconds -= $Hours * 3600; - $Minutes = floor($Seconds / 60); - $Seconds -= $Minutes * 60; - - if($Hours < 10) - { - $Hours = '0'.(string)$Hours; - } - if($Minutes < 10) - { - $Minutes = '0'.(string)$Minutes; - } - if($Seconds < 10) - { - $Seconds = '0'.(string)$Seconds; - } - - if($ChronoType === false) - { - $DAllowed = array - ( - 'd' => false, - 'h' => false, - 'm' => false, - 's' => false - ); - - if($Format) - { - if(strstr($Format, 'd') === false) - { - $DAllowed['d'] = true; - } - if(strstr($Format, 'h') === false) - { - $DAllowed['h'] = true; - } - if(strstr($Format, 'm') === false) - { - $DAllowed['m'] = true; - } - if(strstr($Format, 's') === false) - { - $DAllowed['s'] = true; - } - } - - if($Days > 0 AND ($DAllowed['d'] !== true)) - { - $Time .= "{$Days}d "; - } - if($DAllowed['h'] !== true) - { - $Time .= "{$Hours}g "; - } - if($DAllowed['m'] !== true) - { - $Time .= "{$Minutes}m "; - } - if($DAllowed['s'] !== true) - { - $Time .= "{$Seconds}s"; - } - } - else - { - if($Days > 0) - { - if(strstr($Format, 'D') !== FALSE) - { - global $_Lang; - $UseLang = ($Days > 1 ? $_Lang['Chrono_DayM'] : $_Lang['Chrono_Day1']); - $Time = "{$Days} {$UseLang} "; - } - else if(strstr($Format, 'd') !== FALSE) - { - $Time = "{$Days}d "; - } - else - { - $Hours += $Days * 24; - } - } - $Time .= "{$Hours}:{$Minutes}:{$Seconds}"; - } - - return $Time; -} - -function pretty_time_hour($seconds, $NoSpace = false) -{ - $min = floor($seconds / 60 % 60); - - if($min != 0) - { - if($NoSpace) - { - $time = $min.'min'; - } - else - { - $time = $min.'min '; - } - } - else - { - $time = ''; - } - - return $time; -} - -function prettyMonth($month, $variant = '0') -{ - global $_Lang; - if(!isset($_Lang['pretty_months_loaded'])) - { - includeLang('months'); - } - return $_Lang['months_variant'.$variant][($month-1)]; -} - -function prettyDate($format, $timestamp = false, $variant = '0') -{ - if(strstr($format, 'm') !== false) - { - $HasMonth = true; - $format = str_replace('m', '{|_|}', $format); - } - $Date = date($format, $timestamp); - if($HasMonth === true) - { - $Month = prettyMonth(date('m', $timestamp), $variant); - $Date = str_replace('{|_|}', $Month, $Date); - } - return $Date; -} - -function ShowBuildTime($time) -{ - global $_Lang; - - return "
    {$_Lang['ConstructionTime']}: ".pretty_time($time); -} - -function Array2String($Array) -{ - foreach($Array as $Key => $Value) - { - $String[] = "{$Key},{$Value}"; - } - return implode(';', $String); -} - -function String2Array($String) -{ - $String = explode(';', $String); - foreach($String as $Data) - { - if(empty($Data)) - { - break; - } - $Data = explode(',', $Data); - $Array[$Data[0]] = $Data[1]; - } - return (isset($Array) ? $Array : null); -} - -?> \ No newline at end of file + 1); + } + + $Return = array(); + foreach($FleetArray as $Ship => $Count) + { + if(!empty($_Vars_Prices[$Ship]['engine'])) + { + foreach($_Vars_Prices[$Ship]['engine'] as $EngineID => $EngineData) + { + if(!isset($EngineData['tech'])) + { + $speedalls[$Ship] = $EngineData['speed']; + if($ReturnInfo === true) + { + $EngineData['engineID'] = $EngineID; + $Return[$Ship]['engine'] = $EngineData; + } + break; + } + + if($Player[$_Vars_GameElements[$EngineData['tech']]] >= $EngineData['minlevel']) + { + $speedalls[$Ship] = $EngineData['speed'] * (1 + ($_Vars_TechSpeedModifiers[$EngineData['tech']] * $Player[$_Vars_GameElements[$EngineData['tech']]])); + if($ReturnInfo === true) + { + $EngineData['engineID'] = $EngineID; + $Return[$Ship]['engine'] = $EngineData; + } + break; + } + } + } + else + { + $speedalls[$Ship] = 0; + } + } + if($Fleet != 0) + { + $speedalls = $speedalls[$Ship]; + } + + if($ReturnInfo === true) + { + return array('speed' => $speedalls, 'info' => $Return); + } + return $speedalls; +} + +function GetShipConsumption($Ship, $Player) +{ + global $_Vars_Prices, $_Vars_GameElements; + + if(!empty($_Vars_Prices[$Ship]['engine'])) + { + foreach($_Vars_Prices[$Ship]['engine'] as $EngineData) + { + if(!isset($EngineData['tech']) || $Player[$_Vars_GameElements[$EngineData['tech']]] >= $EngineData['minlevel']) + { + $Consumption = $EngineData['consumption']; + break; + } + } + } + else + { + $Consumption = 0; + } + + return $Consumption; +} + +function GetFleetConsumption($FleetArray, $SpeedFactor, $MissionDuration, $MissionDistance, $Player) +{ + $consumption = 0; + foreach($FleetArray as $Ship => $Count) + { + if($Ship > 0) + { + $ShipSpeed = GetFleetMaxSpeed('', $Ship, $Player); + $ShipConsumption = GetShipConsumption($Ship, $Player); + $spd = 35000 / ($MissionDuration * $SpeedFactor - 10) * sqrt($MissionDistance * 10 / $ShipSpeed); + $basicConsumption = $ShipConsumption * $Count; + $consumption += $basicConsumption * $MissionDistance / 35000 * (($spd / 10) + 1) * (($spd / 10) + 1); + } + } + + return (round($consumption) + 1); +} + +function GetStartAdressLink($FleetRow, $FleetType, $FromWindow = false) +{ + $Link = ''; + $Link .= ""; + $Link .= "[{$FleetRow['fleet_start_galaxy']}:{$FleetRow['fleet_start_system']}:{$FleetRow['fleet_start_planet']}]"; + return $Link; +} + +function GetTargetAdressLink($FleetRow, $FleetType, $FromWindow = false) +{ + $Link = ''; + $Link .= ""; + $Link .= "[{$FleetRow['fleet_end_galaxy']}:{$FleetRow['fleet_end_system']}:{$FleetRow['fleet_end_planet']}]"; + return $Link; +} + +function BuildHostileFleetPlayerLink($FleetRow, $FromWindow = false) +{ + global $_Lang, $_SkinPath; + + $Link = ''; + $Link .= $FleetRow['owner_name']." "; + $Link .= ""; + $Link .= "\"{$_Lang['ov_message']}\""; + return $Link; +} + +function CreatePlanetLink($Galaxy, $System, $Planet) +{ + $Link = ''; + $Link .= ""; + $Link .= "[{$Galaxy}:{$System}:{$Planet}]"; + return $Link; +} + +function GetNextJumpWaitTime($CurMoon) +{ + global $_Vars_GameElements; + + $JumpGateLevel = $CurMoon[$_Vars_GameElements[43]]; + $LastJumpTime = $CurMoon['last_jump_time']; + if($JumpGateLevel > 0) + { + $WaitBetweenJmp = 3600 * (1 / $JumpGateLevel); + $NextJumpTime = $LastJumpTime + $WaitBetweenJmp; + + $Now = time(); + if($NextJumpTime >= $Now) + { + $RestWait = $NextJumpTime - $Now; + $RestString = ' '.pretty_time($RestWait); + } + else + { + $RestWait = 0; + $RestString = ''; + } + } + else + { + $RestWait = 0; + $RestString = ''; + } + $RetValue['string'] = $RestString; + $RetValue['value'] = $RestWait; + + return $RetValue; +} + +function CreateFleetPopupedFleetLink($FleetRow, $Texte) +{ + global $_Lang; + + $FleetArray = String2Array($FleetRow['fleet_array']); + if(!empty($FleetArray)) + { + foreach($FleetArray as $ShipID => $ShipCount) + { + $CreateTitle[] = "{$_Lang['tech'][$ShipID]}:".prettyNumber($ShipCount).""; + } + } + if($FleetRow['fleet_resource_metal'] > 0 OR $FleetRow['fleet_resource_crystal'] > 0 OR $FleetRow['fleet_resource_deuterium'] > 0) + { + $CreateTitle[] = ' '; + if($FleetRow['fleet_resource_metal'] > 0) + { + $CreateTitle[] = "{$_Lang['Metal']}:".prettyNumber($FleetRow['fleet_resource_metal']).""; + } + if($FleetRow['fleet_resource_crystal'] > 0) + { + $CreateTitle[] = "{$_Lang['Crystal']}:".prettyNumber($FleetRow['fleet_resource_crystal']).""; + } + if($FleetRow['fleet_resource_deuterium'] > 0) + { + $CreateTitle[] = "{$_Lang['Deuterium']}:".prettyNumber($FleetRow['fleet_resource_deuterium']).""; + } + } + + return ''.$Texte.''; +} + +// String-related functions +function pretty_time($Seconds, $ChronoType = false, $Format = false) +{ + $Time = ''; + + $Seconds = floor($Seconds); + $Days = floor($Seconds / TIME_DAY); + $Seconds -= $Days * TIME_DAY; + $Hours = floor($Seconds / 3600); + $Seconds -= $Hours * 3600; + $Minutes = floor($Seconds / 60); + $Seconds -= $Minutes * 60; + + if($Hours < 10) + { + $Hours = '0'.(string)$Hours; + } + if($Minutes < 10) + { + $Minutes = '0'.(string)$Minutes; + } + if($Seconds < 10) + { + $Seconds = '0'.(string)$Seconds; + } + + if($ChronoType === false) + { + $DAllowed = array + ( + 'd' => false, + 'h' => false, + 'm' => false, + 's' => false + ); + + if($Format) + { + if(strstr($Format, 'd') === false) + { + $DAllowed['d'] = true; + } + if(strstr($Format, 'h') === false) + { + $DAllowed['h'] = true; + } + if(strstr($Format, 'm') === false) + { + $DAllowed['m'] = true; + } + if(strstr($Format, 's') === false) + { + $DAllowed['s'] = true; + } + } + + if($Days > 0 AND ($DAllowed['d'] !== true)) + { + $Time .= "{$Days}d "; + } + if($DAllowed['h'] !== true) + { + $Time .= "{$Hours}g "; + } + if($DAllowed['m'] !== true) + { + $Time .= "{$Minutes}m "; + } + if($DAllowed['s'] !== true) + { + $Time .= "{$Seconds}s"; + } + } + else + { + if($Days > 0) + { + if(strstr($Format, 'D') !== FALSE) + { + global $_Lang; + $UseLang = ($Days > 1 ? $_Lang['Chrono_DayM'] : $_Lang['Chrono_Day1']); + $Time = "{$Days} {$UseLang} "; + } + else if(strstr($Format, 'd') !== FALSE) + { + $Time = "{$Days}d "; + } + else + { + $Hours += $Days * 24; + } + } + $Time .= "{$Hours}:{$Minutes}:{$Seconds}"; + } + + return $Time; +} + +function pretty_time_hour($seconds, $NoSpace = false) +{ + $min = floor($seconds / 60 % 60); + + if($min != 0) + { + if($NoSpace) + { + $time = $min.'min'; + } + else + { + $time = $min.'min '; + } + } + else + { + $time = ''; + } + + return $time; +} + +function prettyMonth($month, $variant = '0') +{ + global $_Lang; + if(!isset($_Lang['pretty_months_loaded'])) + { + includeLang('months'); + } + return $_Lang['months_variant'.$variant][($month-1)]; +} + +function prettyDate($format, $timestamp = false, $variant = '0') +{ + if(strstr($format, 'm') !== false) + { + $HasMonth = true; + $format = str_replace('m', '{|_|}', $format); + } + $Date = date($format, $timestamp); + if($HasMonth === true) + { + $Month = prettyMonth(date('m', $timestamp), $variant); + $Date = str_replace('{|_|}', $Month, $Date); + } + return $Date; +} + +function ShowBuildTime($time) +{ + global $_Lang; + + return "
    {$_Lang['ConstructionTime']}: ".pretty_time($time); +} + +function Array2String($Array) +{ + foreach($Array as $Key => $Value) + { + $String[] = "{$Key},{$Value}"; + } + return implode(';', $String); +} + +function String2Array($String) +{ + $String = explode(';', $String); + foreach($String as $Data) + { + if(empty($Data)) + { + break; + } + $Data = explode(',', $Data); + $Array[$Data[0]] = $Data[1]; + } + return (isset($Array) ? $Array : null); +} + +?> diff --git a/includes/vars.php b/includes/vars.php index 32625ea4b..39b3de21d 100644 --- a/includes/vars.php +++ b/includes/vars.php @@ -1,76 +1,76 @@ - array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), - 'military' => array(1, 2, 6, 9, 10), - 'civil' => array(3, 4, 5, 7, 8), - ); - $_Vars_AllyRankLabels = array - ( - 'name', 'like_admin', 'mlist', 'mlist_online', 'sendmsg', 'admingen', 'lookreq', - 'managereq', 'mlist_mod', 'ranks_mod', 'cankick', 'warnpact', 'caninvite', 'canusechat', - ); - $_Vars_TechSpeedModifiers = array - ( - 115 => 0.1, - 117 => 0.2, - 118 => 0.3, - ); - - $_Vars_PremiumBuildings = array - ( - 50 => 1, - ); - $_Vars_PremiumBuildingPrices= array - ( - 50 => 20, - ); - - $_Vars_IndestructibleBuildings = array - ( - 50 => 1, - 33 => 1, - 41 => 1, - ); - - $_Vars_MaxElementLevel = array - ( - 50 => 1, - ); - - $_Vars_BuildingsFixedBuildTime = array - ( - 50 => 3600000, - ); - - $_Vars_ProAccountData = array - ( - array - ( - 'shopID' => 1, - 'time' => 7, - 'cost' => 15 - ), - array - ( - 'shopID' => 2, - 'time' => 25, - 'cost' => 45 - ), - ); -} - -?> \ No newline at end of file + array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), + 'military' => array(1, 2, 6, 9, 10), + 'civil' => array(3, 4, 5, 7, 8), + ); + $_Vars_AllyRankLabels = array + ( + 'name', 'like_admin', 'mlist', 'mlist_online', 'sendmsg', 'admingen', 'lookreq', + 'managereq', 'mlist_mod', 'ranks_mod', 'cankick', 'warnpact', 'caninvite', 'canusechat', + ); + $_Vars_TechSpeedModifiers = array + ( + 115 => 0.1, + 117 => 0.2, + 118 => 0.3, + ); + + $_Vars_PremiumBuildings = array + ( + 50 => 1, + ); + $_Vars_PremiumBuildingPrices= array + ( + 50 => 20, + ); + + $_Vars_IndestructibleBuildings = array + ( + 50 => 1, + 33 => 1, + 41 => 1, + ); + + $_Vars_MaxElementLevel = array + ( + 50 => 1, + ); + + $_Vars_BuildingsFixedBuildTime = array + ( + 50 => 3600000, + ); + + $_Vars_ProAccountData = array + ( + array + ( + 'shopID' => 1, + 'time' => 7, + 'cost' => 15 + ), + array + ( + 'shopID' => 2, + 'time' => 25, + 'cost' => 45 + ), + ); +} + +?> diff --git a/includes/vars_combatdata.php b/includes/vars_combatdata.php index 3ada30ea3..82b2f1027 100644 --- a/includes/vars_combatdata.php +++ b/includes/vars_combatdata.php @@ -1,1196 +1,1196 @@ - array - ( - 'shield' => 10, - 'attack' => 5, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 5, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 1, - 217 => 1, - 218 => 1, - 219 => 4, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 1, - 402 => 1, - 403 => 1, - 404 => 1, - 405 => 1, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 203 => array - ( - 'shield' => 25, - 'attack' => 5, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 5, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 1, - 217 => 1, - 218 => 1, - 219 => 4, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 1, - 402 => 1, - 403 => 1, - 404 => 1, - 405 => 1, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 204 => array - ( - 'shield' => 10, - 'attack' => 50, - 'sd' => array - ( - 202 => 2, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 5, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 1, - 217 => 1, - 218 => 1, - 219 => 4, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 1, - 402 => 1, - 403 => 1, - 404 => 1, - 405 => 1, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 205 => array - ( - 'shield' => 25, - 'attack' => 150, - 'sd' => array - ( - 202 => 3, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 5, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 1, - 217 => 1, - 218 => 1, - 219 => 4, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 1, - 402 => 1, - 403 => 1, - 404 => 1, - 405 => 1, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 206 => array - ( - 'shield' => 50, - 'attack' => 400, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 6, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 5, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 1, - 217 => 1, - 218 => 1, - 219 => 4, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 10, - 402 => 1, - 403 => 1, - 404 => 1, - 405 => 1, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 207 => array - ( - 'shield' => 200, - 'attack' => 1000, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 5, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 1, - 217 => 1, - 218 => 1, - 219 => 4, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 8, - 402 => 1, - 403 => 1, - 404 => 1, - 405 => 1, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 208 => array - ( - 'shield' => 100, - 'attack' => 50, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 5, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 1, - 217 => 1, - 218 => 1, - 219 => 4, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 1, - 402 => 1, - 403 => 1, - 404 => 1, - 405 => 1, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 209 => array - ( - 'shield' => 10, - 'attack' => 1, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 5, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 1, - 217 => 1, - 218 => 1, - 219 => 4, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 1, - 402 => 1, - 403 => 1, - 404 => 1, - 405 => 1, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 210 => array - ( - 'shield' => 0, - 'attack' => 0, - 'sd' => array - ( - 202 => 0, - 203 => 0, - 204 => 0, - 205 => 0, - 206 => 0, - 207 => 0, - 208 => 0, - 209 => 0, - 210 => 0, - 211 => 0, - 212 => 0, - 213 => 0, - 214 => 0, - 215 => 0, - 216 => 0, - 217 => 0, - 218 => 0, - 219 => 0, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 0, - 402 => 0, - 403 => 0, - 404 => 0, - 405 => 0, - 406 => 0, - 407 => 0, - 408 => 0 - ) - ), - 211 => array - ( - 'shield' => 500, - 'attack' => 1000, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 5, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 1, - 217 => 1, - 218 => 1, - 219 => 4, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 20, - 402 => 20, - 403 => 10, - 404 => 1, - 405 => 10, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 212 => array - ( - 'shield' => 10, - 'attack' => 1, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 1, - 211 => 1, - 212 => 0, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 1, - 217 => 1, - 218 => 1, - 219 => 0, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 1, - 402 => 1, - 403 => 1, - 404 => 1, - 405 => 1, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 213 => array - ( - 'shield' => 500, - 'attack' => 2000, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 5, - 213 => 1, - 214 => 1, - 215 => 2, - 216 => 1, - 217 => 1, - 218 => 1, - 219 => 4, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 1, - 402 => 10, - 403 => 1, - 404 => 1, - 405 => 1, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 214 => array - ( - 'shield' => 50000, - 'attack' => 200000, - 'sd' => array - ( - 202 => 250, - 203 => 250, - 204 => 200, - 205 => 100, - 206 => 33, - 207 => 30, - 208 => 250, - 209 => 250, - 210 => 1250, - 211 => 25, - 212 => 1250, - 213 => 5, - 214 => 1, - 215 => 15, - 216 => 1, - 217 => 30, - 218 => 1, - 219 => 900, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 200, - 402 => 200, - 403 => 100, - 404 => 50, - 405 => 100, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 215 => array - ( - 'shield' => 400, - 'attack' => 700, - 'sd' => array - ( - 202 => 3, - 203 => 3, - 204 => 1, - 205 => 4, - 206 => 4, - 207 => 7, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 5, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 1, - 217 => 2, - 218 => 1, - 219 => 1, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 1, - 402 => 1, - 403 => 1, - 404 => 1, - 405 => 1, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 216 => array - ( - 'shield' => 60000, - 'attack' => 100000, - 'sd' => array - ( - 202 => 5, - 203 => 5, - 204 => 5, - 205 => 5, - 206 => 5, - 207 => 5, - 208 => 5, - 209 => 5, - 210 => 5, - 211 => 3, - 212 => 0, - 213 => 2, - 214 => 7, - 215 => 1, - 216 => 0, - 217 => 5, - 218 => 1, - 219 => 5, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 0, - 402 => 0, - 403 => 0, - 404 => 0, - 405 => 0, - 406 => 0, - 407 => 0, - 408 => 0 - ) - ), - 217 => array - ( - 'shield' => 40, - 'attack' => 5, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 5, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 1, - 217 => 1, - 218 => 1, - 219 => 1, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 1, - 402 => 1, - 403 => 1, - 404 => 1, - 405 => 1, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 218 => array - ( - 'shield' => 70000, - 'attack' => 400000, - 'sd' => array - ( - 202 => 15, - 203 => 15, - 204 => 15, - 205 => 15, - 206 => 15, - 207 => 15, - 208 => 15, - 209 => 15, - 210 => 10, - 211 => 15, - 212 => 15, - 213 => 10, - 214 => 5, - 215 => 10, - 216 => 5, - 217 => 15, - 218 => 1, - 219 => 15, - 220 => 3, - 221 => 3, - 222 => 2, - 223 => 1, - 224 => 1, - 401 => 30, - 402 => 30, - 403 => 10, - 404 => 5, - 405 => 10, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 219 => array - ( - 'shield' => 1, - 'attack' => 1, - 'sd' => array - ( - 202 => 0, - 203 => 0, - 204 => 0, - 205 => 0, - 206 => 0, - 207 => 0, - 208 => 0, - 209 => 0, - 210 => 0, - 211 => 0, - 212 => 0, - 213 => 0, - 214 => 0, - 215 => 0, - 216 => 0, - 217 => 0, - 218 => 0, - 219 => 1, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 0, - 402 => 0, - 403 => 0, - 404 => 0, - 405 => 0, - 406 => 0, - 407 => 0, - 408 => 0 - ) - ), - 220 => array - ( - 'shield' => 30000, - 'attack' => 2000, - 'sd' => array - ( - 202 => 800, - 203 => 300, - 204 => 850, - 205 => 400, - 206 => 50, - 207 => 5, - 208 => 5, - 209 => 40, - 210 => 290, - 211 => 2, - 212 => 500, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 1, - 217 => 1, - 218 => 1, - 219 => 200, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 1, - 402 => 1, - 403 => 1, - 404 => 1, - 405 => 1, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 221 => array - ( - 'shield' => 5000, - 'attack' => 35000, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 1, - 211 => 1, - 212 => 45, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 1, - 217 => 1, - 218 => 1, - 219 => 10, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 150, - 402 => 150, - 403 => 75, - 404 => 30, - 405 => 75, - 406 => 7, - 407 => 1, - 408 => 1 - ) - ), - 222 => array - ( - 'shield' => 10000, - 'attack' => 47500, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 15, - 207 => 35, - 208 => 6, - 209 => 6, - 210 => 1, - 211 => 12, - 212 => 3, - 213 => 50, - 214 => 10, - 215 => 60, - 216 => 6, - 217 => 25, - 218 => 3, - 219 => 1, - 220 => 3, - 221 => 3, - 222 => 1, - 223 => 1, - 224 => 1, - 401 => 1, - 402 => 6, - 403 => 1, - 404 => 1, - 405 => 1, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 223 => array - ( - 'shield' => 20000, - 'attack' => 440000, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 5, - 208 => 1, - 209 => 1, - 210 => 1, - 211 => 5, - 212 => 3, - 213 => 32, - 214 => 16, - 215 => 32, - 216 => 9, - 217 => 20, - 218 => 9, - 219 => 1, - 220 => 9, - 221 => 6, - 222 => 5, - 223 => 1, - 224 => 1, - 401 => 1, - 402 => 25, - 403 => 15, - 404 => 5, - 405 => 15, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 224 => array - ( - 'shield' => 50000, - 'attack' => 500000, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 5, - 208 => 1, - 209 => 1, - 210 => 1, - 211 => 20, - 212 => 1, - 213 => 30, - 214 => 45, - 215 => 30, - 216 => 50, - 217 => 1, - 218 => 12, - 219 => 80, - 220 => 14, - 221 => 8, - 222 => 10, - 223 => 2, - 224 => 1, - 401 => 1, - 402 => 1, - 403 => 1, - 404 => 1, - 405 => 1, - 406 => 1, - 407 => 1, - 408 => 1 - ) - ), - 401 => array - ( - 'shield' => 20, - 'attack' => 80, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 0, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 0, - 217 => 1, - 218 => 1, - 219 => 1, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1 - ) - ), - 402 => array - ( - 'shield' => 25, - 'attack' => 100, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 0, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 0, - 217 => 1, - 218 => 1, - 219 => 1, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1 - ) - ), - 403 => array - ( - 'shield' => 100, - 'attack' => 250, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 0, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 0, - 217 => 1, - 218 => 1, - 219 => 1, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1 - ) - ), - 404 => array - ( - 'shield' => 200, - 'attack' => 1100, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 0, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 0, - 217 => 1, - 218 => 1, - 219 => 1, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1 - ) - ), - 405 => array - ( - 'shield' => 500, - 'attack' => 150, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 0, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 0, - 217 => 1, - 218 => 1, - 219 => 1, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1 - ) - ), - 406 => array - ( - 'shield' => 300, - 'attack' => 3000, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 5, - 211 => 1, - 212 => 0, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 0, - 217 => 1, - 218 => 1, - 219 => 1, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1 - ) - ), - 407 => array - ( - 'shield' => 2000, - 'attack' => 1, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 1, - 211 => 1, - 212 => 0, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 0, - 217 => 1, - 218 => 1, - 219 => 1, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1 - ) - ), - 408 => array - ( - 'shield' => 10000, - 'attack' => 1, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 1, - 211 => 1, - 212 => 0, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 0, - 217 => 1, - 218 => 1, - 219 => 1, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1 - ) - ), - 409 => array - ( - 'shield' => 1000000, - 'attack' => 1000000, - 'sd' => array - ( - 202 => 1, - 203 => 1, - 204 => 1, - 205 => 1, - 206 => 1, - 207 => 1, - 208 => 1, - 209 => 1, - 210 => 1, - 211 => 1, - 212 => 0, - 213 => 1, - 214 => 1, - 215 => 1, - 216 => 0, - 217 => 1, - 218 => 1, - 219 => 1, - 220 => 1, - 221 => 1, - 222 => 1, - 223 => 1, - 224 => 1 - ) - ), - 502 => array - ( - 'shield' => 1, - 'attack' => 1 - ), - 503 => array - ( - 'shield' => 1, - 'attack' => 12000 - ), - ); -} - -?> \ No newline at end of file + array + ( + 'shield' => 10, + 'attack' => 5, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 5, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 1, + 217 => 1, + 218 => 1, + 219 => 4, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 1, + 402 => 1, + 403 => 1, + 404 => 1, + 405 => 1, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 203 => array + ( + 'shield' => 25, + 'attack' => 5, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 5, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 1, + 217 => 1, + 218 => 1, + 219 => 4, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 1, + 402 => 1, + 403 => 1, + 404 => 1, + 405 => 1, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 204 => array + ( + 'shield' => 10, + 'attack' => 50, + 'sd' => array + ( + 202 => 2, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 5, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 1, + 217 => 1, + 218 => 1, + 219 => 4, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 1, + 402 => 1, + 403 => 1, + 404 => 1, + 405 => 1, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 205 => array + ( + 'shield' => 25, + 'attack' => 150, + 'sd' => array + ( + 202 => 3, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 5, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 1, + 217 => 1, + 218 => 1, + 219 => 4, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 1, + 402 => 1, + 403 => 1, + 404 => 1, + 405 => 1, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 206 => array + ( + 'shield' => 50, + 'attack' => 400, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 6, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 5, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 1, + 217 => 1, + 218 => 1, + 219 => 4, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 10, + 402 => 1, + 403 => 1, + 404 => 1, + 405 => 1, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 207 => array + ( + 'shield' => 200, + 'attack' => 1000, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 5, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 1, + 217 => 1, + 218 => 1, + 219 => 4, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 8, + 402 => 1, + 403 => 1, + 404 => 1, + 405 => 1, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 208 => array + ( + 'shield' => 100, + 'attack' => 50, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 5, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 1, + 217 => 1, + 218 => 1, + 219 => 4, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 1, + 402 => 1, + 403 => 1, + 404 => 1, + 405 => 1, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 209 => array + ( + 'shield' => 10, + 'attack' => 1, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 5, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 1, + 217 => 1, + 218 => 1, + 219 => 4, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 1, + 402 => 1, + 403 => 1, + 404 => 1, + 405 => 1, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 210 => array + ( + 'shield' => 0, + 'attack' => 0, + 'sd' => array + ( + 202 => 0, + 203 => 0, + 204 => 0, + 205 => 0, + 206 => 0, + 207 => 0, + 208 => 0, + 209 => 0, + 210 => 0, + 211 => 0, + 212 => 0, + 213 => 0, + 214 => 0, + 215 => 0, + 216 => 0, + 217 => 0, + 218 => 0, + 219 => 0, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 0, + 402 => 0, + 403 => 0, + 404 => 0, + 405 => 0, + 406 => 0, + 407 => 0, + 408 => 0 + ) + ), + 211 => array + ( + 'shield' => 500, + 'attack' => 1000, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 5, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 1, + 217 => 1, + 218 => 1, + 219 => 4, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 20, + 402 => 20, + 403 => 10, + 404 => 1, + 405 => 10, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 212 => array + ( + 'shield' => 10, + 'attack' => 1, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 1, + 211 => 1, + 212 => 0, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 1, + 217 => 1, + 218 => 1, + 219 => 0, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 1, + 402 => 1, + 403 => 1, + 404 => 1, + 405 => 1, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 213 => array + ( + 'shield' => 500, + 'attack' => 2000, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 5, + 213 => 1, + 214 => 1, + 215 => 2, + 216 => 1, + 217 => 1, + 218 => 1, + 219 => 4, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 1, + 402 => 10, + 403 => 1, + 404 => 1, + 405 => 1, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 214 => array + ( + 'shield' => 50000, + 'attack' => 200000, + 'sd' => array + ( + 202 => 250, + 203 => 250, + 204 => 200, + 205 => 100, + 206 => 33, + 207 => 30, + 208 => 250, + 209 => 250, + 210 => 1250, + 211 => 25, + 212 => 1250, + 213 => 5, + 214 => 1, + 215 => 15, + 216 => 1, + 217 => 30, + 218 => 1, + 219 => 900, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 200, + 402 => 200, + 403 => 100, + 404 => 50, + 405 => 100, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 215 => array + ( + 'shield' => 400, + 'attack' => 700, + 'sd' => array + ( + 202 => 3, + 203 => 3, + 204 => 1, + 205 => 4, + 206 => 4, + 207 => 7, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 5, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 1, + 217 => 2, + 218 => 1, + 219 => 1, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 1, + 402 => 1, + 403 => 1, + 404 => 1, + 405 => 1, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 216 => array + ( + 'shield' => 60000, + 'attack' => 100000, + 'sd' => array + ( + 202 => 5, + 203 => 5, + 204 => 5, + 205 => 5, + 206 => 5, + 207 => 5, + 208 => 5, + 209 => 5, + 210 => 5, + 211 => 3, + 212 => 0, + 213 => 2, + 214 => 7, + 215 => 1, + 216 => 0, + 217 => 5, + 218 => 1, + 219 => 5, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 0, + 402 => 0, + 403 => 0, + 404 => 0, + 405 => 0, + 406 => 0, + 407 => 0, + 408 => 0 + ) + ), + 217 => array + ( + 'shield' => 40, + 'attack' => 5, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 5, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 1, + 217 => 1, + 218 => 1, + 219 => 1, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 1, + 402 => 1, + 403 => 1, + 404 => 1, + 405 => 1, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 218 => array + ( + 'shield' => 70000, + 'attack' => 400000, + 'sd' => array + ( + 202 => 15, + 203 => 15, + 204 => 15, + 205 => 15, + 206 => 15, + 207 => 15, + 208 => 15, + 209 => 15, + 210 => 10, + 211 => 15, + 212 => 15, + 213 => 10, + 214 => 5, + 215 => 10, + 216 => 5, + 217 => 15, + 218 => 1, + 219 => 15, + 220 => 3, + 221 => 3, + 222 => 2, + 223 => 1, + 224 => 1, + 401 => 30, + 402 => 30, + 403 => 10, + 404 => 5, + 405 => 10, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 219 => array + ( + 'shield' => 1, + 'attack' => 1, + 'sd' => array + ( + 202 => 0, + 203 => 0, + 204 => 0, + 205 => 0, + 206 => 0, + 207 => 0, + 208 => 0, + 209 => 0, + 210 => 0, + 211 => 0, + 212 => 0, + 213 => 0, + 214 => 0, + 215 => 0, + 216 => 0, + 217 => 0, + 218 => 0, + 219 => 1, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 0, + 402 => 0, + 403 => 0, + 404 => 0, + 405 => 0, + 406 => 0, + 407 => 0, + 408 => 0 + ) + ), + 220 => array + ( + 'shield' => 30000, + 'attack' => 2000, + 'sd' => array + ( + 202 => 800, + 203 => 300, + 204 => 850, + 205 => 400, + 206 => 50, + 207 => 5, + 208 => 5, + 209 => 40, + 210 => 290, + 211 => 2, + 212 => 500, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 1, + 217 => 1, + 218 => 1, + 219 => 200, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 1, + 402 => 1, + 403 => 1, + 404 => 1, + 405 => 1, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 221 => array + ( + 'shield' => 5000, + 'attack' => 35000, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 1, + 211 => 1, + 212 => 45, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 1, + 217 => 1, + 218 => 1, + 219 => 10, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 150, + 402 => 150, + 403 => 75, + 404 => 30, + 405 => 75, + 406 => 7, + 407 => 1, + 408 => 1 + ) + ), + 222 => array + ( + 'shield' => 10000, + 'attack' => 47500, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 15, + 207 => 35, + 208 => 6, + 209 => 6, + 210 => 1, + 211 => 12, + 212 => 3, + 213 => 50, + 214 => 10, + 215 => 60, + 216 => 6, + 217 => 25, + 218 => 3, + 219 => 1, + 220 => 3, + 221 => 3, + 222 => 1, + 223 => 1, + 224 => 1, + 401 => 1, + 402 => 6, + 403 => 1, + 404 => 1, + 405 => 1, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 223 => array + ( + 'shield' => 20000, + 'attack' => 440000, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 5, + 208 => 1, + 209 => 1, + 210 => 1, + 211 => 5, + 212 => 3, + 213 => 32, + 214 => 16, + 215 => 32, + 216 => 9, + 217 => 20, + 218 => 9, + 219 => 1, + 220 => 9, + 221 => 6, + 222 => 5, + 223 => 1, + 224 => 1, + 401 => 1, + 402 => 25, + 403 => 15, + 404 => 5, + 405 => 15, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 224 => array + ( + 'shield' => 50000, + 'attack' => 500000, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 5, + 208 => 1, + 209 => 1, + 210 => 1, + 211 => 20, + 212 => 1, + 213 => 30, + 214 => 45, + 215 => 30, + 216 => 50, + 217 => 1, + 218 => 12, + 219 => 80, + 220 => 14, + 221 => 8, + 222 => 10, + 223 => 2, + 224 => 1, + 401 => 1, + 402 => 1, + 403 => 1, + 404 => 1, + 405 => 1, + 406 => 1, + 407 => 1, + 408 => 1 + ) + ), + 401 => array + ( + 'shield' => 20, + 'attack' => 80, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 0, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 0, + 217 => 1, + 218 => 1, + 219 => 1, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1 + ) + ), + 402 => array + ( + 'shield' => 25, + 'attack' => 100, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 0, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 0, + 217 => 1, + 218 => 1, + 219 => 1, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1 + ) + ), + 403 => array + ( + 'shield' => 100, + 'attack' => 250, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 0, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 0, + 217 => 1, + 218 => 1, + 219 => 1, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1 + ) + ), + 404 => array + ( + 'shield' => 200, + 'attack' => 1100, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 0, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 0, + 217 => 1, + 218 => 1, + 219 => 1, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1 + ) + ), + 405 => array + ( + 'shield' => 500, + 'attack' => 150, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 0, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 0, + 217 => 1, + 218 => 1, + 219 => 1, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1 + ) + ), + 406 => array + ( + 'shield' => 300, + 'attack' => 3000, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 5, + 211 => 1, + 212 => 0, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 0, + 217 => 1, + 218 => 1, + 219 => 1, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1 + ) + ), + 407 => array + ( + 'shield' => 2000, + 'attack' => 1, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 1, + 211 => 1, + 212 => 0, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 0, + 217 => 1, + 218 => 1, + 219 => 1, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1 + ) + ), + 408 => array + ( + 'shield' => 10000, + 'attack' => 1, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 1, + 211 => 1, + 212 => 0, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 0, + 217 => 1, + 218 => 1, + 219 => 1, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1 + ) + ), + 409 => array + ( + 'shield' => 1000000, + 'attack' => 1000000, + 'sd' => array + ( + 202 => 1, + 203 => 1, + 204 => 1, + 205 => 1, + 206 => 1, + 207 => 1, + 208 => 1, + 209 => 1, + 210 => 1, + 211 => 1, + 212 => 0, + 213 => 1, + 214 => 1, + 215 => 1, + 216 => 0, + 217 => 1, + 218 => 1, + 219 => 1, + 220 => 1, + 221 => 1, + 222 => 1, + 223 => 1, + 224 => 1 + ) + ), + 502 => array + ( + 'shield' => 1, + 'attack' => 1 + ), + 503 => array + ( + 'shield' => 1, + 'attack' => 12000 + ), + ); +} + +?> diff --git a/includes/vars_elementcategories.php b/includes/vars_elementcategories.php index 9312136d8..dd3a51c56 100644 --- a/includes/vars_elementcategories.php +++ b/includes/vars_elementcategories.php @@ -1,18 +1,18 @@ - \ No newline at end of file + diff --git a/includes/vars_militaryupgrades.php b/includes/vars_militaryupgrades.php index 5e54e5f62..63a4fe8c9 100644 --- a/includes/vars_militaryupgrades.php +++ b/includes/vars_militaryupgrades.php @@ -1,67 +1,67 @@ - array - ( - 121 => 2 - ), - 211 => array - ( - 122 => 5 - ), - 214 => array - ( - 199 => 1 - ), - 215 => array - ( - 120 => 12 - ), - 216 => array - ( - 120 => 12, - 122 => 12 - ), - 218 => array - ( - 125 => 4 - ), - 220 => array - ( - 121 => 12 - ), - 222 => array - ( - 122 => 18 - ), - 223 => array - ( - 125 => 6 - ), - 224 => array - ( - 126 => 2 - ), - 402 => array - ( - 120 => 3 - ), - 403 => array - ( - 120 => 6 - ), - 405 => array - ( - 121 => 4 - ), - 406 => array - ( - 122 => 7 - ), - ); -} - -?> \ No newline at end of file + array + ( + 121 => 2 + ), + 211 => array + ( + 122 => 5 + ), + 214 => array + ( + 199 => 1 + ), + 215 => array + ( + 120 => 12 + ), + 216 => array + ( + 120 => 12, + 122 => 12 + ), + 218 => array + ( + 125 => 4 + ), + 220 => array + ( + 121 => 12 + ), + 222 => array + ( + 122 => 18 + ), + 223 => array + ( + 125 => 6 + ), + 224 => array + ( + 126 => 2 + ), + 402 => array + ( + 120 => 3 + ), + 403 => array + ( + 120 => 6 + ), + 405 => array + ( + 121 => 4 + ), + 406 => array + ( + 122 => 7 + ), + ); +} + +?> diff --git a/includes/vars_prices.php b/includes/vars_prices.php index 684a53bff..c27480c28 100644 --- a/includes/vars_prices.php +++ b/includes/vars_prices.php @@ -1,860 +1,860 @@ - array - ( - 'metal' => 60, - 'crystal' => 15, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1.5 - ), - 2 => array - ( - 'metal' => 48, - 'crystal' => 24, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1.6 - ), - 3 => array - ( - 'metal' => 225, - 'crystal' => 75, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1.5 - ), - 4 => array - ( - 'metal' => 75, - 'crystal' => 30, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1.5 - ), - 12 => array - ( - 'metal' => 900, - 'crystal' => 360, - 'deuterium' => 180, - 'energy' => 0, - 'factor' => 1.8 - ), - 14 => array - ( - 'metal' => 400, - 'crystal' => 120, - 'deuterium' => 200, - 'energy' => 0, - 'factor' => 2 - ), - 15 => array - ( - 'metal' => 1000000, - 'crystal' => 500000, - 'deuterium' => 100000, - 'energy' => 0, - 'factor' => 2 - ), - 21 => array - ( - 'metal' => 400, - 'crystal' => 200, - 'deuterium' => 100, - 'energy' => 0, - 'factor' => 2 - ), - 22 => array - ( - 'metal' => 2000, - 'crystal' => 0, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1.5 - ), - 23 => array - ( - 'metal' => 2000, - 'crystal' => 1000, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1.5 - ), - 24 => array - ( - 'metal' => 2000, - 'crystal' => 2000, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1.5 - ), - 31 => array - ( - 'metal' => 200, - 'crystal' => 400, - 'deuterium' => 200, - 'energy' => 0, - 'factor' => 2 - ), - 33 => array - ( - 'metal' => 0, - 'crystal' => 50000, - 'deuterium' => 100000, - 'energy_max' => 1000, - 'factor' => 2 - ), - 34 => array - ( - 'metal' => 20000, - 'crystal' => 40000, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 2 - ), - 41 => array - ( - 'metal' => 20000, - 'crystal' => 40000, - 'deuterium' => 20000, - 'energy' => 0, - 'factor' => 2 - ), - 42 => array - ( - 'metal' => 20000, - 'crystal' => 40000, - 'deuterium' => 20000, - 'energy' => 0, - 'factor' => 2 - ), - 43 => array - ( - 'metal' => 2000000, - 'crystal' => 4000000, - 'deuterium' => 2000000, - 'energy' => 0, - 'factor' => 2 - ), - 44 => array - ( - 'metal' => 20000, - 'crystal' => 20000, - 'deuterium' => 1000, - 'energy' => 0, - 'factor' => 2 - ), - 50 => array - ( - 'metal' => 0, - 'crystal' => 0, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 2 - ), - 106 => array - ( - 'metal' => 200, - 'crystal' => 1000, - 'deuterium' => 200, - 'energy' => 0, - 'factor' => 2 - ), - 108 => array - ( - 'metal' => 0, - 'crystal' => 400, - 'deuterium' => 600, - 'energy' => 0, - 'factor' => 2 - ), - 109 => array - ( - 'metal' => 800, - 'crystal' => 200, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 2 - ), - 110 => array - ( - 'metal' => 200, - 'crystal' => 600, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 2 - ), - 111 => array - ( - 'metal' => 1000, - 'crystal' => 0, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 2 - ), - 113 => array - ( - 'metal' => 0, - 'crystal' => 800, - 'deuterium' => 400, - 'energy' => 0, - 'factor' => 2 - ), - 114 => array - ( - 'metal' => 0, - 'crystal' => 4000, - 'deuterium' => 2000, - 'energy' => 0, - 'factor' => 2 - ), - 115 => array - ( - 'metal' => 400, - 'crystal' => 0, - 'deuterium' => 600, - 'energy' => 0, - 'factor' => 2 - ), - 117 => array - ( - 'metal' => 2000, - 'crystal' => 4000, - 'deuterium' => 600, - 'energy' => 0, - 'factor' => 2 - ), - 118 => array - ( - 'metal' => 10000, - 'crystal' => 20000, - 'deuterium' => 6000, - 'energy' => 0, - 'factor' => 2 - ), - 120 => array - ( - 'metal' => 200, - 'crystal' => 100, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 2 - ), - 121 => array - ( - 'metal' => 1000, - 'crystal' => 300, - 'deuterium' => 100, - 'energy' => 0, - 'factor' => 2 - ), - 122 => array - ( - 'metal' => 2000, - 'crystal' => 4000, - 'deuterium' => 1000, - 'energy' => 0, - 'factor' => 2 - ), - 123 => array - ( - 'metal' => 240000, - 'crystal' => 400000, - 'deuterium' => 160000, - 'energy' => 0, - 'factor' => 2 - ), - 124 => array - ( - 'metal' => 4000, - 'crystal' => 8000, - 'deuterium' => 4000, - 'energy' => 0, - 'factor' => 2 - ), - 125 => array - ( - 'metal' => 1000000, - 'crystal' => 2000000, - 'deuterium' => 4000000, - 'energy' => 0, - 'factor' => 2 - ), - 126 => array - ( - 'metal' => 1000000000, - 'crystal' => 1200000000, - 'deuterium' => 800000000, - 'energy' => 0, - 'factor' => 1.5 - ), - 199 => array - ( - 'metal' => 0, - 'crystal' => 0, - 'deuterium' => 0, - 'energy_max' => 300000, - 'factor' => 3 - ), - - 202 => array - ( - 'metal' => 2000, - 'crystal' => 2000, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 117, - 'minlevel' => 5, - 'speed' => 10000, - 'consumption' => 40 - ), - array - ( - 'tech' => 115, - 'minlevel' => 0, - 'speed' => 5000, - 'consumption' => 20 - ) - ), - 'weapons' => array(1), - 'capacity' => 5000 - ), - 203 => array - ( - 'metal' => 6000, - 'crystal' => 6000, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 115, - 'minlevel' => 0, - 'speed' => 7500, - 'consumption' => 50 - ) - ), - 'weapons' => array(1), - 'capacity' => 25000 - ), - 204 => array - ( - 'metal' => 3000, - 'crystal' => 1000, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 115, - 'minlevel' => 0, - 'speed' => 12500, - 'consumption' => 20 - ) - ), - 'weapons' => array(1), - 'capacity' => 50 - ), - 205 => array - ( - 'metal' => 6000, - 'crystal' => 4000, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 117, - 'minlevel' => 0, - 'speed' => 10000, - 'consumption' => 75 - ) - ), - 'weapons' => array(1), - 'capacity' => 100 - ), - 206 => array - ( - 'metal' => 20000, - 'crystal' => 7000, - 'deuterium' => 2000, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 117, - 'minlevel' => 0, - 'speed' => 15000, - 'consumption' => 300 - ) - ), - 'weapons' => array(121), - 'capacity' => 800 - ), - 207 => array - ( - 'metal' => 45000, - 'crystal' => 15000, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 118, - 'minlevel' => 0, - 'speed' => 10000, - 'consumption' => 500 - ) - ), - 'weapons' => array(1), - 'capacity' => 1500 - ), - 208 => array - ( - 'metal' => 10000, - 'crystal' => 20000, - 'deuterium' => 10000, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 117, - 'minlevel' => 0, - 'speed' => 2500, - 'consumption' => 1000 - ) - ), - 'weapons' => array(1), - 'capacity' => 7500 - ), - 209 => array - ( - 'metal' => 10000, - 'crystal' => 6000, - 'deuterium' => 2000, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 115, - 'minlevel' => 0, - 'speed' => 2000, - 'consumption' => 300 - ) - ), - 'weapons' => array(1), - 'capacity' => 20000 - ), - 210 => array - ( - 'metal' => 0, - 'crystal' => 1000, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 115, - 'minlevel' => 0, - 'speed' => 100000000, - 'consumption' => 1 - ) - ), - 'capacity' => 5, - 'cantPillage' => true, - ), - 211 => array - ( - 'metal' => 50000, - 'crystal' => 25000, - 'deuterium' => 15000, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 118, - 'minlevel' => 8, - 'speed' => 5000, - 'consumption' => 1000 - ), - array - ( - 'tech' => 117, - 'minlevel' => 0, - 'speed' => 4000, - 'consumption' => 1000 - ) - ), - 'weapons' => array(122), - 'capacity' => 500 - ), - 212 => array - ( - 'metal' => 0, - 'crystal' => 2000, - 'deuterium' => 500, - 'energy' => 0, - 'factor' => 1, - 'weapons' => array(1), - 'capacity' => 0 - ), - 213 => array - ( - 'metal' => 60000, - 'crystal' => 50000, - 'deuterium' => 15000, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 118, - 'minlevel' => 0, - 'speed' => 5000, - 'consumption' => 1000 - ) - ), - 'weapons' => array(1), - 'capacity' => 2000 - ), - 214 => array - ( - 'metal' => 5000000, - 'crystal' => 4000000, - 'deuterium' => 1000000, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 118, - 'minlevel' => 0, - 'speed' => 100, - 'consumption' => 1 - ) - ), - 'weapons' => array(199), - 'capacity' => 1000000 - ), - 215 => array - ( - 'metal' => 30000, - 'crystal' => 40000, - 'deuterium' => 15000, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 118, - 'minlevel' => 0, - 'speed' => 10000, - 'consumption' => 250 - ) - ), - 'weapons' => array(120), - 'capacity' => 750 - ), - 216 => array - ( - 'metal' => 2500000, - 'crystal' => 3500000, - 'deuterium' => 1000000, - 'energy' => 0, - 'factor' => 1, - 'weapons' => array(120, 122), - 'capacity' => 0 - ), - 217 => array - ( - 'metal' => 25000, - 'crystal' => 25000, - 'deuterium' => 10000, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 118, - 'minlevel' => 0, - 'speed' => 17500, - 'consumption' => 500 - ) - ), - 'weapons' => array(1), - 'capacity' => 125000 - ), - 218 => array - ( - 'metal' => 6000000, - 'crystal' => 3500000, - 'deuterium' => 3500000, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 118, - 'minlevel' => 0, - 'speed' => 12000, - 'consumption' => 200 - ) - ), - 'weapons' => array(125), - 'capacity' => 1500 - ), - 219 => array - ( - 'metal' => 5000, - 'crystal' => 10000, - 'deuterium' => 5000, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'speed' => 15, - 'consumption' => 100 - ) - ), - 'weapons' => array(1), - 'capacity' => 50 - ), - 220 => array - ( - 'metal' => 5000000, - 'crystal' => 2000000, - 'deuterium' => 1000000, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 118, - 'minlevel' => 0, - 'speed' => 4000, - 'consumption' => 400 - ) - ), - 'weapons' => array(121), - 'capacity' => 5000 - ), - 221 => array - ( - 'metal' => 2500000, - 'crystal' => 3500000, - 'deuterium' => 4500000, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 118, - 'minlevel' => 0, - 'speed' => 4500, - 'consumption' => 400 - ) - ), - 'weapons' => array(1), - 'capacity' => 4000 - ), - 222 => array - ( - 'metal' => 5000000, - 'crystal' => 3000000, - 'deuterium' => 4000000, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 118, - 'minlevel' => 0, - 'speed' => 7500, - 'consumption' => 450 - ) - ), - 'weapons' => array(122), - 'capacity' => 8500 - ), - 223 => array - ( - 'metal' => 4500000, - 'crystal' => 5500000, - 'deuterium' => 6000000, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 118, - 'minlevel' => 0, - 'speed' => 1500, - 'consumption' => 350 - ) - ), - 'weapons' => array(125), - 'capacity' => 7500 - ), - 224 => array - ( - 'metal' => 6500000, - 'crystal' => 8000000, - 'deuterium' => 10000000, - 'energy' => 0, - 'factor' => 1, - 'engine' => array - ( - array - ( - 'tech' => 118, - 'minlevel' => 0, - 'speed' => 1250, - 'consumption' => 600 - ) - ), - 'weapons' => array(126), - 'capacity' => 14000 - ), - - 401 => array - ( - 'metal' => 2000, - 'crystal' => 0, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1, - 'weapons' => array(1), - ), - 402 => array - ( - 'metal' => 1500, - 'crystal' => 500, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1, - 'weapons' => array(120), - ), - 403 => array - ( - 'metal' => 6000, - 'crystal' => 2000, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1, - 'weapons' => array(120), - ), - 404 => array - ( - 'metal' => 20000, - 'crystal' => 15000, - 'deuterium' => 2000, - 'energy' => 0, - 'factor' => 1, - 'weapons' => array(1), - ), - 405 => array - ( - 'metal' => 2000, - 'crystal' => 6000, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1, - 'weapons' => array(121), - ), - 406 => array - ( - 'metal' => 50000, - 'crystal' => 50000, - 'deuterium' => 30000, - 'energy' => 0, - 'factor' => 1, - 'weapons' => array(122), - ), - 407 => array - ( - 'metal' => 10000, - 'crystal' => 10000, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1, - 'weapons' => array(1), - ), - 408 => array - ( - 'metal' => 50000, - 'crystal' => 50000, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1, - 'weapons' => array(1), - ), - 409 => array - ( - 'metal' => 10000000, - 'crystal' => 5000000, - 'deuterium' => 2500000, - 'energy' => 0, - 'factor' => 1, - 'weapons' => array(1), - ), - - 502 => array - ( - 'metal' => 8000, - 'crystal' => 0, - 'deuterium' => 2000, - 'energy' => 0, - 'factor' => 1, - 'weapons' => array(1), - ), - 503 => array - ( - 'metal' => 12500, - 'crystal' => 2500, - 'deuterium' => 10000, - 'energy' => 0, - 'factor' => 1, - 'weapons' => array(1), - ), - ); -} - -?> \ No newline at end of file + array + ( + 'metal' => 60, + 'crystal' => 15, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1.5 + ), + 2 => array + ( + 'metal' => 48, + 'crystal' => 24, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1.6 + ), + 3 => array + ( + 'metal' => 225, + 'crystal' => 75, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1.5 + ), + 4 => array + ( + 'metal' => 75, + 'crystal' => 30, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1.5 + ), + 12 => array + ( + 'metal' => 900, + 'crystal' => 360, + 'deuterium' => 180, + 'energy' => 0, + 'factor' => 1.8 + ), + 14 => array + ( + 'metal' => 400, + 'crystal' => 120, + 'deuterium' => 200, + 'energy' => 0, + 'factor' => 2 + ), + 15 => array + ( + 'metal' => 1000000, + 'crystal' => 500000, + 'deuterium' => 100000, + 'energy' => 0, + 'factor' => 2 + ), + 21 => array + ( + 'metal' => 400, + 'crystal' => 200, + 'deuterium' => 100, + 'energy' => 0, + 'factor' => 2 + ), + 22 => array + ( + 'metal' => 2000, + 'crystal' => 0, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1.5 + ), + 23 => array + ( + 'metal' => 2000, + 'crystal' => 1000, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1.5 + ), + 24 => array + ( + 'metal' => 2000, + 'crystal' => 2000, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1.5 + ), + 31 => array + ( + 'metal' => 200, + 'crystal' => 400, + 'deuterium' => 200, + 'energy' => 0, + 'factor' => 2 + ), + 33 => array + ( + 'metal' => 0, + 'crystal' => 50000, + 'deuterium' => 100000, + 'energy_max' => 1000, + 'factor' => 2 + ), + 34 => array + ( + 'metal' => 20000, + 'crystal' => 40000, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 2 + ), + 41 => array + ( + 'metal' => 20000, + 'crystal' => 40000, + 'deuterium' => 20000, + 'energy' => 0, + 'factor' => 2 + ), + 42 => array + ( + 'metal' => 20000, + 'crystal' => 40000, + 'deuterium' => 20000, + 'energy' => 0, + 'factor' => 2 + ), + 43 => array + ( + 'metal' => 2000000, + 'crystal' => 4000000, + 'deuterium' => 2000000, + 'energy' => 0, + 'factor' => 2 + ), + 44 => array + ( + 'metal' => 20000, + 'crystal' => 20000, + 'deuterium' => 1000, + 'energy' => 0, + 'factor' => 2 + ), + 50 => array + ( + 'metal' => 0, + 'crystal' => 0, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 2 + ), + 106 => array + ( + 'metal' => 200, + 'crystal' => 1000, + 'deuterium' => 200, + 'energy' => 0, + 'factor' => 2 + ), + 108 => array + ( + 'metal' => 0, + 'crystal' => 400, + 'deuterium' => 600, + 'energy' => 0, + 'factor' => 2 + ), + 109 => array + ( + 'metal' => 800, + 'crystal' => 200, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 2 + ), + 110 => array + ( + 'metal' => 200, + 'crystal' => 600, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 2 + ), + 111 => array + ( + 'metal' => 1000, + 'crystal' => 0, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 2 + ), + 113 => array + ( + 'metal' => 0, + 'crystal' => 800, + 'deuterium' => 400, + 'energy' => 0, + 'factor' => 2 + ), + 114 => array + ( + 'metal' => 0, + 'crystal' => 4000, + 'deuterium' => 2000, + 'energy' => 0, + 'factor' => 2 + ), + 115 => array + ( + 'metal' => 400, + 'crystal' => 0, + 'deuterium' => 600, + 'energy' => 0, + 'factor' => 2 + ), + 117 => array + ( + 'metal' => 2000, + 'crystal' => 4000, + 'deuterium' => 600, + 'energy' => 0, + 'factor' => 2 + ), + 118 => array + ( + 'metal' => 10000, + 'crystal' => 20000, + 'deuterium' => 6000, + 'energy' => 0, + 'factor' => 2 + ), + 120 => array + ( + 'metal' => 200, + 'crystal' => 100, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 2 + ), + 121 => array + ( + 'metal' => 1000, + 'crystal' => 300, + 'deuterium' => 100, + 'energy' => 0, + 'factor' => 2 + ), + 122 => array + ( + 'metal' => 2000, + 'crystal' => 4000, + 'deuterium' => 1000, + 'energy' => 0, + 'factor' => 2 + ), + 123 => array + ( + 'metal' => 240000, + 'crystal' => 400000, + 'deuterium' => 160000, + 'energy' => 0, + 'factor' => 2 + ), + 124 => array + ( + 'metal' => 4000, + 'crystal' => 8000, + 'deuterium' => 4000, + 'energy' => 0, + 'factor' => 2 + ), + 125 => array + ( + 'metal' => 1000000, + 'crystal' => 2000000, + 'deuterium' => 4000000, + 'energy' => 0, + 'factor' => 2 + ), + 126 => array + ( + 'metal' => 1000000000, + 'crystal' => 1200000000, + 'deuterium' => 800000000, + 'energy' => 0, + 'factor' => 1.5 + ), + 199 => array + ( + 'metal' => 0, + 'crystal' => 0, + 'deuterium' => 0, + 'energy_max' => 300000, + 'factor' => 3 + ), + + 202 => array + ( + 'metal' => 2000, + 'crystal' => 2000, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 117, + 'minlevel' => 5, + 'speed' => 10000, + 'consumption' => 40 + ), + array + ( + 'tech' => 115, + 'minlevel' => 0, + 'speed' => 5000, + 'consumption' => 20 + ) + ), + 'weapons' => array(1), + 'capacity' => 5000 + ), + 203 => array + ( + 'metal' => 6000, + 'crystal' => 6000, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 115, + 'minlevel' => 0, + 'speed' => 7500, + 'consumption' => 50 + ) + ), + 'weapons' => array(1), + 'capacity' => 25000 + ), + 204 => array + ( + 'metal' => 3000, + 'crystal' => 1000, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 115, + 'minlevel' => 0, + 'speed' => 12500, + 'consumption' => 20 + ) + ), + 'weapons' => array(1), + 'capacity' => 50 + ), + 205 => array + ( + 'metal' => 6000, + 'crystal' => 4000, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 117, + 'minlevel' => 0, + 'speed' => 10000, + 'consumption' => 75 + ) + ), + 'weapons' => array(1), + 'capacity' => 100 + ), + 206 => array + ( + 'metal' => 20000, + 'crystal' => 7000, + 'deuterium' => 2000, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 117, + 'minlevel' => 0, + 'speed' => 15000, + 'consumption' => 300 + ) + ), + 'weapons' => array(121), + 'capacity' => 800 + ), + 207 => array + ( + 'metal' => 45000, + 'crystal' => 15000, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 118, + 'minlevel' => 0, + 'speed' => 10000, + 'consumption' => 500 + ) + ), + 'weapons' => array(1), + 'capacity' => 1500 + ), + 208 => array + ( + 'metal' => 10000, + 'crystal' => 20000, + 'deuterium' => 10000, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 117, + 'minlevel' => 0, + 'speed' => 2500, + 'consumption' => 1000 + ) + ), + 'weapons' => array(1), + 'capacity' => 7500 + ), + 209 => array + ( + 'metal' => 10000, + 'crystal' => 6000, + 'deuterium' => 2000, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 115, + 'minlevel' => 0, + 'speed' => 2000, + 'consumption' => 300 + ) + ), + 'weapons' => array(1), + 'capacity' => 20000 + ), + 210 => array + ( + 'metal' => 0, + 'crystal' => 1000, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 115, + 'minlevel' => 0, + 'speed' => 100000000, + 'consumption' => 1 + ) + ), + 'capacity' => 5, + 'cantPillage' => true, + ), + 211 => array + ( + 'metal' => 50000, + 'crystal' => 25000, + 'deuterium' => 15000, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 118, + 'minlevel' => 8, + 'speed' => 5000, + 'consumption' => 1000 + ), + array + ( + 'tech' => 117, + 'minlevel' => 0, + 'speed' => 4000, + 'consumption' => 1000 + ) + ), + 'weapons' => array(122), + 'capacity' => 500 + ), + 212 => array + ( + 'metal' => 0, + 'crystal' => 2000, + 'deuterium' => 500, + 'energy' => 0, + 'factor' => 1, + 'weapons' => array(1), + 'capacity' => 0 + ), + 213 => array + ( + 'metal' => 60000, + 'crystal' => 50000, + 'deuterium' => 15000, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 118, + 'minlevel' => 0, + 'speed' => 5000, + 'consumption' => 1000 + ) + ), + 'weapons' => array(1), + 'capacity' => 2000 + ), + 214 => array + ( + 'metal' => 5000000, + 'crystal' => 4000000, + 'deuterium' => 1000000, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 118, + 'minlevel' => 0, + 'speed' => 100, + 'consumption' => 1 + ) + ), + 'weapons' => array(199), + 'capacity' => 1000000 + ), + 215 => array + ( + 'metal' => 30000, + 'crystal' => 40000, + 'deuterium' => 15000, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 118, + 'minlevel' => 0, + 'speed' => 10000, + 'consumption' => 250 + ) + ), + 'weapons' => array(120), + 'capacity' => 750 + ), + 216 => array + ( + 'metal' => 2500000, + 'crystal' => 3500000, + 'deuterium' => 1000000, + 'energy' => 0, + 'factor' => 1, + 'weapons' => array(120, 122), + 'capacity' => 0 + ), + 217 => array + ( + 'metal' => 25000, + 'crystal' => 25000, + 'deuterium' => 10000, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 118, + 'minlevel' => 0, + 'speed' => 17500, + 'consumption' => 500 + ) + ), + 'weapons' => array(1), + 'capacity' => 125000 + ), + 218 => array + ( + 'metal' => 6000000, + 'crystal' => 3500000, + 'deuterium' => 3500000, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 118, + 'minlevel' => 0, + 'speed' => 12000, + 'consumption' => 200 + ) + ), + 'weapons' => array(125), + 'capacity' => 1500 + ), + 219 => array + ( + 'metal' => 5000, + 'crystal' => 10000, + 'deuterium' => 5000, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'speed' => 15, + 'consumption' => 100 + ) + ), + 'weapons' => array(1), + 'capacity' => 50 + ), + 220 => array + ( + 'metal' => 5000000, + 'crystal' => 2000000, + 'deuterium' => 1000000, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 118, + 'minlevel' => 0, + 'speed' => 4000, + 'consumption' => 400 + ) + ), + 'weapons' => array(121), + 'capacity' => 5000 + ), + 221 => array + ( + 'metal' => 2500000, + 'crystal' => 3500000, + 'deuterium' => 4500000, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 118, + 'minlevel' => 0, + 'speed' => 4500, + 'consumption' => 400 + ) + ), + 'weapons' => array(1), + 'capacity' => 4000 + ), + 222 => array + ( + 'metal' => 5000000, + 'crystal' => 3000000, + 'deuterium' => 4000000, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 118, + 'minlevel' => 0, + 'speed' => 7500, + 'consumption' => 450 + ) + ), + 'weapons' => array(122), + 'capacity' => 8500 + ), + 223 => array + ( + 'metal' => 4500000, + 'crystal' => 5500000, + 'deuterium' => 6000000, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 118, + 'minlevel' => 0, + 'speed' => 1500, + 'consumption' => 350 + ) + ), + 'weapons' => array(125), + 'capacity' => 7500 + ), + 224 => array + ( + 'metal' => 6500000, + 'crystal' => 8000000, + 'deuterium' => 10000000, + 'energy' => 0, + 'factor' => 1, + 'engine' => array + ( + array + ( + 'tech' => 118, + 'minlevel' => 0, + 'speed' => 1250, + 'consumption' => 600 + ) + ), + 'weapons' => array(126), + 'capacity' => 14000 + ), + + 401 => array + ( + 'metal' => 2000, + 'crystal' => 0, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1, + 'weapons' => array(1), + ), + 402 => array + ( + 'metal' => 1500, + 'crystal' => 500, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1, + 'weapons' => array(120), + ), + 403 => array + ( + 'metal' => 6000, + 'crystal' => 2000, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1, + 'weapons' => array(120), + ), + 404 => array + ( + 'metal' => 20000, + 'crystal' => 15000, + 'deuterium' => 2000, + 'energy' => 0, + 'factor' => 1, + 'weapons' => array(1), + ), + 405 => array + ( + 'metal' => 2000, + 'crystal' => 6000, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1, + 'weapons' => array(121), + ), + 406 => array + ( + 'metal' => 50000, + 'crystal' => 50000, + 'deuterium' => 30000, + 'energy' => 0, + 'factor' => 1, + 'weapons' => array(122), + ), + 407 => array + ( + 'metal' => 10000, + 'crystal' => 10000, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1, + 'weapons' => array(1), + ), + 408 => array + ( + 'metal' => 50000, + 'crystal' => 50000, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1, + 'weapons' => array(1), + ), + 409 => array + ( + 'metal' => 10000000, + 'crystal' => 5000000, + 'deuterium' => 2500000, + 'energy' => 0, + 'factor' => 1, + 'weapons' => array(1), + ), + + 502 => array + ( + 'metal' => 8000, + 'crystal' => 0, + 'deuterium' => 2000, + 'energy' => 0, + 'factor' => 1, + 'weapons' => array(1), + ), + 503 => array + ( + 'metal' => 12500, + 'crystal' => 2500, + 'deuterium' => 10000, + 'energy' => 0, + 'factor' => 1, + 'weapons' => array(1), + ), + ); +} + +?> diff --git a/includes/vars_requirements.php b/includes/vars_requirements.php index e8cb31e10..56f29468d 100644 --- a/includes/vars_requirements.php +++ b/includes/vars_requirements.php @@ -1,349 +1,349 @@ - array - ( - 3 => 5, - 113 => 3 - ), - 15 => array - ( - 14 => 10, - 108 => 10 - ), - 21 => array - ( - 14 => 2 - ), - 33 => array - ( - 15 => 1, - 113 => 12 - ), - 42 => array - ( - 41 => 1 - ), - 43 => array - ( - 41 => 1, - 114 => 7 - ), - - // Technologies - 106 => array - ( - 31 => 3 - ), - 108 => array - ( - 31 => 1 - ), - 109 => array - ( - 31 => 4 - ), - 110 => array - ( - 113 => 3, - 31 => 6 - ), - 111 => array - ( - 31 => 2 - ), - 113 => array - ( - 31 => 1 - ), - 114 => array - ( - 113 => 5, - 110 => 5, - 31 => 7 - ), - 115 => array - ( - 113 => 1, - 31 => 1 - ), - 117 => array - ( - 113 => 1, - 31 => 2 - ), - 118 => array - ( - 114 => 3, - 31 => 7 - ), - 120 => array - ( - 31 => 1, - 113 => 2 - ), - 121 => array - ( - 31 => 4, - 120 => 5, - 113 => 4 - ), - 122 => array - ( - 31 => 5, - 113 => 8, - 120 => 10, - 121 => 5 - ), - 123 => array - ( - 31 => 10, - 108 => 8, - 114 => 8 - ), - 124 => array - ( - 31 => 3, - 108 => 4, - 117 => 3 - ), - 125 => array - ( - 110 => 10, - 113 => 13, - 120 => 14, - 121 => 8, - 122 => 13 - ), - 126 => array - ( - 31 => 22, - 110 => 20, - 109 => 16, - 110 => 18, - 113 => 20, - 120 => 18, - 122 => 15 - ), - 199 => array - ( - 31 => 12 - ), - - // Ships - 202 => array - ( - 21 => 2, - 115 => 2 - ), - 203 => array - ( - 21 => 4, - 115 => 6 - ), - 204 => array - ( - 21 => 1, - 115 => 1 - ), - 205 => array - ( - 21 => 3, - 111 => 2, - 117 => 2 - ), - 206 => array - ( - 21 => 5, - 117 => 4, - 121 => 2 - ), - 207 => array - ( - 21 => 7, - 118 => 4 - ), - 208 => array - ( - 21 => 4, - 117 => 3 - ), - 209 => array - ( - 21 => 4, - 115 => 6, - 110 => 2 - ), - 210 => array - ( - 21 => 3, - 115 => 3, - 106 => 2 - ), - 211 => array - ( - 117 => 6, - 21 => 8, - 122 => 5 - ), - 212 => array - ( - 21 => 1 - ), - 213 => array - ( - 21 => 9, - 118 => 6, - 114 => 5 - ), - 214 => array - ( - 21 => 12, - 118 => 7, - 114 => 6, - 199 => 1 - ), - 215 => array - ( - 114 => 5, - 120 => 12, - 118 => 5, - 21 => 8 - ), - 216 => array - ( - 21 => 8, - 120 => 12, - 111 => 6, - 110 => 10, - 122 => 12, - 108 => 10 - ), - 217 => array - ( - 21 => 8, - 15 => 1, - 118 => 6, - 111 => 5 - ), - 218 => array - ( - 21 => 15, - 118 => 7, - 110 => 12, - 111 => 6, - 125 => 4, - 108 => 12 - ), - 219 => array - ( - 21 => 4, - 115 => 4, - 110 => 4 - ), - 220 => array - ( - 21 => 16, - 118 => 10, - 110 => 15, - 115 => 8, - 108 => 15, - 121 => 12 - ), - 221 => array - ( - 21 => 10, - 118 => 10, - 113 => 16 - ), - 222 => array - ( - 21 => 18, - 118 => 12, - 122 => 18 - ), - 223 => array - ( - 21 => 20, - 118 => 9, - 110 => 15, - 125 => 6 - ), - 224 => array - ( - 21 => 25, - 108 => 18, - 114 => 10, - 118 => 15, - 110 => 20, - 113 => 22, - 126 => 2 - ), - - // Defence Systems - 401 => array - ( - 21 => 1 - ), - 402 => array - ( - 113 => 1, - 21 => 2, - 120 => 3 - ), - 403 => array - ( - 113 => 3, - 21 => 4, - 120 => 6 - ), - 404 => array - ( - 21 => 6, - 113 => 6, - 109 => 3, - 110 => 1 - ), - 405 => array - ( - 21 => 4, - 121 => 4 - ), - 406 => array - ( - 21 => 8, - 122 => 7 - ), - 407 => array - ( - 110 => 2, - 21 => 1 - ), - 408 => array - ( - 110 => 6, - 21 => 6 - ), - - // Missiles - 502 => array - ( - 44 => 2 - ), - 503 => array - ( - 44 => 4 - ), - ); -} - -?> \ No newline at end of file + array + ( + 3 => 5, + 113 => 3 + ), + 15 => array + ( + 14 => 10, + 108 => 10 + ), + 21 => array + ( + 14 => 2 + ), + 33 => array + ( + 15 => 1, + 113 => 12 + ), + 42 => array + ( + 41 => 1 + ), + 43 => array + ( + 41 => 1, + 114 => 7 + ), + + // Technologies + 106 => array + ( + 31 => 3 + ), + 108 => array + ( + 31 => 1 + ), + 109 => array + ( + 31 => 4 + ), + 110 => array + ( + 113 => 3, + 31 => 6 + ), + 111 => array + ( + 31 => 2 + ), + 113 => array + ( + 31 => 1 + ), + 114 => array + ( + 113 => 5, + 110 => 5, + 31 => 7 + ), + 115 => array + ( + 113 => 1, + 31 => 1 + ), + 117 => array + ( + 113 => 1, + 31 => 2 + ), + 118 => array + ( + 114 => 3, + 31 => 7 + ), + 120 => array + ( + 31 => 1, + 113 => 2 + ), + 121 => array + ( + 31 => 4, + 120 => 5, + 113 => 4 + ), + 122 => array + ( + 31 => 5, + 113 => 8, + 120 => 10, + 121 => 5 + ), + 123 => array + ( + 31 => 10, + 108 => 8, + 114 => 8 + ), + 124 => array + ( + 31 => 3, + 108 => 4, + 117 => 3 + ), + 125 => array + ( + 110 => 10, + 113 => 13, + 120 => 14, + 121 => 8, + 122 => 13 + ), + 126 => array + ( + 31 => 22, + 110 => 20, + 109 => 16, + 110 => 18, + 113 => 20, + 120 => 18, + 122 => 15 + ), + 199 => array + ( + 31 => 12 + ), + + // Ships + 202 => array + ( + 21 => 2, + 115 => 2 + ), + 203 => array + ( + 21 => 4, + 115 => 6 + ), + 204 => array + ( + 21 => 1, + 115 => 1 + ), + 205 => array + ( + 21 => 3, + 111 => 2, + 117 => 2 + ), + 206 => array + ( + 21 => 5, + 117 => 4, + 121 => 2 + ), + 207 => array + ( + 21 => 7, + 118 => 4 + ), + 208 => array + ( + 21 => 4, + 117 => 3 + ), + 209 => array + ( + 21 => 4, + 115 => 6, + 110 => 2 + ), + 210 => array + ( + 21 => 3, + 115 => 3, + 106 => 2 + ), + 211 => array + ( + 117 => 6, + 21 => 8, + 122 => 5 + ), + 212 => array + ( + 21 => 1 + ), + 213 => array + ( + 21 => 9, + 118 => 6, + 114 => 5 + ), + 214 => array + ( + 21 => 12, + 118 => 7, + 114 => 6, + 199 => 1 + ), + 215 => array + ( + 114 => 5, + 120 => 12, + 118 => 5, + 21 => 8 + ), + 216 => array + ( + 21 => 8, + 120 => 12, + 111 => 6, + 110 => 10, + 122 => 12, + 108 => 10 + ), + 217 => array + ( + 21 => 8, + 15 => 1, + 118 => 6, + 111 => 5 + ), + 218 => array + ( + 21 => 15, + 118 => 7, + 110 => 12, + 111 => 6, + 125 => 4, + 108 => 12 + ), + 219 => array + ( + 21 => 4, + 115 => 4, + 110 => 4 + ), + 220 => array + ( + 21 => 16, + 118 => 10, + 110 => 15, + 115 => 8, + 108 => 15, + 121 => 12 + ), + 221 => array + ( + 21 => 10, + 118 => 10, + 113 => 16 + ), + 222 => array + ( + 21 => 18, + 118 => 12, + 122 => 18 + ), + 223 => array + ( + 21 => 20, + 118 => 9, + 110 => 15, + 125 => 6 + ), + 224 => array + ( + 21 => 25, + 108 => 18, + 114 => 10, + 118 => 15, + 110 => 20, + 113 => 22, + 126 => 2 + ), + + // Defence Systems + 401 => array + ( + 21 => 1 + ), + 402 => array + ( + 113 => 1, + 21 => 2, + 120 => 3 + ), + 403 => array + ( + 113 => 3, + 21 => 4, + 120 => 6 + ), + 404 => array + ( + 21 => 6, + 113 => 6, + 109 => 3, + 110 => 1 + ), + 405 => array + ( + 21 => 4, + 121 => 4 + ), + 406 => array + ( + 21 => 8, + 122 => 7 + ), + 407 => array + ( + 110 => 2, + 21 => 1 + ), + 408 => array + ( + 110 => 6, + 21 => 6 + ), + + // Missiles + 502 => array + ( + 44 => 2 + ), + 503 => array + ( + 44 => 4 + ), + ); +} + +?> diff --git a/includes/vars_resources.php b/includes/vars_resources.php index 079f8f7a5..346f2531a 100644 --- a/includes/vars_resources.php +++ b/includes/vars_resources.php @@ -1,89 +1,89 @@ - 'metal_mine', - 2 => 'crystal_mine', - 3 => 'deuterium_synthesizer', - 4 => 'solar_plant', - 12 => 'fusion_reactor', - 14 => 'robotic_factory', - 15 => 'nanite_factory', - 21 => 'shipyard', - 22 => 'metal_storage', - 23 => 'crystal_storage', - 24 => 'deuterium_tank', - 31 => 'research_lab', - 33 => 'terraformer', - 34 => 'alliance_depot', - 41 => 'lunar_base', - 42 => 'sensor_phalanx', - 43 => 'jumpgate', - 44 => 'missile_silo', - 50 => 'quantumgate', - - // Technology - 106 => 'tech_espionage', - 108 => 'tech_computer', - 109 => 'tech_weapons', - 110 => 'tech_armour', - 111 => 'tech_shielding', - 113 => 'tech_energy', - 114 => 'tech_hyperspace', - 115 => 'tech_combustiondrive', - 117 => 'tech_impulsedrive', - 118 => 'tech_hyperspacedrive', - 120 => 'tech_laser', - 121 => 'tech_ion', - 122 => 'tech_plasma', - 123 => 'tech_interresearchnetwork', - 124 => 'tech_expedition', - 125 => 'tech_antimatter', - 126 => 'tech_disintegration', - 199 => 'tech_graviton', - - // Ships - 202 => 'small_cargo_ship', - 203 => 'big_cargo_ship', - 204 => 'light_fighter', - 205 => 'heavy_fighter', - 206 => 'cruiser', - 207 => 'battleship', - 208 => 'colony_ship', - 209 => 'recycler', - 210 => 'espionage_probe', - 211 => 'bomber', - 212 => 'solar_satellite', - 213 => 'destroyer', - 214 => 'deathstar', - 215 => 'battlecruiser', - 216 => 'orbital_station', - 217 => 'mega_cargo_ship', - 218 => 'annihilator', - 219 => 'space_shuttle', - 220 => 'space_carrier', - 221 => 'hadron_bomber', - 222 => 'plasmic_ship', - 223 => 'proton_destroyer', - 224 => 'disintegrating_ship', - - // Defence Systems - 401 => 'rocket_launcher', - 402 => 'light_laser', - 403 => 'heavy_laser', - 404 => 'gauss_cannon', - 405 => 'ion_cannon', - 406 => 'plasma_turret', - 407 => 'small_shield_dome', - 408 => 'large_shield_dome', - - // Rockets - 502 => 'antiballistic_missile', - 503 => 'interplanetary_missile', - ); -} - -?> \ No newline at end of file + 'metal_mine', + 2 => 'crystal_mine', + 3 => 'deuterium_synthesizer', + 4 => 'solar_plant', + 12 => 'fusion_reactor', + 14 => 'robotic_factory', + 15 => 'nanite_factory', + 21 => 'shipyard', + 22 => 'metal_storage', + 23 => 'crystal_storage', + 24 => 'deuterium_tank', + 31 => 'research_lab', + 33 => 'terraformer', + 34 => 'alliance_depot', + 41 => 'lunar_base', + 42 => 'sensor_phalanx', + 43 => 'jumpgate', + 44 => 'missile_silo', + 50 => 'quantumgate', + + // Technology + 106 => 'tech_espionage', + 108 => 'tech_computer', + 109 => 'tech_weapons', + 110 => 'tech_armour', + 111 => 'tech_shielding', + 113 => 'tech_energy', + 114 => 'tech_hyperspace', + 115 => 'tech_combustiondrive', + 117 => 'tech_impulsedrive', + 118 => 'tech_hyperspacedrive', + 120 => 'tech_laser', + 121 => 'tech_ion', + 122 => 'tech_plasma', + 123 => 'tech_interresearchnetwork', + 124 => 'tech_expedition', + 125 => 'tech_antimatter', + 126 => 'tech_disintegration', + 199 => 'tech_graviton', + + // Ships + 202 => 'small_cargo_ship', + 203 => 'big_cargo_ship', + 204 => 'light_fighter', + 205 => 'heavy_fighter', + 206 => 'cruiser', + 207 => 'battleship', + 208 => 'colony_ship', + 209 => 'recycler', + 210 => 'espionage_probe', + 211 => 'bomber', + 212 => 'solar_satellite', + 213 => 'destroyer', + 214 => 'deathstar', + 215 => 'battlecruiser', + 216 => 'orbital_station', + 217 => 'mega_cargo_ship', + 218 => 'annihilator', + 219 => 'space_shuttle', + 220 => 'space_carrier', + 221 => 'hadron_bomber', + 222 => 'plasmic_ship', + 223 => 'proton_destroyer', + 224 => 'disintegrating_ship', + + // Defence Systems + 401 => 'rocket_launcher', + 402 => 'light_laser', + 403 => 'heavy_laser', + 404 => 'gauss_cannon', + 405 => 'ion_cannon', + 406 => 'plasma_turret', + 407 => 'small_shield_dome', + 408 => 'large_shield_dome', + + // Rockets + 502 => 'antiballistic_missile', + 503 => 'interplanetary_missile', + ); +} + +?> diff --git a/includes/vars_resproduction.php b/includes/vars_resproduction.php index 602a06622..faeb18c52 100644 --- a/includes/vars_resproduction.php +++ b/includes/vars_resproduction.php @@ -1,106 +1,106 @@ - array - ( - 'metal' => 40, - 'crystal' => 10, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1.5, - 'formule' => array - ( - 'metal' => 'return (30 * $BuildLevel * pow((1.1), $BuildLevel)) * (0.1 * $BuildLevelFactor);', - 'crystal' => 'return "0";', - 'deuterium' => 'return "0";', - 'energy' => 'return - (10 * $BuildLevel * pow((1.1), $BuildLevel)) * (0.1 * $BuildLevelFactor);' - ) - ), - // Crystal Mine - 2 => array - ( - 'metal' => 30, - 'crystal' => 15, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1.6, - 'formule' => array - ( - 'metal' => 'return "0";', - 'crystal' => 'return (20 * $BuildLevel * pow((1.1), $BuildLevel)) * (0.1 * $BuildLevelFactor);', - 'deuterium' => 'return "0";', - 'energy' => 'return - (10 * $BuildLevel * pow((1.1), $BuildLevel)) * (0.1 * $BuildLevelFactor);' - ) - ), - // Deuterium Extractor - 3 => array - ( - 'metal' => 150, - 'crystal' => 50, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1.5, - 'formule' => array - ( - 'metal' => 'return "0";', - 'crystal' => 'return "0";', - 'deuterium' => 'return((10 * $BuildLevel * pow((1.1), $BuildLevel)) * (-0.002 * $BuildTemp + 1.28)) * (0.1 * $BuildLevelFactor);', - 'energy' => 'return - (20 * $BuildLevel * pow((1.1), $BuildLevel)) * (0.1 * $BuildLevelFactor);' - ) - ), - // Solar Energy Plant - 4 => array - ( - 'metal' => 50, - 'crystal' => 20, - 'deuterium' => 0, - 'energy' => 0, - 'factor' => 1.5, - 'formule' => array - ( - 'metal' => 'return "0";', - 'crystal' => 'return "0";', - 'deuterium' => 'return "0";', - 'energy' => 'return (20 * $BuildLevel * pow((1.1), $BuildLevel)) * (0.1 * $BuildLevelFactor);' - ) - ), - // Fusion Energy Planet - 12 => array - ( - 'metal' => 500, - 'crystal' => 200, - 'deuterium' => 100, - 'energy' => 0, - 'factor' => 1.8, - 'formule' => array - ( - 'metal' => 'return "0";', - 'crystal' => 'return "0";', - 'deuterium' => 'return ((10 * $BuildLevel * pow((1.1), $BuildLevel)) * (0.1 * $BuildLevelFactor) * (-1));', - 'energy' => 'return (50 * $BuildLevel * pow((1.1), $BuildLevel)) * (0.1 * $BuildLevelFactor);' - ) - ), - // Solar Satelite - 212 => array - ( - 'metal' => 0, - 'crystal' => 2000, - 'deuterium' => 500, - 'energy' => 0, - 'factor' => 0.5, - 'formule' => array - ( - 'metal' => 'return "0";', - 'crystal' => 'return "0";', - 'deuterium' => 'return "0";', - 'energy' => 'return(($BuildTemp / 4) + 20) * $BuildLevel * (0.1 * $BuildLevelFactor);' - ) - ) - ); -} - -?> \ No newline at end of file + array + ( + 'metal' => 40, + 'crystal' => 10, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1.5, + 'formule' => array + ( + 'metal' => 'return (30 * $BuildLevel * pow((1.1), $BuildLevel)) * (0.1 * $BuildLevelFactor);', + 'crystal' => 'return "0";', + 'deuterium' => 'return "0";', + 'energy' => 'return - (10 * $BuildLevel * pow((1.1), $BuildLevel)) * (0.1 * $BuildLevelFactor);' + ) + ), + // Crystal Mine + 2 => array + ( + 'metal' => 30, + 'crystal' => 15, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1.6, + 'formule' => array + ( + 'metal' => 'return "0";', + 'crystal' => 'return (20 * $BuildLevel * pow((1.1), $BuildLevel)) * (0.1 * $BuildLevelFactor);', + 'deuterium' => 'return "0";', + 'energy' => 'return - (10 * $BuildLevel * pow((1.1), $BuildLevel)) * (0.1 * $BuildLevelFactor);' + ) + ), + // Deuterium Extractor + 3 => array + ( + 'metal' => 150, + 'crystal' => 50, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1.5, + 'formule' => array + ( + 'metal' => 'return "0";', + 'crystal' => 'return "0";', + 'deuterium' => 'return((10 * $BuildLevel * pow((1.1), $BuildLevel)) * (-0.002 * $BuildTemp + 1.28)) * (0.1 * $BuildLevelFactor);', + 'energy' => 'return - (20 * $BuildLevel * pow((1.1), $BuildLevel)) * (0.1 * $BuildLevelFactor);' + ) + ), + // Solar Energy Plant + 4 => array + ( + 'metal' => 50, + 'crystal' => 20, + 'deuterium' => 0, + 'energy' => 0, + 'factor' => 1.5, + 'formule' => array + ( + 'metal' => 'return "0";', + 'crystal' => 'return "0";', + 'deuterium' => 'return "0";', + 'energy' => 'return (20 * $BuildLevel * pow((1.1), $BuildLevel)) * (0.1 * $BuildLevelFactor);' + ) + ), + // Fusion Energy Planet + 12 => array + ( + 'metal' => 500, + 'crystal' => 200, + 'deuterium' => 100, + 'energy' => 0, + 'factor' => 1.8, + 'formule' => array + ( + 'metal' => 'return "0";', + 'crystal' => 'return "0";', + 'deuterium' => 'return ((10 * $BuildLevel * pow((1.1), $BuildLevel)) * (0.1 * $BuildLevelFactor) * (-1));', + 'energy' => 'return (50 * $BuildLevel * pow((1.1), $BuildLevel)) * (0.1 * $BuildLevelFactor);' + ) + ), + // Solar Satelite + 212 => array + ( + 'metal' => 0, + 'crystal' => 2000, + 'deuterium' => 500, + 'energy' => 0, + 'factor' => 0.5, + 'formule' => array + ( + 'metal' => 'return "0";', + 'crystal' => 'return "0";', + 'deuterium' => 'return "0";', + 'energy' => 'return(($BuildTemp / 4) + 20) * $BuildLevel * (0.1 * $BuildLevelFactor);' + ) + ) + ); +} + +?> diff --git a/includes/vars_tasks.php b/includes/vars_tasks.php index 76320b584..55b1fa3fc 100644 --- a/includes/vars_tasks.php +++ b/includes/vars_tasks.php @@ -1,1523 +1,1523 @@ - array - ( - 'requirements' => array(), - 'skip' => array - ( - 'possible' => true, - 'tasksrew' => false, - 'catrew' => true - ), - 'reward' => array - ( - array('type' => 'PREMIUM_ITEM', 'elementID' => 12) - ), - 'tasks' => array - ( - 1 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CONSTRUCTION_END', - 'jobs' => array - ( - array('type' => 'CONSTRUCTION_END', 'elementID' => 1, 'level' => 8), - array('type' => 'CONSTRUCTION_END', 'elementID' => 2, 'level' => 8), - array('type' => 'CONSTRUCTION_END', 'elementID' => 4, 'level' => 10) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 10000, 'cry' => 10000) - ) - ), - 2 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CONSTRUCTION_END', - 'jobs' => array - ( - array('type' => 'CONSTRUCTION_END', 'elementID' => 3, 'level' => 8) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 5000) - ) - ), - 3 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CONSTRUCTION_END|CONSTRUCT_SHIPS_OR_DEFENSE', - 'jobs' => array - ( - array('type' => 'CONSTRUCTION_END', 'elementID' => 14, 'level' => 2), - array('type' => 'CONSTRUCTION_END', 'elementID' => 21, 'level' => 1), - array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 401, 'count' => 5000, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'PLANET_ELEMENT', 'elementID' => 401, 'count' => 5000) - ) - ), - 4 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CONSTRUCTION_END', - 'jobs' => array - ( - array('type' => 'CONSTRUCTION_END', 'elementID' => 22, 'level' => 5), - array('type' => 'CONSTRUCTION_END', 'elementID' => 23, 'level' => 5), - array('type' => 'CONSTRUCTION_END', 'elementID' => 24, 'level' => 5) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 50000, 'cry' => 50000, 'deu' => 20000) - ) - ), - 5 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CONSTRUCTION_END|RESEARCH_END', - 'jobs' => array - ( - array('type' => 'CONSTRUCTION_END', 'elementID' => 31, 'level' => 1), - array('type' => 'RESEARCH_END', 'elementID' => 108, 'level' => 2), - array('type' => 'RESEARCH_END', 'elementID' => 113, 'level' => 2) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 25000, 'deu' => 25000) - ) - ), - 6 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CONSTRUCTION_END|CONSTRUCT_SHIPS_OR_DEFENSE|RESEARCH_END', - 'jobs' => array - ( - array('type' => 'CONSTRUCTION_END', 'elementID' => 21, 'level' => 2), - array('type' => 'RESEARCH_END', 'elementID' => 115, 'level' => 1), - array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 202, 'count' => 500, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'PLANET_ELEMENT', 'elementID' => 202, 'count' => 500), - array('type' => 'PLANET_ELEMENT', 'elementID' => 204, 'count' => 500) - ) - ), - 7 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE|COLONIZE_PLANET', - 'jobs' => array - ( - array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 208, 'count' => 1, 'statusField' => 'count'), - array('type' => 'COLONIZE_PLANET', 'count' => 1, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'PLANET_ELEMENT', 'elementID' => 208, 'count' => 2) - ) - ), - 8 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE', - 'jobs' => array - ( - array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 212, 'count' => 200, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'PLANET_ELEMENT', 'elementID' => 212, 'count' => 200) - ) - ), - 9 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE|SPY_OTHER_USER|USE_SIMULATOR', - 'jobs' => array - ( - array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 210, 'count' => 100, 'statusField' => 'count'), - array('type' => 'SPY_OTHER_USER'), - array('type' => 'USE_SIMULATOR', 'd' => 1) - ), - 'reward' => array - ( - array('type' => 'PLANET_ELEMENT', 'elementID' => 210, 'count' => 500), - array('type' => 'PLANET_ELEMENT', 'elementID' => 206, 'count' => 20) - ) - ), - 10 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE|RECYCLE_DEBRIS', - 'jobs' => array - ( - array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 209, 'count' => 100, 'statusField' => 'count'), - array('type' => 'RECYCLE_DEBRIS', 'd' => 1) - ), - 'reward' => array - ( - array('type' => 'PLANET_ELEMENT', 'elementID' => 209, 'count' => 200) - ) - ), - 11 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BUDDY_OR_ALLY_TASK', - 'jobs' => array - ( - array('type' => 'BUDDY_OR_ALLY_TASK') - ), - 'reward' => array - ( - array('type' => 'PLANET_ELEMENT', 'elementID' => 207, 'count' => 10) - ) - ), - 12 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE', - 'jobs' => array - ( - array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 219, 'count' => 1, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 150000, 'cry' => 150000, 'deu' => 150000) - ) - ), - 13 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END|MULTIPLE_CONSTRUCTION_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 108, 'level' => 10), - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 15, 'level' => 1, 'count' => 3, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 2000000, 'cry' => 1000000, 'deu' => 200000) - ) - ), - 14 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE|DESTROY_MOON', - 'jobs' => array - ( - array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 214, 'count' => 1, 'statusField' => 'count'), - array('type' => 'DESTROY_MOON', 'count' => 1, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'PLANET_ELEMENT', 'elementID' => 214, 'count' => 10), - ) - ), - 15 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE', - 'jobs' => array - ( - array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 217, 'count' => 50, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'PLANET_ELEMENT', 'elementID' => 217, 'count' => 50), - ) - ), - 16 => array - ( - 'requirements' => array(), - 'jobtypes' => 'COLONIZE_PLANET', - 'jobs' => array - ( - array('type' => 'COLONIZE_PLANET', 'count' => 9, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'PLANET_ELEMENT', 'elementID' => 217, 'count' => 200) - ) - ), - 17 => array - ( - 'requirements' => array(), - 'jobtypes' => 'MULTIPLE_CONSTRUCTION_END', - 'jobs' => array - ( - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 1, 'level' => 20, 'count' => 5, 'statusField' => 'count'), - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 2, 'level' => 20, 'count' => 5, 'statusField' => 'count'), - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 3, 'level' => 20, 'count' => 5, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 5000000, 'cry' => 5000000, 'deu' => 2000000) - ) - ), - 18 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CONSTRUCTION_END', - 'jobs' => array - ( - array('type' => 'CONSTRUCTION_END', 'elementID' => 41, 'level' => 1) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 4000000, 'cry' => 8000000, 'deu' => 4000000) - ) - ), - 19 => array - ( - 'requirements' => array - ( - array('type' => 'TASK', 'elementID' => 12), - array('type' => 'TASK', 'elementID' => 18) - ), - 'jobtypes' => 'INTRODUCTION_FLEETSAVE_END', - 'jobs' => array - ( - array('type' => 'INTRODUCTION_FLEETSAVE_END') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 10000000) - ) - ) - ), - ), - 2 => array - ( - 'requirements' => array(), - 'skip' => array - ( - 'possible' => false, - ), - 'reward' => array(), - 'tasks' => array - ( - 20 => array - ( - 'requirements' => array(), - 'jobtypes' => 'DESTROY_MOON', - 'jobs' => array - ( - array('type' => 'DESTROY_MOON', 'count' => 50, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 1000000000) - ) - ), - 21 => array - ( - 'requirements' => array(), - 'jobtypes' => 'DESTROY_MOON', - 'jobs' => array - ( - array('type' => 'DESTROY_MOON', 'count' => 150, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 3000000000) - ) - ), - 22 => array - ( - 'requirements' => array(), - 'jobtypes' => 'DESTROY_MOON', - 'jobs' => array - ( - array('type' => 'DESTROY_MOON', 'count' => 500, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 10000000000) - ) - ), - 23 => array - ( - 'requirements' => array(), - 'jobtypes' => 'DESTROY_MOON_NOFLEETLOSS', - 'jobs' => array - ( - array('type' => 'DESTROY_MOON_NOFLEETLOSS', 'count' => 50, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 5000000000) - ) - ), - 24 => array - ( - 'requirements' => array(), - 'jobtypes' => 'DESTROY_MOON_NOFLEETLOSS', - 'jobs' => array - ( - array('type' => 'DESTROY_MOON_NOFLEETLOSS', 'count' => 100, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 10000000000) - ) - ), - 25 => array - ( - 'requirements' => array(), - 'jobtypes' => 'DESTROY_MOON_NOFLEETLOSS', - 'jobs' => array - ( - array('type' => 'DESTROY_MOON_NOFLEETLOSS', 'count' => 200, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 20000000000) - ) - ), - 26 => array - ( - 'requirements' => array(), - 'jobtypes' => 'DESTROY_MOON_NOFLEETLOSS', - 'jobs' => array - ( - array('type' => 'DESTROY_MOON_NOFLEETLOSS', 'count' => 50, 'statusField' => 'count', 'minimalDiameter' => 8000) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 25000000000) - ) - ), - 27 => array - ( - 'requirements' => array(), - 'jobtypes' => 'DESTROY_MOON', - 'jobs' => array - ( - array('type' => 'DESTROY_MOON', 'count' => 25, 'statusField' => 'count', 'minimalDiameter' => 9000) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 25000000000) - ) - ), - 28 => array - ( - 'requirements' => array(), - 'jobtypes' => 'DESTROY_MOON', - 'jobs' => array - ( - array('type' => 'DESTROY_MOON', 'count' => 5, 'statusField' => 'count', 'minimalDiameter' => 9900) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 100000000000) - ) - ), - 29 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CREATE_MOON', - 'jobs' => array - ( - array('type' => 'CREATE_MOON', 'count' => 100, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 20000000000) - ) - ), - 30 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CREATE_MOON', - 'jobs' => array - ( - array('type' => 'CREATE_MOON', 'count' => 250, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 50000000000) - ) - ), - 31 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CREATE_MOON', - 'jobs' => array - ( - array('type' => 'CREATE_MOON', 'count' => 500, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 100000000000) - ) - ), - 32 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_DESTROY_MILITARYUNITS', - 'jobs' => array - ( - array('type' => 'BATTLE_DESTROY_MILITARYUNITS', 'count' => 100000000, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 1000000000) - ) - ), - 33 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_DESTROY_MILITARYUNITS', - 'jobs' => array - ( - array('type' => 'BATTLE_DESTROY_MILITARYUNITS', 'count' => 1000000000, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 10000000000) - ) - ), - 34 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_DESTROY_MILITARYUNITS', - 'jobs' => array - ( - array('type' => 'BATTLE_DESTROY_MILITARYUNITS', 'count' => 5000000000, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 50000000000) - ) - ), - 35 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO', - 'jobs' => array - ( - array('type' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO', 'count' => 1, 'statusField' => 'count', 'minimalEnemyCost' => 10000000000, 'maximalOwnValue' => 0.6) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 500000000) - ) - ), - 36 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO', - 'jobs' => array - ( - array('type' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO', 'count' => 1, 'statusField' => 'count', 'minimalEnemyCost' => 300000000000, 'maximalOwnValue' => 0.5) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 15000000000) - ) - ), - 37 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO', - 'jobs' => array - ( - array('type' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO', 'count' => 1, 'statusField' => 'count', 'minimalEnemyCost' => 1000000000000, 'maximalOwnValue' => 0.4) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 50000000000) - ) - ), - 38 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS', - 'jobs' => array - ( - array('type' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS', 'count' => 3, 'statusField' => 'count', 'minimalEnemyCost' => 10000000000, 'maximalOwnValue' => 0.35) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 1000000000) - ) - ), - 39 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS', - 'jobs' => array - ( - array('type' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS', 'count' => 3, 'statusField' => 'count', 'minimalEnemyCost' => 500000000000, 'maximalOwnValue' => 0.30) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 50000000000) - ) - ), - 40 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS', - 'jobs' => array - ( - array('type' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS', 'count' => 3, 'statusField' => 'count', 'minimalEnemyCost' => 1500000000000, 'maximalOwnValue' => 0.25) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 150000000000) - ) - ), - 41 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WIN', - 'jobs' => array - ( - array('type' => 'BATTLE_WIN', 'count' => 1000, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 30000000) - ) - ), - 42 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WIN', - 'jobs' => array - ( - array('type' => 'BATTLE_WIN', 'count' => 5000, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 100000000) - ) - ), - 43 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WIN', - 'jobs' => array - ( - array('type' => 'BATTLE_WIN', 'count' => 10000, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 300000000) - ) - ), - 44 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WIN', - 'jobs' => array - ( - array('type' => 'BATTLE_WIN', 'count' => 25000, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 1000000000) - ) - ), - 45 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WIN', - 'jobs' => array - ( - array('type' => 'BATTLE_WIN', 'count' => 50000, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 3000000000) - ) - ), - 46 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WINORDRAW_SOLO_LIMIT', - 'jobs' => array - ( - array('type' => 'BATTLE_WINORDRAW_SOLO_LIMIT', 'count' => 25, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 100000) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 4000000000) - ) - ), - 47 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WINORDRAW_SOLO_LIMIT', - 'jobs' => array - ( - array('type' => 'BATTLE_WINORDRAW_SOLO_LIMIT', 'count' => 50, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 100000) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 16000000000) - ) - ), - 48 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WINORDRAW_SOLO_LIMIT', - 'jobs' => array - ( - array('type' => 'BATTLE_WINORDRAW_SOLO_LIMIT', 'count' => 100, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 100000) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 40000000000) - ) - ), - 49 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WINORDRAW_SOLO_LIMIT', - 'jobs' => array - ( - array('type' => 'BATTLE_WINORDRAW_SOLO_LIMIT', 'count' => 15, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 500000) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 10000000000) - ) - ), - 50 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WINORDRAW_SOLO_LIMIT', - 'jobs' => array - ( - array('type' => 'BATTLE_WINORDRAW_SOLO_LIMIT', 'count' => 30, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 500000) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 40000000000) - ) - ), - 51 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WINORDRAW_SOLO_LIMIT', - 'jobs' => array - ( - array('type' => 'BATTLE_WINORDRAW_SOLO_LIMIT', 'count' => 50, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 500000) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 100000000000) - ) - ), - 52 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WINORDRAW_LIMIT', - 'jobs' => array - ( - array('type' => 'BATTLE_WINORDRAW_LIMIT', 'count' => 15, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 1000000) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 15000000000) - ) - ), - 53 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WINORDRAW_LIMIT', - 'jobs' => array - ( - array('type' => 'BATTLE_WINORDRAW_LIMIT', 'count' => 30, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 1000000) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 50000000000) - ) - ), - 54 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WINORDRAW_LIMIT', - 'jobs' => array - ( - array('type' => 'BATTLE_WINORDRAW_LIMIT', 'count' => 50, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 1000000) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 125000000000) - ) - ), - 55 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WINORDRAW_ACS_LIMIT', - 'jobs' => array - ( - array('type' => 'BATTLE_WINORDRAW_ACS_LIMIT', 'count' => 5, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 5000000) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 500000000000) - ) - ), - 56 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_BLOCK_MOONDESTROY', - 'jobs' => array - ( - array('type' => 'BATTLE_BLOCK_MOONDESTROY') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 4000000000) - ) - ), - 57 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WINORDRAW_SOLO_TOTALLIMIT', - 'jobs' => array - ( - array('type' => 'BATTLE_WINORDRAW_SOLO_TOTALLIMIT', 'count' => 50000000, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 1000000000000) - ) - ), - 58 => array - ( - 'requirements' => array(), - 'jobtypes' => 'DEBRIS_COLLECT_METAL|DEBRIS_COLLECT_CRYSTAL', - 'jobs' => array - ( - array('type' => 'DEBRIS_COLLECT_METAL', 'count' => 30000000000000, 'statusField' => 'count'), - array('type' => 'DEBRIS_COLLECT_CRYSTAL', 'count' => 15000000000000, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 500000000000, 'cry' => 500000000000) - ) - ), - 59 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_COLLECT_METAL|BATTLE_COLLECT_CRYSTAL|BATTLE_COLLECT_DEUTERIUM', - 'jobs' => array - ( - array('type' => 'BATTLE_COLLECT_METAL', 'count' => 100000000000, 'statusField' => 'count'), - array('type' => 'BATTLE_COLLECT_CRYSTAL', 'count' => 100000000000, 'statusField' => 'count'), - array('type' => 'BATTLE_COLLECT_DEUTERIUM', 'count' => 100000000000, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 5000000000) - ) - ), - 60 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_COLLECT_METAL|BATTLE_COLLECT_CRYSTAL|BATTLE_COLLECT_DEUTERIUM', - 'jobs' => array - ( - array('type' => 'BATTLE_COLLECT_METAL', 'count' => 500000000000, 'statusField' => 'count'), - array('type' => 'BATTLE_COLLECT_CRYSTAL', 'count' => 500000000000, 'statusField' => 'count'), - array('type' => 'BATTLE_COLLECT_DEUTERIUM', 'count' => 500000000000, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 20000000000) - ) - ), - 61 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_COLLECT_METAL|BATTLE_COLLECT_CRYSTAL|BATTLE_COLLECT_DEUTERIUM', - 'jobs' => array - ( - array('type' => 'BATTLE_COLLECT_METAL', 'count' => 1000000000000, 'statusField' => 'count'), - array('type' => 'BATTLE_COLLECT_CRYSTAL', 'count' => 1000000000000, 'statusField' => 'count'), - array('type' => 'BATTLE_COLLECT_DEUTERIUM', 'count' => 1000000000000, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 40000000000) - ) - ), - 62 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE_MULTIID', - 'jobs' => array - ( - array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE_MULTIID', 'elementIDs' => array(204, 205), 'count' => 1000000000, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 90000000000, 'cry' => 30000000000) - ) - ), - 63 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE_MULTIID', - 'jobs' => array - ( - array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE_MULTIID', 'elementIDs' => array(204, 205), 'count' => 10000000000, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 1000000000000, 'cry' => 350000000000) - ) - ), - ), - ), - 3 => array - ( - 'requirements' => array(), - 'skip' => array - ( - 'possible' => false, - ), - 'reward' => array(), - 'tasks' => array - ( - 64 => array - ( - 'requirements' => array(), - 'jobtypes' => 'MULTIPLE_CONSTRUCTION_END', - 'jobs' => array - ( - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 1, 'level' => 30, 'count' => 10, 'statusField' => 'count'), - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 2, 'level' => 30, 'count' => 10, 'statusField' => 'count'), - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 3, 'level' => 30, 'count' => 10, 'statusField' => 'count'), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 25000000, 'cry' => 10000000) - ) - ), - 65 => array - ( - 'requirements' => array(), - 'jobtypes' => 'MULTIPLE_CONSTRUCTION_END', - 'jobs' => array - ( - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 1, 'level' => 40, 'count' => 10, 'statusField' => 'count'), - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 2, 'level' => 40, 'count' => 10, 'statusField' => 'count'), - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 3, 'level' => 40, 'count' => 10, 'statusField' => 'count'), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 2000000000, 'cry' => 850000000) - ) - ), - 66 => array - ( - 'requirements' => array(), - 'jobtypes' => 'MULTIPLE_CONSTRUCTION_END', - 'jobs' => array - ( - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 1, 'level' => 50, 'count' => 5, 'statusField' => 'count'), - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 2, 'level' => 50, 'count' => 5, 'statusField' => 'count'), - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 3, 'level' => 50, 'count' => 5, 'statusField' => 'count'), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 60000000000, 'cry' => 28000000000) - ) - ), - 67 => array - ( - 'requirements' => array(), - 'jobtypes' => 'MULTIPLE_CONSTRUCTION_END', - 'jobs' => array - ( - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 1, 'level' => 50, 'count' => 10, 'statusField' => 'count'), - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 2, 'level' => 50, 'count' => 10, 'statusField' => 'count'), - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 3, 'level' => 50, 'count' => 10, 'statusField' => 'count'), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 120000000000, 'cry' => 60000000000) - ) - ), - 68 => array - ( - 'requirements' => array(), - 'jobtypes' => 'REACH_EXTRACTION_LEVEL', - 'jobs' => array - ( - array('type' => 'REACH_EXTRACTION_LEVEL', 'buildingID' => 1, 'resource' => 'metal', 'level' => 45000000), - array('type' => 'REACH_EXTRACTION_LEVEL', 'buildingID' => 2, 'resource' => 'crystal', 'level' => 30000000), - array('type' => 'REACH_EXTRACTION_LEVEL', 'buildingID' => 3, 'resource' => 'deuterium', 'level' => 22000000), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 75000000000, 'cry' => 50000000000, 'deu' => 37000000000) - ) - ), - 69 => array - ( - 'requirements' => array(), - 'jobtypes' => 'MULTIPLE_CONSTRUCTION_END', - 'jobs' => array - ( - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 22, 'level' => 25, 'count' => 5, 'statusField' => 'count'), - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 23, 'level' => 25, 'count' => 5, 'statusField' => 'count'), - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 24, 'level' => 25, 'count' => 5, 'statusField' => 'count'), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 100000000, 'cry' => 50000000) - ) - ), - 70 => array - ( - 'requirements' => array(), - 'jobtypes' => 'REACH_TERRAFORMING_LEVEL', - 'jobs' => array - ( - array('type' => 'REACH_TERRAFORMING_LEVEL', 'fields' => 700), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 200000000, 'deu' => 400000000) - ) - ), - 71 => array - ( - 'requirements' => array(), - 'jobtypes' => 'REACH_TOTAL_EXTRACTION_LEVEL', - 'jobs' => array - ( - array('type' => 'REACH_TOTAL_EXTRACTION_LEVEL', 'buildingID' => 3, 'resource' => 'deuterium', 'level' => 200000000, 'statusField' => 'level'), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 75000000000) - ) - ), - ) - ), - 4 => array - ( - 'requirements' => array(), - 'skip' => array - ( - 'possible' => false, - ), - 'reward' => array(), - 'tasks' => array - ( - 72 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 109, 'level' => 25), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 2000000000) - ) - ), - 73 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 109, 'level' => 30), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 64000000000) - ) - ), - 74 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 110, 'level' => 25), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 5000000000) - ) - ), - 75 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 110, 'level' => 30), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 160000000000) - ) - ), - 76 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 111, 'level' => 25), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 10000000000) - ) - ), - 77 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 111, 'level' => 30), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 320000000000) - ) - ), - 78 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 120, 'level' => 25), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 1000000000) - ) - ), - 79 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 120, 'level' => 30), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 30000000000) - ) - ), - 80 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 120, 'level' => 33), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'met' => 300000000000) - ) - ), - 81 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 121, 'level' => 20), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 50000000) - ) - ), - 82 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 121, 'level' => 25), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 1500000000) - ) - ), - 83 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 121, 'level' => 28), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 15000000000) - ) - ), - 84 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 122, 'level' => 20), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 500000000) - ) - ), - 85 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 122, 'level' => 25), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 15000000000) - ) - ), - 86 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 122, 'level' => 28), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 150000000000) - ) - ), - 87 => array - ( - 'requirements' => array(), - 'jobtypes' => 'RESEARCH_END', - 'jobs' => array - ( - array('type' => 'RESEARCH_END', 'elementID' => 123, 'level' => 9), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 50000000) - ) - ), - 88 => array - ( - 'requirements' => array(), - 'jobtypes' => 'MULTIPLE_CONSTRUCTION_END', - 'jobs' => array - ( - array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 31, 'level' => 22, 'count' => 10, 'statusField' => 'count'), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'cry' => 1000000000, 'deu' => 1000000000) - ) - ), - 89 => array - ( - 'requirements' => array(), - 'jobtypes' => 'REACH_TECHPOINTS_LEVEL', - 'jobs' => array - ( - array('type' => 'REACH_TECHPOINTS_LEVEL', 'level' => 5000000, 'statusField' => 'level'), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 5000000) - ) - ), - 90 => array - ( - 'requirements' => array(), - 'jobtypes' => 'REACH_TECHPOINTS_LEVEL', - 'jobs' => array - ( - array('type' => 'REACH_TECHPOINTS_LEVEL', 'level' => 10000000, 'statusField' => 'level'), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 10000000) - ) - ), - 91 => array - ( - 'requirements' => array(), - 'jobtypes' => 'REACH_TECHPOINTS_LEVEL', - 'jobs' => array - ( - array('type' => 'REACH_TECHPOINTS_LEVEL', 'level' => 50000000, 'statusField' => 'level'), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 50000000) - ) - ), - 92 => array - ( - 'requirements' => array(), - 'jobtypes' => 'REACH_TECHPOINTS_LEVEL', - 'jobs' => array - ( - array('type' => 'REACH_TECHPOINTS_LEVEL', 'level' => 200000000, 'statusField' => 'level'), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 200000000) - ) - ), - 93 => array - ( - 'requirements' => array(), - 'jobtypes' => 'REACH_TECHPOINTS_LEVEL', - 'jobs' => array - ( - array('type' => 'REACH_TECHPOINTS_LEVEL', 'level' => 500000000, 'statusField' => 'level'), - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 500000000) - ) - ), - ) - ), - 5 => array - ( - 'requirements' => array(), - 'skip' => array - ( - 'possible' => false, - ), - 'reward' => array(), - 'tasks' => array - ( - 94 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CREATE_MOON_FRIENDLY', - 'jobs' => array - ( - array('type' => 'CREATE_MOON_FRIENDLY', 'count' => 5, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 2500000) - ) - ), - 95 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CREATE_MOON_FRIENDLY', - 'jobs' => array - ( - array('type' => 'CREATE_MOON_FRIENDLY', 'count' => 20, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 7500000) - ) - ), - 96 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CREATE_MOON_FRIENDLY', - 'jobs' => array - ( - array('type' => 'CREATE_MOON_FRIENDLY', 'count' => 50, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 15000000) - ) - ), - 97 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CREATE_MOON_FRIENDLY', - 'jobs' => array - ( - array('type' => 'CREATE_MOON_FRIENDLY', 'count' => 125, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 30000000) - ) - ), - 98 => array - ( - 'requirements' => array(), - 'jobtypes' => 'CREATE_MOON_FRIENDLY', - 'jobs' => array - ( - array('type' => 'CREATE_MOON_FRIENDLY', 'count' => 250, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 50000000) - ) - ), - 99 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WINORDRAW_ACS_LIMIT', - 'jobs' => array - ( - array('type' => 'BATTLE_WINORDRAW_ACS_LIMIT', 'count' => 25, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 10000, 'hasToBeLeader' => true) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 10000000) - ) - ), - 100 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WINORDRAW_ACS_LIMIT', - 'jobs' => array - ( - array('type' => 'BATTLE_WINORDRAW_ACS_LIMIT', 'count' => 50, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 10000, 'hasToBeLeader' => true) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 20000000) - ) - ), - 101 => array - ( - 'requirements' => array(), - 'jobtypes' => 'BATTLE_WINORDRAW_ACS_LIMIT', - 'jobs' => array - ( - array('type' => 'BATTLE_WINORDRAW_ACS_LIMIT', 'count' => 150, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 10000, 'hasToBeLeader' => true) - ), - 'reward' => array - ( - array('type' => 'RESOURCES', 'deu' => 50000000) - ) - ), - ) - ), - 6 => array - ( - 'requirements' => array(), - 'skip' => array - ( - 'possible' => false, - ), - 'reward' => array(), - 'tasks' => array - ( - 102 => array - ( - 'requirements' => array(), - 'jobtypes' => 'NEWUSER_REGISTER', - 'jobs' => array - ( - array('type' => 'NEWUSER_REGISTER', 'count' => 10, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'PREMIUM_RESOURCE', 'value' => 25) - ) - ), - 103 => array - ( - 'requirements' => array(), - 'jobtypes' => 'NEWUSER_REGISTER', - 'jobs' => array - ( - array('type' => 'NEWUSER_REGISTER', 'count' => 20, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'PREMIUM_RESOURCE', 'value' => 25) - ) - ), - 104 => array - ( - 'requirements' => array(), - 'jobtypes' => 'NEWUSER_REGISTER', - 'jobs' => array - ( - array('type' => 'NEWUSER_REGISTER', 'count' => 40, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'PREMIUM_RESOURCE', 'value' => 50) - ) - ), - 105 => array - ( - 'requirements' => array(), - 'jobtypes' => 'INVITEDUSER_BOUGHT_DE', - 'jobs' => array - ( - array('type' => 'INVITEDUSER_BOUGHT_DE', 'count' => 40) - ), - 'reward' => array - ( - array('type' => 'PREMIUM_RESOURCE', 'value' => 10) - ) - ), - 106 => array - ( - 'requirements' => array(), - 'jobtypes' => 'INVITEDUSERS_BOUGHT_DE_USERCOUNT', - 'jobs' => array - ( - array('type' => 'INVITEDUSERS_BOUGHT_DE_USERCOUNT', 'count' => 5, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'PREMIUM_RESOURCE', 'value' => 25) - ) - ), - 107 => array - ( - 'requirements' => array(), - 'jobtypes' => 'INVITEDUSERS_BOUGHT_DE_LIMIT', - 'jobs' => array - ( - array('type' => 'INVITEDUSERS_BOUGHT_DE_LIMIT', 'count' => 400, 'statusField' => 'count') - ), - 'reward' => array - ( - array('type' => 'PREMIUM_RESOURCE', 'value' => 50) - ) - ), - ) - ), - ); - // Last Cat ID: 6 - // Last Task ID: 107 -} - -?> \ No newline at end of file + array + ( + 'requirements' => array(), + 'skip' => array + ( + 'possible' => true, + 'tasksrew' => false, + 'catrew' => true + ), + 'reward' => array + ( + array('type' => 'PREMIUM_ITEM', 'elementID' => 12) + ), + 'tasks' => array + ( + 1 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CONSTRUCTION_END', + 'jobs' => array + ( + array('type' => 'CONSTRUCTION_END', 'elementID' => 1, 'level' => 8), + array('type' => 'CONSTRUCTION_END', 'elementID' => 2, 'level' => 8), + array('type' => 'CONSTRUCTION_END', 'elementID' => 4, 'level' => 10) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 10000, 'cry' => 10000) + ) + ), + 2 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CONSTRUCTION_END', + 'jobs' => array + ( + array('type' => 'CONSTRUCTION_END', 'elementID' => 3, 'level' => 8) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 5000) + ) + ), + 3 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CONSTRUCTION_END|CONSTRUCT_SHIPS_OR_DEFENSE', + 'jobs' => array + ( + array('type' => 'CONSTRUCTION_END', 'elementID' => 14, 'level' => 2), + array('type' => 'CONSTRUCTION_END', 'elementID' => 21, 'level' => 1), + array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 401, 'count' => 5000, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'PLANET_ELEMENT', 'elementID' => 401, 'count' => 5000) + ) + ), + 4 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CONSTRUCTION_END', + 'jobs' => array + ( + array('type' => 'CONSTRUCTION_END', 'elementID' => 22, 'level' => 5), + array('type' => 'CONSTRUCTION_END', 'elementID' => 23, 'level' => 5), + array('type' => 'CONSTRUCTION_END', 'elementID' => 24, 'level' => 5) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 50000, 'cry' => 50000, 'deu' => 20000) + ) + ), + 5 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CONSTRUCTION_END|RESEARCH_END', + 'jobs' => array + ( + array('type' => 'CONSTRUCTION_END', 'elementID' => 31, 'level' => 1), + array('type' => 'RESEARCH_END', 'elementID' => 108, 'level' => 2), + array('type' => 'RESEARCH_END', 'elementID' => 113, 'level' => 2) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 25000, 'deu' => 25000) + ) + ), + 6 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CONSTRUCTION_END|CONSTRUCT_SHIPS_OR_DEFENSE|RESEARCH_END', + 'jobs' => array + ( + array('type' => 'CONSTRUCTION_END', 'elementID' => 21, 'level' => 2), + array('type' => 'RESEARCH_END', 'elementID' => 115, 'level' => 1), + array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 202, 'count' => 500, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'PLANET_ELEMENT', 'elementID' => 202, 'count' => 500), + array('type' => 'PLANET_ELEMENT', 'elementID' => 204, 'count' => 500) + ) + ), + 7 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE|COLONIZE_PLANET', + 'jobs' => array + ( + array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 208, 'count' => 1, 'statusField' => 'count'), + array('type' => 'COLONIZE_PLANET', 'count' => 1, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'PLANET_ELEMENT', 'elementID' => 208, 'count' => 2) + ) + ), + 8 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE', + 'jobs' => array + ( + array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 212, 'count' => 200, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'PLANET_ELEMENT', 'elementID' => 212, 'count' => 200) + ) + ), + 9 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE|SPY_OTHER_USER|USE_SIMULATOR', + 'jobs' => array + ( + array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 210, 'count' => 100, 'statusField' => 'count'), + array('type' => 'SPY_OTHER_USER'), + array('type' => 'USE_SIMULATOR', 'd' => 1) + ), + 'reward' => array + ( + array('type' => 'PLANET_ELEMENT', 'elementID' => 210, 'count' => 500), + array('type' => 'PLANET_ELEMENT', 'elementID' => 206, 'count' => 20) + ) + ), + 10 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE|RECYCLE_DEBRIS', + 'jobs' => array + ( + array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 209, 'count' => 100, 'statusField' => 'count'), + array('type' => 'RECYCLE_DEBRIS', 'd' => 1) + ), + 'reward' => array + ( + array('type' => 'PLANET_ELEMENT', 'elementID' => 209, 'count' => 200) + ) + ), + 11 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BUDDY_OR_ALLY_TASK', + 'jobs' => array + ( + array('type' => 'BUDDY_OR_ALLY_TASK') + ), + 'reward' => array + ( + array('type' => 'PLANET_ELEMENT', 'elementID' => 207, 'count' => 10) + ) + ), + 12 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE', + 'jobs' => array + ( + array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 219, 'count' => 1, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 150000, 'cry' => 150000, 'deu' => 150000) + ) + ), + 13 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END|MULTIPLE_CONSTRUCTION_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 108, 'level' => 10), + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 15, 'level' => 1, 'count' => 3, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 2000000, 'cry' => 1000000, 'deu' => 200000) + ) + ), + 14 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE|DESTROY_MOON', + 'jobs' => array + ( + array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 214, 'count' => 1, 'statusField' => 'count'), + array('type' => 'DESTROY_MOON', 'count' => 1, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'PLANET_ELEMENT', 'elementID' => 214, 'count' => 10), + ) + ), + 15 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE', + 'jobs' => array + ( + array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE', 'elementID' => 217, 'count' => 50, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'PLANET_ELEMENT', 'elementID' => 217, 'count' => 50), + ) + ), + 16 => array + ( + 'requirements' => array(), + 'jobtypes' => 'COLONIZE_PLANET', + 'jobs' => array + ( + array('type' => 'COLONIZE_PLANET', 'count' => 9, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'PLANET_ELEMENT', 'elementID' => 217, 'count' => 200) + ) + ), + 17 => array + ( + 'requirements' => array(), + 'jobtypes' => 'MULTIPLE_CONSTRUCTION_END', + 'jobs' => array + ( + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 1, 'level' => 20, 'count' => 5, 'statusField' => 'count'), + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 2, 'level' => 20, 'count' => 5, 'statusField' => 'count'), + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 3, 'level' => 20, 'count' => 5, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 5000000, 'cry' => 5000000, 'deu' => 2000000) + ) + ), + 18 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CONSTRUCTION_END', + 'jobs' => array + ( + array('type' => 'CONSTRUCTION_END', 'elementID' => 41, 'level' => 1) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 4000000, 'cry' => 8000000, 'deu' => 4000000) + ) + ), + 19 => array + ( + 'requirements' => array + ( + array('type' => 'TASK', 'elementID' => 12), + array('type' => 'TASK', 'elementID' => 18) + ), + 'jobtypes' => 'INTRODUCTION_FLEETSAVE_END', + 'jobs' => array + ( + array('type' => 'INTRODUCTION_FLEETSAVE_END') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 10000000) + ) + ) + ), + ), + 2 => array + ( + 'requirements' => array(), + 'skip' => array + ( + 'possible' => false, + ), + 'reward' => array(), + 'tasks' => array + ( + 20 => array + ( + 'requirements' => array(), + 'jobtypes' => 'DESTROY_MOON', + 'jobs' => array + ( + array('type' => 'DESTROY_MOON', 'count' => 50, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 1000000000) + ) + ), + 21 => array + ( + 'requirements' => array(), + 'jobtypes' => 'DESTROY_MOON', + 'jobs' => array + ( + array('type' => 'DESTROY_MOON', 'count' => 150, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 3000000000) + ) + ), + 22 => array + ( + 'requirements' => array(), + 'jobtypes' => 'DESTROY_MOON', + 'jobs' => array + ( + array('type' => 'DESTROY_MOON', 'count' => 500, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 10000000000) + ) + ), + 23 => array + ( + 'requirements' => array(), + 'jobtypes' => 'DESTROY_MOON_NOFLEETLOSS', + 'jobs' => array + ( + array('type' => 'DESTROY_MOON_NOFLEETLOSS', 'count' => 50, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 5000000000) + ) + ), + 24 => array + ( + 'requirements' => array(), + 'jobtypes' => 'DESTROY_MOON_NOFLEETLOSS', + 'jobs' => array + ( + array('type' => 'DESTROY_MOON_NOFLEETLOSS', 'count' => 100, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 10000000000) + ) + ), + 25 => array + ( + 'requirements' => array(), + 'jobtypes' => 'DESTROY_MOON_NOFLEETLOSS', + 'jobs' => array + ( + array('type' => 'DESTROY_MOON_NOFLEETLOSS', 'count' => 200, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 20000000000) + ) + ), + 26 => array + ( + 'requirements' => array(), + 'jobtypes' => 'DESTROY_MOON_NOFLEETLOSS', + 'jobs' => array + ( + array('type' => 'DESTROY_MOON_NOFLEETLOSS', 'count' => 50, 'statusField' => 'count', 'minimalDiameter' => 8000) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 25000000000) + ) + ), + 27 => array + ( + 'requirements' => array(), + 'jobtypes' => 'DESTROY_MOON', + 'jobs' => array + ( + array('type' => 'DESTROY_MOON', 'count' => 25, 'statusField' => 'count', 'minimalDiameter' => 9000) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 25000000000) + ) + ), + 28 => array + ( + 'requirements' => array(), + 'jobtypes' => 'DESTROY_MOON', + 'jobs' => array + ( + array('type' => 'DESTROY_MOON', 'count' => 5, 'statusField' => 'count', 'minimalDiameter' => 9900) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 100000000000) + ) + ), + 29 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CREATE_MOON', + 'jobs' => array + ( + array('type' => 'CREATE_MOON', 'count' => 100, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 20000000000) + ) + ), + 30 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CREATE_MOON', + 'jobs' => array + ( + array('type' => 'CREATE_MOON', 'count' => 250, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 50000000000) + ) + ), + 31 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CREATE_MOON', + 'jobs' => array + ( + array('type' => 'CREATE_MOON', 'count' => 500, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 100000000000) + ) + ), + 32 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_DESTROY_MILITARYUNITS', + 'jobs' => array + ( + array('type' => 'BATTLE_DESTROY_MILITARYUNITS', 'count' => 100000000, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 1000000000) + ) + ), + 33 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_DESTROY_MILITARYUNITS', + 'jobs' => array + ( + array('type' => 'BATTLE_DESTROY_MILITARYUNITS', 'count' => 1000000000, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 10000000000) + ) + ), + 34 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_DESTROY_MILITARYUNITS', + 'jobs' => array + ( + array('type' => 'BATTLE_DESTROY_MILITARYUNITS', 'count' => 5000000000, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 50000000000) + ) + ), + 35 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO', + 'jobs' => array + ( + array('type' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO', 'count' => 1, 'statusField' => 'count', 'minimalEnemyCost' => 10000000000, 'maximalOwnValue' => 0.6) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 500000000) + ) + ), + 36 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO', + 'jobs' => array + ( + array('type' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO', 'count' => 1, 'statusField' => 'count', 'minimalEnemyCost' => 300000000000, 'maximalOwnValue' => 0.5) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 15000000000) + ) + ), + 37 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO', + 'jobs' => array + ( + array('type' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_SOLO', 'count' => 1, 'statusField' => 'count', 'minimalEnemyCost' => 1000000000000, 'maximalOwnValue' => 0.4) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 50000000000) + ) + ), + 38 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS', + 'jobs' => array + ( + array('type' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS', 'count' => 3, 'statusField' => 'count', 'minimalEnemyCost' => 10000000000, 'maximalOwnValue' => 0.35) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 1000000000) + ) + ), + 39 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS', + 'jobs' => array + ( + array('type' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS', 'count' => 3, 'statusField' => 'count', 'minimalEnemyCost' => 500000000000, 'maximalOwnValue' => 0.30) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 50000000000) + ) + ), + 40 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS', + 'jobs' => array + ( + array('type' => 'BATTLE_DESTROY_MOREEXPENSIVEFLEET_ACS', 'count' => 3, 'statusField' => 'count', 'minimalEnemyCost' => 1500000000000, 'maximalOwnValue' => 0.25) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 150000000000) + ) + ), + 41 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WIN', + 'jobs' => array + ( + array('type' => 'BATTLE_WIN', 'count' => 1000, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 30000000) + ) + ), + 42 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WIN', + 'jobs' => array + ( + array('type' => 'BATTLE_WIN', 'count' => 5000, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 100000000) + ) + ), + 43 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WIN', + 'jobs' => array + ( + array('type' => 'BATTLE_WIN', 'count' => 10000, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 300000000) + ) + ), + 44 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WIN', + 'jobs' => array + ( + array('type' => 'BATTLE_WIN', 'count' => 25000, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 1000000000) + ) + ), + 45 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WIN', + 'jobs' => array + ( + array('type' => 'BATTLE_WIN', 'count' => 50000, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 3000000000) + ) + ), + 46 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WINORDRAW_SOLO_LIMIT', + 'jobs' => array + ( + array('type' => 'BATTLE_WINORDRAW_SOLO_LIMIT', 'count' => 25, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 100000) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 4000000000) + ) + ), + 47 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WINORDRAW_SOLO_LIMIT', + 'jobs' => array + ( + array('type' => 'BATTLE_WINORDRAW_SOLO_LIMIT', 'count' => 50, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 100000) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 16000000000) + ) + ), + 48 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WINORDRAW_SOLO_LIMIT', + 'jobs' => array + ( + array('type' => 'BATTLE_WINORDRAW_SOLO_LIMIT', 'count' => 100, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 100000) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 40000000000) + ) + ), + 49 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WINORDRAW_SOLO_LIMIT', + 'jobs' => array + ( + array('type' => 'BATTLE_WINORDRAW_SOLO_LIMIT', 'count' => 15, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 500000) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 10000000000) + ) + ), + 50 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WINORDRAW_SOLO_LIMIT', + 'jobs' => array + ( + array('type' => 'BATTLE_WINORDRAW_SOLO_LIMIT', 'count' => 30, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 500000) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 40000000000) + ) + ), + 51 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WINORDRAW_SOLO_LIMIT', + 'jobs' => array + ( + array('type' => 'BATTLE_WINORDRAW_SOLO_LIMIT', 'count' => 50, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 500000) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 100000000000) + ) + ), + 52 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WINORDRAW_LIMIT', + 'jobs' => array + ( + array('type' => 'BATTLE_WINORDRAW_LIMIT', 'count' => 15, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 1000000) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 15000000000) + ) + ), + 53 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WINORDRAW_LIMIT', + 'jobs' => array + ( + array('type' => 'BATTLE_WINORDRAW_LIMIT', 'count' => 30, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 1000000) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 50000000000) + ) + ), + 54 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WINORDRAW_LIMIT', + 'jobs' => array + ( + array('type' => 'BATTLE_WINORDRAW_LIMIT', 'count' => 50, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 1000000) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 125000000000) + ) + ), + 55 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WINORDRAW_ACS_LIMIT', + 'jobs' => array + ( + array('type' => 'BATTLE_WINORDRAW_ACS_LIMIT', 'count' => 5, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 5000000) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 500000000000) + ) + ), + 56 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_BLOCK_MOONDESTROY', + 'jobs' => array + ( + array('type' => 'BATTLE_BLOCK_MOONDESTROY') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 4000000000) + ) + ), + 57 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WINORDRAW_SOLO_TOTALLIMIT', + 'jobs' => array + ( + array('type' => 'BATTLE_WINORDRAW_SOLO_TOTALLIMIT', 'count' => 50000000, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 1000000000000) + ) + ), + 58 => array + ( + 'requirements' => array(), + 'jobtypes' => 'DEBRIS_COLLECT_METAL|DEBRIS_COLLECT_CRYSTAL', + 'jobs' => array + ( + array('type' => 'DEBRIS_COLLECT_METAL', 'count' => 30000000000000, 'statusField' => 'count'), + array('type' => 'DEBRIS_COLLECT_CRYSTAL', 'count' => 15000000000000, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 500000000000, 'cry' => 500000000000) + ) + ), + 59 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_COLLECT_METAL|BATTLE_COLLECT_CRYSTAL|BATTLE_COLLECT_DEUTERIUM', + 'jobs' => array + ( + array('type' => 'BATTLE_COLLECT_METAL', 'count' => 100000000000, 'statusField' => 'count'), + array('type' => 'BATTLE_COLLECT_CRYSTAL', 'count' => 100000000000, 'statusField' => 'count'), + array('type' => 'BATTLE_COLLECT_DEUTERIUM', 'count' => 100000000000, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 5000000000) + ) + ), + 60 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_COLLECT_METAL|BATTLE_COLLECT_CRYSTAL|BATTLE_COLLECT_DEUTERIUM', + 'jobs' => array + ( + array('type' => 'BATTLE_COLLECT_METAL', 'count' => 500000000000, 'statusField' => 'count'), + array('type' => 'BATTLE_COLLECT_CRYSTAL', 'count' => 500000000000, 'statusField' => 'count'), + array('type' => 'BATTLE_COLLECT_DEUTERIUM', 'count' => 500000000000, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 20000000000) + ) + ), + 61 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_COLLECT_METAL|BATTLE_COLLECT_CRYSTAL|BATTLE_COLLECT_DEUTERIUM', + 'jobs' => array + ( + array('type' => 'BATTLE_COLLECT_METAL', 'count' => 1000000000000, 'statusField' => 'count'), + array('type' => 'BATTLE_COLLECT_CRYSTAL', 'count' => 1000000000000, 'statusField' => 'count'), + array('type' => 'BATTLE_COLLECT_DEUTERIUM', 'count' => 1000000000000, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 40000000000) + ) + ), + 62 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE_MULTIID', + 'jobs' => array + ( + array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE_MULTIID', 'elementIDs' => array(204, 205), 'count' => 1000000000, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 90000000000, 'cry' => 30000000000) + ) + ), + 63 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CONSTRUCT_SHIPS_OR_DEFENSE_MULTIID', + 'jobs' => array + ( + array('type' => 'CONSTRUCT_SHIPS_OR_DEFENSE_MULTIID', 'elementIDs' => array(204, 205), 'count' => 10000000000, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 1000000000000, 'cry' => 350000000000) + ) + ), + ), + ), + 3 => array + ( + 'requirements' => array(), + 'skip' => array + ( + 'possible' => false, + ), + 'reward' => array(), + 'tasks' => array + ( + 64 => array + ( + 'requirements' => array(), + 'jobtypes' => 'MULTIPLE_CONSTRUCTION_END', + 'jobs' => array + ( + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 1, 'level' => 30, 'count' => 10, 'statusField' => 'count'), + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 2, 'level' => 30, 'count' => 10, 'statusField' => 'count'), + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 3, 'level' => 30, 'count' => 10, 'statusField' => 'count'), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 25000000, 'cry' => 10000000) + ) + ), + 65 => array + ( + 'requirements' => array(), + 'jobtypes' => 'MULTIPLE_CONSTRUCTION_END', + 'jobs' => array + ( + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 1, 'level' => 40, 'count' => 10, 'statusField' => 'count'), + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 2, 'level' => 40, 'count' => 10, 'statusField' => 'count'), + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 3, 'level' => 40, 'count' => 10, 'statusField' => 'count'), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 2000000000, 'cry' => 850000000) + ) + ), + 66 => array + ( + 'requirements' => array(), + 'jobtypes' => 'MULTIPLE_CONSTRUCTION_END', + 'jobs' => array + ( + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 1, 'level' => 50, 'count' => 5, 'statusField' => 'count'), + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 2, 'level' => 50, 'count' => 5, 'statusField' => 'count'), + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 3, 'level' => 50, 'count' => 5, 'statusField' => 'count'), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 60000000000, 'cry' => 28000000000) + ) + ), + 67 => array + ( + 'requirements' => array(), + 'jobtypes' => 'MULTIPLE_CONSTRUCTION_END', + 'jobs' => array + ( + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 1, 'level' => 50, 'count' => 10, 'statusField' => 'count'), + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 2, 'level' => 50, 'count' => 10, 'statusField' => 'count'), + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 3, 'level' => 50, 'count' => 10, 'statusField' => 'count'), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 120000000000, 'cry' => 60000000000) + ) + ), + 68 => array + ( + 'requirements' => array(), + 'jobtypes' => 'REACH_EXTRACTION_LEVEL', + 'jobs' => array + ( + array('type' => 'REACH_EXTRACTION_LEVEL', 'buildingID' => 1, 'resource' => 'metal', 'level' => 45000000), + array('type' => 'REACH_EXTRACTION_LEVEL', 'buildingID' => 2, 'resource' => 'crystal', 'level' => 30000000), + array('type' => 'REACH_EXTRACTION_LEVEL', 'buildingID' => 3, 'resource' => 'deuterium', 'level' => 22000000), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 75000000000, 'cry' => 50000000000, 'deu' => 37000000000) + ) + ), + 69 => array + ( + 'requirements' => array(), + 'jobtypes' => 'MULTIPLE_CONSTRUCTION_END', + 'jobs' => array + ( + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 22, 'level' => 25, 'count' => 5, 'statusField' => 'count'), + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 23, 'level' => 25, 'count' => 5, 'statusField' => 'count'), + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 24, 'level' => 25, 'count' => 5, 'statusField' => 'count'), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 100000000, 'cry' => 50000000) + ) + ), + 70 => array + ( + 'requirements' => array(), + 'jobtypes' => 'REACH_TERRAFORMING_LEVEL', + 'jobs' => array + ( + array('type' => 'REACH_TERRAFORMING_LEVEL', 'fields' => 700), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 200000000, 'deu' => 400000000) + ) + ), + 71 => array + ( + 'requirements' => array(), + 'jobtypes' => 'REACH_TOTAL_EXTRACTION_LEVEL', + 'jobs' => array + ( + array('type' => 'REACH_TOTAL_EXTRACTION_LEVEL', 'buildingID' => 3, 'resource' => 'deuterium', 'level' => 200000000, 'statusField' => 'level'), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 75000000000) + ) + ), + ) + ), + 4 => array + ( + 'requirements' => array(), + 'skip' => array + ( + 'possible' => false, + ), + 'reward' => array(), + 'tasks' => array + ( + 72 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 109, 'level' => 25), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 2000000000) + ) + ), + 73 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 109, 'level' => 30), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 64000000000) + ) + ), + 74 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 110, 'level' => 25), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 5000000000) + ) + ), + 75 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 110, 'level' => 30), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 160000000000) + ) + ), + 76 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 111, 'level' => 25), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 10000000000) + ) + ), + 77 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 111, 'level' => 30), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 320000000000) + ) + ), + 78 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 120, 'level' => 25), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 1000000000) + ) + ), + 79 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 120, 'level' => 30), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 30000000000) + ) + ), + 80 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 120, 'level' => 33), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'met' => 300000000000) + ) + ), + 81 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 121, 'level' => 20), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 50000000) + ) + ), + 82 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 121, 'level' => 25), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 1500000000) + ) + ), + 83 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 121, 'level' => 28), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 15000000000) + ) + ), + 84 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 122, 'level' => 20), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 500000000) + ) + ), + 85 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 122, 'level' => 25), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 15000000000) + ) + ), + 86 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 122, 'level' => 28), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 150000000000) + ) + ), + 87 => array + ( + 'requirements' => array(), + 'jobtypes' => 'RESEARCH_END', + 'jobs' => array + ( + array('type' => 'RESEARCH_END', 'elementID' => 123, 'level' => 9), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 50000000) + ) + ), + 88 => array + ( + 'requirements' => array(), + 'jobtypes' => 'MULTIPLE_CONSTRUCTION_END', + 'jobs' => array + ( + array('type' => 'MULTIPLE_CONSTRUCTION_END', 'elementID' => 31, 'level' => 22, 'count' => 10, 'statusField' => 'count'), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'cry' => 1000000000, 'deu' => 1000000000) + ) + ), + 89 => array + ( + 'requirements' => array(), + 'jobtypes' => 'REACH_TECHPOINTS_LEVEL', + 'jobs' => array + ( + array('type' => 'REACH_TECHPOINTS_LEVEL', 'level' => 5000000, 'statusField' => 'level'), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 5000000) + ) + ), + 90 => array + ( + 'requirements' => array(), + 'jobtypes' => 'REACH_TECHPOINTS_LEVEL', + 'jobs' => array + ( + array('type' => 'REACH_TECHPOINTS_LEVEL', 'level' => 10000000, 'statusField' => 'level'), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 10000000) + ) + ), + 91 => array + ( + 'requirements' => array(), + 'jobtypes' => 'REACH_TECHPOINTS_LEVEL', + 'jobs' => array + ( + array('type' => 'REACH_TECHPOINTS_LEVEL', 'level' => 50000000, 'statusField' => 'level'), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 50000000) + ) + ), + 92 => array + ( + 'requirements' => array(), + 'jobtypes' => 'REACH_TECHPOINTS_LEVEL', + 'jobs' => array + ( + array('type' => 'REACH_TECHPOINTS_LEVEL', 'level' => 200000000, 'statusField' => 'level'), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 200000000) + ) + ), + 93 => array + ( + 'requirements' => array(), + 'jobtypes' => 'REACH_TECHPOINTS_LEVEL', + 'jobs' => array + ( + array('type' => 'REACH_TECHPOINTS_LEVEL', 'level' => 500000000, 'statusField' => 'level'), + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 500000000) + ) + ), + ) + ), + 5 => array + ( + 'requirements' => array(), + 'skip' => array + ( + 'possible' => false, + ), + 'reward' => array(), + 'tasks' => array + ( + 94 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CREATE_MOON_FRIENDLY', + 'jobs' => array + ( + array('type' => 'CREATE_MOON_FRIENDLY', 'count' => 5, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 2500000) + ) + ), + 95 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CREATE_MOON_FRIENDLY', + 'jobs' => array + ( + array('type' => 'CREATE_MOON_FRIENDLY', 'count' => 20, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 7500000) + ) + ), + 96 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CREATE_MOON_FRIENDLY', + 'jobs' => array + ( + array('type' => 'CREATE_MOON_FRIENDLY', 'count' => 50, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 15000000) + ) + ), + 97 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CREATE_MOON_FRIENDLY', + 'jobs' => array + ( + array('type' => 'CREATE_MOON_FRIENDLY', 'count' => 125, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 30000000) + ) + ), + 98 => array + ( + 'requirements' => array(), + 'jobtypes' => 'CREATE_MOON_FRIENDLY', + 'jobs' => array + ( + array('type' => 'CREATE_MOON_FRIENDLY', 'count' => 250, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 50000000) + ) + ), + 99 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WINORDRAW_ACS_LIMIT', + 'jobs' => array + ( + array('type' => 'BATTLE_WINORDRAW_ACS_LIMIT', 'count' => 25, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 10000, 'hasToBeLeader' => true) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 10000000) + ) + ), + 100 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WINORDRAW_ACS_LIMIT', + 'jobs' => array + ( + array('type' => 'BATTLE_WINORDRAW_ACS_LIMIT', 'count' => 50, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 10000, 'hasToBeLeader' => true) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 20000000) + ) + ), + 101 => array + ( + 'requirements' => array(), + 'jobtypes' => 'BATTLE_WINORDRAW_ACS_LIMIT', + 'jobs' => array + ( + array('type' => 'BATTLE_WINORDRAW_ACS_LIMIT', 'count' => 150, 'statusField' => 'count', 'minimalEnemyPercentLimit' => 10000, 'hasToBeLeader' => true) + ), + 'reward' => array + ( + array('type' => 'RESOURCES', 'deu' => 50000000) + ) + ), + ) + ), + 6 => array + ( + 'requirements' => array(), + 'skip' => array + ( + 'possible' => false, + ), + 'reward' => array(), + 'tasks' => array + ( + 102 => array + ( + 'requirements' => array(), + 'jobtypes' => 'NEWUSER_REGISTER', + 'jobs' => array + ( + array('type' => 'NEWUSER_REGISTER', 'count' => 10, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'PREMIUM_RESOURCE', 'value' => 25) + ) + ), + 103 => array + ( + 'requirements' => array(), + 'jobtypes' => 'NEWUSER_REGISTER', + 'jobs' => array + ( + array('type' => 'NEWUSER_REGISTER', 'count' => 20, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'PREMIUM_RESOURCE', 'value' => 25) + ) + ), + 104 => array + ( + 'requirements' => array(), + 'jobtypes' => 'NEWUSER_REGISTER', + 'jobs' => array + ( + array('type' => 'NEWUSER_REGISTER', 'count' => 40, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'PREMIUM_RESOURCE', 'value' => 50) + ) + ), + 105 => array + ( + 'requirements' => array(), + 'jobtypes' => 'INVITEDUSER_BOUGHT_DE', + 'jobs' => array + ( + array('type' => 'INVITEDUSER_BOUGHT_DE', 'count' => 40) + ), + 'reward' => array + ( + array('type' => 'PREMIUM_RESOURCE', 'value' => 10) + ) + ), + 106 => array + ( + 'requirements' => array(), + 'jobtypes' => 'INVITEDUSERS_BOUGHT_DE_USERCOUNT', + 'jobs' => array + ( + array('type' => 'INVITEDUSERS_BOUGHT_DE_USERCOUNT', 'count' => 5, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'PREMIUM_RESOURCE', 'value' => 25) + ) + ), + 107 => array + ( + 'requirements' => array(), + 'jobtypes' => 'INVITEDUSERS_BOUGHT_DE_LIMIT', + 'jobs' => array + ( + array('type' => 'INVITEDUSERS_BOUGHT_DE_LIMIT', 'count' => 400, 'statusField' => 'count') + ), + 'reward' => array + ( + array('type' => 'PREMIUM_RESOURCE', 'value' => 50) + ) + ), + ) + ), + ); + // Last Cat ID: 6 + // Last Task ID: 107 +} + +?> diff --git a/index.php b/index.php index 432505ac9..736b04351 100644 --- a/index.php +++ b/index.php @@ -2,24 +2,24 @@ if(!empty($_GET['r'])) { - $ID = intval($_GET['r']); - if($ID > 0) - { - define('INSIDE', true); + $ID = intval($_GET['r']); + if($ID > 0) + { + define('INSIDE', true); - $_EnginePath = './'; - include($_EnginePath.'includes/constants.php'); - - if($_COOKIE[REFERING_COOKIENAME] <= 0) - { - setcookie(REFERING_COOKIENAME, $ID, time() + (14*24*60*60), '', GAMEURL_DOMAIN); - } - header('Location: reg.php'); - die(); - } + $_EnginePath = './'; + include($_EnginePath.'includes/constants.php'); + + if($_COOKIE[REFERING_COOKIENAME] <= 0) + { + setcookie(REFERING_COOKIENAME, $ID, time() + (14*24*60*60), '', GAMEURL_DOMAIN); + } + header('Location: reg.php'); + die(); + } } header('Location: login.php'); die(); -?> \ No newline at end of file +?> diff --git a/infos.php b/infos.php index 03b9c32d2..94417c531 100644 --- a/infos.php +++ b/infos.php @@ -1,685 +1,685 @@ - 0) - { - $bloc = array(); - $bloc['fleet_setmax'] = $_Lang['fleet_setmax']; - $bloc['fleet_setmin'] = $_Lang['fleet_setmin']; - - $bloc['fleet_id'] = $ShipID; - $bloc['fleet_name'] = $_Lang['tech'][$ShipID]; - $bloc['fleet_max'] = prettyNumber($CurrentPlanet[$_Vars_GameElements[$ShipID]]); - $bloc['fleet_countmax'] = $CurrentPlanet[$_Vars_GameElements[$ShipID]]; - $Result .= parsetemplate($RowsTPL, $bloc); - } - } - if(empty($Result)) - { - return false; - } - return $Result; - } - - function Teleport_MoonsList($CurrentUser, $CurrentPlanet) - { - global $_Vars_GameElements; - - $Query_GetMoons = ''; - $Query_GetMoons .= "SELECT `id`, `galaxy`, `system`, `planet`, `name`, `{$_Vars_GameElements[43]}`, `last_jump_time` FROM {{table}} WHERE "; - $Query_GetMoons .= "`id_owner` = {$CurrentUser['id']} AND `id` != {$CurrentPlanet['id']} AND `planet_type` = 3;"; - $MoonList = doquery($Query_GetMoons, 'planets'); - - if(mysql_num_rows($MoonList) > 0) - { - $TPL_MoonsList = gettemplate('infos_teleport_moonslist'); - $Combo = ''; - - while($CurMoon = mysql_fetch_assoc($MoonList)) - { - if($CurMoon[$_Vars_GameElements[43]] > 0) - { - $RestString = GetNextJumpWaitTime($CurMoon); - if(!empty($RestString['string'])) - { - $RestString['string'] = trim($RestString['string']); - $RestString['string'] = " ({$RestString['string']})"; - } - $Combo .= parsetemplate($TPL_MoonsList, array - ( - 'MoonID' => $CurMoon['id'], - 'Galaxy' => $CurMoon['galaxy'], - 'System' => $CurMoon['system'], - 'Planet' => $CurMoon['planet'], - 'Name' => $CurMoon['name'], - 'TimeString' => $RestString['string'] - )); - } - } - if(!empty($Combo)) - { - return $Combo; - } - } - return false; - } - - function ShowProductionTable($CurrentUser, $CurrentPlanet, $BuildID, $Template) - { - global $_Vars_ResProduction, $_Vars_GameElements, $_Vars_ElementCategories, $_GameConfig, $_EnginePath; - - include($_EnginePath.'includes/functions/GetMissileRange.php'); - - if(!in_array($BuildID, $_Vars_ElementCategories['tech'])) - { - $CurrentLevel = $CurrentPlanet[$_Vars_GameElements[$BuildID]]; - } - else - { - $CurrentLevel = $CurrentUser[$_Vars_GameElements[$BuildID]]; - } - - if($BuildID != 42 AND $BuildID != 117) - { - // Calculate Current Production (on CurrentBuildLevel) - $Now = time(); - - $BuildLevelFactor = 10; - $BuildTemp = $CurrentPlanet['temp_max']; - - $GeoMulti = (($CurrentUser['geologist_time'] > $Now) ? 1.15 : 1); - $EngMulti = (($CurrentUser['engineer_time'] > $Now) ? 1.10 : 1); - - $BuildLevel = ($CurrentLevel > 0) ? $CurrentLevel : 0; - $Prod[1] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['metal']) * $_GameConfig['resource_multiplier'] * $GeoMulti); - $Prod[2] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['crystal']) * $_GameConfig['resource_multiplier'] * $GeoMulti); - if($BuildID != 12) - { - $Prod[3] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['deuterium']) * $_GameConfig['resource_multiplier'] * $GeoMulti); - } - else - { - $Prod[3] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']); - } - - if($BuildID >= 4) - { - $Prod[4] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['energy']) * $EngMulti); - } - else - { - $Prod[4] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['energy'])); - } - - if($BuildID != 12) - { - $ActualNeed = floor($Prod[4]); - $ActualProd = floor($Prod[$BuildID]); - } - else - { - $ActualNeed = floor($Prod[3]); - $ActualProd = floor($Prod[4]); - } - } - - $BuildStartLvl = $CurrentLevel - 3; - if($BuildStartLvl < 0) - { - $BuildStartLvl = 0; - } - $Table = ''; - $BuildEndLevel = $BuildStartLvl + 10; - for($BuildLevel = $BuildStartLvl; $BuildLevel < $BuildEndLevel; $BuildLevel += 1) - { - $bloc = array(); - if($CurrentLevel == $BuildLevel) - { - $bloc['build_lvl'] = "{$BuildLevel}"; - $bloc['IsCurrent'] = ' class="thisLevel"'; - } - else - { - $bloc['build_lvl'] = $BuildLevel; - } - - if($BuildID == 42) - { - if($BuildLevel == 0) - { - $bloc['build_range'] = '0'; - } - else - { - $bloc['build_range'] = prettyNumber(($BuildLevel * $BuildLevel) - 1); - } - } - else if($BuildID == 117) - { - $bloc['build_range'] = GetMissileRange($_User, $BuildLevel); - } - else - { - $Prod[1] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['metal']) * $_GameConfig['resource_multiplier'] * $GeoMulti); - $Prod[2] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['crystal']) * $_GameConfig['resource_multiplier'] * $GeoMulti); - if($BuildID != 12) - { - $Prod[3] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['deuterium']) * $_GameConfig['resource_multiplier'] * $GeoMulti); - } - else - { - $Prod[3] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']); - } - if($BuildID >= 4) - { - $Prod[4] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['energy']) * $EngMulti); - } - else - { - $Prod[4] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['energy'])); - } - - if($BuildID != 12) - { - $bloc['build_prod'] = prettyNumber(floor($Prod[$BuildID])); - $bloc['build_prod_diff'] = prettyColorNumber(floor($Prod[$BuildID] - $ActualProd)); - $bloc['build_need'] = prettyColorNumber(floor($Prod[4])); - $bloc['build_need_diff'] = prettyColorNumber(floor($Prod[4] - $ActualNeed)); - } - else - { - $bloc['build_prod'] = prettyNumber(floor($Prod[4])); - $bloc['build_prod_diff'] = prettyColorNumber(floor($Prod[4] - $ActualProd)); - $bloc['build_need'] = prettyColorNumber(floor($Prod[3])); - $bloc['build_need_diff'] = prettyColorNumber(floor($Prod[3] - $ActualNeed)); - } - } - $Table .= parsetemplate($Template, $bloc); - } - - return $Table; - } - - function RapidFire_Against($BuildID) - { - global $_Lang, $_Vars_CombatData, $TPL_RapidFire_Row; - - $ResultString = ''; - foreach($_Vars_CombatData[$BuildID]['sd'] as $ElementID => $Count) - { - if($Count > 1) - { - $Count = prettyNumber($Count); - $ResultString .= parsetemplate($TPL_RapidFire_Row, array - ( - 'Title' => $_Lang['nfo_rf_again'], - 'ElementID' => $ElementID, - 'ElementName' => $_Lang['tech'][$ElementID], - 'Color' => 'lime', - 'Count' => prettyNumber($Count) - )); - } - } - return $ResultString; - } - - function RapidFire_From($BuildID) - { - global $_Lang, $_Vars_CombatData, $TPL_RapidFire_Row; - - $ResultString = ''; - foreach($_Vars_CombatData as $ShipID => $Data) - { - if(isset($Data['sd'][$BuildID]) && $Data['sd'][$BuildID] > 1) - { - $Data['sd'][$BuildID] = prettyNumber($Data['sd'][$BuildID]); - $ResultString .= parsetemplate($TPL_RapidFire_Row, array - ( - 'Title' => $_Lang['nfo_rf_from'], - 'ElementID' => $ShipID, - 'ElementName' => $_Lang['tech'][$ShipID], - 'Color' => 'red', - 'Count' => prettyNumber($Data['sd'][$BuildID]) - )); - } - } - return $ResultString; - } - // End of Internal functions - - $BuildID = $_GET['gid']; - - includeLang('infos'); - - $GateTPL = ''; - $DestroyTPL = ''; - $TPL_Production_Header = ''; - - $parse = $_Lang; - $parse['Insert_AllowPrettyInputBox'] = ($_User['settings_useprettyinputbox'] == 1 ? 'true' : 'false'); - $parse['skinpath'] = $_SkinPath; - $parse['name'] = $_Lang['info'][$BuildID]['name']; - $parse['image'] = $BuildID; - $parse['description'] = $_Lang['info'][$BuildID]['description']; - $parse['element_typ'] = $_Lang['tech'][0]; - - if($BuildID >= 1 AND $BuildID <= 3) - { - // Mines - $DestroyTPL = gettemplate('info_buildings_destroy'); - if($_Planet['planet_type'] == 1) - { - $PageTPL = gettemplate('info_buildings_table'); - $TPL_Production_Header = gettemplate('infos_production_header_mines'); - $TPL_Production_Rows = gettemplate('infos_production_rows_mines'); - } - else - { - $PageTPL = gettemplate('info_buildings_general'); - } - } - else if($BuildID == 4) - { - // Solar Power Station - $DestroyTPL = gettemplate('info_buildings_destroy'); - if($_Planet['planet_type'] == 1) - { - $PageTPL = gettemplate('info_buildings_table'); - $TPL_Production_Header = gettemplate('infos_production_header_solarplant'); - $TPL_Production_Rows = gettemplate('infos_production_rows_solarplant'); - } - else - { - $PageTPL = gettemplate('info_buildings_general'); - } - } - else if($BuildID == 12) - { - // Fusion Power Station - $DestroyTPL = gettemplate('info_buildings_destroy'); - if($_Planet['planet_type'] == 1) - { - $PageTPL = gettemplate('info_buildings_table'); - $TPL_Production_Header = gettemplate('infos_production_header_fusionplant'); - $TPL_Production_Rows = gettemplate('infos_production_rows_fusionplant'); - } - else - { - $PageTPL = gettemplate('info_buildings_general'); - } - } - else if($BuildID >= 14 AND $BuildID <= 32) - { - // Other Buildings - $PageTPL = gettemplate('info_buildings_general'); - $DestroyTPL = gettemplate('info_buildings_destroy'); - } - else if($BuildID == 33) - { - // Terraformer - $PageTPL = gettemplate('info_buildings_general'); - } - else if($BuildID == 34) - { - // Ally Deposit - $PageTPL = gettemplate('info_buildings_general'); - $DestroyTPL = gettemplate('info_buildings_destroy'); - } - else if($BuildID == 44) - { - // Rocket Silo - $PageTPL = gettemplate('info_buildings_general'); - $Show_DestroyMissiles = true; - $DestroyTPL = gettemplate('info_buildings_destroy'); - } - else if($BuildID == 41) - { - // Moon Station - $PageTPL = gettemplate('info_buildings_general'); - } - else if($BuildID == 42) - { - // Phalanx - if($_Planet['planet_type'] == 3) - { - $PageTPL = gettemplate('info_buildings_table'); - $TPL_Production_Header = gettemplate('infos_production_header_phalanx'); - $TPL_Production_Rows = gettemplate('infos_production_rows_phalanx'); - } - else - { - $PageTPL = gettemplate('info_buildings_general'); - } - $DestroyTPL = gettemplate('info_buildings_destroy'); - } - else if($BuildID == 43) - { - // Teleport - $PageTPL = gettemplate('info_buildings_general'); - $GateTPL = gettemplate('gate_fleet_table'); - $DestroyTPL = gettemplate('info_buildings_destroy'); - } - else if($BuildID == 50) - { - // Quantum Gate - $PageTPL = gettemplate('info_buildings_general'); - if($_Planet['quantumgate'] > 0) - { - if(!$ChronoAppletIncluded) - { - include("{$_EnginePath}/includes/functions/InsertJavaScriptChronoApplet.php"); - $ChronoAppletIncluded = true; - } - $NextUseTimestamp = ($_Planet['quantumgate_lastuse'] + (QUANTUMGATE_INTERVAL_HOURS * TIME_HOUR)) - time(); - if($NextUseTimestamp < 0) - { - $NextUseTimestamp = 0; - } - if($NextUseTimestamp == 0) - { - $QuantumGate .= ''.$_Lang['GateReadyToUse'].''; - } - else - { - $QuantumGate .= InsertJavaScriptChronoApplet('quantum', '0', $NextUseTimestamp); - $QuantumGate .= ''.$_Lang['GateReadyToUseIn'].':
    '.(pretty_time($NextUseTimestamp, true)).''; - } - $parse['AdditionalInfo'] = '
    '.$QuantumGate.'
     '; - } - } - else if(in_array($BuildID, $_Vars_ElementCategories['tech'])) - { - // Technologies - $parse['element_typ'] = $_Lang['tech'][100]; - if($BuildID == 117) - { - $PageTPL = gettemplate('info_buildings_table'); - $TPL_Production_Header = gettemplate('infos_production_header_missiles'); - $TPL_Production_Rows = gettemplate('infos_production_rows_missiles'); - } - else - { - $PageTPL = gettemplate('info_buildings_general'); - } - } - else if(in_array($BuildID, $_Vars_ElementCategories['fleet']) OR in_array($BuildID, $_Vars_ElementCategories['defense'])) - { - // Ships & Defense - $InShips = (in_array($BuildID, $_Vars_ElementCategories['fleet']) ? true : false); - - if($InShips) - { - $PageTPL = gettemplate('info_buildings_fleet'); - $parse['element_typ'] = $_Lang['tech'][200]; - } - else - { - $PageTPL = gettemplate('info_buildings_defense'); - $parse['element_typ'] = $_Lang['tech'][400]; - } - - if($InShips OR !in_array($BuildID, $_Vars_ElementCategories['rockets'])) - { - $TPL_RapidFire_Row = gettemplate('infos_rapidfire_row'); - $parse['rf_info_to'] = RapidFire_Against($BuildID); - $parse['rf_info_fr'] = RapidFire_From($BuildID); - } - - $ThisElement_Hull = ($_Vars_Prices[$BuildID]['metal'] + $_Vars_Prices[$BuildID]['crystal']); - $ThisElement_Sheld = $_Vars_CombatData[$BuildID]['shield']; - $ThisElement_Force = $_Vars_CombatData[$BuildID]['attack']; - - $ThisElement_Modifiers_Hull = (0.1 * $_User[$_Vars_GameElements[111]]); - $ThisElement_Modifiers_Shield = (0.1 * $_User[$_Vars_GameElements[110]]); - $ThisElement_Modifiers_Force = (0.1 * $_User[$_Vars_GameElements[109]]); - if(!empty($_Vars_CombatUpgrades[$BuildID])) - { - foreach($_Vars_CombatUpgrades[$BuildID] as $UpTech => $ReqLevel) - { - $TechAvailable = $_User[$_Vars_GameElements[$UpTech]]; - if($TechAvailable > $ReqLevel) - { - $ThisElement_Modifiers_Force += ($TechAvailable - $ReqLevel) * 0.05; - } - } - } - - $parse['Insert_Hull_Modifier'] = $ThisElement_Modifiers_Hull * 100; - $parse['Insert_Shield_Modifier'] = $ThisElement_Modifiers_Shield * 100; - $parse['Insert_Force_Modifier'] = $ThisElement_Modifiers_Force * 100; - - $parse['Insert_Hull_Base'] = prettyNumber($ThisElement_Hull); - $parse['Insert_Hull_Modified'] = prettyNumber($ThisElement_Hull * (1 + $ThisElement_Modifiers_Hull)); - $parse['Insert_Shield_Base'] = prettyNumber($ThisElement_Sheld); - $parse['Insert_Shield_Modified'] = prettyNumber($ThisElement_Sheld * (1 + $ThisElement_Modifiers_Shield)); - $parse['Insert_Force_Base'] = prettyNumber($ThisElement_Force); - $parse['Insert_Force_Modified'] = prettyNumber($ThisElement_Force * (1 + $ThisElement_Modifiers_Force)); - - if(!empty($_Vars_Prices[$BuildID]['weapons'])) - { - foreach($_Vars_Prices[$BuildID]['weapons'] as $ThisWeaponType) - { - $ThisWeaponString = $_Lang['weaponTypes'][$ThisWeaponType]; - if(!empty($_Vars_CombatUpgrades[$BuildID][$ThisWeaponType])) - { - $ThisWeaponString = ''.$ThisWeaponString.' ('.$_Vars_CombatUpgrades[$BuildID][$ThisWeaponType].')'; - } - - $parse['Insert_WeaponType'][] = $ThisWeaponString; - } - $parse['Insert_WeaponType'] = implode(', ', $parse['Insert_WeaponType']); - } - else - { - $parse['Insert_WeaponType'] = $_Lang['weaponTypes'][0]; - } - - if($InShips) - { - $ThisElement_Storage = $_Vars_Prices[$BuildID]['capacity']; - - $ThisElement_SpeedCalc = GetFleetMaxSpeed(array(), $BuildID, $_User, true); - - $ThisElement_EngineTech = null; - if(isset($ThisElement_SpeedCalc['info'][$BuildID]['engine']['tech'])) - { - $ThisElement_EngineTech = $ThisElement_SpeedCalc['info'][$BuildID]['engine']['tech']; - } - $ThisElement_Modifiers_Speed = 0; - if(!empty($ThisElement_EngineTech)) - { - $ThisElement_Modifiers_Speed = ($_Vars_TechSpeedModifiers[$ThisElement_EngineTech] * $_User[$_Vars_GameElements[$ThisElement_EngineTech]]); - } - - $parse['Insert_Speed_Modifier'] = $ThisElement_Modifiers_Speed * 100; - $parse['Insert_Storage_Base'] = prettyNumber($ThisElement_Storage); - - if(!empty($_Vars_Prices[$BuildID]['engine'])) - { - $EnginesCount = count($_Vars_Prices[$BuildID]['engine']); - $ThisEngineList = $_Vars_Prices[$BuildID]['engine']; - krsort($ThisEngineList); - foreach($ThisEngineList as $EngineID => $EngineData) - { - if($EnginesCount > 1 AND $EngineID == $ThisElement_SpeedCalc['info'][$BuildID]['engine']['engineID']) - { - $ThisSpeed = ''.prettyNumber($EngineData['speed']).''; - $ThisConsumption = ''.prettyNumber($EngineData['consumption']).''; - } - else - { - $ThisSpeed = prettyNumber($EngineData['speed']); - $ThisConsumption = prettyNumber($EngineData['consumption']); - } - $parse['Insert_Speed_Base'][] = $ThisSpeed; - $parse['Insert_Fuel_Base'][] = $ThisConsumption; - } - $parse['Insert_Speed_Base'] = implode(' / ', $parse['Insert_Speed_Base']); - $parse['Insert_Fuel_Base'] = implode(' / ', $parse['Insert_Fuel_Base']); - } - else - { - $parse['Insert_Speed_Base'] = 0; - $parse['Insert_Fuel_Base'] = 0; - } - $parse['Insert_Speed_Modified'] = prettyNumber($ThisElement_SpeedCalc['speed']); - } - } - else - { - message($_Lang['Infos_BadElementID'], $_Lang['nfo_page_title']); - } - - if($TPL_Production_Header != '') - { - $parse['table_head'] = parsetemplate($TPL_Production_Header, $_Lang); - $parse['table_data'] = ShowProductionTable($_User, $_Planet, $BuildID, $TPL_Production_Rows); - } - - $page = parsetemplate($PageTPL, $parse); - - if(!isOnVacation($_User)) - { - // Missile Destroy Function - if(isset($Show_DestroyMissiles)) - { - if($_Planet[$_Vars_GameElements[$BuildID]] > 0) - { - $TPL_DestroyRockets_Body = gettemplate('destroy_rockets_table'); - $TPL_DestroyRockets_Row = gettemplate('destroy_rockets_row'); - $parse['DestroyRockets_Insert_Rows'] = ''; - foreach($_Vars_ElementCategories['rockets'] as $ThisID) - { - $parse['DestroyRockets_ID'] = $ThisID; - $parse['DestroyRockets_Name'] = $_Lang['info'][$ThisID]['name']; - $parse['DestroyRockets_Count'] = $_Planet[$_Vars_GameElements[$ThisID]]; - $parse['DestroyRockets_PrettyCount'] = prettyNumber($_Planet[$_Vars_GameElements[$ThisID]]); - - $parse['DestroyRockets_Insert_Rows'] .= parsetemplate($TPL_DestroyRockets_Row, $parse); - } - - $page .= parsetemplate($TPL_DestroyRockets_Body, $parse); - } - } - - // Teleport Functions - if($GateTPL != '') - { - if($_Planet[$_Vars_GameElements[$BuildID]] > 0) - { - $RestString = GetNextJumpWaitTime($_Planet); - $parse['gate_start_link'] = "[{$_Planet['galaxy']}:{$_Planet['system']}:{$_Planet['planet']}] {$_Planet['name']}"; - if($RestString['value'] != 0) - { - if(!$ChronoAppletIncluded) - { - include("{$_EnginePath}/includes/functions/InsertJavaScriptChronoApplet.php"); - $ChronoAppletIncluded = true; - } - $parse['gate_time_script'] = InsertJavaScriptChronoApplet('Gate', '1', $RestString['value']); - $parse['gate_wait_time'] = $_Lang['gate_nextjump_timer'].'
    '.pretty_time($RestString['value'], true).'
    '; - $parse['PHP_JumpGate_SubmitColor'] = 'orange'; - } - else - { - $parse['PHP_JumpGate_SubmitColor'] = 'lime'; - $parse['gate_time_script'] = ''; - $parse['gate_wait_time'] = ''; - $parse['Gate_HideNextJumpTimer'] = 'style="display: none;"'; - } - $parse['Gate_HideInfoBox'] = 'style="display: none;"'; - - $parse['gate_dest_moons'] = Teleport_MoonsList($_User, $_Planet); - if($parse['gate_dest_moons'] === false) - { - $parse['Gate_HideInfoBox'] = ''; - $parse['Gate_HideSelector'] = 'style="display: none;"'; - $parse['Gate_HideShips'] = 'style="display: none;"'; - $parse['gate_infobox'][] = $_Lang['gate_nomoonswithtp']; - } - - $parse['gate_fleet_rows'] = Teleport_FleetList($_Planet); - if($parse['gate_fleet_rows'] === false) - { - $parse['Gate_HideInfoBox'] = ''; - $parse['Gate_HideShips'] = 'style="display: none;"'; - $parse['gate_infobox'][] = $_Lang['gate_noshipstotp']; - } - - if(!empty($parse['gate_infobox'])) - { - $parse['gate_infobox'] = implode('
    ', $parse['gate_infobox']); - $parse['Gate_HideInfoBox'] = ''; - } - - $page .= parsetemplate($GateTPL, $parse); - } - } - - // Building Destroy Function - if($DestroyTPL != '') - { - if($_Planet[$_Vars_GameElements[$BuildID]] > 0 && (!isset($_Vars_IndestructibleBuildings[$BuildID]) || $_Vars_IndestructibleBuildings[$BuildID] != 1)) - { - $NeededRessources = GetBuildingPrice($_User, $_Planet, $BuildID, true, true); - $DestroyTime = GetBuildingTime($_User, $_Planet, $BuildID) / 2; - $parse['destroyurl'] = 'buildings.php?cmd=destroy&building='.$BuildID; - $parse['levelvalue'] = $_Planet[$_Vars_GameElements[$BuildID]]; - $parse['nfo_metal'] = $_Lang['Metal']; - $parse['nfo_crysta'] = $_Lang['Crystal']; - $parse['nfo_deuter'] = $_Lang['Deuterium']; - $parse['metal'] = prettyNumber($NeededRessources['metal']); - $parse['crystal'] = prettyNumber($NeededRessources['crystal']); - $parse['deuterium'] = prettyNumber($NeededRessources['deuterium']); - if($NeededRessources['metal'] > $_Planet['metal']) - { - $parse['Met_Color'] = 'red'; - } - else - { - $parse['Met_Color'] = 'lime'; - } - if($NeededRessources['crystal'] > $_Planet['crystal']) - { - $parse['Cry_Color'] = 'red'; - } - else - { - $parse['Cry_Color'] = 'lime'; - } - if($NeededRessources['deuterium'] > $_Planet['deuterium']) - { - $parse['Deu_Color'] = 'red'; - } - else - { - $parse['Deu_Color'] = 'lime'; - } - $parse['destroytime'] = pretty_time($DestroyTime); - $page .= parsetemplate($DestroyTPL, $parse); - } - } - } - - display($page, $_Lang['nfo_page_title'], false); - -?> \ No newline at end of file + 0) + { + $bloc = array(); + $bloc['fleet_setmax'] = $_Lang['fleet_setmax']; + $bloc['fleet_setmin'] = $_Lang['fleet_setmin']; + + $bloc['fleet_id'] = $ShipID; + $bloc['fleet_name'] = $_Lang['tech'][$ShipID]; + $bloc['fleet_max'] = prettyNumber($CurrentPlanet[$_Vars_GameElements[$ShipID]]); + $bloc['fleet_countmax'] = $CurrentPlanet[$_Vars_GameElements[$ShipID]]; + $Result .= parsetemplate($RowsTPL, $bloc); + } + } + if(empty($Result)) + { + return false; + } + return $Result; +} + +function Teleport_MoonsList($CurrentUser, $CurrentPlanet) +{ + global $_Vars_GameElements; + + $Query_GetMoons = ''; + $Query_GetMoons .= "SELECT `id`, `galaxy`, `system`, `planet`, `name`, `{$_Vars_GameElements[43]}`, `last_jump_time` FROM {{table}} WHERE "; + $Query_GetMoons .= "`id_owner` = {$CurrentUser['id']} AND `id` != {$CurrentPlanet['id']} AND `planet_type` = 3;"; + $MoonList = doquery($Query_GetMoons, 'planets'); + + if(mysql_num_rows($MoonList) > 0) + { + $TPL_MoonsList = gettemplate('infos_teleport_moonslist'); + $Combo = ''; + + while($CurMoon = mysql_fetch_assoc($MoonList)) + { + if($CurMoon[$_Vars_GameElements[43]] > 0) + { + $RestString = GetNextJumpWaitTime($CurMoon); + if(!empty($RestString['string'])) + { + $RestString['string'] = trim($RestString['string']); + $RestString['string'] = " ({$RestString['string']})"; + } + $Combo .= parsetemplate($TPL_MoonsList, array + ( + 'MoonID' => $CurMoon['id'], + 'Galaxy' => $CurMoon['galaxy'], + 'System' => $CurMoon['system'], + 'Planet' => $CurMoon['planet'], + 'Name' => $CurMoon['name'], + 'TimeString' => $RestString['string'] + )); + } + } + if(!empty($Combo)) + { + return $Combo; + } + } + return false; +} + +function ShowProductionTable($CurrentUser, $CurrentPlanet, $BuildID, $Template) +{ + global $_Vars_ResProduction, $_Vars_GameElements, $_Vars_ElementCategories, $_GameConfig, $_EnginePath; + + include($_EnginePath.'includes/functions/GetMissileRange.php'); + + if(!in_array($BuildID, $_Vars_ElementCategories['tech'])) + { + $CurrentLevel = $CurrentPlanet[$_Vars_GameElements[$BuildID]]; + } + else + { + $CurrentLevel = $CurrentUser[$_Vars_GameElements[$BuildID]]; + } + + if($BuildID != 42 AND $BuildID != 117) + { + // Calculate Current Production (on CurrentBuildLevel) + $Now = time(); + + $BuildLevelFactor = 10; + $BuildTemp = $CurrentPlanet['temp_max']; + + $GeoMulti = (($CurrentUser['geologist_time'] > $Now) ? 1.15 : 1); + $EngMulti = (($CurrentUser['engineer_time'] > $Now) ? 1.10 : 1); + + $BuildLevel = ($CurrentLevel > 0) ? $CurrentLevel : 0; + $Prod[1] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['metal']) * $_GameConfig['resource_multiplier'] * $GeoMulti); + $Prod[2] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['crystal']) * $_GameConfig['resource_multiplier'] * $GeoMulti); + if($BuildID != 12) + { + $Prod[3] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['deuterium']) * $_GameConfig['resource_multiplier'] * $GeoMulti); + } + else + { + $Prod[3] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']); + } + + if($BuildID >= 4) + { + $Prod[4] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['energy']) * $EngMulti); + } + else + { + $Prod[4] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['energy'])); + } + + if($BuildID != 12) + { + $ActualNeed = floor($Prod[4]); + $ActualProd = floor($Prod[$BuildID]); + } + else + { + $ActualNeed = floor($Prod[3]); + $ActualProd = floor($Prod[4]); + } + } + + $BuildStartLvl = $CurrentLevel - 3; + if($BuildStartLvl < 0) + { + $BuildStartLvl = 0; + } + $Table = ''; + $BuildEndLevel = $BuildStartLvl + 10; + for($BuildLevel = $BuildStartLvl; $BuildLevel < $BuildEndLevel; $BuildLevel += 1) + { + $bloc = array(); + if($CurrentLevel == $BuildLevel) + { + $bloc['build_lvl'] = "{$BuildLevel}"; + $bloc['IsCurrent'] = ' class="thisLevel"'; + } + else + { + $bloc['build_lvl'] = $BuildLevel; + } + + if($BuildID == 42) + { + if($BuildLevel == 0) + { + $bloc['build_range'] = '0'; + } + else + { + $bloc['build_range'] = prettyNumber(($BuildLevel * $BuildLevel) - 1); + } + } + else if($BuildID == 117) + { + $bloc['build_range'] = GetMissileRange($_User, $BuildLevel); + } + else + { + $Prod[1] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['metal']) * $_GameConfig['resource_multiplier'] * $GeoMulti); + $Prod[2] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['crystal']) * $_GameConfig['resource_multiplier'] * $GeoMulti); + if($BuildID != 12) + { + $Prod[3] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['deuterium']) * $_GameConfig['resource_multiplier'] * $GeoMulti); + } + else + { + $Prod[3] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['deuterium']) * $_GameConfig['resource_multiplier']); + } + if($BuildID >= 4) + { + $Prod[4] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['energy']) * $EngMulti); + } + else + { + $Prod[4] = floor(eval($_Vars_ResProduction[$BuildID]['formule']['energy'])); + } + + if($BuildID != 12) + { + $bloc['build_prod'] = prettyNumber(floor($Prod[$BuildID])); + $bloc['build_prod_diff'] = prettyColorNumber(floor($Prod[$BuildID] - $ActualProd)); + $bloc['build_need'] = prettyColorNumber(floor($Prod[4])); + $bloc['build_need_diff'] = prettyColorNumber(floor($Prod[4] - $ActualNeed)); + } + else + { + $bloc['build_prod'] = prettyNumber(floor($Prod[4])); + $bloc['build_prod_diff'] = prettyColorNumber(floor($Prod[4] - $ActualProd)); + $bloc['build_need'] = prettyColorNumber(floor($Prod[3])); + $bloc['build_need_diff'] = prettyColorNumber(floor($Prod[3] - $ActualNeed)); + } + } + $Table .= parsetemplate($Template, $bloc); + } + + return $Table; +} + +function RapidFire_Against($BuildID) +{ + global $_Lang, $_Vars_CombatData, $TPL_RapidFire_Row; + + $ResultString = ''; + foreach($_Vars_CombatData[$BuildID]['sd'] as $ElementID => $Count) + { + if($Count > 1) + { + $Count = prettyNumber($Count); + $ResultString .= parsetemplate($TPL_RapidFire_Row, array + ( + 'Title' => $_Lang['nfo_rf_again'], + 'ElementID' => $ElementID, + 'ElementName' => $_Lang['tech'][$ElementID], + 'Color' => 'lime', + 'Count' => prettyNumber($Count) + )); + } + } + return $ResultString; +} + +function RapidFire_From($BuildID) +{ + global $_Lang, $_Vars_CombatData, $TPL_RapidFire_Row; + + $ResultString = ''; + foreach($_Vars_CombatData as $ShipID => $Data) + { + if(isset($Data['sd'][$BuildID]) && $Data['sd'][$BuildID] > 1) + { + $Data['sd'][$BuildID] = prettyNumber($Data['sd'][$BuildID]); + $ResultString .= parsetemplate($TPL_RapidFire_Row, array + ( + 'Title' => $_Lang['nfo_rf_from'], + 'ElementID' => $ShipID, + 'ElementName' => $_Lang['tech'][$ShipID], + 'Color' => 'red', + 'Count' => prettyNumber($Data['sd'][$BuildID]) + )); + } + } + return $ResultString; +} +// End of Internal functions + +$BuildID = $_GET['gid']; + +includeLang('infos'); + +$GateTPL = ''; +$DestroyTPL = ''; +$TPL_Production_Header = ''; + +$parse = $_Lang; +$parse['Insert_AllowPrettyInputBox'] = ($_User['settings_useprettyinputbox'] == 1 ? 'true' : 'false'); +$parse['skinpath'] = $_SkinPath; +$parse['name'] = $_Lang['info'][$BuildID]['name']; +$parse['image'] = $BuildID; +$parse['description'] = $_Lang['info'][$BuildID]['description']; +$parse['element_typ'] = $_Lang['tech'][0]; + +if($BuildID >= 1 AND $BuildID <= 3) +{ + // Mines + $DestroyTPL = gettemplate('info_buildings_destroy'); + if($_Planet['planet_type'] == 1) + { + $PageTPL = gettemplate('info_buildings_table'); + $TPL_Production_Header = gettemplate('infos_production_header_mines'); + $TPL_Production_Rows = gettemplate('infos_production_rows_mines'); + } + else + { + $PageTPL = gettemplate('info_buildings_general'); + } +} +else if($BuildID == 4) +{ + // Solar Power Station + $DestroyTPL = gettemplate('info_buildings_destroy'); + if($_Planet['planet_type'] == 1) + { + $PageTPL = gettemplate('info_buildings_table'); + $TPL_Production_Header = gettemplate('infos_production_header_solarplant'); + $TPL_Production_Rows = gettemplate('infos_production_rows_solarplant'); + } + else + { + $PageTPL = gettemplate('info_buildings_general'); + } +} +else if($BuildID == 12) +{ + // Fusion Power Station + $DestroyTPL = gettemplate('info_buildings_destroy'); + if($_Planet['planet_type'] == 1) + { + $PageTPL = gettemplate('info_buildings_table'); + $TPL_Production_Header = gettemplate('infos_production_header_fusionplant'); + $TPL_Production_Rows = gettemplate('infos_production_rows_fusionplant'); + } + else + { + $PageTPL = gettemplate('info_buildings_general'); + } +} +else if($BuildID >= 14 AND $BuildID <= 32) +{ + // Other Buildings + $PageTPL = gettemplate('info_buildings_general'); + $DestroyTPL = gettemplate('info_buildings_destroy'); +} +else if($BuildID == 33) +{ + // Terraformer + $PageTPL = gettemplate('info_buildings_general'); +} +else if($BuildID == 34) +{ + // Ally Deposit + $PageTPL = gettemplate('info_buildings_general'); + $DestroyTPL = gettemplate('info_buildings_destroy'); +} +else if($BuildID == 44) +{ + // Rocket Silo + $PageTPL = gettemplate('info_buildings_general'); + $Show_DestroyMissiles = true; + $DestroyTPL = gettemplate('info_buildings_destroy'); +} +else if($BuildID == 41) +{ + // Moon Station + $PageTPL = gettemplate('info_buildings_general'); +} +else if($BuildID == 42) +{ + // Phalanx + if($_Planet['planet_type'] == 3) + { + $PageTPL = gettemplate('info_buildings_table'); + $TPL_Production_Header = gettemplate('infos_production_header_phalanx'); + $TPL_Production_Rows = gettemplate('infos_production_rows_phalanx'); + } + else + { + $PageTPL = gettemplate('info_buildings_general'); + } + $DestroyTPL = gettemplate('info_buildings_destroy'); +} +else if($BuildID == 43) +{ + // Teleport + $PageTPL = gettemplate('info_buildings_general'); + $GateTPL = gettemplate('gate_fleet_table'); + $DestroyTPL = gettemplate('info_buildings_destroy'); +} +else if($BuildID == 50) +{ + // Quantum Gate + $PageTPL = gettemplate('info_buildings_general'); + if($_Planet['quantumgate'] > 0) + { + if(!$ChronoAppletIncluded) + { + include("{$_EnginePath}/includes/functions/InsertJavaScriptChronoApplet.php"); + $ChronoAppletIncluded = true; + } + $NextUseTimestamp = ($_Planet['quantumgate_lastuse'] + (QUANTUMGATE_INTERVAL_HOURS * TIME_HOUR)) - time(); + if($NextUseTimestamp < 0) + { + $NextUseTimestamp = 0; + } + if($NextUseTimestamp == 0) + { + $QuantumGate .= ''.$_Lang['GateReadyToUse'].''; + } + else + { + $QuantumGate .= InsertJavaScriptChronoApplet('quantum', '0', $NextUseTimestamp); + $QuantumGate .= ''.$_Lang['GateReadyToUseIn'].':
    '.(pretty_time($NextUseTimestamp, true)).''; + } + $parse['AdditionalInfo'] = '
    '.$QuantumGate.'
     '; + } +} +else if(in_array($BuildID, $_Vars_ElementCategories['tech'])) +{ + // Technologies + $parse['element_typ'] = $_Lang['tech'][100]; + if($BuildID == 117) + { + $PageTPL = gettemplate('info_buildings_table'); + $TPL_Production_Header = gettemplate('infos_production_header_missiles'); + $TPL_Production_Rows = gettemplate('infos_production_rows_missiles'); + } + else + { + $PageTPL = gettemplate('info_buildings_general'); + } +} +else if(in_array($BuildID, $_Vars_ElementCategories['fleet']) OR in_array($BuildID, $_Vars_ElementCategories['defense'])) +{ + // Ships & Defense + $InShips = (in_array($BuildID, $_Vars_ElementCategories['fleet']) ? true : false); + + if($InShips) + { + $PageTPL = gettemplate('info_buildings_fleet'); + $parse['element_typ'] = $_Lang['tech'][200]; + } + else + { + $PageTPL = gettemplate('info_buildings_defense'); + $parse['element_typ'] = $_Lang['tech'][400]; + } + + if($InShips OR !in_array($BuildID, $_Vars_ElementCategories['rockets'])) + { + $TPL_RapidFire_Row = gettemplate('infos_rapidfire_row'); + $parse['rf_info_to'] = RapidFire_Against($BuildID); + $parse['rf_info_fr'] = RapidFire_From($BuildID); + } + + $ThisElement_Hull = ($_Vars_Prices[$BuildID]['metal'] + $_Vars_Prices[$BuildID]['crystal']); + $ThisElement_Sheld = $_Vars_CombatData[$BuildID]['shield']; + $ThisElement_Force = $_Vars_CombatData[$BuildID]['attack']; + + $ThisElement_Modifiers_Hull = (0.1 * $_User[$_Vars_GameElements[111]]); + $ThisElement_Modifiers_Shield = (0.1 * $_User[$_Vars_GameElements[110]]); + $ThisElement_Modifiers_Force = (0.1 * $_User[$_Vars_GameElements[109]]); + if(!empty($_Vars_CombatUpgrades[$BuildID])) + { + foreach($_Vars_CombatUpgrades[$BuildID] as $UpTech => $ReqLevel) + { + $TechAvailable = $_User[$_Vars_GameElements[$UpTech]]; + if($TechAvailable > $ReqLevel) + { + $ThisElement_Modifiers_Force += ($TechAvailable - $ReqLevel) * 0.05; + } + } + } + + $parse['Insert_Hull_Modifier'] = $ThisElement_Modifiers_Hull * 100; + $parse['Insert_Shield_Modifier'] = $ThisElement_Modifiers_Shield * 100; + $parse['Insert_Force_Modifier'] = $ThisElement_Modifiers_Force * 100; + + $parse['Insert_Hull_Base'] = prettyNumber($ThisElement_Hull); + $parse['Insert_Hull_Modified'] = prettyNumber($ThisElement_Hull * (1 + $ThisElement_Modifiers_Hull)); + $parse['Insert_Shield_Base'] = prettyNumber($ThisElement_Sheld); + $parse['Insert_Shield_Modified'] = prettyNumber($ThisElement_Sheld * (1 + $ThisElement_Modifiers_Shield)); + $parse['Insert_Force_Base'] = prettyNumber($ThisElement_Force); + $parse['Insert_Force_Modified'] = prettyNumber($ThisElement_Force * (1 + $ThisElement_Modifiers_Force)); + + if(!empty($_Vars_Prices[$BuildID]['weapons'])) + { + foreach($_Vars_Prices[$BuildID]['weapons'] as $ThisWeaponType) + { + $ThisWeaponString = $_Lang['weaponTypes'][$ThisWeaponType]; + if(!empty($_Vars_CombatUpgrades[$BuildID][$ThisWeaponType])) + { + $ThisWeaponString = ''.$ThisWeaponString.' ('.$_Vars_CombatUpgrades[$BuildID][$ThisWeaponType].')'; + } + + $parse['Insert_WeaponType'][] = $ThisWeaponString; + } + $parse['Insert_WeaponType'] = implode(', ', $parse['Insert_WeaponType']); + } + else + { + $parse['Insert_WeaponType'] = $_Lang['weaponTypes'][0]; + } + + if($InShips) + { + $ThisElement_Storage = $_Vars_Prices[$BuildID]['capacity']; + + $ThisElement_SpeedCalc = GetFleetMaxSpeed(array(), $BuildID, $_User, true); + + $ThisElement_EngineTech = null; + if(isset($ThisElement_SpeedCalc['info'][$BuildID]['engine']['tech'])) + { + $ThisElement_EngineTech = $ThisElement_SpeedCalc['info'][$BuildID]['engine']['tech']; + } + $ThisElement_Modifiers_Speed = 0; + if(!empty($ThisElement_EngineTech)) + { + $ThisElement_Modifiers_Speed = ($_Vars_TechSpeedModifiers[$ThisElement_EngineTech] * $_User[$_Vars_GameElements[$ThisElement_EngineTech]]); + } + + $parse['Insert_Speed_Modifier'] = $ThisElement_Modifiers_Speed * 100; + $parse['Insert_Storage_Base'] = prettyNumber($ThisElement_Storage); + + if(!empty($_Vars_Prices[$BuildID]['engine'])) + { + $EnginesCount = count($_Vars_Prices[$BuildID]['engine']); + $ThisEngineList = $_Vars_Prices[$BuildID]['engine']; + krsort($ThisEngineList); + foreach($ThisEngineList as $EngineID => $EngineData) + { + if($EnginesCount > 1 AND $EngineID == $ThisElement_SpeedCalc['info'][$BuildID]['engine']['engineID']) + { + $ThisSpeed = ''.prettyNumber($EngineData['speed']).''; + $ThisConsumption = ''.prettyNumber($EngineData['consumption']).''; + } + else + { + $ThisSpeed = prettyNumber($EngineData['speed']); + $ThisConsumption = prettyNumber($EngineData['consumption']); + } + $parse['Insert_Speed_Base'][] = $ThisSpeed; + $parse['Insert_Fuel_Base'][] = $ThisConsumption; + } + $parse['Insert_Speed_Base'] = implode(' / ', $parse['Insert_Speed_Base']); + $parse['Insert_Fuel_Base'] = implode(' / ', $parse['Insert_Fuel_Base']); + } + else + { + $parse['Insert_Speed_Base'] = 0; + $parse['Insert_Fuel_Base'] = 0; + } + $parse['Insert_Speed_Modified'] = prettyNumber($ThisElement_SpeedCalc['speed']); + } +} +else +{ + message($_Lang['Infos_BadElementID'], $_Lang['nfo_page_title']); +} + +if($TPL_Production_Header != '') +{ + $parse['table_head'] = parsetemplate($TPL_Production_Header, $_Lang); + $parse['table_data'] = ShowProductionTable($_User, $_Planet, $BuildID, $TPL_Production_Rows); +} + +$page = parsetemplate($PageTPL, $parse); + +if(!isOnVacation($_User)) +{ + // Missile Destroy Function + if(isset($Show_DestroyMissiles)) + { + if($_Planet[$_Vars_GameElements[$BuildID]] > 0) + { + $TPL_DestroyRockets_Body = gettemplate('destroy_rockets_table'); + $TPL_DestroyRockets_Row = gettemplate('destroy_rockets_row'); + $parse['DestroyRockets_Insert_Rows'] = ''; + foreach($_Vars_ElementCategories['rockets'] as $ThisID) + { + $parse['DestroyRockets_ID'] = $ThisID; + $parse['DestroyRockets_Name'] = $_Lang['info'][$ThisID]['name']; + $parse['DestroyRockets_Count'] = $_Planet[$_Vars_GameElements[$ThisID]]; + $parse['DestroyRockets_PrettyCount'] = prettyNumber($_Planet[$_Vars_GameElements[$ThisID]]); + + $parse['DestroyRockets_Insert_Rows'] .= parsetemplate($TPL_DestroyRockets_Row, $parse); + } + + $page .= parsetemplate($TPL_DestroyRockets_Body, $parse); + } + } + + // Teleport Functions + if($GateTPL != '') + { + if($_Planet[$_Vars_GameElements[$BuildID]] > 0) + { + $RestString = GetNextJumpWaitTime($_Planet); + $parse['gate_start_link'] = "[{$_Planet['galaxy']}:{$_Planet['system']}:{$_Planet['planet']}] {$_Planet['name']}"; + if($RestString['value'] != 0) + { + if(!$ChronoAppletIncluded) + { + include("{$_EnginePath}/includes/functions/InsertJavaScriptChronoApplet.php"); + $ChronoAppletIncluded = true; + } + $parse['gate_time_script'] = InsertJavaScriptChronoApplet('Gate', '1', $RestString['value']); + $parse['gate_wait_time'] = $_Lang['gate_nextjump_timer'].'
    '.pretty_time($RestString['value'], true).'
    '; + $parse['PHP_JumpGate_SubmitColor'] = 'orange'; + } + else + { + $parse['PHP_JumpGate_SubmitColor'] = 'lime'; + $parse['gate_time_script'] = ''; + $parse['gate_wait_time'] = ''; + $parse['Gate_HideNextJumpTimer'] = 'style="display: none;"'; + } + $parse['Gate_HideInfoBox'] = 'style="display: none;"'; + + $parse['gate_dest_moons'] = Teleport_MoonsList($_User, $_Planet); + if($parse['gate_dest_moons'] === false) + { + $parse['Gate_HideInfoBox'] = ''; + $parse['Gate_HideSelector'] = 'style="display: none;"'; + $parse['Gate_HideShips'] = 'style="display: none;"'; + $parse['gate_infobox'][] = $_Lang['gate_nomoonswithtp']; + } + + $parse['gate_fleet_rows'] = Teleport_FleetList($_Planet); + if($parse['gate_fleet_rows'] === false) + { + $parse['Gate_HideInfoBox'] = ''; + $parse['Gate_HideShips'] = 'style="display: none;"'; + $parse['gate_infobox'][] = $_Lang['gate_noshipstotp']; + } + + if(!empty($parse['gate_infobox'])) + { + $parse['gate_infobox'] = implode('
    ', $parse['gate_infobox']); + $parse['Gate_HideInfoBox'] = ''; + } + + $page .= parsetemplate($GateTPL, $parse); + } + } + + // Building Destroy Function + if($DestroyTPL != '') + { + if($_Planet[$_Vars_GameElements[$BuildID]] > 0 && (!isset($_Vars_IndestructibleBuildings[$BuildID]) || $_Vars_IndestructibleBuildings[$BuildID] != 1)) + { + $NeededRessources = GetBuildingPrice($_User, $_Planet, $BuildID, true, true); + $DestroyTime = GetBuildingTime($_User, $_Planet, $BuildID) / 2; + $parse['destroyurl'] = 'buildings.php?cmd=destroy&building='.$BuildID; + $parse['levelvalue'] = $_Planet[$_Vars_GameElements[$BuildID]]; + $parse['nfo_metal'] = $_Lang['Metal']; + $parse['nfo_crysta'] = $_Lang['Crystal']; + $parse['nfo_deuter'] = $_Lang['Deuterium']; + $parse['metal'] = prettyNumber($NeededRessources['metal']); + $parse['crystal'] = prettyNumber($NeededRessources['crystal']); + $parse['deuterium'] = prettyNumber($NeededRessources['deuterium']); + if($NeededRessources['metal'] > $_Planet['metal']) + { + $parse['Met_Color'] = 'red'; + } + else + { + $parse['Met_Color'] = 'lime'; + } + if($NeededRessources['crystal'] > $_Planet['crystal']) + { + $parse['Cry_Color'] = 'red'; + } + else + { + $parse['Cry_Color'] = 'lime'; + } + if($NeededRessources['deuterium'] > $_Planet['deuterium']) + { + $parse['Deu_Color'] = 'red'; + } + else + { + $parse['Deu_Color'] = 'lime'; + } + $parse['destroytime'] = pretty_time($DestroyTime); + $page .= parsetemplate($DestroyTPL, $parse); + } + } +} + +display($page, $_Lang['nfo_page_title'], false); + +?> diff --git a/install/index.php b/install/index.php index 1e50e4b80..3cbd8a337 100644 --- a/install/index.php +++ b/install/index.php @@ -1,493 +1,493 @@ - $Value) - { - $_Lang['PHP_RequirementsList'][] = sprintf($_Lang['CheckError_TestRow'], ($Value === true ? 'red' : 'lime'), ($Value === true ? $_Lang['CheckError_Fail'] : $_Lang['CheckError_Success']), $_Lang['Requirements_'.$Key]); - } - $_Lang['PHP_RequirementsList'] = implode('
    ', $_Lang['PHP_RequirementsList']); - $_Lang['PHP_InfoBox_Text'] = sprintf($_Lang['CheckError_Template'], $_Lang['PHP_RequirementsList']); -} -else -{ - $_Lang['PHP_HideInfoBox'] = 'display: none;'; - - if(isset($_POST['install'])) - { - // Check if every needed field is not empty - $_Install_RequiredFields = array - ( - 'set_dbconfig_host', 'set_dbconfig_user', 'set_dbconfig_name', 'set_const_domain', - 'set_admin_username', 'set_admin_password', 'set_admin_email', - 'set_uni_gamename', 'set_uni_gamespeed', 'set_uni_fleetspeed', 'set_uni_resourcespeed', 'set_uni_motherfields', - 'set_uni_fleetdebris', 'set_uni_defensedebris', 'set_uni_missiledebris', - ); - - foreach($_POST as $key => $value) - { - $_Lang[$key] = $value; - } - if(isset($_POST['set_const_recaptcha_enable']) && $_POST['set_const_recaptcha_enable'] == 'on') - { - $_Lang['set_const_recaptcha_enable'] = 'checked'; - } - if(isset($_POST['set_uni_mailactivationneeded']) && $_POST['set_uni_mailactivationneeded'] == 'on') - { - $_Lang['set_uni_mailactivationneeded'] = 'checked'; - } - if(isset($_POST['set_uni_telemetryenable']) && $_POST['set_uni_telemetryenable'] == 'on') - { - $_Lang['set_uni_telemetryenable'] = 'checked'; - } - if(isset($_POST['set_uni_noobprt_enable']) && $_POST['set_uni_noobprt_enable'] == 'on') - { - $_Lang['set_uni_noobprt_enable'] = 'checked'; - } - if(isset($_POST['set_uni_antifarmenable']) && $_POST['set_uni_antifarmenable'] == 'on') - { - $_Lang['set_uni_antifarmenable'] = 'checked'; - } - if(isset($_POST['set_uni_antibashenable']) && $_POST['set_uni_antibashenable'] == 'on') - { - $_Lang['set_uni_antibashenable'] = 'checked'; - } - - if(function_exists('apc_fetch')) - { - $_Install_RequiredFields[] = 'set_const_uniid'; - } - if(isset($_POST['set_const_recaptcha_enable']) && $_POST['set_const_recaptcha_enable'] == 'on') - { - $_Install_RequiredFields[] = 'set_const_recaptcha_public'; - $_Install_RequiredFields[] = 'set_const_recaptcha_private'; - } - if(isset($_POST['set_uni_noobprt_enable']) && $_POST['set_uni_noobprt_enable'] == 'on') - { - $_Install_RequiredFields[] = 'set_uni_noobprt_basictime'; - $_Install_RequiredFields[] = 'set_uni_noobprt_basicmultiplier'; - $_Install_RequiredFields[] = 'set_uni_noobprt_remove'; - $_Install_RequiredFields[] = 'set_uni_noobprt_idledays'; - $_Install_RequiredFields[] = 'set_uni_noobprt_firstlogin'; - } - if(isset($_POST['set_uni_antifarmenable']) && $_POST['set_uni_antifarmenable'] == 'on') - { - $_Install_RequiredFields[] = 'set_uni_antifarmratio'; - $_Install_RequiredFields[] = 'set_uni_antifarmtotalcount'; - $_Install_RequiredFields[] = 'set_uni_antifarmplanetcount'; - } - if(isset($_POST['set_uni_antibashenable']) && $_POST['set_uni_antibashenable'] == 'on') - { - $_Install_RequiredFields[] = 'set_uni_antibashinterval'; - $_Install_RequiredFields[] = 'set_uni_antibashtotalcount'; - $_Install_RequiredFields[] = 'set_uni_antibashplanetcount'; - } - - $_Install_CanProceed = true; - foreach($_Install_RequiredFields as $Value) - { - if(!isset($_POST[$Value]) || empty($_POST[$Value])) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_'.$Value] = 'class="redBorder"'; - } - } - - if($_Install_CanProceed) - { - // Check if every given field is correct - $_Install_Vars['set_uni_gamespeed'] = floatval($_POST['set_uni_gamespeed']); - $_Install_Vars['set_uni_fleetspeed'] = floatval($_POST['set_uni_fleetspeed']); - $_Install_Vars['set_uni_resourcespeed'] = round($_POST['set_uni_resourcespeed']); - $_Install_Vars['set_uni_motherfields'] = round($_POST['set_uni_motherfields']); - $_Install_Vars['set_uni_fleetdebris'] = round($_POST['set_uni_fleetdebris']); - $_Install_Vars['set_uni_defensedebris'] = round($_POST['set_uni_defensedebris']); - $_Install_Vars['set_uni_missiledebris'] = round($_POST['set_uni_missiledebris']); - $_Install_Vars['set_uni_noobprt_basictime'] = round($_POST['set_uni_noobprt_basictime']); - $_Install_Vars['set_uni_noobprt_basicmultiplier'] = floatval($_POST['set_uni_noobprt_basicmultiplier']); - $_Install_Vars['set_uni_noobprt_remove'] = round($_POST['set_uni_noobprt_remove']); - $_Install_Vars['set_uni_noobprt_idledays'] = round($_POST['set_uni_noobprt_idledays']); - $_Install_Vars['set_uni_noobprt_firstlogin'] = round($_POST['set_uni_noobprt_firstlogin']); - $_Install_Vars['set_uni_antifarmratio'] = floatval($_POST['set_uni_antifarmratio']); - $_Install_Vars['set_uni_antifarmtotalcount'] = round($_POST['set_uni_antifarmtotalcount']); - $_Install_Vars['set_uni_antifarmplanetcount'] = round($_POST['set_uni_antifarmplanetcount']); - $_Install_Vars['set_uni_antibashinterval'] = round($_POST['set_uni_antibashinterval']); - $_Install_Vars['set_uni_antibashtotalcount'] = round($_POST['set_uni_antibashtotalcount']); - $_Install_Vars['set_uni_antibashplanetcount'] = round($_POST['set_uni_antibashplanetcount']); - - if($_Install_Vars['set_uni_gamespeed'] <= 0) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_gamespeed'] = 'class="redBorder"'; - } - if($_Install_Vars['set_uni_fleetspeed'] <= 0) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_fleetspeed'] = 'class="redBorder"'; - } - if($_Install_Vars['set_uni_resourcespeed'] <= 0) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_resourcespeed'] = 'class="redBorder"'; - } - if($_Install_Vars['set_uni_motherfields'] <= 0) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_motherfields'] = 'class="redBorder"'; - } - if($_Install_Vars['set_uni_fleetdebris'] < 0 || $_Install_Vars['set_uni_fleetdebris'] > 100) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_fleetdebris'] = 'class="redBorder"'; - } - if($_Install_Vars['set_uni_defensedebris'] < 0 || $_Install_Vars['set_uni_defensedebris'] > 100) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_defensedebris'] = 'class="redBorder"'; - } - if($_Install_Vars['set_uni_missiledebris'] < 0 || $_Install_Vars['set_uni_missiledebris'] > 100) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_missiledebris'] = 'class="redBorder"'; - } - if(isset($_POST['set_uni_noobprt_enable']) && $_POST['set_uni_noobprt_enable'] == 'on') - { - if($_Install_Vars['set_uni_noobprt_basictime'] <= 0) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_noobprt_basictime'] = 'class="redBorder"'; - } - if($_Install_Vars['set_uni_noobprt_basicmultiplier'] <= 0) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_noobprt_basicmultiplier'] = 'class="redBorder"'; - } - if($_Install_Vars['set_uni_noobprt_remove'] <= 0) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_noobprt_remove'] = 'class="redBorder"'; - } - if($_Install_Vars['set_uni_noobprt_idledays'] <= 0) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_noobprt_idledays'] = 'class="redBorder"'; - } - if($_Install_Vars['set_uni_noobprt_firstlogin'] < 0) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_noobprt_firstlogin'] = 'class="redBorder"'; - } - } - if(isset($_POST['set_uni_antifarmenable']) && $_POST['set_uni_antifarmenable'] == 'on') - { - if($_Install_Vars['set_uni_antifarmratio'] <= 0) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_antifarmratio'] = 'class="redBorder"'; - } - if($_Install_Vars['set_uni_antifarmtotalcount'] <= 0) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_antifarmtotalcount'] = 'class="redBorder"'; - } - if($_Install_Vars['set_uni_antifarmplanetcount'] <= 0) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_antifarmplanetcount'] = 'class="redBorder"'; - } - } - if(isset($_POST['set_uni_antibashenable']) && $_POST['set_uni_antibashenable'] == 'on') - { - if($_Install_Vars['set_uni_antibashinterval'] <= 0) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_antibashinterval'] = 'class="redBorder"'; - } - if($_Install_Vars['set_uni_antibashtotalcount'] <= 0) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_antibashtotalcount'] = 'class="redBorder"'; - } - if($_Install_Vars['set_uni_antibashplanetcount'] <= 0) - { - $_Install_CanProceed = false; - $_Lang['PHP_BadVal_set_uni_antibashplanetcount'] = 'class="redBorder"'; - } - } - - if($_Install_CanProceed) - { - // Try to establish a connection with DataBase Server - $_Install_DBLink = mysql_connect($_POST['set_dbconfig_host'], $_POST['set_dbconfig_user'], $_POST['set_dbconfig_pass']); - if($_Install_DBLink !== false) - { - // Try to select game DataBase - $_Install_DBSelect = mysql_select_db($_POST['set_dbconfig_name']); - if($_Install_DBSelect) - { - // Try to write all required data to files - $_Install_TPL_Config = array - ( - 'Host' => $_POST['set_dbconfig_host'], - 'Username' => $_POST['set_dbconfig_user'], - 'Password' => $_POST['set_dbconfig_pass'], - 'DBName' => $_POST['set_dbconfig_name'], - 'DBPrefix' => $_POST['set_dbconfig_prefix'].'_', - 'SecretWord' => generateRandomHash(20) - ); - $_Install_TPL_Constants = array - ( - 'UNIID' => $_POST['set_const_uniid'], - 'AdminEmail' => $_POST['set_admin_email'], - 'Domain' => $_POST['set_const_domain'], - 'GenerateSubdomainLink' => (!empty($_POST['set_const_subdomain']) ? ($_POST['set_const_subdomain'].'.'.$_POST['set_const_domain']) : $_POST['set_const_domain']), - 'AutoTool_ZipLog_Hash' => md5($_POST['set_uni_autotoolpass_gziplog']), - 'AutoTool_StatBuilder_Hash' => md5($_POST['set_uni_autotoolpass_statbuilder']), - 'AutoTool_GC_Hash' => md5($_POST['set_uni_autotoolpass_gc']), - 'GameName' => $_POST['set_uni_gamename'], - 'Reg_RequireEmailConfirm' => (isset($_POST['set_uni_mailactivationneeded']) && $_POST['set_uni_mailactivationneeded'] == 'on' ? 'true' : 'false'), - 'Reg_RecaptchaEnabled' => (isset($_POST['set_const_recaptcha_enable']) && $_POST['set_const_recaptcha_enable'] == 'on' ? 'true' : 'false'), - 'Reg_Recaptcha_Private' => $_POST['set_const_recaptcha_private'], - 'Reg_Recaptcha_Public' => $_POST['set_const_recaptcha_public'], - 'InsertServerMainOpenTime' => time() - ); - $_Install_RegisterJS = array('ReplaceDomain' => $_POST['set_const_domain']); - - $_Install_CreateConfig = parseFile('install_filetpl_config.tpl', $_Install_TPL_Config); - $_Install_CreateConstants = parseFile('install_filetpl_constants.tpl', $_Install_TPL_Constants); - $_Install_ReplaceRegisterJS = parseFile('../js/register.js', $_Install_RegisterJS); - - $_Install_SaveConfig = file_put_contents('../'.$_Install_ConfigFile.'.php', $_Install_CreateConfig); - $_Install_SaveConstants = file_put_contents('../includes/constants.php', $_Install_CreateConstants); - $_Install_SaveRegisterJS = file_put_contents('../js/register.js', $_Install_ReplaceRegisterJS); - - if($_Install_SaveConfig && $_Install_SaveConstants) - { - if($_Install_SaveRegisterJS) - { - // Now, final try - call every query - $_Install_QueriesData = array - ( - 'prefix' => $_POST['set_dbconfig_prefix'], - 'Config_GameName' => $_POST['set_uni_gamename'], - 'Config_GameSpeed' => $_Install_Vars['set_uni_gamespeed'] * 2500, - 'Config_FleetSpeed' => $_Install_Vars['set_uni_fleetspeed'] * 2500, - 'Config_ResourceSpeed' => $_Install_Vars['set_uni_resourcespeed'], - 'Config_FleetDebris' => $_Install_Vars['set_uni_fleetdebris'], - 'Config_DefenseDebris' => $_Install_Vars['set_uni_defensedebris'], - 'Config_MissileDebris' => $_Install_Vars['set_uni_missiledebris'], - 'Config_InitialFields' => $_Install_Vars['set_uni_motherfields'], - 'Config_CookieName' => preg_replace('/\s+/', '', strtoupper($_POST['set_uni_gamename'])).'_CK', - 'Config_NoobProtection_Enable' => (isset($_POST['set_uni_noobprt_enable']) && $_POST['set_uni_noobprt_enable'] == 'on' ? '1' : '0'), - 'Config_NoobProtection_BasicLimit_Time' => $_Install_Vars['set_uni_noobprt_basictime'], - 'Config_NoobProtection_BasicLimit_Multiplier' => $_Install_Vars['set_uni_noobprt_basicmultiplier'], - 'Config_NoobProtection_ProtectionRemove' => $_Install_Vars['set_uni_noobprt_remove'], - 'Config_NoobProtection_IdleDaysProtection' => $_Install_Vars['set_uni_noobprt_idledays'], - 'Config_NoobProtection_FirstLoginProtection' => $_Install_Vars['set_uni_noobprt_firstlogin'], - 'Config_AntiFarm_Enable' => (isset($_POST['set_uni_antifarmenable']) && $_POST['set_uni_antifarmenable'] == 'on' ? '1' : '0'), - 'Config_AntiFarm_UserStatsRate' => $_Install_Vars['set_uni_antifarmratio'], - 'Config_AntiFarm_CountTotal' => $_Install_Vars['set_uni_antifarmtotalcount'], - 'Config_AntiFarm_CountPlanet' => $_Install_Vars['set_uni_antifarmplanetcount'], - 'Config_BashLimit_Enabled' => (isset($_POST['set_uni_antibashenable']) && $_POST['set_uni_antibashenable'] == 'on' ? '1' : '0'), - 'Config_BashLimit_Interval' => $_Install_Vars['set_uni_antibashinterval'], - 'Config_BashLimit_CountTotal' => $_Install_Vars['set_uni_antibashtotalcount'], - 'Config_BashLimit_CountPlanet' => $_Install_Vars['set_uni_antibashplanetcount'], - 'Config_TelemetryEnabled' => (isset($_POST['set_uni_telemetryenable']) && $_POST['set_uni_telemetryenable'] == 'on' ? '1' : '0'), - 'AdminUser_name' => $_POST['set_admin_username'], - 'AdminUser_passhash' => md5($_POST['set_admin_password']), - 'AdminUser_email' => $_POST['set_admin_email'], - ); - - $_Install_DoQueries = parseFile('install_database.sql', $_Install_QueriesData); - - $_Install_DoQueries = explode('-- --------------------------------------------------------', $_Install_DoQueries); - - foreach($_Install_DoQueries as $ThisQuery) - { - $_Install_QueryResult = mysql_query($ThisQuery); - if($_Install_QueryResult === false) - { - break; - } - } - - if($_Install_QueryResult) - { - $_Lang['PHP_HideInfoBox'] = ''; - $_Lang['PHP_HideFormBox'] = 'display: none;'; - $_Lang['PHP_InfoBox_Color'] = 'lime'; - $_Lang['PHP_InfoBox_Center'] = 'center'; - $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallSuccess']; - - file_put_contents('lock', ''); - } - else - { - $_Lang['PHP_HideInfoBox'] = ''; - $_Lang['PHP_InfoBox_Color'] = 'red'; - $_Lang['PHP_InfoBox_Center'] = 'center'; - $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_QueryFail']; - } - } - else - { - $_Lang['PHP_HideInfoBox'] = ''; - $_Lang['PHP_InfoBox_Color'] = 'red'; - $_Lang['PHP_InfoBox_Center'] = 'center'; - $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_FailToSaveRegister']; - } - } - else - { - $_Lang['PHP_HideInfoBox'] = ''; - $_Lang['PHP_InfoBox_Color'] = 'red'; - $_Lang['PHP_InfoBox_Center'] = 'center'; - if(!$_Install_SaveConfig && !$_Install_SaveConstants) - { - $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_FailToSaveBothFiles']; - } - else if(!$_Install_SaveConfig) - { - $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_FailToSaveConfig']; - } - else - { - $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_FailToSaveConstants']; - } - } - } - else - { - $_Lang['PHP_HideInfoBox'] = ''; - $_Lang['PHP_InfoBox_Color'] = 'red'; - $_Lang['PHP_InfoBox_Center'] = 'center'; - $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_CannotSelectDatabase']; - } - } - else - { - $_Lang['PHP_HideInfoBox'] = ''; - $_Lang['PHP_InfoBox_Color'] = 'red'; - $_Lang['PHP_InfoBox_Center'] = 'center'; - $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_CannotConnectToMySQL']; - } - } - else - { - $_Lang['PHP_HideInfoBox'] = ''; - $_Lang['PHP_InfoBox_Color'] = 'red'; - $_Lang['PHP_InfoBox_Center'] = 'center'; - $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_BadVars']; - } - } - else - { - $_Lang['PHP_HideInfoBox'] = ''; - $_Lang['PHP_InfoBox_Color'] = 'red'; - $_Lang['PHP_InfoBox_Center'] = 'center'; - $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_EmptyFields']; - } - } -} - -display(); - -?> \ No newline at end of file + $Value) + { + $_Lang['PHP_RequirementsList'][] = sprintf($_Lang['CheckError_TestRow'], ($Value === true ? 'red' : 'lime'), ($Value === true ? $_Lang['CheckError_Fail'] : $_Lang['CheckError_Success']), $_Lang['Requirements_'.$Key]); + } + $_Lang['PHP_RequirementsList'] = implode('
    ', $_Lang['PHP_RequirementsList']); + $_Lang['PHP_InfoBox_Text'] = sprintf($_Lang['CheckError_Template'], $_Lang['PHP_RequirementsList']); +} +else +{ + $_Lang['PHP_HideInfoBox'] = 'display: none;'; + + if(isset($_POST['install'])) + { + // Check if every needed field is not empty + $_Install_RequiredFields = array + ( + 'set_dbconfig_host', 'set_dbconfig_user', 'set_dbconfig_name', 'set_const_domain', + 'set_admin_username', 'set_admin_password', 'set_admin_email', + 'set_uni_gamename', 'set_uni_gamespeed', 'set_uni_fleetspeed', 'set_uni_resourcespeed', 'set_uni_motherfields', + 'set_uni_fleetdebris', 'set_uni_defensedebris', 'set_uni_missiledebris', + ); + + foreach($_POST as $key => $value) + { + $_Lang[$key] = $value; + } + if(isset($_POST['set_const_recaptcha_enable']) && $_POST['set_const_recaptcha_enable'] == 'on') + { + $_Lang['set_const_recaptcha_enable'] = 'checked'; + } + if(isset($_POST['set_uni_mailactivationneeded']) && $_POST['set_uni_mailactivationneeded'] == 'on') + { + $_Lang['set_uni_mailactivationneeded'] = 'checked'; + } + if(isset($_POST['set_uni_telemetryenable']) && $_POST['set_uni_telemetryenable'] == 'on') + { + $_Lang['set_uni_telemetryenable'] = 'checked'; + } + if(isset($_POST['set_uni_noobprt_enable']) && $_POST['set_uni_noobprt_enable'] == 'on') + { + $_Lang['set_uni_noobprt_enable'] = 'checked'; + } + if(isset($_POST['set_uni_antifarmenable']) && $_POST['set_uni_antifarmenable'] == 'on') + { + $_Lang['set_uni_antifarmenable'] = 'checked'; + } + if(isset($_POST['set_uni_antibashenable']) && $_POST['set_uni_antibashenable'] == 'on') + { + $_Lang['set_uni_antibashenable'] = 'checked'; + } + + if(function_exists('apc_fetch')) + { + $_Install_RequiredFields[] = 'set_const_uniid'; + } + if(isset($_POST['set_const_recaptcha_enable']) && $_POST['set_const_recaptcha_enable'] == 'on') + { + $_Install_RequiredFields[] = 'set_const_recaptcha_public'; + $_Install_RequiredFields[] = 'set_const_recaptcha_private'; + } + if(isset($_POST['set_uni_noobprt_enable']) && $_POST['set_uni_noobprt_enable'] == 'on') + { + $_Install_RequiredFields[] = 'set_uni_noobprt_basictime'; + $_Install_RequiredFields[] = 'set_uni_noobprt_basicmultiplier'; + $_Install_RequiredFields[] = 'set_uni_noobprt_remove'; + $_Install_RequiredFields[] = 'set_uni_noobprt_idledays'; + $_Install_RequiredFields[] = 'set_uni_noobprt_firstlogin'; + } + if(isset($_POST['set_uni_antifarmenable']) && $_POST['set_uni_antifarmenable'] == 'on') + { + $_Install_RequiredFields[] = 'set_uni_antifarmratio'; + $_Install_RequiredFields[] = 'set_uni_antifarmtotalcount'; + $_Install_RequiredFields[] = 'set_uni_antifarmplanetcount'; + } + if(isset($_POST['set_uni_antibashenable']) && $_POST['set_uni_antibashenable'] == 'on') + { + $_Install_RequiredFields[] = 'set_uni_antibashinterval'; + $_Install_RequiredFields[] = 'set_uni_antibashtotalcount'; + $_Install_RequiredFields[] = 'set_uni_antibashplanetcount'; + } + + $_Install_CanProceed = true; + foreach($_Install_RequiredFields as $Value) + { + if(!isset($_POST[$Value]) || empty($_POST[$Value])) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_'.$Value] = 'class="redBorder"'; + } + } + + if($_Install_CanProceed) + { + // Check if every given field is correct + $_Install_Vars['set_uni_gamespeed'] = floatval($_POST['set_uni_gamespeed']); + $_Install_Vars['set_uni_fleetspeed'] = floatval($_POST['set_uni_fleetspeed']); + $_Install_Vars['set_uni_resourcespeed'] = round($_POST['set_uni_resourcespeed']); + $_Install_Vars['set_uni_motherfields'] = round($_POST['set_uni_motherfields']); + $_Install_Vars['set_uni_fleetdebris'] = round($_POST['set_uni_fleetdebris']); + $_Install_Vars['set_uni_defensedebris'] = round($_POST['set_uni_defensedebris']); + $_Install_Vars['set_uni_missiledebris'] = round($_POST['set_uni_missiledebris']); + $_Install_Vars['set_uni_noobprt_basictime'] = round($_POST['set_uni_noobprt_basictime']); + $_Install_Vars['set_uni_noobprt_basicmultiplier'] = floatval($_POST['set_uni_noobprt_basicmultiplier']); + $_Install_Vars['set_uni_noobprt_remove'] = round($_POST['set_uni_noobprt_remove']); + $_Install_Vars['set_uni_noobprt_idledays'] = round($_POST['set_uni_noobprt_idledays']); + $_Install_Vars['set_uni_noobprt_firstlogin'] = round($_POST['set_uni_noobprt_firstlogin']); + $_Install_Vars['set_uni_antifarmratio'] = floatval($_POST['set_uni_antifarmratio']); + $_Install_Vars['set_uni_antifarmtotalcount'] = round($_POST['set_uni_antifarmtotalcount']); + $_Install_Vars['set_uni_antifarmplanetcount'] = round($_POST['set_uni_antifarmplanetcount']); + $_Install_Vars['set_uni_antibashinterval'] = round($_POST['set_uni_antibashinterval']); + $_Install_Vars['set_uni_antibashtotalcount'] = round($_POST['set_uni_antibashtotalcount']); + $_Install_Vars['set_uni_antibashplanetcount'] = round($_POST['set_uni_antibashplanetcount']); + + if($_Install_Vars['set_uni_gamespeed'] <= 0) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_gamespeed'] = 'class="redBorder"'; + } + if($_Install_Vars['set_uni_fleetspeed'] <= 0) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_fleetspeed'] = 'class="redBorder"'; + } + if($_Install_Vars['set_uni_resourcespeed'] <= 0) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_resourcespeed'] = 'class="redBorder"'; + } + if($_Install_Vars['set_uni_motherfields'] <= 0) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_motherfields'] = 'class="redBorder"'; + } + if($_Install_Vars['set_uni_fleetdebris'] < 0 || $_Install_Vars['set_uni_fleetdebris'] > 100) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_fleetdebris'] = 'class="redBorder"'; + } + if($_Install_Vars['set_uni_defensedebris'] < 0 || $_Install_Vars['set_uni_defensedebris'] > 100) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_defensedebris'] = 'class="redBorder"'; + } + if($_Install_Vars['set_uni_missiledebris'] < 0 || $_Install_Vars['set_uni_missiledebris'] > 100) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_missiledebris'] = 'class="redBorder"'; + } + if(isset($_POST['set_uni_noobprt_enable']) && $_POST['set_uni_noobprt_enable'] == 'on') + { + if($_Install_Vars['set_uni_noobprt_basictime'] <= 0) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_noobprt_basictime'] = 'class="redBorder"'; + } + if($_Install_Vars['set_uni_noobprt_basicmultiplier'] <= 0) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_noobprt_basicmultiplier'] = 'class="redBorder"'; + } + if($_Install_Vars['set_uni_noobprt_remove'] <= 0) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_noobprt_remove'] = 'class="redBorder"'; + } + if($_Install_Vars['set_uni_noobprt_idledays'] <= 0) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_noobprt_idledays'] = 'class="redBorder"'; + } + if($_Install_Vars['set_uni_noobprt_firstlogin'] < 0) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_noobprt_firstlogin'] = 'class="redBorder"'; + } + } + if(isset($_POST['set_uni_antifarmenable']) && $_POST['set_uni_antifarmenable'] == 'on') + { + if($_Install_Vars['set_uni_antifarmratio'] <= 0) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_antifarmratio'] = 'class="redBorder"'; + } + if($_Install_Vars['set_uni_antifarmtotalcount'] <= 0) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_antifarmtotalcount'] = 'class="redBorder"'; + } + if($_Install_Vars['set_uni_antifarmplanetcount'] <= 0) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_antifarmplanetcount'] = 'class="redBorder"'; + } + } + if(isset($_POST['set_uni_antibashenable']) && $_POST['set_uni_antibashenable'] == 'on') + { + if($_Install_Vars['set_uni_antibashinterval'] <= 0) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_antibashinterval'] = 'class="redBorder"'; + } + if($_Install_Vars['set_uni_antibashtotalcount'] <= 0) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_antibashtotalcount'] = 'class="redBorder"'; + } + if($_Install_Vars['set_uni_antibashplanetcount'] <= 0) + { + $_Install_CanProceed = false; + $_Lang['PHP_BadVal_set_uni_antibashplanetcount'] = 'class="redBorder"'; + } + } + + if($_Install_CanProceed) + { + // Try to establish a connection with DataBase Server + $_Install_DBLink = mysql_connect($_POST['set_dbconfig_host'], $_POST['set_dbconfig_user'], $_POST['set_dbconfig_pass']); + if($_Install_DBLink !== false) + { + // Try to select game DataBase + $_Install_DBSelect = mysql_select_db($_POST['set_dbconfig_name']); + if($_Install_DBSelect) + { + // Try to write all required data to files + $_Install_TPL_Config = array + ( + 'Host' => $_POST['set_dbconfig_host'], + 'Username' => $_POST['set_dbconfig_user'], + 'Password' => $_POST['set_dbconfig_pass'], + 'DBName' => $_POST['set_dbconfig_name'], + 'DBPrefix' => $_POST['set_dbconfig_prefix'].'_', + 'SecretWord' => generateRandomHash(20) + ); + $_Install_TPL_Constants = array + ( + 'UNIID' => $_POST['set_const_uniid'], + 'AdminEmail' => $_POST['set_admin_email'], + 'Domain' => $_POST['set_const_domain'], + 'GenerateSubdomainLink' => (!empty($_POST['set_const_subdomain']) ? ($_POST['set_const_subdomain'].'.'.$_POST['set_const_domain']) : $_POST['set_const_domain']), + 'AutoTool_ZipLog_Hash' => md5($_POST['set_uni_autotoolpass_gziplog']), + 'AutoTool_StatBuilder_Hash' => md5($_POST['set_uni_autotoolpass_statbuilder']), + 'AutoTool_GC_Hash' => md5($_POST['set_uni_autotoolpass_gc']), + 'GameName' => $_POST['set_uni_gamename'], + 'Reg_RequireEmailConfirm' => (isset($_POST['set_uni_mailactivationneeded']) && $_POST['set_uni_mailactivationneeded'] == 'on' ? 'true' : 'false'), + 'Reg_RecaptchaEnabled' => (isset($_POST['set_const_recaptcha_enable']) && $_POST['set_const_recaptcha_enable'] == 'on' ? 'true' : 'false'), + 'Reg_Recaptcha_Private' => $_POST['set_const_recaptcha_private'], + 'Reg_Recaptcha_Public' => $_POST['set_const_recaptcha_public'], + 'InsertServerMainOpenTime' => time() + ); + $_Install_RegisterJS = array('ReplaceDomain' => $_POST['set_const_domain']); + + $_Install_CreateConfig = parseFile('install_filetpl_config.tpl', $_Install_TPL_Config); + $_Install_CreateConstants = parseFile('install_filetpl_constants.tpl', $_Install_TPL_Constants); + $_Install_ReplaceRegisterJS = parseFile('../js/register.js', $_Install_RegisterJS); + + $_Install_SaveConfig = file_put_contents('../'.$_Install_ConfigFile.'.php', $_Install_CreateConfig); + $_Install_SaveConstants = file_put_contents('../includes/constants.php', $_Install_CreateConstants); + $_Install_SaveRegisterJS = file_put_contents('../js/register.js', $_Install_ReplaceRegisterJS); + + if($_Install_SaveConfig && $_Install_SaveConstants) + { + if($_Install_SaveRegisterJS) + { + // Now, final try - call every query + $_Install_QueriesData = array + ( + 'prefix' => $_POST['set_dbconfig_prefix'], + 'Config_GameName' => $_POST['set_uni_gamename'], + 'Config_GameSpeed' => $_Install_Vars['set_uni_gamespeed'] * 2500, + 'Config_FleetSpeed' => $_Install_Vars['set_uni_fleetspeed'] * 2500, + 'Config_ResourceSpeed' => $_Install_Vars['set_uni_resourcespeed'], + 'Config_FleetDebris' => $_Install_Vars['set_uni_fleetdebris'], + 'Config_DefenseDebris' => $_Install_Vars['set_uni_defensedebris'], + 'Config_MissileDebris' => $_Install_Vars['set_uni_missiledebris'], + 'Config_InitialFields' => $_Install_Vars['set_uni_motherfields'], + 'Config_CookieName' => preg_replace('/\s+/', '', strtoupper($_POST['set_uni_gamename'])).'_CK', + 'Config_NoobProtection_Enable' => (isset($_POST['set_uni_noobprt_enable']) && $_POST['set_uni_noobprt_enable'] == 'on' ? '1' : '0'), + 'Config_NoobProtection_BasicLimit_Time' => $_Install_Vars['set_uni_noobprt_basictime'], + 'Config_NoobProtection_BasicLimit_Multiplier' => $_Install_Vars['set_uni_noobprt_basicmultiplier'], + 'Config_NoobProtection_ProtectionRemove' => $_Install_Vars['set_uni_noobprt_remove'], + 'Config_NoobProtection_IdleDaysProtection' => $_Install_Vars['set_uni_noobprt_idledays'], + 'Config_NoobProtection_FirstLoginProtection' => $_Install_Vars['set_uni_noobprt_firstlogin'], + 'Config_AntiFarm_Enable' => (isset($_POST['set_uni_antifarmenable']) && $_POST['set_uni_antifarmenable'] == 'on' ? '1' : '0'), + 'Config_AntiFarm_UserStatsRate' => $_Install_Vars['set_uni_antifarmratio'], + 'Config_AntiFarm_CountTotal' => $_Install_Vars['set_uni_antifarmtotalcount'], + 'Config_AntiFarm_CountPlanet' => $_Install_Vars['set_uni_antifarmplanetcount'], + 'Config_BashLimit_Enabled' => (isset($_POST['set_uni_antibashenable']) && $_POST['set_uni_antibashenable'] == 'on' ? '1' : '0'), + 'Config_BashLimit_Interval' => $_Install_Vars['set_uni_antibashinterval'], + 'Config_BashLimit_CountTotal' => $_Install_Vars['set_uni_antibashtotalcount'], + 'Config_BashLimit_CountPlanet' => $_Install_Vars['set_uni_antibashplanetcount'], + 'Config_TelemetryEnabled' => (isset($_POST['set_uni_telemetryenable']) && $_POST['set_uni_telemetryenable'] == 'on' ? '1' : '0'), + 'AdminUser_name' => $_POST['set_admin_username'], + 'AdminUser_passhash' => md5($_POST['set_admin_password']), + 'AdminUser_email' => $_POST['set_admin_email'], + ); + + $_Install_DoQueries = parseFile('install_database.sql', $_Install_QueriesData); + + $_Install_DoQueries = explode('-- --------------------------------------------------------', $_Install_DoQueries); + + foreach($_Install_DoQueries as $ThisQuery) + { + $_Install_QueryResult = mysql_query($ThisQuery); + if($_Install_QueryResult === false) + { + break; + } + } + + if($_Install_QueryResult) + { + $_Lang['PHP_HideInfoBox'] = ''; + $_Lang['PHP_HideFormBox'] = 'display: none;'; + $_Lang['PHP_InfoBox_Color'] = 'lime'; + $_Lang['PHP_InfoBox_Center'] = 'center'; + $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallSuccess']; + + file_put_contents('lock', ''); + } + else + { + $_Lang['PHP_HideInfoBox'] = ''; + $_Lang['PHP_InfoBox_Color'] = 'red'; + $_Lang['PHP_InfoBox_Center'] = 'center'; + $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_QueryFail']; + } + } + else + { + $_Lang['PHP_HideInfoBox'] = ''; + $_Lang['PHP_InfoBox_Color'] = 'red'; + $_Lang['PHP_InfoBox_Center'] = 'center'; + $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_FailToSaveRegister']; + } + } + else + { + $_Lang['PHP_HideInfoBox'] = ''; + $_Lang['PHP_InfoBox_Color'] = 'red'; + $_Lang['PHP_InfoBox_Center'] = 'center'; + if(!$_Install_SaveConfig && !$_Install_SaveConstants) + { + $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_FailToSaveBothFiles']; + } + else if(!$_Install_SaveConfig) + { + $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_FailToSaveConfig']; + } + else + { + $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_FailToSaveConstants']; + } + } + } + else + { + $_Lang['PHP_HideInfoBox'] = ''; + $_Lang['PHP_InfoBox_Color'] = 'red'; + $_Lang['PHP_InfoBox_Center'] = 'center'; + $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_CannotSelectDatabase']; + } + } + else + { + $_Lang['PHP_HideInfoBox'] = ''; + $_Lang['PHP_InfoBox_Color'] = 'red'; + $_Lang['PHP_InfoBox_Center'] = 'center'; + $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_CannotConnectToMySQL']; + } + } + else + { + $_Lang['PHP_HideInfoBox'] = ''; + $_Lang['PHP_InfoBox_Color'] = 'red'; + $_Lang['PHP_InfoBox_Center'] = 'center'; + $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_BadVars']; + } + } + else + { + $_Lang['PHP_HideInfoBox'] = ''; + $_Lang['PHP_InfoBox_Color'] = 'red'; + $_Lang['PHP_InfoBox_Center'] = 'center'; + $_Lang['PHP_InfoBox_Text'] = $_Lang['InstallError_EmptyFields']; + } + } +} + +display(); + +?> diff --git a/install/install_body.tpl b/install/install_body.tpl index 6fd8d4e49..dce98a8e6 100644 --- a/install/install_body.tpl +++ b/install/install_body.tpl @@ -1,317 +1,317 @@ - - - - {PageTitle} - - - - - - - - - -
    - -
    -

    {PageTitle}

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    {LocalhostInfo}
     
    {PHP_InfoBox_Text}
     
    {Install_Info}
    {Header_DBConfig}
    {Label_DBHost} (*){Tip_DBHost}
    {Label_DBUser} (*){Tip_DBUser}
    {Label_DBPass} (*){Tip_DBPass}
    {Label_DBName} (*){Tip_DBName}
    {Label_DBPrefix}{Tip_DBPrefix}
    {Header_Constants}
    {Label_Const_UniID}{Tip_Const_UniID}
    {Label_Const_Domain} (*){Tip_Const_Domain}
    {Label_Const_Subdomain}{Tip_Const_Subdomain}
    {Label_Const_ReCaptcha_Enable}{Tip_Const_ReCaptcha_Enable}
    {Label_Const_ReCaptcha_Public}{Tip_Const_ReCaptcha_Public}
    {Label_Const_ReCaptcha_Private}{Tip_Const_ReCaptcha_Public}
    {Header_AdminUser}
    {Label_Admin_Username} (*){Tip_Admin_Username}
    {Label_Admin_Password} (*){Tip_Admin_Password}
    {Label_Admin_Email} (*){Tip_Admin_Email}
    {Header_UniMain}
    {Label_Uni_GameName} (*){Tip_Uni_GameName}
    {Label_Uni_GameSpeed} (*){Tip_Uni_GameSpeed}
    {Label_Uni_FleetSpeed} (*){Tip_Uni_FleetSpeed}
    {Label_Uni_ResourceSpeed} (*){Tip_Uni_ResourceSpeed}
    {Label_Uni_MotherFields} (*){Tip_Uni_MotherFields}
    {Label_Uni_FleetDebris} (*){Tip_Uni_FleetDebris}
    {Label_Uni_DefenseDebris} (*){Tip_Uni_DefenseDebris}
    {Label_Uni_MissileDebris} (*){Tip_Uni_MissileDebris}
    {Label_Uni_MailActivationNeeded}{Tip_Uni_MailActivationNeeded}
    {Label_Uni_TelemetryEnable}{Tip_Uni_TelemetryEnable}
    {Label_Uni_AutoToolPass_StatBuilder}{Tip_Uni_AutoToolPass_StatBuilder}
    {Label_Uni_AutoToolPass_GarbageCollector}{Tip_Uni_AutoToolPass_GarbageCollector}
    {Label_Uni_AutoToolPass_GZipLog}{Tip_Uni_AutoToolPass_GZipLog}
    {Header_UniProtections}
    {Label_Uni_NoobProtectionEnable}{Tip_Uni_NoobProtectionEnable}
    {Label_Uni_NoobProtectionBasicTimeLimit}{Tip_Uni_NoobProtectionBasicTimeLimit}
    {Label_Uni_NoobProtectionBasicLimitMultiplier}{Tip_Uni_NoobProtectionBasicLimitMultiplier}
    {Label_Uni_NoobProtectionRemove}{Tip_Uni_NoobProtectionRemove}
    {Label_Uni_NoobProtectionIdleDays}{Tip_Uni_NoobProtectionIdleDays}
    {Label_Uni_NoobProtectionFirstLogin}{Tip_Uni_NoobProtectionFirstLogin}
    {Header_UniAntiAbuse}
    {Label_Uni_AntiFarm_Enabled}{Tip_Uni_AntiFarm_Enabled}
    {Label_Uni_AntiFarm_Ratio}{Tip_Uni_AntiFarm_Ratio}
    {Label_Uni_AntiFarm_TotalCount}{Tip_Uni_AntiFarm_TotalCount}
    {Label_Uni_AntiFarm_PlanetCount}{Tip_Uni_AntiFarm_PlanetCount}
    {Label_Uni_AntiBash_Enabled}{Tip_Uni_AntiBash_Enabled}
    {Label_Uni_AntiBash_Interval}{Tip_Uni_AntiBash_Interval}
    {Label_Uni_AntiBash_TotalCount}{Tip_Uni_AntiBash_TotalCount}
    {Label_Uni_AntiBash_PlanetCount}{Tip_Uni_AntiBash_PlanetCount}
    -
    -
    - - \ No newline at end of file + + + + {PageTitle} + + + + + + + + + +
    + +
    +

    {PageTitle}

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    {LocalhostInfo}
     
    {PHP_InfoBox_Text}
     
    {Install_Info}
    {Header_DBConfig}
    {Label_DBHost} (*){Tip_DBHost}
    {Label_DBUser} (*){Tip_DBUser}
    {Label_DBPass} (*){Tip_DBPass}
    {Label_DBName} (*){Tip_DBName}
    {Label_DBPrefix}{Tip_DBPrefix}
    {Header_Constants}
    {Label_Const_UniID}{Tip_Const_UniID}
    {Label_Const_Domain} (*){Tip_Const_Domain}
    {Label_Const_Subdomain}{Tip_Const_Subdomain}
    {Label_Const_ReCaptcha_Enable}{Tip_Const_ReCaptcha_Enable}
    {Label_Const_ReCaptcha_Public}{Tip_Const_ReCaptcha_Public}
    {Label_Const_ReCaptcha_Private}{Tip_Const_ReCaptcha_Public}
    {Header_AdminUser}
    {Label_Admin_Username} (*){Tip_Admin_Username}
    {Label_Admin_Password} (*){Tip_Admin_Password}
    {Label_Admin_Email} (*){Tip_Admin_Email}
    {Header_UniMain}
    {Label_Uni_GameName} (*){Tip_Uni_GameName}
    {Label_Uni_GameSpeed} (*){Tip_Uni_GameSpeed}
    {Label_Uni_FleetSpeed} (*){Tip_Uni_FleetSpeed}
    {Label_Uni_ResourceSpeed} (*){Tip_Uni_ResourceSpeed}
    {Label_Uni_MotherFields} (*){Tip_Uni_MotherFields}
    {Label_Uni_FleetDebris} (*){Tip_Uni_FleetDebris}
    {Label_Uni_DefenseDebris} (*){Tip_Uni_DefenseDebris}
    {Label_Uni_MissileDebris} (*){Tip_Uni_MissileDebris}
    {Label_Uni_MailActivationNeeded}{Tip_Uni_MailActivationNeeded}
    {Label_Uni_TelemetryEnable}{Tip_Uni_TelemetryEnable}
    {Label_Uni_AutoToolPass_StatBuilder}{Tip_Uni_AutoToolPass_StatBuilder}
    {Label_Uni_AutoToolPass_GarbageCollector}{Tip_Uni_AutoToolPass_GarbageCollector}
    {Label_Uni_AutoToolPass_GZipLog}{Tip_Uni_AutoToolPass_GZipLog}
    {Header_UniProtections}
    {Label_Uni_NoobProtectionEnable}{Tip_Uni_NoobProtectionEnable}
    {Label_Uni_NoobProtectionBasicTimeLimit}{Tip_Uni_NoobProtectionBasicTimeLimit}
    {Label_Uni_NoobProtectionBasicLimitMultiplier}{Tip_Uni_NoobProtectionBasicLimitMultiplier}
    {Label_Uni_NoobProtectionRemove}{Tip_Uni_NoobProtectionRemove}
    {Label_Uni_NoobProtectionIdleDays}{Tip_Uni_NoobProtectionIdleDays}
    {Label_Uni_NoobProtectionFirstLogin}{Tip_Uni_NoobProtectionFirstLogin}
    {Header_UniAntiAbuse}
    {Label_Uni_AntiFarm_Enabled}{Tip_Uni_AntiFarm_Enabled}
    {Label_Uni_AntiFarm_Ratio}{Tip_Uni_AntiFarm_Ratio}
    {Label_Uni_AntiFarm_TotalCount}{Tip_Uni_AntiFarm_TotalCount}
    {Label_Uni_AntiFarm_PlanetCount}{Tip_Uni_AntiFarm_PlanetCount}
    {Label_Uni_AntiBash_Enabled}{Tip_Uni_AntiBash_Enabled}
    {Label_Uni_AntiBash_Interval}{Tip_Uni_AntiBash_Interval}
    {Label_Uni_AntiBash_TotalCount}{Tip_Uni_AntiBash_TotalCount}
    {Label_Uni_AntiBash_PlanetCount}{Tip_Uni_AntiBash_PlanetCount}
    +
    +
    + + diff --git a/install/install_filetpl_config.tpl b/install/install_filetpl_config.tpl index b54a807a5..01c8b54d1 100644 --- a/install/install_filetpl_config.tpl +++ b/install/install_filetpl_config.tpl @@ -1,12 +1,12 @@ - '{Host}', - 'user' => '{Username}', - 'pass' => '{Password}', - 'name' => '{DBName}', - 'prefix' => '{DBPrefix}', - 'secretword' => '{SecretWord}' -); -?> \ No newline at end of file + '{Host}', + 'user' => '{Username}', + 'pass' => '{Password}', + 'name' => '{DBName}', + 'prefix' => '{DBPrefix}', + 'secretword' => '{SecretWord}' +); +?> diff --git a/install/install_filetpl_constants.tpl b/install/install_filetpl_constants.tpl index b965c3338..fe8348c17 100644 --- a/install/install_filetpl_constants.tpl +++ b/install/install_filetpl_constants.tpl @@ -1,234 +1,234 @@ - \ No newline at end of file + diff --git a/install/install_functions.php b/install/install_functions.php index 91cdf2930..221eb99c9 100644 --- a/install/install_functions.php +++ b/install/install_functions.php @@ -1,40 +1,40 @@ - \ No newline at end of file + diff --git a/js/admin/index.php b/js/admin/index.php index 58f7bb163..bc99142d1 100644 --- a/js/admin/index.php +++ b/js/admin/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file +?> diff --git a/js/index.php b/js/index.php index 58f7bb163..bc99142d1 100644 --- a/js/index.php +++ b/js/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file +?> diff --git a/js/register.js b/js/register.js index 70390ebdc..b67b5c067 100644 --- a/js/register.js +++ b/js/register.js @@ -209,7 +209,7 @@ function regCallback(ResponseObject) { for(var CookieID in ResponseObject.Cookie) { - $.cookie(ResponseObject.Cookie[CookieID].Name, ResponseObject.Cookie[CookieID].Value, { domain: '.{ReplaceDomain}'}); + $.cookie(ResponseObject.Cookie[CookieID].Name, ResponseObject.Cookie[CookieID].Value, { domain: '.172.19.0.3'}); } } diff --git a/jumpgate.php b/jumpgate.php index 45005a4fe..e0ecb700a 100644 --- a/jumpgate.php +++ b/jumpgate.php @@ -1,121 +1,121 @@ - 0) - { - if($_Planet[$_Vars_GameElements[$ShipID]] > 0) - { - if($ThisCount > $_Planet[$_Vars_GameElements[$ShipID]]) - { - $ThisCount = $_Planet[$_Vars_GameElements[$ShipID]]; - } - $JumpData_Fleet[$ShipID] = $ThisCount; - } - } - } - } - - if(empty($JumpData_Fleet)) - { - ShowMessage($_Lang['GateJump_BadPOSTFound']); - } - - $JumpData_Time = time(); - foreach($JumpData_Fleet as $ShipID => $ShipCount) - { - $_Planet[$_Vars_GameElements[$ShipID]] -= $ShipCount; - $Query_UpdateThis_Fields[] = "`{$_Vars_GameElements[$ShipID]}` = `{$_Vars_GameElements[$ShipID]}` - {$ShipCount}"; - $Query_UpdateTarget_Fields[] = "`{$_Vars_GameElements[$ShipID]}` = `{$_Vars_GameElements[$ShipID]}` + {$ShipCount}"; - } - $Query_UpdateThis_Fields[] = "`last_jump_time` = {$JumpData_Time}"; - $Query_UpdateTarget_Fields[] = "`last_jump_time` = {$JumpData_Time}"; - - $Query_UpdateThis = ''; - $Query_UpdateThis .= "UPDATE {{table}} SET "; - $Query_UpdateThis .= implode(', ', $Query_UpdateThis_Fields); - $Query_UpdateThis .= " WHERE `id` = {$_Planet['id']} LIMIT 1;"; - - $Query_UpdateTarget = ''; - $Query_UpdateTarget .= "UPDATE {{table}} SET "; - $Query_UpdateTarget .= implode(', ', $Query_UpdateTarget_Fields); - $Query_UpdateTarget .= " WHERE `id` = {$Target_ID} LIMIT 1;"; - - $Query_UpdateUser = ''; - $Query_UpdateUser .= "UPDATE {{table}} SET `current_planet` = {$Target_ID} "; - $Query_UpdateUser .= "WHERE `id` = {$_User['id']} LIMIT 1;"; - - $_Planet['last_jump_time'] = $JumpData_Time; - - doquery($Query_UpdateThis, 'planets'); - doquery($Query_UpdateTarget, 'planets'); - if(isset($_POST['changemoon']) && $_POST['changemoon'] == 'on') - { - doquery($Query_UpdateUser, 'users'); - } - - $UserDev_Log[] = array('PlanetID' => $_Planet['id'], 'Date' => $JumpData_Time, 'Place' => 27, 'Code' => 0, 'ElementID' => $Target_ID, 'AdditionalData' => Array2String($JumpData_Fleet)); - - $This_NewJumpState = GetNextJumpWaitTime($_Planet); - ShowMessage("{$_Lang['GateJump_Done']} {$This_NewJumpState['string']}"); - -?> \ No newline at end of file + 0) + { + if($_Planet[$_Vars_GameElements[$ShipID]] > 0) + { + if($ThisCount > $_Planet[$_Vars_GameElements[$ShipID]]) + { + $ThisCount = $_Planet[$_Vars_GameElements[$ShipID]]; + } + $JumpData_Fleet[$ShipID] = $ThisCount; + } + } + } +} + +if(empty($JumpData_Fleet)) +{ + ShowMessage($_Lang['GateJump_BadPOSTFound']); +} + +$JumpData_Time = time(); +foreach($JumpData_Fleet as $ShipID => $ShipCount) +{ + $_Planet[$_Vars_GameElements[$ShipID]] -= $ShipCount; + $Query_UpdateThis_Fields[] = "`{$_Vars_GameElements[$ShipID]}` = `{$_Vars_GameElements[$ShipID]}` - {$ShipCount}"; + $Query_UpdateTarget_Fields[] = "`{$_Vars_GameElements[$ShipID]}` = `{$_Vars_GameElements[$ShipID]}` + {$ShipCount}"; +} +$Query_UpdateThis_Fields[] = "`last_jump_time` = {$JumpData_Time}"; +$Query_UpdateTarget_Fields[] = "`last_jump_time` = {$JumpData_Time}"; + +$Query_UpdateThis = ''; +$Query_UpdateThis .= "UPDATE {{table}} SET "; +$Query_UpdateThis .= implode(', ', $Query_UpdateThis_Fields); +$Query_UpdateThis .= " WHERE `id` = {$_Planet['id']} LIMIT 1;"; + +$Query_UpdateTarget = ''; +$Query_UpdateTarget .= "UPDATE {{table}} SET "; +$Query_UpdateTarget .= implode(', ', $Query_UpdateTarget_Fields); +$Query_UpdateTarget .= " WHERE `id` = {$Target_ID} LIMIT 1;"; + +$Query_UpdateUser = ''; +$Query_UpdateUser .= "UPDATE {{table}} SET `current_planet` = {$Target_ID} "; +$Query_UpdateUser .= "WHERE `id` = {$_User['id']} LIMIT 1;"; + +$_Planet['last_jump_time'] = $JumpData_Time; + +doquery($Query_UpdateThis, 'planets'); +doquery($Query_UpdateTarget, 'planets'); +if(isset($_POST['changemoon']) && $_POST['changemoon'] == 'on') +{ + doquery($Query_UpdateUser, 'users'); +} + +$UserDev_Log[] = array('PlanetID' => $_Planet['id'], 'Date' => $JumpData_Time, 'Place' => 27, 'Code' => 0, 'ElementID' => $Target_ID, 'AdditionalData' => Array2String($JumpData_Fleet)); + +$This_NewJumpState = GetNextJumpWaitTime($_Planet); +ShowMessage("{$_Lang['GateJump_Done']} {$This_NewJumpState['string']}"); + +?> diff --git a/language/en/index.php b/language/en/index.php index ee150fd01..bc99142d1 100644 --- a/language/en/index.php +++ b/language/en/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/language/index.php b/language/index.php index ee150fd01..bc99142d1 100644 --- a/language/index.php +++ b/language/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/language/pl/admin/index.php b/language/pl/admin/index.php index 2c5d40047..bc99142d1 100644 --- a/language/pl/admin/index.php +++ b/language/pl/admin/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/language/pl/index.php b/language/pl/index.php index 2c5d40047..bc99142d1 100644 --- a/language/pl/index.php +++ b/language/pl/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/login.php b/login.php index 23588519a..cbccda7aa 100644 --- a/login.php +++ b/login.php @@ -1,226 +1,226 @@ - $_POST['uniSelect'], - 'username' => $_POST['username'], - 'password' => $_POST['password'], - 'rememberme' => $_POST['rememberme'] - ))); - header("HTTP/1.1 301 Moved Permanently"); - header('Location: http://'.$_POST['uniSelect'].'.'.GAMEURL_DOMAIN.'/login.php?post='.$PostRedirect); - die(); - } - else - { - message($_Lang['Login_BadUniversum'], $_Lang['Err_Title']); - } - } - } - - if(LOCALHOST === FALSE AND TESTSERVER === FALSE) - { - if(time() < SERVER_MAINOPEN_TSTAMP) - { - message(sprintf($_Lang['Login_UniversumNotStarted'], prettyDate('d m Y', SERVER_MAINOPEN_TSTAMP, 1), date('H:i:s', SERVER_MAINOPEN_TSTAMP)), $_Lang['Page_Title']); - } - } - $Username = trim($_POST['username']); - if(preg_match(REGEXP_USERNAME_ABSOLUTE, $Username)) - { - $Search['mode'] = 1; - $Search['where'] = "`username` = '{$Username}'"; - $Search['password'] = md5($_POST['password']); - $Search['IPHash'] = md5($_SERVER['REMOTE_ADDR']); - - $Query_LoginProtection = "SELECT `FailCount` FROM {{table}} WHERE `IP` = '{$Search['IPHash']}' AND `Date` >= (UNIX_TIMESTAMP() - ".LOGINPROTECTION_LOCKTIME.") LIMIT 1;"; - $Result_LoginProtection = doquery($Query_LoginProtection, 'login_protection', true); - if($Result_LoginProtection['FailCount'] >= LOGINPROTECTION_MAXATTEMPTS) - { - $Search['error'] = 5; - $Search['where'] = ''; - } - } - else - { - $Search['error'] = 1; - } - } - elseif(!empty($_COOKIE[$_GameConfig['COOKIE_NAME']])) - { - $explodeCookie = explode('/%/', $_COOKIE[$_GameConfig['COOKIE_NAME']]); - $UserID = intval($explodeCookie[0]); - if($UserID > 0) - { - $Search['mode'] = 2; - $Search['where'] = "`id` = {$UserID}"; - $Search['password'] = $explodeCookie[2]; - } - else - { - $Search['error'] = 2; - } - } - - if(!empty($Search['where'])) - { - $Query_User_Fields = "`id`, `username`, `password`, `isAI`"; - $Query_User_GetData = "SELECT {$Query_User_Fields} FROM {{table}} WHERE {$Search['where']} LIMIT 1;"; - $UserData = doquery($Query_User_GetData, 'users', true); - if($UserData['id'] > 0) - { - include_once($_EnginePath.'/includes/functions/IPandUA_Logger.php'); - if(LOCALHOST) - { - require($_EnginePath.'config.localhost.php'); - } - else if(TESTSERVER) - { - require($_EnginePath.'config.testserver.php'); - } - else - { - require($_EnginePath.'config.php'); - } - $PasswordOK = false; - if($Search['mode'] == 1 AND $UserData['password'] == $Search['password']) - { - $PasswordOK = true; - } - elseif($Search['mode'] == 2 AND md5($UserData['password'].'--'.$__ServerConnectionSettings['secretword']) == $Search['password']) - { - $PasswordOK = true; - } - if($PasswordOK === true) - { - // User is ready to Login - if($Search['mode'] == 1) - { - if($_POST['rememberme'] == 'on') - { - $Cookie_Expire = time() + TIME_YEAR; - $Cookie_Remember = 1; - } - else - { - $Cookie_Expire = 0; - $Cookie_Remember = 0; - } - $Cookie_Set = $UserData['id'].'/%/'.$UserData['username'].'/%/'.md5($UserData['password'].'--'.$__ServerConnectionSettings['secretword']).'/%/'.$Cookie_Remember; - setcookie($_GameConfig['COOKIE_NAME'], $Cookie_Set, $Cookie_Expire, '/', '', false, true); - } - IPandUA_Logger($UserData); - unset($__ServerConnectionSettings); - header("Location: ./overview.php"); - die(); - } - else - { - $Search['error'] = 4; - } - } - else - { - $Search['error'] = 3; - } - } - if(!empty($Search['error'])) - { - if($Search['mode'] == 1 AND !empty($Search['IPHash'])) - { - $Query_UpdateLoginProtection = ''; - $Query_UpdateLoginProtection .= "INSERT INTO {{table}} (`IP`, `Date`, `FailCount`) VALUES ('{$Search['IPHash']}', UNIX_TIMESTAMP(), 1) "; - $Query_UpdateLoginProtection .= "ON DUPLICATE KEY UPDATE "; - $Query_UpdateLoginProtection .= "`FailCount` = IF(`Date` < (UNIX_TIMESTAMP() - ".LOGINPROTECTION_LOCKTIME."), 1, IF(`FailCount` < ".LOGINPROTECTION_MAXATTEMPTS.", `FailCount` + 1, `FailCount`)), "; - $Query_UpdateLoginProtection .= "`Date` = IF(`FailCount` < ".LOGINPROTECTION_MAXATTEMPTS." OR `Date` < (UNIX_TIMESTAMP() - ".LOGINPROTECTION_LOCKTIME."), UNIX_TIMESTAMP(), `Date`);"; - doquery($Query_UpdateLoginProtection, 'login_protection'); - } - - if($UserData['id'] > 0) - { - IPandUA_Logger($UserData, true); - } - if($Search['mode'] == 2) - { - setcookie($_GameConfig['COOKIE_NAME'], false, 0, '/', ''); - } - if($Search['error'] == 1) - { - message($_Lang['Login_BadSignsUser'], $_Lang['Err_Title']); - } - elseif($Search['error'] == 2) - { - message($_Lang['Login_FailCookieUser'], $_Lang['Err_Title']); - } - elseif($Search['error'] == 3 AND $Search['mode'] == 1) - { - message($_Lang['Login_FailUser'], $_Lang['Err_Title']); - } - elseif($Search['error'] == 3 AND $Search['mode'] == 2) - { - message($_Lang['Login_FailCookieUser'], $_Lang['Err_Title']); - } - elseif($Search['error'] == 4 AND $Search['mode'] == 1) - { - message($_Lang['Login_FailPassword'], $_Lang['Err_Title']); - } - elseif($Search['error'] == 4 AND $Search['mode'] == 2) - { - message($_Lang['Login_FailCookiePassword'], $_Lang['Err_Title']); - } - elseif($Search['error'] == 5) - { - message($_Lang['Login_FailLoginProtection'], $_Lang['Err_Title']); - } - else - { - message($_Lang['Login_UnknownError'], $_Lang['Err_Title']); - } - } - - if(!LOGINPAGE_ALLOW_LOGINPHP) - { - if(LOCALHOST === FALSE AND TESTSERVER === FALSE) - { - header("HTTP/1.1 301 Moved Permanently"); - header('Location: '.GAMEURL_STRICT); - die(); - } - } - - $_Lang['PHP_InsertUniCode'] = LOGINPAGE_UNIVERSUMCODE; - if($_GameConfig['game_disable']) - { - $_Lang['type'] = 'button" onclick="alert(\''.str_replace('
    ', "\n", $_GameConfig['close_reason']).'\')'; - $_Lang['LoginButton'] = $_Lang['Body_ServerOffline']; - } - else - { - $_Lang['type'] = 'submit'; - $_Lang['LoginButton'] = $_Lang['Body_Submit']; - } - display(parsetemplate(gettemplate('login_body'), $_Lang), $_Lang['Page_Title']); - -?> \ No newline at end of file + $_POST['uniSelect'], + 'username' => $_POST['username'], + 'password' => $_POST['password'], + 'rememberme' => $_POST['rememberme'] + ))); + header("HTTP/1.1 301 Moved Permanently"); + header('Location: http://'.$_POST['uniSelect'].'.'.GAMEURL_DOMAIN.'/login.php?post='.$PostRedirect); + die(); + } + else + { + message($_Lang['Login_BadUniversum'], $_Lang['Err_Title']); + } + } + } + + if(LOCALHOST === FALSE AND TESTSERVER === FALSE) + { + if(time() < SERVER_MAINOPEN_TSTAMP) + { + message(sprintf($_Lang['Login_UniversumNotStarted'], prettyDate('d m Y', SERVER_MAINOPEN_TSTAMP, 1), date('H:i:s', SERVER_MAINOPEN_TSTAMP)), $_Lang['Page_Title']); + } + } + $Username = trim($_POST['username']); + if(preg_match(REGEXP_USERNAME_ABSOLUTE, $Username)) + { + $Search['mode'] = 1; + $Search['where'] = "`username` = '{$Username}'"; + $Search['password'] = md5($_POST['password']); + $Search['IPHash'] = md5($_SERVER['REMOTE_ADDR']); + + $Query_LoginProtection = "SELECT `FailCount` FROM {{table}} WHERE `IP` = '{$Search['IPHash']}' AND `Date` >= (UNIX_TIMESTAMP() - ".LOGINPROTECTION_LOCKTIME.") LIMIT 1;"; + $Result_LoginProtection = doquery($Query_LoginProtection, 'login_protection', true); + if($Result_LoginProtection['FailCount'] >= LOGINPROTECTION_MAXATTEMPTS) + { + $Search['error'] = 5; + $Search['where'] = ''; + } + } + else + { + $Search['error'] = 1; + } +} +elseif(!empty($_COOKIE[$_GameConfig['COOKIE_NAME']])) +{ + $explodeCookie = explode('/%/', $_COOKIE[$_GameConfig['COOKIE_NAME']]); + $UserID = intval($explodeCookie[0]); + if($UserID > 0) + { + $Search['mode'] = 2; + $Search['where'] = "`id` = {$UserID}"; + $Search['password'] = $explodeCookie[2]; + } + else + { + $Search['error'] = 2; + } +} + +if(!empty($Search['where'])) +{ + $Query_User_Fields = "`id`, `username`, `password`, `isAI`"; + $Query_User_GetData = "SELECT {$Query_User_Fields} FROM {{table}} WHERE {$Search['where']} LIMIT 1;"; + $UserData = doquery($Query_User_GetData, 'users', true); + if($UserData['id'] > 0) + { + include_once($_EnginePath.'/includes/functions/IPandUA_Logger.php'); + if(LOCALHOST) + { + require($_EnginePath.'config.localhost.php'); + } + else if(TESTSERVER) + { + require($_EnginePath.'config.testserver.php'); + } + else + { + require($_EnginePath.'config.php'); + } + $PasswordOK = false; + if($Search['mode'] == 1 AND $UserData['password'] == $Search['password']) + { + $PasswordOK = true; + } + elseif($Search['mode'] == 2 AND md5($UserData['password'].'--'.$__ServerConnectionSettings['secretword']) == $Search['password']) + { + $PasswordOK = true; + } + if($PasswordOK === true) + { + // User is ready to Login + if($Search['mode'] == 1) + { + if($_POST['rememberme'] == 'on') + { + $Cookie_Expire = time() + TIME_YEAR; + $Cookie_Remember = 1; + } + else + { + $Cookie_Expire = 0; + $Cookie_Remember = 0; + } + $Cookie_Set = $UserData['id'].'/%/'.$UserData['username'].'/%/'.md5($UserData['password'].'--'.$__ServerConnectionSettings['secretword']).'/%/'.$Cookie_Remember; + setcookie($_GameConfig['COOKIE_NAME'], $Cookie_Set, $Cookie_Expire, '/', '', false, true); + } + IPandUA_Logger($UserData); + unset($__ServerConnectionSettings); + header("Location: ./overview.php"); + die(); + } + else + { + $Search['error'] = 4; + } + } + else + { + $Search['error'] = 3; + } +} +if(!empty($Search['error'])) +{ + if($Search['mode'] == 1 AND !empty($Search['IPHash'])) + { + $Query_UpdateLoginProtection = ''; + $Query_UpdateLoginProtection .= "INSERT INTO {{table}} (`IP`, `Date`, `FailCount`) VALUES ('{$Search['IPHash']}', UNIX_TIMESTAMP(), 1) "; + $Query_UpdateLoginProtection .= "ON DUPLICATE KEY UPDATE "; + $Query_UpdateLoginProtection .= "`FailCount` = IF(`Date` < (UNIX_TIMESTAMP() - ".LOGINPROTECTION_LOCKTIME."), 1, IF(`FailCount` < ".LOGINPROTECTION_MAXATTEMPTS.", `FailCount` + 1, `FailCount`)), "; + $Query_UpdateLoginProtection .= "`Date` = IF(`FailCount` < ".LOGINPROTECTION_MAXATTEMPTS." OR `Date` < (UNIX_TIMESTAMP() - ".LOGINPROTECTION_LOCKTIME."), UNIX_TIMESTAMP(), `Date`);"; + doquery($Query_UpdateLoginProtection, 'login_protection'); + } + + if($UserData['id'] > 0) + { + IPandUA_Logger($UserData, true); + } + if($Search['mode'] == 2) + { + setcookie($_GameConfig['COOKIE_NAME'], false, 0, '/', ''); + } + if($Search['error'] == 1) + { + message($_Lang['Login_BadSignsUser'], $_Lang['Err_Title']); + } + elseif($Search['error'] == 2) + { + message($_Lang['Login_FailCookieUser'], $_Lang['Err_Title']); + } + elseif($Search['error'] == 3 AND $Search['mode'] == 1) + { + message($_Lang['Login_FailUser'], $_Lang['Err_Title']); + } + elseif($Search['error'] == 3 AND $Search['mode'] == 2) + { + message($_Lang['Login_FailCookieUser'], $_Lang['Err_Title']); + } + elseif($Search['error'] == 4 AND $Search['mode'] == 1) + { + message($_Lang['Login_FailPassword'], $_Lang['Err_Title']); + } + elseif($Search['error'] == 4 AND $Search['mode'] == 2) + { + message($_Lang['Login_FailCookiePassword'], $_Lang['Err_Title']); + } + elseif($Search['error'] == 5) + { + message($_Lang['Login_FailLoginProtection'], $_Lang['Err_Title']); + } + else + { + message($_Lang['Login_UnknownError'], $_Lang['Err_Title']); + } +} + +if(!LOGINPAGE_ALLOW_LOGINPHP) +{ + if(LOCALHOST === FALSE AND TESTSERVER === FALSE) + { + header("HTTP/1.1 301 Moved Permanently"); + header('Location: '.GAMEURL_STRICT); + die(); + } +} + +$_Lang['PHP_InsertUniCode'] = LOGINPAGE_UNIVERSUMCODE; +if($_GameConfig['game_disable']) +{ + $_Lang['type'] = 'button" onclick="alert(\''.str_replace('
    ', "\n", $_GameConfig['close_reason']).'\')'; + $_Lang['LoginButton'] = $_Lang['Body_ServerOffline']; +} +else +{ + $_Lang['type'] = 'submit'; + $_Lang['LoginButton'] = $_Lang['Body_Submit']; +} +display(parsetemplate(gettemplate('login_body'), $_Lang), $_Lang['Page_Title']); + +?> diff --git a/logout.php b/logout.php index 4767a0502..7d84816ad 100644 --- a/logout.php +++ b/logout.php @@ -1,34 +1,34 @@ - \ No newline at end of file + diff --git a/lostcode.php b/lostcode.php index 0ff8b9616..a91391a18 100644 --- a/lostcode.php +++ b/lostcode.php @@ -1,91 +1,92 @@ -'.GAMEURL.'activate.php?code='.$Code.''; - $EMail = parsetemplate($_Lang['mail_template'], $parse); - $Return = SendMail($Mail, $_Lang['mail_title'], $EMail); - - return $Return; - } - - if(isLogged()) - { - message($_Lang['Cannot_usethis_till_logged'], $_Lang['Title_System'], 'overview.php', 3); - } - - if(isset($_POST['email'])) - { - $email = trim($_POST['email']); - if(!empty($email)) - { - if(is_email($email)) - { - $email = mysql_real_escape_string($email); - $Result = doquery("SELECT `id`,`activation_code`, `last_send_activationcode` FROM {{table}} WHERE `email` = '{$email}';", 'users', true); - if($Result) - { - if(!empty($Result['activation_code'])) - { - if(($Result['last_send_activationcode'] + TIME_HOUR) < time()) - { - $NewCode = md5(mt_rand(0, 99999999999)); - $Id = $Result['id']; - - $Result = SendCodeEmail($email, $NewCode); - if($Result === true) - { - doquery("UPDATE {{table}} SET `activation_code` = '{$NewCode}', `last_send_activationcode` = UNIX_TIMESTAMP() WHERE `id` = {$Id}", 'users'); - $Msg = $_Lang['new_code_sent']; - } - else - { - $Msg = sprintf($_Lang['smtp_error'], $Result); - } - } - else - { - $Msg = $_Lang['prevent_spaming']; - } - } - else - { - $Msg = $_Lang['acc_already_activated']; - } - } - else - { - $Msg = $_Lang['no_email_in_db']; - } - } - else - { - $Msg = $_Lang['bad_email_given']; - } - } - else - { - $Msg = $_Lang['no_mail_given']; - } - message($Msg, $_Lang['Title']); - } - else - { - $parse = $_Lang; - $parse['GameURL'] = $_GameConfig['game_name']; - $parse['servername'] = $_GameConfig['game_name']; - display(parsetemplate(gettemplate('lostcode'), $parse), $_Lang['Title'], false); - } -?> \ No newline at end of file +'.GAMEURL.'activate.php?code='.$Code.''; + $EMail = parsetemplate($_Lang['mail_template'], $parse); + $Return = SendMail($Mail, $_Lang['mail_title'], $EMail); + + return $Return; +} + +if(isLogged()) +{ + message($_Lang['Cannot_usethis_till_logged'], $_Lang['Title_System'], 'overview.php', 3); +} + +if(isset($_POST['email'])) +{ + $email = trim($_POST['email']); + if(!empty($email)) + { + if(is_email($email)) + { + $email = mysql_real_escape_string($email); + $Result = doquery("SELECT `id`,`activation_code`, `last_send_activationcode` FROM {{table}} WHERE `email` = '{$email}';", 'users', true); + if($Result) + { + if(!empty($Result['activation_code'])) + { + if(($Result['last_send_activationcode'] + TIME_HOUR) < time()) + { + $NewCode = md5(mt_rand(0, 99999999999)); + $Id = $Result['id']; + + $Result = SendCodeEmail($email, $NewCode); + if($Result === true) + { + doquery("UPDATE {{table}} SET `activation_code` = '{$NewCode}', `last_send_activationcode` = UNIX_TIMESTAMP() WHERE `id` = {$Id}", 'users'); + $Msg = $_Lang['new_code_sent']; + } + else + { + $Msg = sprintf($_Lang['smtp_error'], $Result); + } + } + else + { + $Msg = $_Lang['prevent_spaming']; + } + } + else + { + $Msg = $_Lang['acc_already_activated']; + } + } + else + { + $Msg = $_Lang['no_email_in_db']; + } + } + else + { + $Msg = $_Lang['bad_email_given']; + } + } + else + { + $Msg = $_Lang['no_mail_given']; + } + message($Msg, $_Lang['Title']); +} +else +{ + $parse = $_Lang; + $parse['GameURL'] = $_GameConfig['game_name']; + $parse['servername'] = $_GameConfig['game_name']; + display(parsetemplate(gettemplate('lostcode'), $parse), $_Lang['Title'], false); +} + +?> diff --git a/lostpassword.php b/lostpassword.php index 296bb1b92..8bcf8a23d 100644 --- a/lostpassword.php +++ b/lostpassword.php @@ -1,124 +1,124 @@ -'.GAMEURL.'lostpassword.php?code='.$Code.''; - $parse['newpass'] = $Pass; - $EMail = parsetemplate($_Lang['mail_template'], $parse); - $Return = SendMail($Mail, $_Lang['mail_title'], $EMail); - - return $Return; - } - - if(isLogged()) - { - message($_Lang['Cannot_usethis_till_logged'], $_Lang['Title_System'], 'overview.php', 3); - } - - if(isset($_POST['email'])) - { - $email = trim($_POST['email']); - if(!empty($email)) - { - if(is_email($email)) - { - $email = mysql_real_escape_string($email); - $Result = doquery("SELECT `id`, `username`, `last_send_newpass` FROM {{table}} WHERE `email` = '{$email}';", 'users', true); - if($Result['id'] > 0) - { - if(($Result['last_send_newpass'] + TIME_HOUR) < time()) - { - $Signs = 'abcdefghijklmnoprstuwxyz0123456789'; - $Length = 7; - $Count = strlen($Signs)-1; - - $NewPass = ''; - for($i = 0; $i < $Length; ++$i) - { - $NewPass .= $Signs[mt_rand(0, $Count)]; - } - - $PassActivateLink = md5(mt_rand(0, 99999999999)); - $Id = $Result['id']; - - $Result = SendPassEmail($email, $NewPass, $PassActivateLink); - if($Result === true) - { - doquery("UPDATE {{table}} SET `new_pass` = MD5('{$NewPass}'), `new_pass_code` = '{$PassActivateLink}', `last_send_newpass` = UNIX_TIMESTAMP() WHERE `id` = {$Id}", 'users'); - $Msg = $_Lang['new_pass_sent']; - } - else - { - $Msg = sprintf($_Lang['smtp_error'], $Result); - } - } - else - { - $Msg = $_Lang['prevent_spaming']; - } - } - else - { - $Msg = $_Lang['no_email_in_db']; - } - } - else - { - $Msg = $_Lang['bad_email_given']; - } - } - else - { - $Msg = $_Lang['no_mail_given']; - } - message($Msg, $_Lang['ResetPass']); - } - else if(isset($_GET['code'])) - { - $_GET['code'] = trim($_GET['code']); - if(!empty($_GET['code'])) - { - if(preg_match('/^[0-9a-zA-Z]{32}$/D', $_GET['code'])) - { - $Result = doquery("SELECT `username`, `new_pass` FROM {{table}} WHERE `new_pass_code` = '{$_GET['code']}';", 'users'); - if(mysql_num_rows($Result) > 0) - { - $Result = mysql_fetch_assoc($Result); - $Username = $Result['username']; - $NewPassword = $Result['new_pass']; - doquery("UPDATE {{table}} SET `new_pass_code` = '', `new_pass` = '', `password` = '{$NewPassword}' WHERE `username` = '{$Username}';", 'users'); - $Msg = sprintf($_Lang['resetpass_completed'], $Username); - } - else - { - $Msg = $_Lang['no_code_in_db']; - } - } - else - { - $Msg = $_Lang['invalid_code_format']; - } - message($Msg, $_Lang['ResetPass']); - } - } - else - { - $parse = $_Lang; - $parse['GameURL'] = GAMEURL_STRICT; - $parse['servername'] = $_GameConfig['game_name']; - display(parsetemplate(gettemplate('lostpassword'), $parse), $_Lang['ResetPass'], false); - } - -?> \ No newline at end of file +'.GAMEURL.'lostpassword.php?code='.$Code.''; + $parse['newpass'] = $Pass; + $EMail = parsetemplate($_Lang['mail_template'], $parse); + $Return = SendMail($Mail, $_Lang['mail_title'], $EMail); + + return $Return; +} + +if(isLogged()) +{ + message($_Lang['Cannot_usethis_till_logged'], $_Lang['Title_System'], 'overview.php', 3); +} + +if(isset($_POST['email'])) +{ + $email = trim($_POST['email']); + if(!empty($email)) + { + if(is_email($email)) + { + $email = mysql_real_escape_string($email); + $Result = doquery("SELECT `id`, `username`, `last_send_newpass` FROM {{table}} WHERE `email` = '{$email}';", 'users', true); + if($Result['id'] > 0) + { + if(($Result['last_send_newpass'] + TIME_HOUR) < time()) + { + $Signs = 'abcdefghijklmnoprstuwxyz0123456789'; + $Length = 7; + $Count = strlen($Signs)-1; + + $NewPass = ''; + for($i = 0; $i < $Length; ++$i) + { + $NewPass .= $Signs[mt_rand(0, $Count)]; + } + + $PassActivateLink = md5(mt_rand(0, 99999999999)); + $Id = $Result['id']; + + $Result = SendPassEmail($email, $NewPass, $PassActivateLink); + if($Result === true) + { + doquery("UPDATE {{table}} SET `new_pass` = MD5('{$NewPass}'), `new_pass_code` = '{$PassActivateLink}', `last_send_newpass` = UNIX_TIMESTAMP() WHERE `id` = {$Id}", 'users'); + $Msg = $_Lang['new_pass_sent']; + } + else + { + $Msg = sprintf($_Lang['smtp_error'], $Result); + } + } + else + { + $Msg = $_Lang['prevent_spaming']; + } + } + else + { + $Msg = $_Lang['no_email_in_db']; + } + } + else + { + $Msg = $_Lang['bad_email_given']; + } + } + else + { + $Msg = $_Lang['no_mail_given']; + } + message($Msg, $_Lang['ResetPass']); +} +else if(isset($_GET['code'])) +{ + $_GET['code'] = trim($_GET['code']); + if(!empty($_GET['code'])) + { + if(preg_match('/^[0-9a-zA-Z]{32}$/D', $_GET['code'])) + { + $Result = doquery("SELECT `username`, `new_pass` FROM {{table}} WHERE `new_pass_code` = '{$_GET['code']}';", 'users'); + if(mysql_num_rows($Result) > 0) + { + $Result = mysql_fetch_assoc($Result); + $Username = $Result['username']; + $NewPassword = $Result['new_pass']; + doquery("UPDATE {{table}} SET `new_pass_code` = '', `new_pass` = '', `password` = '{$NewPassword}' WHERE `username` = '{$Username}';", 'users'); + $Msg = sprintf($_Lang['resetpass_completed'], $Username); + } + else + { + $Msg = $_Lang['no_code_in_db']; + } + } + else + { + $Msg = $_Lang['invalid_code_format']; + } + message($Msg, $_Lang['ResetPass']); + } +} +else +{ + $parse = $_Lang; + $parse['GameURL'] = GAMEURL_STRICT; + $parse['servername'] = $_GameConfig['game_name']; + display(parsetemplate(gettemplate('lostpassword'), $parse), $_Lang['ResetPass'], false); +} + +?> diff --git a/merchant.php b/merchant.php index e5d548061..24ee39265 100644 --- a/merchant.php +++ b/merchant.php @@ -1,442 +1,442 @@ - $CurrentPlanet['id'], 'Date' => time(), 'Place' => 23, 'Code' => $_POST['res'], 'ElementID' => $SetElementID, 'AdditionalData' => $AdditionalData); - - if(!isPro()) - { - $CurrentUser['trader_usesCount'] -= 1; - doquery("UPDATE {{table}} SET `trader_usesCount` = `trader_usesCount` - 1 WHERE `id` = {$CurrentUser['id']};", 'users'); - if($CurrentUser['trader_usesCount'] <= 0) - { - header('Location: ?show=ok'); - safeDie(); - } - } - - $parse['TraderMsg_Hide'] = ''; - $parse['TraderMsg_Color'] = 'lime'; - $parse['TraderMsg_Text'] = $_Lang['Trader_Done']; - } - } - } - - $_GET['step'] = 2; - $_GET['mode'] = $_POST['mode']; - $_GET['res'] = $_POST['res']; - } - - if(isset($_GET['step']) && $_GET['step'] == 2) - { - if(!isPro($CurrentUser) AND $CurrentUser['trader_usesCount'] <= 0) - { - message($_Lang['Trader_CantUseTrader'], $_Lang['Trader_Title']); - } - - if(!isset($_GET['mode']) || ($_GET['mode'] != 1 && $_GET['mode'] != 2)) - { - $_GET['mode'] = 1; - } - if(!isset($_GET['res']) || !in_array($_GET['res'], array(1, 2, 3))) - { - $_GET['res'] = 1; - } - - $parse['InsertMainResource'] = $_Lang['MainResource_Mode'.$_GET['mode']]; - $parse['InsertOtherResources'] = $_Lang['OtherResources_Mode'.$_GET['mode']]; - - switch($_GET['res']) - { - case '1': - { - // Metal - $PageTPL = gettemplate('merchant_metal'); - $parse['mod_ma_res_a'] = '2'; - $parse['mod_ma_res_b'] = '4'; - if($_GET['mode'] == 1) - { - $parse['Trader_ModeNRes'] = $_Lang['Trader_SellMet']; - $parse['Trader_NeedOrReceive'] = $_Lang['Trader_Needen']; - $parse['InsertTraderMode'] = '1'; - } - else - { - $parse['Trader_ModeNRes'] = $_Lang['Trader_BuyMet']; - $parse['Trader_NeedOrReceive'] = $_Lang['Trader_Receiving']; - $parse['InsertTraderMode'] = '2'; - } - $parse['Insert_ResM'] = 'met'; - $parse['Insert_ResA'] = 'cry'; - $parse['Insert_ResB'] = 'deu'; - break; - } - case '2': - { - // Crystal - $PageTPL = gettemplate('merchant_crystal'); - $parse['mod_ma_res_a'] = '0.5'; - $parse['mod_ma_res_b'] = '2'; - if($_GET['mode'] == 1) - { - $parse['Trader_ModeNRes'] = $_Lang['Trader_SellCry']; - $parse['Trader_NeedOrReceive'] = $_Lang['Trader_Needen']; - $parse['InsertTraderMode'] = '1'; - } - else - { - $parse['Trader_ModeNRes'] = $_Lang['Trader_BuyCry']; - $parse['Trader_NeedOrReceive'] = $_Lang['Trader_Receiving']; - $parse['InsertTraderMode'] = '2'; - } - $parse['Insert_ResM'] = 'cry'; - $parse['Insert_ResA'] = 'met'; - $parse['Insert_ResB'] = 'deu'; - break; - } - case '3': - { - // Deuterium - $PageTPL = gettemplate('merchant_deuterium'); - $parse['mod_ma_res_a'] = '0.25'; - $parse['mod_ma_res_b'] = '0.5'; - if($_GET['mode'] == 1) - { - $parse['Trader_ModeNRes'] = $_Lang['Trader_SellDeu']; - $parse['Trader_NeedOrReceive'] = $_Lang['Trader_Needen']; - $parse['InsertTraderMode'] = '1'; - } - else - { - $parse['Trader_ModeNRes'] = $_Lang['Trader_BuyDeu']; - $parse['Trader_NeedOrReceive'] = $_Lang['Trader_Receiving']; - $parse['InsertTraderMode'] = '2'; - } - $parse['Insert_ResM'] = 'deu'; - $parse['Insert_ResA'] = 'met'; - $parse['Insert_ResB'] = 'cry'; - break; - } - } - } - else - { - if(isset($_GET['show']) && $_GET['show'] == 'ok') - { - $parse['TraderMsg_Hide'] = ''; - $parse['TraderMsg_Color'] = 'lime'; - $parse['TraderMsg_Text'] = $_Lang['Trader_Done']; - } - else - { - $parse['TraderMsg_Hide'] = 'inv'; - } - - $PageTPL = gettemplate('merchant_main'); - } - - if(!isPro($CurrentUser)) - { - $parse['Insert_TraderRight'] = "{$_Lang['Trader_Uses_BuyMore']}"; - if($CurrentUser['trader_usesCount'] <= 0) - { - $parse['Insert_TraderUsesColor'] = $parse['Insert_AddRed'] = 'red'; - $parse['Insert_TraderRight'] = "{$_Lang['Trader_Uses_BlockedBuy']}"; - } - else if($CurrentUser['trader_usesCount'] < 5) - { - $parse['Insert_TraderUsesColor'] = 'orange'; - } - $parse['Insert_TraderUses'] = prettyNumber($CurrentUser['trader_usesCount']); - } - else - { - $parse['Insert_TraderUsesColor'] = 'lime'; - $parse['Insert_TraderUses'] = $_Lang['Trader_Uses_Infinite']; - $parse['Insert_TraderRight'] = "({$_Lang['Trader_Uses_InStandBy']}: ".prettyNumber($CurrentUser['trader_usesCount']).")"; - } - - $Page = parsetemplate($PageTPL, $parse); - - display($Page, $_Lang['Trader_Title']); - -?> \ No newline at end of file + $CurrentPlanet['id'], 'Date' => time(), 'Place' => 23, 'Code' => $_POST['res'], 'ElementID' => $SetElementID, 'AdditionalData' => $AdditionalData); + + if(!isPro()) + { + $CurrentUser['trader_usesCount'] -= 1; + doquery("UPDATE {{table}} SET `trader_usesCount` = `trader_usesCount` - 1 WHERE `id` = {$CurrentUser['id']};", 'users'); + if($CurrentUser['trader_usesCount'] <= 0) + { + header('Location: ?show=ok'); + safeDie(); + } + } + + $parse['TraderMsg_Hide'] = ''; + $parse['TraderMsg_Color'] = 'lime'; + $parse['TraderMsg_Text'] = $_Lang['Trader_Done']; + } + } + } + + $_GET['step'] = 2; + $_GET['mode'] = $_POST['mode']; + $_GET['res'] = $_POST['res']; +} + +if(isset($_GET['step']) && $_GET['step'] == 2) +{ + if(!isPro($CurrentUser) AND $CurrentUser['trader_usesCount'] <= 0) + { + message($_Lang['Trader_CantUseTrader'], $_Lang['Trader_Title']); + } + + if(!isset($_GET['mode']) || ($_GET['mode'] != 1 && $_GET['mode'] != 2)) + { + $_GET['mode'] = 1; + } + if(!isset($_GET['res']) || !in_array($_GET['res'], array(1, 2, 3))) + { + $_GET['res'] = 1; + } + + $parse['InsertMainResource'] = $_Lang['MainResource_Mode'.$_GET['mode']]; + $parse['InsertOtherResources'] = $_Lang['OtherResources_Mode'.$_GET['mode']]; + + switch($_GET['res']) + { + case '1': + { + // Metal + $PageTPL = gettemplate('merchant_metal'); + $parse['mod_ma_res_a'] = '2'; + $parse['mod_ma_res_b'] = '4'; + if($_GET['mode'] == 1) + { + $parse['Trader_ModeNRes'] = $_Lang['Trader_SellMet']; + $parse['Trader_NeedOrReceive'] = $_Lang['Trader_Needen']; + $parse['InsertTraderMode'] = '1'; + } + else + { + $parse['Trader_ModeNRes'] = $_Lang['Trader_BuyMet']; + $parse['Trader_NeedOrReceive'] = $_Lang['Trader_Receiving']; + $parse['InsertTraderMode'] = '2'; + } + $parse['Insert_ResM'] = 'met'; + $parse['Insert_ResA'] = 'cry'; + $parse['Insert_ResB'] = 'deu'; + break; + } + case '2': + { + // Crystal + $PageTPL = gettemplate('merchant_crystal'); + $parse['mod_ma_res_a'] = '0.5'; + $parse['mod_ma_res_b'] = '2'; + if($_GET['mode'] == 1) + { + $parse['Trader_ModeNRes'] = $_Lang['Trader_SellCry']; + $parse['Trader_NeedOrReceive'] = $_Lang['Trader_Needen']; + $parse['InsertTraderMode'] = '1'; + } + else + { + $parse['Trader_ModeNRes'] = $_Lang['Trader_BuyCry']; + $parse['Trader_NeedOrReceive'] = $_Lang['Trader_Receiving']; + $parse['InsertTraderMode'] = '2'; + } + $parse['Insert_ResM'] = 'cry'; + $parse['Insert_ResA'] = 'met'; + $parse['Insert_ResB'] = 'deu'; + break; + } + case '3': + { + // Deuterium + $PageTPL = gettemplate('merchant_deuterium'); + $parse['mod_ma_res_a'] = '0.25'; + $parse['mod_ma_res_b'] = '0.5'; + if($_GET['mode'] == 1) + { + $parse['Trader_ModeNRes'] = $_Lang['Trader_SellDeu']; + $parse['Trader_NeedOrReceive'] = $_Lang['Trader_Needen']; + $parse['InsertTraderMode'] = '1'; + } + else + { + $parse['Trader_ModeNRes'] = $_Lang['Trader_BuyDeu']; + $parse['Trader_NeedOrReceive'] = $_Lang['Trader_Receiving']; + $parse['InsertTraderMode'] = '2'; + } + $parse['Insert_ResM'] = 'deu'; + $parse['Insert_ResA'] = 'met'; + $parse['Insert_ResB'] = 'cry'; + break; + } + } +} +else +{ + if(isset($_GET['show']) && $_GET['show'] == 'ok') + { + $parse['TraderMsg_Hide'] = ''; + $parse['TraderMsg_Color'] = 'lime'; + $parse['TraderMsg_Text'] = $_Lang['Trader_Done']; + } + else + { + $parse['TraderMsg_Hide'] = 'inv'; + } + + $PageTPL = gettemplate('merchant_main'); +} + +if(!isPro($CurrentUser)) +{ + $parse['Insert_TraderRight'] = "{$_Lang['Trader_Uses_BuyMore']}"; + if($CurrentUser['trader_usesCount'] <= 0) + { + $parse['Insert_TraderUsesColor'] = $parse['Insert_AddRed'] = 'red'; + $parse['Insert_TraderRight'] = "{$_Lang['Trader_Uses_BlockedBuy']}"; + } + else if($CurrentUser['trader_usesCount'] < 5) + { + $parse['Insert_TraderUsesColor'] = 'orange'; + } + $parse['Insert_TraderUses'] = prettyNumber($CurrentUser['trader_usesCount']); +} +else +{ + $parse['Insert_TraderUsesColor'] = 'lime'; + $parse['Insert_TraderUses'] = $_Lang['Trader_Uses_Infinite']; + $parse['Insert_TraderRight'] = "({$_Lang['Trader_Uses_InStandBy']}: ".prettyNumber($CurrentUser['trader_usesCount']).")"; +} + +$Page = parsetemplate($PageTPL, $parse); + +display($Page, $_Lang['Trader_Title']); + +?> diff --git a/messages.php b/messages.php index fc7ae6d85..15977791f 100644 --- a/messages.php +++ b/messages.php @@ -1,1294 +1,1294 @@ - '#FFFF00', 1 => '#FF6699', 2 => '#FF3300', 3 => '#FF9900', 4 => '#9540BF', 5 => '#009933', - 15 => '#6661FF', 80 => 'white', 50 => 'skyblue', 70 => '#75F121', 100 => '#ABABAB' - ); - $MsgColors = array(0 => 'c0', 1 => 'c1', 2 => 'c2', 3 => 'c3', 4 => 'c4', 5 => 'c5', 15 => 'c15', 80 => 'c80', 50 => 'c50', 70 => 'c70', 100 => 'c100'); - $SimTechs = array(109, 110, 111, 120, 121, 122, 125, 126, 199); - $SimTechsRep = array(109 => 1, 110 => 2, 111 => 3, 120 => 4, 121 => 5, 122 => 6, 125 => 7, 126 => 8, 199 => 9); - $_MaxLength_Subject = 100; - $_MaxLength_Text = 5000; - - $_UseThreads = ($_User['settings_UseMsgThreads'] == 1 ? true : false); - - $_ThisCategory = (isset($_GET['messcat']) ? intval($_GET['messcat']) : 0); - $DeleteWhat = (isset($_POST['deletemessages']) ? $_POST['deletemessages'] : ''); - if(!empty($DeleteWhat) || (isset($_POST['delid']) && $_POST['delid'] > 0)) - { - $_GET['mode'] = 'delete'; - if(isset($_POST['delid']) && $_POST['delid'] > 0) - { - $_POST['deletemessages'] = ''; - } - } - $CreatedForms = 0; - - if(!isset($_GET['mode'])) - { - $_GET['mode'] = ''; - } - switch($_GET['mode']) - { - case 'write': - // Message Sending System - $SetTitle = $_Lang['mess_pagetitle_send']; - $AllowSend = false; - - $FormData['username'] = null; - $FormData['uid'] = null; - $FormData['replyto'] = 0; - $FormData['subject'] = null; - $FormData['text'] = null; - $FormData['lock_username'] = false; - $FormData['lock_subject'] = false; - - if(empty($_POST['subject']) AND !empty($_GET['subject'])) - { - $_POST['subject'] = $_GET['subject']; - } - if(empty($_POST['text']) AND !empty($_GET['insert'])) - { - $_POST['text'] = $_GET['insert']; - } - - if(!empty($_GET['replyto']) OR !empty($_POST['replyto'])) - { - if(!empty($_POST['replyto'])) - { - $ReplyID = round($_POST['replyto']); - } - else - { - $ReplyID = round($_GET['replyto']); - } - if($ReplyID > 0) - { - $GetReplyMsg = ''; - $GetReplyMsg .= "SELECT `m`.`id`, `m`.`Thread_ID`, `m`.`subject`, `m`.`text`, `u`.`id` AS `user_id`, `u`.`username`, `u`.`authlevel` FROM {{table}} AS `m` "; - $GetReplyMsg .= "LEFT JOIN `{{prefix}}users` AS `u` ON `u`.`id` = IF(`m`.`id_owner` != {$_User['id']}, `m`.`id_owner`, `m`.`id_sender`) "; - $GetReplyMsg .= "WHERE (`m`.`id` = {$ReplyID} OR `m`.`Thread_ID` = {$ReplyID}) AND (`m`.`id_owner` = {$_User['id']} OR `m`.`id_sender` = {$_User['id']}) AND `deleted` = false LIMIT 1;"; - - $ReplyMsg = doquery($GetReplyMsg, 'messages', true); - if($ReplyMsg['id'] > 0) - { - if(preg_match('/^\{COPY\_MSG\_\#([0-9]{1,}){1}\}$/D', $ReplyMsg['text'], $ThisMatch)) - { - $GetCopyMsg = doquery("SELECT `subject` FROM {{table}} WHERE `id` = {$ThisMatch[1]} LIMIT 1;", 'messages', true); - $ReplyMsg['subject'] = $GetCopyMsg['subject']; - } - - $FormData['username'] = $ReplyMsg['username']; - $FormData['uid'] = $ReplyMsg['user_id']; - $FormData['authlevel'] = $ReplyMsg['authlevel']; - $FormData['subject'] = $ReplyMsg['subject']; - $FormData['replyto'] = $ReplyID; - $FormData['Thread_Started'] = ($ReplyMsg['Thread_ID'] > 0 ? true : false); - if($FormData['Thread_Started'] === false) - { - $CreateReCounter = 1; - } - else - { - $GetThreadCount = doquery("SELECT COUNT(*) AS `Count` FROM {{table}} WHERE `Thread_ID` = {$ReplyID};", 'messages', true); - $CreateReCounter = $GetThreadCount['Count']; - } - $FormData['lock_username'] = true; - $FormData['lock_subject'] = true; - $AllowSend = true; - - $FormData['subject'] = preg_replace('#'.$_Lang['mess_answer_prefix'].'\[[0-9]{1,}\]\: #si', '', $FormData['subject']); - $FormData['subject'] = $_Lang['mess_answer_prefix'].'['.$CreateReCounter.']: '.$FormData['subject']; - } - else - { - $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_CantReply']); - } - } - else - { - $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_CantReply']); - } - } - else - { - if(!empty($_GET['uid']) OR !empty($_POST['uid'])) - { - if(!empty($_POST['uid'])) - { - $UserID = intval($_POST['uid']); - $UIDFromPost = true; - } - else - { - $UserID = intval($_GET['uid']); - $UIDFromPost = false; - } - if($UserID > 0) - { - $CheckUser = doquery("SELECT `id`, `username`, `authlevel` FROM {{table}} WHERE `id` = {$UserID} LIMIT 1;", 'users', true); - if($CheckUser['id'] == $UserID) - { - $FormData['username'] = $CheckUser['username']; - $FormData['uid'] = $UserID; - $FormData['authlevel'] = $CheckUser['authlevel']; - if($UIDFromPost === false) - { - $FormData['lock_username'] = true; - } - $AllowSend = true; - } - else - { - $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_UserNoExist']); - } - } - else - { - $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_BadUserID']); - } - } - - if(!empty($_POST['uname']) && $_POST['uname'] != $FormData['username']) - { - $FormData['username'] = ''; - $FormData['uid'] = ''; - $FormData['authlevel'] = ''; - $AllowSend = false; - - $UserName = trim($_POST['uname']); - if(preg_match(REGEXP_USERNAME_ABSOLUTE, $UserName)) - { - $CheckUser = doquery("SELECT `id`, `authlevel` FROM {{table}} WHERE `username` = '{$UserName}' LIMIT 1;", 'users', true); - if($CheckUser['id'] > 0) - { - $FormData['username'] = $UserName; - $FormData['uid'] = $CheckUser['id']; - $FormData['authlevel'] = $CheckUser['authlevel']; - $AllowSend = true; - } - else - { - $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_UserNoExist']); - } - } - else - { - $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_BadUserName']); - } - } - } - - if($FormData['uid'] > 0 && $FormData['uid'] == $_User['id']) - { - $FormData['username'] = ''; - $FormData['uid'] = ''; - $FormData['lock_username'] = false; - $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_CantWriteToYourself']); - $AllowSend = false; - } - $FormData['type'] = 1; - if(isset($_POST['send_as_admin_msg']) && $_POST['send_as_admin_msg'] == 'on') - { - if(!CheckAuth('supportadmin')) - { - $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_CantUseAdminMsg']); - $AllowSend = false; - } - else - { - $FormData['type'] = 80; - $parse['FormInsert_checkSendAsAdmin'] = 'checked'; - } - } - - $_POST['text'] = (isset($_POST['text']) ? stripslashes(trim($_POST['text'])) : ''); - $_POST['subject'] = (isset($_POST['subject']) ? stripslashes(trim($_POST['subject'])) : ''); - if(get_magic_quotes_gpc()) - { - $_POST['text'] = stripslashes($_POST['text']); - $_POST['subject'] = stripslashes($_POST['subject']); - } - - if(empty($FormData['subject'])) - { - $FormData['subject'] = substr(strip_tags($_POST['subject']), 0, $_MaxLength_Subject); - } - $FormData['text'] = substr(strip_tags($_POST['text']), 0, $_MaxLength_Text); - - if(isset($_POST['send_msg'])) - { - if($FormData['uid'] == 0 && empty($MsgBox)) - { - $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_NoUserID']); - $AllowSend = false; - } - - if(empty($FormData['subject'])) - { - $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_SubjectEmpty']); - $AllowSend = false; - } - if(empty($FormData['text'])) - { - $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_TextEmpty']); - $AllowSend = false; - } - else - { - include($_EnginePath.'includes/functions/FilterMessages.php'); - if(FilterMessages($_POST['text'], 1)) - { - $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_TextSPAM']); - $AllowSend = false; - } - } - - if($FormData['uid'] > 0 && !CheckAuth('user', AUTHCHECK_HIGHER) AND !CheckAuth('user', AUTHCHECK_HIGHER, $FormData)) - { - $Query_IgnoreSystem = ''; - $Query_IgnoreSystem .= "SELECT `OwnerID` FROM {{table}} WHERE "; - $Query_IgnoreSystem .= "(`OwnerID` = {$_User['id']} AND `IgnoredID` = {$FormData['uid']}) OR "; - $Query_IgnoreSystem .= "(`OwnerID` = {$FormData['uid']} AND `IgnoredID` = {$_User['id']}) "; - $Query_IgnoreSystem .= "LIMIT 2; -- messages.php|IgnoreSystem"; - $Result_IgnoreSystem = doquery($Query_IgnoreSystem, 'ignoresystem'); - if(mysql_num_rows($Result_IgnoreSystem) > 0) - { - $AllowSend = false; - while($IgnoreData = mysql_fetch_assoc($Result_IgnoreSystem)) - { - if($IgnoreData['OwnerID'] == $_User['id']) - { - $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_IgnoreYour']); - } - else - { - $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_IgnoreHis']); - } - } - } - } - - if($AllowSend === true) - { - $FormSend['type'] = $FormData['type']; - $FormSend['subject'] = $FormData['subject']; - $FormSend['text'] = $FormData['text']; - $FormSend['uid'] = $FormData['uid']; - $FormSend['Thread_ID'] = $FormData['replyto']; - $FormSend['Thread_IsLast'] = ($FormSend['Thread_ID'] > 0 ? 1 : 0); - - if($FormSend['Thread_ID'] > 0) - { - if($FormData['Thread_Started'] === false) - { - doquery("UPDATE {{table}} SET `Thread_ID` = `id`, `Thread_IsLast` = 1 WHERE `id` = {$FormSend['Thread_ID']} LIMIT 1;", 'messages'); - } - else - { - doquery("UPDATE {{table}} SET `Thread_IsLast` = 0 WHERE `Thread_ID` = {$FormSend['Thread_ID']} AND `id_owner` = {$FormSend['uid']};", 'messages'); - } - } - - Cache_Message($FormSend['uid'], $_User['id'], $Now, $FormSend['type'], '', $FormSend['subject'], $FormSend['text'], $FormSend['Thread_ID'], $FormSend['Thread_IsLast']); - - if(preg_match('#'.$_Lang['mess_answer_prefix'].'\[([0-9]{1,})\]\: #si', $FormData['subject'], $ThisMatch)) - { - $FormData['subject'] = preg_replace('#'.$_Lang['mess_answer_prefix'].'\[[0-9]{1,}\]\: #si', $_Lang['mess_answer_prefix'].'['.($ThisMatch[1] + 1).']: ', $FormData['subject']); - } - $MsgBox[] = array('color' => 'lime', 'text' => $_Lang['Info_MsgSend']); - } - } - - $parse['FormInsert_username'] = $FormData['username']; - $parse['FormInsert_uid'] = $FormData['uid']; - $parse['FormInsert_replyto'] = $FormData['replyto']; - $parse['FormInsert_subject'] = $FormData['subject']; - $parse['FormInsert_text'] = $FormData['text']; - if($FormData['lock_username'] === true) - { - $parse['FormInsert_LockUsername'] = 'disabled'; - } - if($FormData['lock_subject'] === true) - { - $parse['FormInsert_LockSubject'] = 'disabled'; - } - - // Let's handle System Messages - if(!empty($MsgBox)) - { - foreach($MsgBox as $MsgData) - { - $MsgBoxData[] = "{$MsgData['text']}"; - } - $parse['Insert_MsgBoxText'] = implode('
    ', $MsgBoxData); - } - else - { - $parse['Insert_HideMsgBox'] = 'inv'; - $parse['Insert_MsgBoxText'] = ' '; - } - - // Now let's show Form to User - if(!CheckAuth('user', AUTHCHECK_HIGHER)) - { - $parse['FormInsert_displaySendAsAdmin'] = 'display: none;'; - } - $_Lang['FormInsert_MaxSigns'] = $_MaxLength_Text; - if($_GameConfig['enable_bbcode'] == 1) - { - $page = parsetemplate(gettemplate('messages_pm_form_bb'), $parse); - } - else - { - $page = parsetemplate(gettemplate('messages_pm_form'), $parse); - } - // It's done! - break; - - case 'delete': - // Delete or do other things with Selected/Nonselected/Add Messages - - $_ThisCategory = intval($_POST['category']); - $DeleteWhat = $_POST['deletemessages']; - $ActionBreak = false; - if(in_array($DeleteWhat, array('deleteall', 'deleteallcat', 'setallread', 'setcatread'))) - { - $TimeStamp = round($_POST['time']); - if($TimeStamp <= 0 OR $TimeStamp > $Now) - { - $DelNotifs[] = $_Lang['Delete_BadTimestamp']; - $ActionBreak = true; - } - } - - if($ActionBreak !== true) - { - if($DeleteWhat == 'deleteall') - { - // User is Deleting all messages at once (exclude AdminMessages) - - $SelectMsgs = doquery("SELECT `Thread_ID` FROM {{table}} WHERE `time` <= {$TimeStamp} AND `id_owner` = {$_User['id']} AND `type` != 80 AND `Thread_ID` > 0;", 'messages'); - doquery("UPDATE {{table}} SET `deleted` = true WHERE `id_owner` = {$_User['id']} AND `type` != 80 AND `time` <= {$TimeStamp};", 'messages'); - $DeletedCount = mysql_affected_rows(); - if(mysql_num_rows($SelectMsgs) > 0) - { - $UpdateThreads = array(); - while($SelectData = mysql_fetch_assoc($SelectMsgs)) - { - if(!in_array($SelectData['Thread_ID'], $UpdateThreads)) - { - $UpdateThreads[] = $SelectData['Thread_ID']; - } - } - $IDs = implode(',', $UpdateThreads); - $SelectIDs = doquery("SELECT MAX(`id`) AS `id` FROM {{table}} WHERE `Thread_ID` IN ({$IDs}) AND `id_owner` = {$_User['id']} AND `deleted` = false GROUP BY `Thread_ID`;", 'messages'); - if(mysql_num_rows($SelectIDs) > 0) - { - while($SelectData = mysql_fetch_assoc($SelectIDs)) - { - $UpdateIDs[] = $SelectData['id']; - } - $IDs = implode(',', $UpdateIDs); - doquery("UPDATE {{table}} SET `Thread_IsLast` = 1 WHERE `id` IN ({$IDs});", 'messages'); - } - } - - if($DeletedCount > 0) - { - $DelMsgs[] = $_Lang['Delete_AllMsgsDeleted']; - } - else - { - $DelNotifs[] = $_Lang['Delete_NoMsgsToDelete']; - } - } - elseif($DeleteWhat == 'deleteallcat') - { - // User is Deleting all messages in this category at once - if(in_array($_ThisCategory, $MessageType) AND $_ThisCategory != 100 AND $_ThisCategory != 80) - { - $SelectMsgs = doquery("SELECT `Thread_ID` FROM {{table}} WHERE `type` = {$_ThisCategory} AND `time` <= {$TimeStamp} AND `id_owner` = {$_User['id']} AND `Thread_ID` > 0;", 'messages'); - doquery("UPDATE {{table}} SET `deleted` = true WHERE `id_owner` = {$_User['id']} AND `type` = {$_ThisCategory} AND `time` <= {$TimeStamp};", 'messages'); - $DeletedCount = mysql_affected_rows(); - if(mysql_num_rows($SelectMsgs) > 0) - { - $UpdateThreads = array(); - while($SelectData = mysql_fetch_assoc($SelectMsgs)) - { - if(!in_array($SelectData['Thread_ID'], $UpdateThreads)) - { - $UpdateThreads[] = $SelectData['Thread_ID']; - } - } - $IDs = implode(',', $UpdateThreads); - $SelectIDs = doquery("SELECT MAX(`id`) AS `id` FROM {{table}} WHERE `Thread_ID` IN ({$IDs}) AND `id_owner` = {$_User['id']} AND `deleted` = false GROUP BY `Thread_ID`;", 'messages'); - if(mysql_num_rows($SelectIDs) > 0) - { - while($SelectData = mysql_fetch_assoc($SelectIDs)) - { - $UpdateIDs[] = $SelectData['id']; - } - $IDs = implode(',', $UpdateIDs); - doquery("UPDATE {{table}} SET `Thread_IsLast` = 1 WHERE `id` IN ({$IDs});", 'messages'); - } - } - if($DeletedCount > 0) - { - $DelMsgs[] = $_Lang['Delete_AllCatMsgsDeleted']; - } - else - { - $DelNotifs[] = $_Lang['Delete_NoMsgsToDelete']; - } - } - else - { - if($_ThisCategory == 80) - { - // Don't let to delete all AdminMessages - $DelNotifs[] = $_Lang['Delete_CannotDeleteAdminMsgsAtOnce']; - } - else - { - $DelNotifs[] = $_Lang['Delete_BadCatSelected']; - } - } - } - else if($DeleteWhat == 'deletemarked') - { - // User is Deleting all Marked messages - $DeleteIDs = false; - if(!empty($_POST['del_all'])) - { - preg_match_all('#([0-9]{1,})#si', $_POST['del_all'], $DeleteIDs); - $DeleteIDs = $DeleteIDs[0]; - } - else - { - foreach($_POST as $Message => $Answer) - { - if(preg_match("/^del([0-9]{1,})$/D", $Message, $MsgMatch) AND $Answer == 'on') - { - $DeleteIDs[] = $MsgMatch[1]; - } - } - } - if($DeleteIDs !== FALSE) - { - $IDs = implode(',', $DeleteIDs); - $SelectMsgs = doquery("SELECT `id`, `Thread_ID` FROM {{table}} WHERE `id` IN ({$IDs}) AND `id_owner` = {$_User['id']} AND `type` != 80;", 'messages'); - if(mysql_num_rows($SelectMsgs) > 0) - { - $DelMsgs[] = $_Lang['Delete_SelectedDeleted']; - - $UpdateThreads = array(); - while($SelectData = mysql_fetch_assoc($SelectMsgs)) - { - $UpdateIDs[] = $SelectData['id']; - if($SelectData['Thread_ID'] > 0) - { - if(!in_array($SelectData['Thread_ID'], $UpdateThreads)) - { - $UpdateThreads[] = $SelectData['Thread_ID']; - } - } - } - $IDs = implode(',', $UpdateIDs); - $UpdateIDs = array(); - doquery("UPDATE {{table}} SET `deleted` = true, `Thread_IsLast` = 0 WHERE `id` IN ({$IDs});", 'messages'); - if(!empty($UpdateThreads)) - { - $IDs = implode(',', $UpdateThreads); - $SelectIDs = doquery("SELECT MAX(`id`) AS `id` FROM {{table}} WHERE `Thread_ID` IN ({$IDs}) AND `id_owner` = {$_User['id']} AND `deleted` = false GROUP BY `Thread_ID`;", 'messages'); - if(mysql_num_rows($SelectIDs) > 0) - { - while($SelectData = mysql_fetch_assoc($SelectIDs)) - { - $UpdateIDs[] = $SelectData['id']; - } - $IDs = implode(',', $UpdateIDs); - doquery("UPDATE {{table}} SET `Thread_IsLast` = 1 WHERE `id` IN ({$IDs});", 'messages'); - } - } - } - else - { - $DelNotifs[] = $_Lang['Delete_BadSelections']; - } - } - else - { - $DelNotifs[] = $_Lang['Delete_NoMsgsSelected']; - } - } - else if($DeleteWhat == 'deleteunmarked') - { - // User is deleting all Unmarked messages - $DeleteIDs = false; - if(!empty($_POST['sm_all'])) - { - preg_match_all('#([0-9]{1,})#si', $_POST['sm_all'], $DeleteIDs); - $DeleteIDs = $DeleteIDs[0]; - } - else - { - foreach($_POST as $Message => $Answer) - { - if(preg_match("/^sm([0-9]{1,})$/D", $Message, $MsgMatch)) - { - if($_POST[('del'.$MsgMatch[1])] != 'on') - { - $DeleteIDs[] = $MsgMatch[1]; - } - } - } - } - if($DeleteIDs !== FALSE) - { - $IDs = implode(',', $DeleteIDs); - $SelectMsgs = doquery("SELECT `id`, `Thread_ID` FROM {{table}} WHERE `id` IN ({$IDs}) AND `id_owner` = {$_User['id']} AND `type` != 80;", 'messages'); - if(mysql_num_rows($SelectMsgs) > 0) - { - $DelMsgs[] = $_Lang['Delete_UnselectedDeleted']; - - $UpdateThreads = array(); - while($SelectData = mysql_fetch_assoc($SelectMsgs)) - { - $UpdateIDs[] = $SelectData['id']; - if($SelectData['Thread_ID'] > 0) - { - if(!in_array($SelectData['Thread_ID'], $UpdateThreads)) - { - $UpdateThreads[] = $SelectData['Thread_ID']; - } - } - } - $IDs = implode(',', $UpdateIDs); - $UpdateIDs = array(); - doquery("UPDATE {{table}} SET `deleted` = true, `Thread_IsLast` = 0 WHERE `id` IN ({$IDs});", 'messages'); - if(!empty($UpdateThreads)) - { - $IDs = implode(',', $UpdateThreads); - $SelectIDs = doquery("SELECT MAX(`id`) AS `id` FROM {{table}} WHERE `Thread_ID` IN ({$IDs}) AND `id_owner` = {$_User['id']} AND `deleted` = false GROUP BY `Thread_ID`;", 'messages'); - if(mysql_num_rows($SelectIDs) > 0) - { - while($SelectData = mysql_fetch_assoc($SelectIDs)) - { - $UpdateIDs[] = $SelectData['id']; - } - $IDs = implode(',', $UpdateIDs); - doquery("UPDATE {{table}} SET `Thread_IsLast` = 1 WHERE `id` IN ({$IDs});", 'messages'); - } - } - } - else - { - $DelNotifs[] = $_Lang['Delete_BadSelections']; - } - } - else - { - $DelNotifs[] = $_Lang['Delete_NoMsgsUnselected']; - } - } - else if($DeleteWhat == 'setallread') - { - // User wants to set All messages as "read" - doquery("UPDATE {{table}} SET `read` = true WHERE `id_owner` = {$_User['id']} AND `type` != 80 AND `time` <= {$TimeStamp};", 'messages'); - if(mysql_affected_rows() > 0) - { - $DelMsgs[] = $_Lang['Delete_AllMsgsRead']; - } - else - { - $DelNotifs[] = $_Lang['Delete_NoMsgsToRead']; - } - } - else if($DeleteWhat == 'setcatread') - { - // User is setting All messages in this Cat as "read" - if(in_array($_ThisCategory, $MessageType) AND $_ThisCategory != 100 AND $_ThisCategory != 80) - { - doquery("UPDATE {{table}} SET `read` = true WHERE `id_owner` = {$_User['id']} AND `type` = {$_ThisCategory} AND `time` <= {$TimeStamp};", 'messages'); - if(mysql_affected_rows() > 0) - { - $DelMsgs[] = $_Lang['Delete_CatMsgsRead']; - } - else - { - $DelNotifs[] = $_Lang['Delete_NoMsgsToRead']; - } - } - else - { - if($_ThisCategory == 80) - { - // Don't let to "read" all AdminMessages - $DelNotifs[] = $_Lang['Delete_CannotReadAdminMsgsAtOnce']; - } - else - { - $DelNotifs[] = $_Lang['Delete_BadCatSelected']; - } - } - } - else - { - // User is Deleting single message - if(!empty($_POST['delid'])) - { - $DeleteID = round(floatval($_POST['delid'])); - $SelectMsg = doquery("SELECT `id`, `Thread_ID` FROM {{table}} WHERE `id` = {$DeleteID} AND `id_owner` = {$_User['id']} LIMIT 1;", 'messages', true); - if($SelectMsg['id'] == $DeleteID) - { - $DelMsgs[] = $_Lang['Delete_MsgDeleted']; - - doquery("UPDATE {{table}} SET `deleted` = true, `Thread_IsLast` = 0 WHERE `id` = {$DeleteID};", 'messages'); - if($SelectMsg['Thread_ID'] > 0) - { - doquery("UPDATE {{table}} SET `Thread_IsLast` = 1 WHERE `Thread_ID` = {$SelectMsg['Thread_ID']} AND `id_owner` = {$_User['id']} AND `deleted` = false ORDER BY `id` DESC LIMIT 1;", 'messages'); - } - } - else - { - $DelNotifs[] = $_Lang['Delete_MsgNoExist']; - } - } - } - } - - if(!empty($DelMsgs)) - { - foreach($DelMsgs as $Data) - { - $MsgBoxData[] = "{$Data}"; - } - } - if(!empty($DelNotifs)) - { - foreach($DelNotifs as $Data) - { - $MsgBoxData[] = "{$Data}"; - } - } - // Don't break here to allow deleting while showing... - - case 'show': - // Show Messages - - if($_User['settings_msgperpage'] <= 0) - { - $_PerPage = 20; - } - else - { - $_PerPage = $_User['settings_msgperpage']; - } - if(isset($_POST['page']) && !empty($_POST['page'])) - { - $_ThisPage = intval($_POST['page']); - } - else - { - $_ThisPage = isset($_GET['page']) ? intval($_GET['page']) : 0; - } - - $PageTPL = gettemplate('message_list'); - $parse['InsertTimestamp'] = $Now; - - if($_User['settings_spyexpand'] == 0) - { - $parse['SpyExpanded'] = 'true'; - $parse['SpyDisplay'] = ''; - } - else - { - $parse['SpyExpanded'] = 'false'; - $parse['SpyDisplay'] = 'display: none;'; - } - - if($_ThisPage > 1) - { - $Start = ($_ThisPage - 1) * $_PerPage; - } - else - { - $_ThisPage = 1; - $Start = 0; - } - - if(!in_array($_ThisCategory, $MessageType)) - { - $_ThisCategory = 100; - } - - $parse['SelectedCat'] = $_Lang['type'][$_ThisCategory]; - if($_ThisCategory == 100) - { - $parse['show_delete_all_cat'] = 'style="display: none;"'; - $GetMsgCountType = "`type` != 80"; - $parse['Hide_NoActions'] = ' style="display: none"'; - } - else - { - $GetMsgCountType = "`type` = {$_ThisCategory}"; - if($_ThisCategory == 80) - { - $parse['Hide_AdminMsg'] = ' style="display: none"'; - } - else - { - $parse['Hide_NoActions'] = ' style="display: none"'; - } - } - if($_UseThreads) - { - $GetMsgCount = doquery("SELECT COUNT(`id`) as `count` FROM {{table}} WHERE `deleted` = false AND `id_owner` = {$_User['id']} AND (`type` NOT IN (".implode(', ', $_CanBeThreaded).") OR `Thread_ID` = 0 OR `Thread_IsLast` = 1) AND {$GetMsgCountType};", 'messages', true); - } - else - { - $GetMsgCount = doquery("SELECT COUNT(`id`) as `count` FROM {{table}} WHERE `deleted` = false AND `id_owner` = {$_User['id']} AND {$GetMsgCountType};", 'messages', true); - } - $MsgCount = $GetMsgCount['count']; - - if($Start >= $MsgCount) - { - $_ThisPage = ceil($MsgCount/$_PerPage); - $Start = ($_ThisPage - 1) * $_PerPage; - } - - $Pagination = ''; - if($MsgCount > $_PerPage) - { - include_once($_EnginePath.'includes/functions/Pagination.php'); - $Pagin = CreatePaginationArray($MsgCount, $_PerPage, $_ThisPage, 7); - $PaginationTPL = "{\$ShowValue}"; - $PaginationViewOpt = array('CurrentPage_Classes' => 'orange', 'Breaker_View' => '...'); - $CreatePagination = implode(' ', ParsePaginationArray($Pagin, $_ThisPage, $PaginationTPL, $PaginationViewOpt)); - - $Pagination = "{$_Lang['Pages']}{$CreatePagination}"; - } - - $parse['ThisPage'] = $_ThisPage; - $parse['MessCategory'] = $_ThisCategory; - $parse['MessCategoryColor'] = $TitleColor[$_ThisCategory]; - $parse['Pagination'] = $Pagination; - $page = ''; - - // Let's show Messages! - if($MsgCount > 0) - { - if($_ThisCategory == 100) - { - $GetMsgsType = '!= 80'; - } - else - { - $GetMsgsType = "= {$_ThisCategory}"; - } - $Query_GetMessages = ''; - $Query_GetMessages .= "SELECT `m`.*, `u`.`username`, `u`.`authlevel` FROM {{table}} AS `m` "; - $Query_GetMessages .= "LEFT JOIN `{{prefix}}users` AS `u` ON `u`.`id` = `m`.`id_sender` "; - if($_UseThreads) - { - $Query_GetMessages .= "WHERE `m`.`deleted` = false AND `m`.`id_owner` = {$_User['id']} AND (`type` NOT IN (".implode(', ', $_CanBeThreaded).") OR `m`.`Thread_ID` = 0 OR `m`.`Thread_IsLast` = 1) AND `m`.`type` {$GetMsgsType} "; - } - else - { - $Query_GetMessages .= "WHERE `m`.`deleted` = false AND `m`.`id_owner` = {$_User['id']} AND `m`.`type` {$GetMsgsType} "; - } - $Query_GetMessages .= "ORDER BY `m`.`time` DESC, `m`.`id` DESC LIMIT {$Start}, {$_PerPage};"; - - $GetMessages = doquery($Query_GetMessages, 'messages'); - - if(mysql_num_rows($GetMessages) > 0) - { - if($_GameConfig['enable_bbcode'] == 1) - { - include($_EnginePath.'includes/functions/BBcodeFunction.php'); - } - - $ReadIDs = false; - $Messages = array(); - $CheckThreads = array(); - - while($CurMess = mysql_fetch_assoc($GetMessages)) - { - $MsgCache[] = $CurMess; - if($_UseThreads AND $CurMess['Thread_ID'] > 0 AND in_array($CurMess['type'], $_CanBeThreaded)) - { - $CheckThreads[] = $CurMess['Thread_ID']; - $CheckThreadsExclude[] = $CurMess['id']; - $ThreadMap[$CurMess['Thread_ID']] = $CurMess['id']; - } - } - - if(!empty($CheckThreads)) - { - $ThreadsIDs = implode(', ', $CheckThreads); - $ExcludeIDs = implode(', ', $CheckThreadsExclude); - $Query_GetThreaded = ''; - $Query_GetThreaded .= "SELECT `m`.*, `u`.`username`, `u`.`authlevel` FROM {{table}} AS `m` "; - $Query_GetThreaded .= "LEFT JOIN `{{prefix}}users` AS `u` ON `u`.`id` = `m`.`id_sender` "; - $Query_GetThreaded .= "WHERE `m`.`deleted` = false AND `m`.`id_owner` = {$_User['id']} AND `read` = false AND `m`.`Thread_ID` IN ({$ThreadsIDs}) AND `m`.`id` NOT IN ({$ExcludeIDs}) "; - $Query_GetThreaded .= "ORDER BY `m`.`id` DESC;"; - - $GetMessages = doquery($Query_GetThreaded, 'messages'); - if(mysql_num_rows($GetMessages) > 0) - { - while($CurMess = mysql_fetch_assoc($GetMessages)) - { - $CurMess['isAdditional'] = true; - $MsgCache[] = $CurMess; - } - } - - foreach($CheckThreads as $ThreadID) - { - $Query_ThreadsLengthWhere[] = "(`Thread_ID` = {$ThreadID} AND `id` <= {$ThreadMap[$ThreadID]})"; - } - $Query_ThreadsLengthWhere = implode(' OR ', $Query_ThreadsLengthWhere); - $Query_ThreadsLength = "SELECT `Thread_ID`, COUNT(*) AS `Count` FROM {{table}} WHERE {$Query_ThreadsLengthWhere} AND (`id_sender` = {$_User['id']} OR `deleted` = false) GROUP BY `Thread_ID`;"; - $GetThreadsLength = doquery($Query_ThreadsLength, 'messages'); - if(mysql_num_rows($GetThreadsLength) > 0) - { - while($ThisThread = mysql_fetch_assoc($GetThreadsLength)) - { - $ThreadsLength[$ThisThread['Thread_ID']] = $ThisThread['Count']; - } - } - } - - foreach($MsgCache as $MsgIndex => $CurMess) - { - $parseMSG = array(); - if($CurMess['read'] == false) - { - $ReadIDs[] = $CurMess['id']; - } - - if($CurMess['id_sender'] == 0) - { - // Message sent by System - $MsgArray = json_decode($CurMess['text'], true); - $CurMess['from'] = $_Lang['msg_const']['senders']['system'][$CurMess['from']]; - $CurMess['subject'] = $_Lang['msg_const']['subjects'][$CurMess['subject']]; - if(empty($MsgArray['msg_text'])) - { - // Constant-formated Message - if(!empty($MsgArray['msg_id'])) - { - $CurMess['text'] = vsprintf($_Lang['msg_const']['msgs'][$MsgArray['msg_id']], $MsgArray['args']); - } - else - { - $CurMess['text'] = sprintf($_Lang['msg_const']['msgs']['err2'], $CurMess['id']); - } - } - else - { - // NonConstant Message (eg. SpyReport) - if((array)$MsgArray['msg_text'] === $MsgArray['msg_text']) - { - if(!empty($MsgArray['sim'])) - { - $CreatedForms += 1; - $Temp = explode(';', $MsgArray['sim']); - foreach($Temp as $Data) - { - $Data = explode(',', $Data); - if(!empty($Data[0])) - { - if(in_array($Data[0], $SimTechs)) - { - $MsgArray['simData']['tech'][$SimTechsRep[$Data[0]]] = $Data[1]; - } - else - { - $MsgArray['simData']['ships'][$Data[0]] = $Data[1]; - } - } - } - $CreateSimForms .= sprintf($_Lang['msg_const']['sim']['form'], $CreatedForms, json_encode($MsgArray['simData'])); - - $_Lang['GoToSimButton'] = sprintf($_Lang['msg_const']['sim']['button'], 'sim_'.$CreatedForms); - } - $CurMess['text'] = implode('', innerReplace(multidim2onedim($MsgArray['msg_text']), $_Lang)); - } - else - { - $CurMess['text'] = sprintf($_Lang['msg_const']['msgs']['err'], $CurMess['id']); - } - } - } - else - { - // Message sent by User - $AddFrom = ''; - if(!empty($CurMess['from'])) - { - $AddFrom = ' '.$CurMess['from']; - } - $CurMess['from'] = "{$_Lang['msg_const']['senders']['rangs'][GetAuthLabel($CurMess)]} {$CurMess['username']}{$AddFrom}"; - - if(in_array($CurMess['type'], array(2, 80)) AND preg_match('/^\{COPY\_MSG\_\#([0-9]{1,}){1}\}$/D', $CurMess['text'], $ThisMatch)) - { - $GetMassMsgs[] = $ThisMatch[1]; - $CopyMsgMap[$ThisMatch[1]][] = $CurMess['id']; - $CurMess['text'] = sprintf($_Lang['msg_const']['msgs']['err4'], $CurMess['id']); - } - else - { - if($_GameConfig['enable_bbcode'] == 1) - { - $CurMess['text'] = bbcode(image($CurMess['text'])); - } - $CurMess['text'] = nl2br($CurMess['text']); - } - - if($CurMess['Thread_ID'] > 0) - { - $parseMSG['isThreaded'] = true; - $parseMSG['Thread_ID'] = $CurMess['Thread_ID']; - } - } - - $parseMSG['CurrMSG_ID'] = $CurMess['id']; - if($CurMess['read'] == false) - { - $parseMSG['CurrMSG_IsUnread'] = ' class="isNew"'; - } - $parseMSG['CurrMSG_date'] = date('d.m.Y', $CurMess['time']); - $parseMSG['CurrMSG_time'] = date('H:i:s', $CurMess['time']); - $parseMSG['CurrMSG_from'] = $CurMess['from']; - $parseMSG['CurrMSG_subject'] = $CurMess['subject']; - $parseMSG['CurrMSG_text'] = $CurMess['text']; - if($_ThisCategory == 100) - { - $parseMSG['CurrMSG_color'] = $MsgColors[$CurMess['type']]; - } - else - { - $parseMSG['CurrMSG_color'] = ''; - } - if($CurMess['type'] == 80) - { - $parseMSG['CurrMSG_HideCheckbox'] = 'class="inv"'; - } - $parseMSG['CurrMSG_send'] = sprintf($_Lang['mess_send_date'], $parseMSG['CurrMSG_date'], $parseMSG['CurrMSG_time']); - if($CurMess['id_sender'] == 0) - { - if($CurMess['type'] == 3) - { - $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_convert']}"; - } - $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_report']}"; - $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_delete_single']}"; - } - else - { - if($CurMess['id_sender'] != $_User['id']) - { - $parseMSG['CurrMSG_buttons'][] = " 0 ? $CurMess['Thread_ID'] : $CurMess['id'])."\">{$_Lang['mess_reply']}"; - } - if($CurMess['type'] == 2 AND $_User['ally_id'] > 0) - { - $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_reply_toally']}"; - } - - if($CurMess['type'] != 80 AND $CurMess['type'] != 2 AND !CheckAuth('user', AUTHCHECK_HIGHER, $CurMess)) - { - $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_ignore']}"; - } - $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_report']}"; - $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_delete_single']}"; - } - if(!empty($parseMSG['CurrMSG_buttons'])) - { - $parseMSG['CurrMSG_buttons'] = implode('', $parseMSG['CurrMSG_buttons']); - } - - if(isset($CurMess['isAdditional']) && $CurMess['isAdditional'] === true) - { - $parseMSG['isAdditional'] = true; - } - - $Messages[$CurMess['id']] = $parseMSG; - } - $MsgCache = null; - - if($ReadIDs !== FALSE) - { - $ReadIDs = implode(', ', $ReadIDs); - doquery("UPDATE {{table}} SET `read` = true WHERE `id` IN ({$ReadIDs}) AND `deleted` = false;", 'messages'); - } - - if(!empty($GetMassMsgs)) - { - if($_ThisCategory == 100) - { - $QryGetMassMsg = doquery("SELECT `id`, `type`, `subject`, `text` FROM {{table}} WHERE `id` IN (".implode(', ', $GetMassMsgs).");", 'messages'); - } - else - { - $QryGetMassMsg = doquery("SELECT `id`, `type`, `subject`, `text`, `from` FROM {{table}} WHERE `id` IN (".implode(', ', $GetMassMsgs).");", 'messages'); - } - while($CopyData = mysql_fetch_assoc($QryGetMassMsg)) - { - if($CopyData['type'] == 80 OR $CopyData['type'] == 2) - { - if($_GameConfig['enable_bbcode'] == 1) - { - $CopyData['text'] = bbcode(image($CopyData['text'])); - } - $CopyData['text'] = nl2br($CopyData['text']); - foreach($CopyMsgMap[$CopyData['id']] as $MsgKey) - { - $Messages[$MsgKey]['CurrMSG_subject'] = $CopyData['subject']; - $Messages[$MsgKey]['CurrMSG_text'] = $CopyData['text']; - if($CopyData['type'] == 2) - { - $Messages[$MsgKey]['CurrMSG_from'] .= ' '.$CopyData['from']; - } - } - } - else - { - foreach($CopyMsgMap[$CopyData['id']] as $MsgKey) - { - $Messages[$MsgKey]['CurrMSG_subject'] = $_Lang['msg_const']['subjects']['019']; - $Messages[$MsgKey]['CurrMSG_text'] = sprintf($_Lang['msg_const']['msgs']['err3'], $CopyData['id']); - } - } - } - } - - $MsgTPL = gettemplate('message_mailbox_body'); - $ThreadMsgTPL = gettemplate('message_mailbox_threaded'); - foreach($Messages as $ThisKey => $MessageData) - { - if(isset($MessageData['isAdditional']) && $MessageData['isAdditional'] === true) - { - $ExcludeThreadIDs[$MessageData['Thread_ID']][] = $MessageData['CurrMSG_ID']; - $Messages[$ThreadMap[$MessageData['Thread_ID']]]['AddMSG_parsed'][] = parsetemplate($MsgTPL, $MessageData); - unset($Messages[$ThisKey]); - } - } - foreach($Messages as $MessageData) - { - if($_UseThreads && isset($MessageData['Thread_ID']) && $MessageData['Thread_ID'] > 0) - { - if(!empty($MessageData['AddMSG_parsed'])) - { - $NeededLength = 1 + count($MessageData['AddMSG_parsed']); - } - else - { - $NeededLength = 1; - } - $ThreadParse = array - ( - 'Hidden' => 0, - 'Lang_Expand' => $_Lang['Action_Expand'], - 'Lang_Collapse' => $_Lang['Action_Collapse'], - 'Lang_Loading' => $_Lang['Action_ThreadLoading'], - 'Insert_ThreadID' => $MessageData['Thread_ID'], - 'Insert_MaxMsgID' => $MessageData['CurrMSG_ID'], - 'Insert_CatID' => $_ThisCategory, - 'Insert_ExcludeIDs' => (!empty($ExcludeThreadIDs[$MessageData['Thread_ID']]) ? implode('_', $ExcludeThreadIDs[$MessageData['Thread_ID']]) : ''), - ); - if(!empty($MessageData['AddMSG_parsed'])) - { - $ThreadParse['Insert_Msgs'] = implode('', $MessageData['AddMSG_parsed']); - } - else - { - $ThreadParse['Insert_HideParsed'] = 'hide'; - $ThreadParse['Hidden'] += 1; - } - if($ThreadsLength[$MessageData['Thread_ID']] <= $NeededLength) - { - $ThreadParse['Insert_HideExpand'] = 'hide'; - $ThreadParse['Hidden'] += 1; - } - else - { - $ThreadParse['Insert_Count'] = prettyNumber($ThreadsLength[$MessageData['Thread_ID']]); - } - if($ThreadParse['Hidden'] < 2) - { - $MessageData['AddMSG_parsed'] = parsetemplate($ThreadMsgTPL, $ThreadParse); - } - } - $AllMessages[] = parsetemplate($MsgTPL, $MessageData); - } - $page .= implode('', $AllMessages); - $Messages = null; - $AllMessages = null; - } - else - { - $page .= "{$_Lang['NoMessages']}"; - } - } - else - { - $parse['Hide_headers'] = ' class="hide"'; - $page .= "{$_Lang['NoMessages']}"; - $parse['Hide_NoActions'] = ' style="display: none"'; - } - - if(!empty($MsgInfos)) - { - foreach($MsgInfos as $Data) - { - $MsgBoxData[] = "{$Data}"; - } - } - - $InsertMsgBox = ''; - if(!empty($MsgBoxData)) - { - $InsertMsgBox = ''.implode('
    ', $MsgBoxData).''; - } - $parse['content'] = $page; - $parse['MsgBox'] = $InsertMsgBox; - - $page = parsetemplate($PageTPL, $parse); - - break; - - default: - // Show Message Categories - $GetCounters = doquery("SELECT `type`, `read`, `Thread_ID`, `Thread_IsLast`, COUNT(*) AS `Count` FROM {{table}} WHERE `id_owner` = {$_User['id']} AND `deleted` = false GROUP BY `type`, `read`, `Thread_ID`, `Thread_IsLast` ORDER BY `Thread_IsLast` DESC;", 'messages'); - if(mysql_num_rows($GetCounters) > 0) - { - $SeenThreads = array(); - $ThreadMainTypes = array(); - while($Counter = mysql_fetch_assoc($GetCounters)) - { - // Handler TypeCount - if($_UseThreads AND $Counter['Thread_ID'] > 0) - { - if($Counter['Thread_IsLast'] == 1) - { - $ThreadMainTypes[$Counter['Thread_ID']] = $Counter['type']; - } - else - { - $Counter['type'] = $ThreadMainTypes[$Counter['Thread_ID']]; - } - if(!in_array($Counter['Thread_ID'], $SeenThreads)) - { - $MsgCounter['threaded'][$Counter['type']] += 1; - } - } - else - { - - $MsgCounter['threaded'][$Counter['type']] += $Counter['Count']; - } - $MsgCounter['total'][$Counter['type']] += $Counter['Count']; - if($Counter['read'] == 0) - { - $MsgCounter['unread'][$Counter['type']] += $Counter['Count']; - } - // Handle TotalCount - if($Counter['type'] != 80) - { - $MsgCounter['total'][100] += $Counter['Count']; - if($Counter['read'] == 0) - { - $MsgCounter['unread'][100] += $Counter['Count']; - } - if($_UseThreads AND $Counter['Thread_ID'] > 0) - { - if(!in_array($Counter['Thread_ID'], $SeenThreads)) - { - $MsgCounter['threaded'][100] += 1; - } - } - else - { - $MsgCounter['threaded'][100] += $Counter['Count']; - } - } - - if($_UseThreads AND $Counter['Thread_ID'] > 0) - { - if(!in_array($Counter['Thread_ID'], $SeenThreads)) - { - $SeenThreads[] = $Counter['Thread_ID']; - } - } - } - } - - $TPL_CatList_Body = gettemplate('messages_catlist_body'); - $TPL_CatList_Row = gettemplate('messages_catlist_row'); - - foreach($MessageType as $TypeID) - { - $ThisClass = 'c'.(string)($TypeID + 0); - $parse['Insert_Styles'] .= ".{$ThisClass} { color: {$TitleColor[$TypeID]}; } "; - $ThisArray = array - ( - 'Insert_CatID' => $TypeID, - 'Insert_CatClass' => $ThisClass, - 'Insert_CatName' => $_Lang['type'][$TypeID], - 'Insert_CatUnread' => prettyNumber($MsgCounter['unread'][$TypeID]), - 'Insert_CatTotal' => (($_UseThreads AND in_array($TypeID, $_CanBeThreaded) AND $MsgCounter['threaded'][$TypeID] < $MsgCounter['total'][$TypeID]) ? prettyNumber($MsgCounter['threaded'][$TypeID]).'/' : '').prettyNumber($MsgCounter['total'][$TypeID]), - ); - $parse['Insert_CategoryList'] .= parsetemplate($TPL_CatList_Row, $ThisArray); - } - - if($_UseThreads) - { - $parse['Insert_Hide_ThreadEnabled'] = 'display: none;'; - } - else - { - $parse['Insert_Hide_ThreadDisabled'] = 'display: none;'; - } - - $page = parsetemplate($TPL_CatList_Body, $parse); - - break; - } - - display($CreateSimForms.$page, $SetTitle); - -?> \ No newline at end of file + '#FFFF00', 1 => '#FF6699', 2 => '#FF3300', 3 => '#FF9900', 4 => '#9540BF', 5 => '#009933', + 15 => '#6661FF', 80 => 'white', 50 => 'skyblue', 70 => '#75F121', 100 => '#ABABAB' +); +$MsgColors = array(0 => 'c0', 1 => 'c1', 2 => 'c2', 3 => 'c3', 4 => 'c4', 5 => 'c5', 15 => 'c15', 80 => 'c80', 50 => 'c50', 70 => 'c70', 100 => 'c100'); +$SimTechs = array(109, 110, 111, 120, 121, 122, 125, 126, 199); +$SimTechsRep = array(109 => 1, 110 => 2, 111 => 3, 120 => 4, 121 => 5, 122 => 6, 125 => 7, 126 => 8, 199 => 9); +$_MaxLength_Subject = 100; +$_MaxLength_Text = 5000; + +$_UseThreads = ($_User['settings_UseMsgThreads'] == 1 ? true : false); + +$_ThisCategory = (isset($_GET['messcat']) ? intval($_GET['messcat']) : 0); +$DeleteWhat = (isset($_POST['deletemessages']) ? $_POST['deletemessages'] : ''); +if(!empty($DeleteWhat) || (isset($_POST['delid']) && $_POST['delid'] > 0)) +{ + $_GET['mode'] = 'delete'; + if(isset($_POST['delid']) && $_POST['delid'] > 0) + { + $_POST['deletemessages'] = ''; + } +} +$CreatedForms = 0; + +if(!isset($_GET['mode'])) +{ + $_GET['mode'] = ''; +} +switch($_GET['mode']) +{ + case 'write': + // Message Sending System + $SetTitle = $_Lang['mess_pagetitle_send']; + $AllowSend = false; + + $FormData['username'] = null; + $FormData['uid'] = null; + $FormData['replyto'] = 0; + $FormData['subject'] = null; + $FormData['text'] = null; + $FormData['lock_username'] = false; + $FormData['lock_subject'] = false; + + if(empty($_POST['subject']) AND !empty($_GET['subject'])) + { + $_POST['subject'] = $_GET['subject']; + } + if(empty($_POST['text']) AND !empty($_GET['insert'])) + { + $_POST['text'] = $_GET['insert']; + } + + if(!empty($_GET['replyto']) OR !empty($_POST['replyto'])) + { + if(!empty($_POST['replyto'])) + { + $ReplyID = round($_POST['replyto']); + } + else + { + $ReplyID = round($_GET['replyto']); + } + if($ReplyID > 0) + { + $GetReplyMsg = ''; + $GetReplyMsg .= "SELECT `m`.`id`, `m`.`Thread_ID`, `m`.`subject`, `m`.`text`, `u`.`id` AS `user_id`, `u`.`username`, `u`.`authlevel` FROM {{table}} AS `m` "; + $GetReplyMsg .= "LEFT JOIN `{{prefix}}users` AS `u` ON `u`.`id` = IF(`m`.`id_owner` != {$_User['id']}, `m`.`id_owner`, `m`.`id_sender`) "; + $GetReplyMsg .= "WHERE (`m`.`id` = {$ReplyID} OR `m`.`Thread_ID` = {$ReplyID}) AND (`m`.`id_owner` = {$_User['id']} OR `m`.`id_sender` = {$_User['id']}) AND `deleted` = false LIMIT 1;"; + + $ReplyMsg = doquery($GetReplyMsg, 'messages', true); + if($ReplyMsg['id'] > 0) + { + if(preg_match('/^\{COPY\_MSG\_\#([0-9]{1,}){1}\}$/D', $ReplyMsg['text'], $ThisMatch)) + { + $GetCopyMsg = doquery("SELECT `subject` FROM {{table}} WHERE `id` = {$ThisMatch[1]} LIMIT 1;", 'messages', true); + $ReplyMsg['subject'] = $GetCopyMsg['subject']; + } + + $FormData['username'] = $ReplyMsg['username']; + $FormData['uid'] = $ReplyMsg['user_id']; + $FormData['authlevel'] = $ReplyMsg['authlevel']; + $FormData['subject'] = $ReplyMsg['subject']; + $FormData['replyto'] = $ReplyID; + $FormData['Thread_Started'] = ($ReplyMsg['Thread_ID'] > 0 ? true : false); + if($FormData['Thread_Started'] === false) + { + $CreateReCounter = 1; + } + else + { + $GetThreadCount = doquery("SELECT COUNT(*) AS `Count` FROM {{table}} WHERE `Thread_ID` = {$ReplyID};", 'messages', true); + $CreateReCounter = $GetThreadCount['Count']; + } + $FormData['lock_username'] = true; + $FormData['lock_subject'] = true; + $AllowSend = true; + + $FormData['subject'] = preg_replace('#'.$_Lang['mess_answer_prefix'].'\[[0-9]{1,}\]\: #si', '', $FormData['subject']); + $FormData['subject'] = $_Lang['mess_answer_prefix'].'['.$CreateReCounter.']: '.$FormData['subject']; + } + else + { + $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_CantReply']); + } + } + else + { + $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_CantReply']); + } + } + else + { + if(!empty($_GET['uid']) OR !empty($_POST['uid'])) + { + if(!empty($_POST['uid'])) + { + $UserID = intval($_POST['uid']); + $UIDFromPost = true; + } + else + { + $UserID = intval($_GET['uid']); + $UIDFromPost = false; + } + if($UserID > 0) + { + $CheckUser = doquery("SELECT `id`, `username`, `authlevel` FROM {{table}} WHERE `id` = {$UserID} LIMIT 1;", 'users', true); + if($CheckUser['id'] == $UserID) + { + $FormData['username'] = $CheckUser['username']; + $FormData['uid'] = $UserID; + $FormData['authlevel'] = $CheckUser['authlevel']; + if($UIDFromPost === false) + { + $FormData['lock_username'] = true; + } + $AllowSend = true; + } + else + { + $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_UserNoExist']); + } + } + else + { + $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_BadUserID']); + } + } + + if(!empty($_POST['uname']) && $_POST['uname'] != $FormData['username']) + { + $FormData['username'] = ''; + $FormData['uid'] = ''; + $FormData['authlevel'] = ''; + $AllowSend = false; + + $UserName = trim($_POST['uname']); + if(preg_match(REGEXP_USERNAME_ABSOLUTE, $UserName)) + { + $CheckUser = doquery("SELECT `id`, `authlevel` FROM {{table}} WHERE `username` = '{$UserName}' LIMIT 1;", 'users', true); + if($CheckUser['id'] > 0) + { + $FormData['username'] = $UserName; + $FormData['uid'] = $CheckUser['id']; + $FormData['authlevel'] = $CheckUser['authlevel']; + $AllowSend = true; + } + else + { + $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_UserNoExist']); + } + } + else + { + $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_BadUserName']); + } + } + } + + if($FormData['uid'] > 0 && $FormData['uid'] == $_User['id']) + { + $FormData['username'] = ''; + $FormData['uid'] = ''; + $FormData['lock_username'] = false; + $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_CantWriteToYourself']); + $AllowSend = false; + } + $FormData['type'] = 1; + if(isset($_POST['send_as_admin_msg']) && $_POST['send_as_admin_msg'] == 'on') + { + if(!CheckAuth('supportadmin')) + { + $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_CantUseAdminMsg']); + $AllowSend = false; + } + else + { + $FormData['type'] = 80; + $parse['FormInsert_checkSendAsAdmin'] = 'checked'; + } + } + + $_POST['text'] = (isset($_POST['text']) ? stripslashes(trim($_POST['text'])) : ''); + $_POST['subject'] = (isset($_POST['subject']) ? stripslashes(trim($_POST['subject'])) : ''); + if(get_magic_quotes_gpc()) + { + $_POST['text'] = stripslashes($_POST['text']); + $_POST['subject'] = stripslashes($_POST['subject']); + } + + if(empty($FormData['subject'])) + { + $FormData['subject'] = substr(strip_tags($_POST['subject']), 0, $_MaxLength_Subject); + } + $FormData['text'] = substr(strip_tags($_POST['text']), 0, $_MaxLength_Text); + + if(isset($_POST['send_msg'])) + { + if($FormData['uid'] == 0 && empty($MsgBox)) + { + $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_NoUserID']); + $AllowSend = false; + } + + if(empty($FormData['subject'])) + { + $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_SubjectEmpty']); + $AllowSend = false; + } + if(empty($FormData['text'])) + { + $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_TextEmpty']); + $AllowSend = false; + } + else + { + include($_EnginePath.'includes/functions/FilterMessages.php'); + if(FilterMessages($_POST['text'], 1)) + { + $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_TextSPAM']); + $AllowSend = false; + } + } + + if($FormData['uid'] > 0 && !CheckAuth('user', AUTHCHECK_HIGHER) AND !CheckAuth('user', AUTHCHECK_HIGHER, $FormData)) + { + $Query_IgnoreSystem = ''; + $Query_IgnoreSystem .= "SELECT `OwnerID` FROM {{table}} WHERE "; + $Query_IgnoreSystem .= "(`OwnerID` = {$_User['id']} AND `IgnoredID` = {$FormData['uid']}) OR "; + $Query_IgnoreSystem .= "(`OwnerID` = {$FormData['uid']} AND `IgnoredID` = {$_User['id']}) "; + $Query_IgnoreSystem .= "LIMIT 2; -- messages.php|IgnoreSystem"; + $Result_IgnoreSystem = doquery($Query_IgnoreSystem, 'ignoresystem'); + if(mysql_num_rows($Result_IgnoreSystem) > 0) + { + $AllowSend = false; + while($IgnoreData = mysql_fetch_assoc($Result_IgnoreSystem)) + { + if($IgnoreData['OwnerID'] == $_User['id']) + { + $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_IgnoreYour']); + } + else + { + $MsgBox[] = array('color' => 'red', 'text' => $_Lang['Errors_IgnoreHis']); + } + } + } + } + + if($AllowSend === true) + { + $FormSend['type'] = $FormData['type']; + $FormSend['subject'] = $FormData['subject']; + $FormSend['text'] = $FormData['text']; + $FormSend['uid'] = $FormData['uid']; + $FormSend['Thread_ID'] = $FormData['replyto']; + $FormSend['Thread_IsLast'] = ($FormSend['Thread_ID'] > 0 ? 1 : 0); + + if($FormSend['Thread_ID'] > 0) + { + if($FormData['Thread_Started'] === false) + { + doquery("UPDATE {{table}} SET `Thread_ID` = `id`, `Thread_IsLast` = 1 WHERE `id` = {$FormSend['Thread_ID']} LIMIT 1;", 'messages'); + } + else + { + doquery("UPDATE {{table}} SET `Thread_IsLast` = 0 WHERE `Thread_ID` = {$FormSend['Thread_ID']} AND `id_owner` = {$FormSend['uid']};", 'messages'); + } + } + + Cache_Message($FormSend['uid'], $_User['id'], $Now, $FormSend['type'], '', $FormSend['subject'], $FormSend['text'], $FormSend['Thread_ID'], $FormSend['Thread_IsLast']); + + if(preg_match('#'.$_Lang['mess_answer_prefix'].'\[([0-9]{1,})\]\: #si', $FormData['subject'], $ThisMatch)) + { + $FormData['subject'] = preg_replace('#'.$_Lang['mess_answer_prefix'].'\[[0-9]{1,}\]\: #si', $_Lang['mess_answer_prefix'].'['.($ThisMatch[1] + 1).']: ', $FormData['subject']); + } + $MsgBox[] = array('color' => 'lime', 'text' => $_Lang['Info_MsgSend']); + } + } + + $parse['FormInsert_username'] = $FormData['username']; + $parse['FormInsert_uid'] = $FormData['uid']; + $parse['FormInsert_replyto'] = $FormData['replyto']; + $parse['FormInsert_subject'] = $FormData['subject']; + $parse['FormInsert_text'] = $FormData['text']; + if($FormData['lock_username'] === true) + { + $parse['FormInsert_LockUsername'] = 'disabled'; + } + if($FormData['lock_subject'] === true) + { + $parse['FormInsert_LockSubject'] = 'disabled'; + } + + // Let's handle System Messages + if(!empty($MsgBox)) + { + foreach($MsgBox as $MsgData) + { + $MsgBoxData[] = "{$MsgData['text']}"; + } + $parse['Insert_MsgBoxText'] = implode('
    ', $MsgBoxData); + } + else + { + $parse['Insert_HideMsgBox'] = 'inv'; + $parse['Insert_MsgBoxText'] = ' '; + } + + // Now let's show Form to User + if(!CheckAuth('user', AUTHCHECK_HIGHER)) + { + $parse['FormInsert_displaySendAsAdmin'] = 'display: none;'; + } + $_Lang['FormInsert_MaxSigns'] = $_MaxLength_Text; + if($_GameConfig['enable_bbcode'] == 1) + { + $page = parsetemplate(gettemplate('messages_pm_form_bb'), $parse); + } + else + { + $page = parsetemplate(gettemplate('messages_pm_form'), $parse); + } + // It's done! + break; + + case 'delete': + // Delete or do other things with Selected/Nonselected/Add Messages + + $_ThisCategory = intval($_POST['category']); + $DeleteWhat = $_POST['deletemessages']; + $ActionBreak = false; + if(in_array($DeleteWhat, array('deleteall', 'deleteallcat', 'setallread', 'setcatread'))) + { + $TimeStamp = round($_POST['time']); + if($TimeStamp <= 0 OR $TimeStamp > $Now) + { + $DelNotifs[] = $_Lang['Delete_BadTimestamp']; + $ActionBreak = true; + } + } + + if($ActionBreak !== true) + { + if($DeleteWhat == 'deleteall') + { + // User is Deleting all messages at once (exclude AdminMessages) + + $SelectMsgs = doquery("SELECT `Thread_ID` FROM {{table}} WHERE `time` <= {$TimeStamp} AND `id_owner` = {$_User['id']} AND `type` != 80 AND `Thread_ID` > 0;", 'messages'); + doquery("UPDATE {{table}} SET `deleted` = true WHERE `id_owner` = {$_User['id']} AND `type` != 80 AND `time` <= {$TimeStamp};", 'messages'); + $DeletedCount = mysql_affected_rows(); + if(mysql_num_rows($SelectMsgs) > 0) + { + $UpdateThreads = array(); + while($SelectData = mysql_fetch_assoc($SelectMsgs)) + { + if(!in_array($SelectData['Thread_ID'], $UpdateThreads)) + { + $UpdateThreads[] = $SelectData['Thread_ID']; + } + } + $IDs = implode(',', $UpdateThreads); + $SelectIDs = doquery("SELECT MAX(`id`) AS `id` FROM {{table}} WHERE `Thread_ID` IN ({$IDs}) AND `id_owner` = {$_User['id']} AND `deleted` = false GROUP BY `Thread_ID`;", 'messages'); + if(mysql_num_rows($SelectIDs) > 0) + { + while($SelectData = mysql_fetch_assoc($SelectIDs)) + { + $UpdateIDs[] = $SelectData['id']; + } + $IDs = implode(',', $UpdateIDs); + doquery("UPDATE {{table}} SET `Thread_IsLast` = 1 WHERE `id` IN ({$IDs});", 'messages'); + } + } + + if($DeletedCount > 0) + { + $DelMsgs[] = $_Lang['Delete_AllMsgsDeleted']; + } + else + { + $DelNotifs[] = $_Lang['Delete_NoMsgsToDelete']; + } + } + elseif($DeleteWhat == 'deleteallcat') + { + // User is Deleting all messages in this category at once + if(in_array($_ThisCategory, $MessageType) AND $_ThisCategory != 100 AND $_ThisCategory != 80) + { + $SelectMsgs = doquery("SELECT `Thread_ID` FROM {{table}} WHERE `type` = {$_ThisCategory} AND `time` <= {$TimeStamp} AND `id_owner` = {$_User['id']} AND `Thread_ID` > 0;", 'messages'); + doquery("UPDATE {{table}} SET `deleted` = true WHERE `id_owner` = {$_User['id']} AND `type` = {$_ThisCategory} AND `time` <= {$TimeStamp};", 'messages'); + $DeletedCount = mysql_affected_rows(); + if(mysql_num_rows($SelectMsgs) > 0) + { + $UpdateThreads = array(); + while($SelectData = mysql_fetch_assoc($SelectMsgs)) + { + if(!in_array($SelectData['Thread_ID'], $UpdateThreads)) + { + $UpdateThreads[] = $SelectData['Thread_ID']; + } + } + $IDs = implode(',', $UpdateThreads); + $SelectIDs = doquery("SELECT MAX(`id`) AS `id` FROM {{table}} WHERE `Thread_ID` IN ({$IDs}) AND `id_owner` = {$_User['id']} AND `deleted` = false GROUP BY `Thread_ID`;", 'messages'); + if(mysql_num_rows($SelectIDs) > 0) + { + while($SelectData = mysql_fetch_assoc($SelectIDs)) + { + $UpdateIDs[] = $SelectData['id']; + } + $IDs = implode(',', $UpdateIDs); + doquery("UPDATE {{table}} SET `Thread_IsLast` = 1 WHERE `id` IN ({$IDs});", 'messages'); + } + } + if($DeletedCount > 0) + { + $DelMsgs[] = $_Lang['Delete_AllCatMsgsDeleted']; + } + else + { + $DelNotifs[] = $_Lang['Delete_NoMsgsToDelete']; + } + } + else + { + if($_ThisCategory == 80) + { + // Don't let to delete all AdminMessages + $DelNotifs[] = $_Lang['Delete_CannotDeleteAdminMsgsAtOnce']; + } + else + { + $DelNotifs[] = $_Lang['Delete_BadCatSelected']; + } + } + } + else if($DeleteWhat == 'deletemarked') + { + // User is Deleting all Marked messages + $DeleteIDs = false; + if(!empty($_POST['del_all'])) + { + preg_match_all('#([0-9]{1,})#si', $_POST['del_all'], $DeleteIDs); + $DeleteIDs = $DeleteIDs[0]; + } + else + { + foreach($_POST as $Message => $Answer) + { + if(preg_match("/^del([0-9]{1,})$/D", $Message, $MsgMatch) AND $Answer == 'on') + { + $DeleteIDs[] = $MsgMatch[1]; + } + } + } + if($DeleteIDs !== FALSE) + { + $IDs = implode(',', $DeleteIDs); + $SelectMsgs = doquery("SELECT `id`, `Thread_ID` FROM {{table}} WHERE `id` IN ({$IDs}) AND `id_owner` = {$_User['id']} AND `type` != 80;", 'messages'); + if(mysql_num_rows($SelectMsgs) > 0) + { + $DelMsgs[] = $_Lang['Delete_SelectedDeleted']; + + $UpdateThreads = array(); + while($SelectData = mysql_fetch_assoc($SelectMsgs)) + { + $UpdateIDs[] = $SelectData['id']; + if($SelectData['Thread_ID'] > 0) + { + if(!in_array($SelectData['Thread_ID'], $UpdateThreads)) + { + $UpdateThreads[] = $SelectData['Thread_ID']; + } + } + } + $IDs = implode(',', $UpdateIDs); + $UpdateIDs = array(); + doquery("UPDATE {{table}} SET `deleted` = true, `Thread_IsLast` = 0 WHERE `id` IN ({$IDs});", 'messages'); + if(!empty($UpdateThreads)) + { + $IDs = implode(',', $UpdateThreads); + $SelectIDs = doquery("SELECT MAX(`id`) AS `id` FROM {{table}} WHERE `Thread_ID` IN ({$IDs}) AND `id_owner` = {$_User['id']} AND `deleted` = false GROUP BY `Thread_ID`;", 'messages'); + if(mysql_num_rows($SelectIDs) > 0) + { + while($SelectData = mysql_fetch_assoc($SelectIDs)) + { + $UpdateIDs[] = $SelectData['id']; + } + $IDs = implode(',', $UpdateIDs); + doquery("UPDATE {{table}} SET `Thread_IsLast` = 1 WHERE `id` IN ({$IDs});", 'messages'); + } + } + } + else + { + $DelNotifs[] = $_Lang['Delete_BadSelections']; + } + } + else + { + $DelNotifs[] = $_Lang['Delete_NoMsgsSelected']; + } + } + else if($DeleteWhat == 'deleteunmarked') + { + // User is deleting all Unmarked messages + $DeleteIDs = false; + if(!empty($_POST['sm_all'])) + { + preg_match_all('#([0-9]{1,})#si', $_POST['sm_all'], $DeleteIDs); + $DeleteIDs = $DeleteIDs[0]; + } + else + { + foreach($_POST as $Message => $Answer) + { + if(preg_match("/^sm([0-9]{1,})$/D", $Message, $MsgMatch)) + { + if($_POST[('del'.$MsgMatch[1])] != 'on') + { + $DeleteIDs[] = $MsgMatch[1]; + } + } + } + } + if($DeleteIDs !== FALSE) + { + $IDs = implode(',', $DeleteIDs); + $SelectMsgs = doquery("SELECT `id`, `Thread_ID` FROM {{table}} WHERE `id` IN ({$IDs}) AND `id_owner` = {$_User['id']} AND `type` != 80;", 'messages'); + if(mysql_num_rows($SelectMsgs) > 0) + { + $DelMsgs[] = $_Lang['Delete_UnselectedDeleted']; + + $UpdateThreads = array(); + while($SelectData = mysql_fetch_assoc($SelectMsgs)) + { + $UpdateIDs[] = $SelectData['id']; + if($SelectData['Thread_ID'] > 0) + { + if(!in_array($SelectData['Thread_ID'], $UpdateThreads)) + { + $UpdateThreads[] = $SelectData['Thread_ID']; + } + } + } + $IDs = implode(',', $UpdateIDs); + $UpdateIDs = array(); + doquery("UPDATE {{table}} SET `deleted` = true, `Thread_IsLast` = 0 WHERE `id` IN ({$IDs});", 'messages'); + if(!empty($UpdateThreads)) + { + $IDs = implode(',', $UpdateThreads); + $SelectIDs = doquery("SELECT MAX(`id`) AS `id` FROM {{table}} WHERE `Thread_ID` IN ({$IDs}) AND `id_owner` = {$_User['id']} AND `deleted` = false GROUP BY `Thread_ID`;", 'messages'); + if(mysql_num_rows($SelectIDs) > 0) + { + while($SelectData = mysql_fetch_assoc($SelectIDs)) + { + $UpdateIDs[] = $SelectData['id']; + } + $IDs = implode(',', $UpdateIDs); + doquery("UPDATE {{table}} SET `Thread_IsLast` = 1 WHERE `id` IN ({$IDs});", 'messages'); + } + } + } + else + { + $DelNotifs[] = $_Lang['Delete_BadSelections']; + } + } + else + { + $DelNotifs[] = $_Lang['Delete_NoMsgsUnselected']; + } + } + else if($DeleteWhat == 'setallread') + { + // User wants to set All messages as "read" + doquery("UPDATE {{table}} SET `read` = true WHERE `id_owner` = {$_User['id']} AND `type` != 80 AND `time` <= {$TimeStamp};", 'messages'); + if(mysql_affected_rows() > 0) + { + $DelMsgs[] = $_Lang['Delete_AllMsgsRead']; + } + else + { + $DelNotifs[] = $_Lang['Delete_NoMsgsToRead']; + } + } + else if($DeleteWhat == 'setcatread') + { + // User is setting All messages in this Cat as "read" + if(in_array($_ThisCategory, $MessageType) AND $_ThisCategory != 100 AND $_ThisCategory != 80) + { + doquery("UPDATE {{table}} SET `read` = true WHERE `id_owner` = {$_User['id']} AND `type` = {$_ThisCategory} AND `time` <= {$TimeStamp};", 'messages'); + if(mysql_affected_rows() > 0) + { + $DelMsgs[] = $_Lang['Delete_CatMsgsRead']; + } + else + { + $DelNotifs[] = $_Lang['Delete_NoMsgsToRead']; + } + } + else + { + if($_ThisCategory == 80) + { + // Don't let to "read" all AdminMessages + $DelNotifs[] = $_Lang['Delete_CannotReadAdminMsgsAtOnce']; + } + else + { + $DelNotifs[] = $_Lang['Delete_BadCatSelected']; + } + } + } + else + { + // User is Deleting single message + if(!empty($_POST['delid'])) + { + $DeleteID = round(floatval($_POST['delid'])); + $SelectMsg = doquery("SELECT `id`, `Thread_ID` FROM {{table}} WHERE `id` = {$DeleteID} AND `id_owner` = {$_User['id']} LIMIT 1;", 'messages', true); + if($SelectMsg['id'] == $DeleteID) + { + $DelMsgs[] = $_Lang['Delete_MsgDeleted']; + + doquery("UPDATE {{table}} SET `deleted` = true, `Thread_IsLast` = 0 WHERE `id` = {$DeleteID};", 'messages'); + if($SelectMsg['Thread_ID'] > 0) + { + doquery("UPDATE {{table}} SET `Thread_IsLast` = 1 WHERE `Thread_ID` = {$SelectMsg['Thread_ID']} AND `id_owner` = {$_User['id']} AND `deleted` = false ORDER BY `id` DESC LIMIT 1;", 'messages'); + } + } + else + { + $DelNotifs[] = $_Lang['Delete_MsgNoExist']; + } + } + } + } + + if(!empty($DelMsgs)) + { + foreach($DelMsgs as $Data) + { + $MsgBoxData[] = "{$Data}"; + } + } + if(!empty($DelNotifs)) + { + foreach($DelNotifs as $Data) + { + $MsgBoxData[] = "{$Data}"; + } + } + // Don't break here to allow deleting while showing... + + case 'show': + // Show Messages + + if($_User['settings_msgperpage'] <= 0) + { + $_PerPage = 20; + } + else + { + $_PerPage = $_User['settings_msgperpage']; + } + if(isset($_POST['page']) && !empty($_POST['page'])) + { + $_ThisPage = intval($_POST['page']); + } + else + { + $_ThisPage = isset($_GET['page']) ? intval($_GET['page']) : 0; + } + + $PageTPL = gettemplate('message_list'); + $parse['InsertTimestamp'] = $Now; + + if($_User['settings_spyexpand'] == 0) + { + $parse['SpyExpanded'] = 'true'; + $parse['SpyDisplay'] = ''; + } + else + { + $parse['SpyExpanded'] = 'false'; + $parse['SpyDisplay'] = 'display: none;'; + } + + if($_ThisPage > 1) + { + $Start = ($_ThisPage - 1) * $_PerPage; + } + else + { + $_ThisPage = 1; + $Start = 0; + } + + if(!in_array($_ThisCategory, $MessageType)) + { + $_ThisCategory = 100; + } + + $parse['SelectedCat'] = $_Lang['type'][$_ThisCategory]; + if($_ThisCategory == 100) + { + $parse['show_delete_all_cat'] = 'style="display: none;"'; + $GetMsgCountType = "`type` != 80"; + $parse['Hide_NoActions'] = ' style="display: none"'; + } + else + { + $GetMsgCountType = "`type` = {$_ThisCategory}"; + if($_ThisCategory == 80) + { + $parse['Hide_AdminMsg'] = ' style="display: none"'; + } + else + { + $parse['Hide_NoActions'] = ' style="display: none"'; + } + } + if($_UseThreads) + { + $GetMsgCount = doquery("SELECT COUNT(`id`) as `count` FROM {{table}} WHERE `deleted` = false AND `id_owner` = {$_User['id']} AND (`type` NOT IN (".implode(', ', $_CanBeThreaded).") OR `Thread_ID` = 0 OR `Thread_IsLast` = 1) AND {$GetMsgCountType};", 'messages', true); + } + else + { + $GetMsgCount = doquery("SELECT COUNT(`id`) as `count` FROM {{table}} WHERE `deleted` = false AND `id_owner` = {$_User['id']} AND {$GetMsgCountType};", 'messages', true); + } + $MsgCount = $GetMsgCount['count']; + + if($Start >= $MsgCount) + { + $_ThisPage = ceil($MsgCount/$_PerPage); + $Start = ($_ThisPage - 1) * $_PerPage; + } + + $Pagination = ''; + if($MsgCount > $_PerPage) + { + include_once($_EnginePath.'includes/functions/Pagination.php'); + $Pagin = CreatePaginationArray($MsgCount, $_PerPage, $_ThisPage, 7); + $PaginationTPL = "{\$ShowValue}"; + $PaginationViewOpt = array('CurrentPage_Classes' => 'orange', 'Breaker_View' => '...'); + $CreatePagination = implode(' ', ParsePaginationArray($Pagin, $_ThisPage, $PaginationTPL, $PaginationViewOpt)); + + $Pagination = "{$_Lang['Pages']}{$CreatePagination}"; + } + + $parse['ThisPage'] = $_ThisPage; + $parse['MessCategory'] = $_ThisCategory; + $parse['MessCategoryColor'] = $TitleColor[$_ThisCategory]; + $parse['Pagination'] = $Pagination; + $page = ''; + + // Let's show Messages! + if($MsgCount > 0) + { + if($_ThisCategory == 100) + { + $GetMsgsType = '!= 80'; + } + else + { + $GetMsgsType = "= {$_ThisCategory}"; + } + $Query_GetMessages = ''; + $Query_GetMessages .= "SELECT `m`.*, `u`.`username`, `u`.`authlevel` FROM {{table}} AS `m` "; + $Query_GetMessages .= "LEFT JOIN `{{prefix}}users` AS `u` ON `u`.`id` = `m`.`id_sender` "; + if($_UseThreads) + { + $Query_GetMessages .= "WHERE `m`.`deleted` = false AND `m`.`id_owner` = {$_User['id']} AND (`type` NOT IN (".implode(', ', $_CanBeThreaded).") OR `m`.`Thread_ID` = 0 OR `m`.`Thread_IsLast` = 1) AND `m`.`type` {$GetMsgsType} "; + } + else + { + $Query_GetMessages .= "WHERE `m`.`deleted` = false AND `m`.`id_owner` = {$_User['id']} AND `m`.`type` {$GetMsgsType} "; + } + $Query_GetMessages .= "ORDER BY `m`.`time` DESC, `m`.`id` DESC LIMIT {$Start}, {$_PerPage};"; + + $GetMessages = doquery($Query_GetMessages, 'messages'); + + if(mysql_num_rows($GetMessages) > 0) + { + if($_GameConfig['enable_bbcode'] == 1) + { + include($_EnginePath.'includes/functions/BBcodeFunction.php'); + } + + $ReadIDs = false; + $Messages = array(); + $CheckThreads = array(); + + while($CurMess = mysql_fetch_assoc($GetMessages)) + { + $MsgCache[] = $CurMess; + if($_UseThreads AND $CurMess['Thread_ID'] > 0 AND in_array($CurMess['type'], $_CanBeThreaded)) + { + $CheckThreads[] = $CurMess['Thread_ID']; + $CheckThreadsExclude[] = $CurMess['id']; + $ThreadMap[$CurMess['Thread_ID']] = $CurMess['id']; + } + } + + if(!empty($CheckThreads)) + { + $ThreadsIDs = implode(', ', $CheckThreads); + $ExcludeIDs = implode(', ', $CheckThreadsExclude); + $Query_GetThreaded = ''; + $Query_GetThreaded .= "SELECT `m`.*, `u`.`username`, `u`.`authlevel` FROM {{table}} AS `m` "; + $Query_GetThreaded .= "LEFT JOIN `{{prefix}}users` AS `u` ON `u`.`id` = `m`.`id_sender` "; + $Query_GetThreaded .= "WHERE `m`.`deleted` = false AND `m`.`id_owner` = {$_User['id']} AND `read` = false AND `m`.`Thread_ID` IN ({$ThreadsIDs}) AND `m`.`id` NOT IN ({$ExcludeIDs}) "; + $Query_GetThreaded .= "ORDER BY `m`.`id` DESC;"; + + $GetMessages = doquery($Query_GetThreaded, 'messages'); + if(mysql_num_rows($GetMessages) > 0) + { + while($CurMess = mysql_fetch_assoc($GetMessages)) + { + $CurMess['isAdditional'] = true; + $MsgCache[] = $CurMess; + } + } + + foreach($CheckThreads as $ThreadID) + { + $Query_ThreadsLengthWhere[] = "(`Thread_ID` = {$ThreadID} AND `id` <= {$ThreadMap[$ThreadID]})"; + } + $Query_ThreadsLengthWhere = implode(' OR ', $Query_ThreadsLengthWhere); + $Query_ThreadsLength = "SELECT `Thread_ID`, COUNT(*) AS `Count` FROM {{table}} WHERE {$Query_ThreadsLengthWhere} AND (`id_sender` = {$_User['id']} OR `deleted` = false) GROUP BY `Thread_ID`;"; + $GetThreadsLength = doquery($Query_ThreadsLength, 'messages'); + if(mysql_num_rows($GetThreadsLength) > 0) + { + while($ThisThread = mysql_fetch_assoc($GetThreadsLength)) + { + $ThreadsLength[$ThisThread['Thread_ID']] = $ThisThread['Count']; + } + } + } + + foreach($MsgCache as $MsgIndex => $CurMess) + { + $parseMSG = array(); + if($CurMess['read'] == false) + { + $ReadIDs[] = $CurMess['id']; + } + + if($CurMess['id_sender'] == 0) + { + // Message sent by System + $MsgArray = json_decode($CurMess['text'], true); + $CurMess['from'] = $_Lang['msg_const']['senders']['system'][$CurMess['from']]; + $CurMess['subject'] = $_Lang['msg_const']['subjects'][$CurMess['subject']]; + if(empty($MsgArray['msg_text'])) + { + // Constant-formated Message + if(!empty($MsgArray['msg_id'])) + { + $CurMess['text'] = vsprintf($_Lang['msg_const']['msgs'][$MsgArray['msg_id']], $MsgArray['args']); + } + else + { + $CurMess['text'] = sprintf($_Lang['msg_const']['msgs']['err2'], $CurMess['id']); + } + } + else + { + // NonConstant Message (eg. SpyReport) + if((array)$MsgArray['msg_text'] === $MsgArray['msg_text']) + { + if(!empty($MsgArray['sim'])) + { + $CreatedForms += 1; + $Temp = explode(';', $MsgArray['sim']); + foreach($Temp as $Data) + { + $Data = explode(',', $Data); + if(!empty($Data[0])) + { + if(in_array($Data[0], $SimTechs)) + { + $MsgArray['simData']['tech'][$SimTechsRep[$Data[0]]] = $Data[1]; + } + else + { + $MsgArray['simData']['ships'][$Data[0]] = $Data[1]; + } + } + } + $CreateSimForms .= sprintf($_Lang['msg_const']['sim']['form'], $CreatedForms, json_encode($MsgArray['simData'])); + + $_Lang['GoToSimButton'] = sprintf($_Lang['msg_const']['sim']['button'], 'sim_'.$CreatedForms); + } + $CurMess['text'] = implode('', innerReplace(multidim2onedim($MsgArray['msg_text']), $_Lang)); + } + else + { + $CurMess['text'] = sprintf($_Lang['msg_const']['msgs']['err'], $CurMess['id']); + } + } + } + else + { + // Message sent by User + $AddFrom = ''; + if(!empty($CurMess['from'])) + { + $AddFrom = ' '.$CurMess['from']; + } + $CurMess['from'] = "{$_Lang['msg_const']['senders']['rangs'][GetAuthLabel($CurMess)]} {$CurMess['username']}{$AddFrom}"; + + if(in_array($CurMess['type'], array(2, 80)) AND preg_match('/^\{COPY\_MSG\_\#([0-9]{1,}){1}\}$/D', $CurMess['text'], $ThisMatch)) + { + $GetMassMsgs[] = $ThisMatch[1]; + $CopyMsgMap[$ThisMatch[1]][] = $CurMess['id']; + $CurMess['text'] = sprintf($_Lang['msg_const']['msgs']['err4'], $CurMess['id']); + } + else + { + if($_GameConfig['enable_bbcode'] == 1) + { + $CurMess['text'] = bbcode(image($CurMess['text'])); + } + $CurMess['text'] = nl2br($CurMess['text']); + } + + if($CurMess['Thread_ID'] > 0) + { + $parseMSG['isThreaded'] = true; + $parseMSG['Thread_ID'] = $CurMess['Thread_ID']; + } + } + + $parseMSG['CurrMSG_ID'] = $CurMess['id']; + if($CurMess['read'] == false) + { + $parseMSG['CurrMSG_IsUnread'] = ' class="isNew"'; + } + $parseMSG['CurrMSG_date'] = date('d.m.Y', $CurMess['time']); + $parseMSG['CurrMSG_time'] = date('H:i:s', $CurMess['time']); + $parseMSG['CurrMSG_from'] = $CurMess['from']; + $parseMSG['CurrMSG_subject'] = $CurMess['subject']; + $parseMSG['CurrMSG_text'] = $CurMess['text']; + if($_ThisCategory == 100) + { + $parseMSG['CurrMSG_color'] = $MsgColors[$CurMess['type']]; + } + else + { + $parseMSG['CurrMSG_color'] = ''; + } + if($CurMess['type'] == 80) + { + $parseMSG['CurrMSG_HideCheckbox'] = 'class="inv"'; + } + $parseMSG['CurrMSG_send'] = sprintf($_Lang['mess_send_date'], $parseMSG['CurrMSG_date'], $parseMSG['CurrMSG_time']); + if($CurMess['id_sender'] == 0) + { + if($CurMess['type'] == 3) + { + $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_convert']}"; + } + $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_report']}"; + $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_delete_single']}"; + } + else + { + if($CurMess['id_sender'] != $_User['id']) + { + $parseMSG['CurrMSG_buttons'][] = " 0 ? $CurMess['Thread_ID'] : $CurMess['id'])."\">{$_Lang['mess_reply']}"; + } + if($CurMess['type'] == 2 AND $_User['ally_id'] > 0) + { + $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_reply_toally']}"; + } + + if($CurMess['type'] != 80 AND $CurMess['type'] != 2 AND !CheckAuth('user', AUTHCHECK_HIGHER, $CurMess)) + { + $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_ignore']}"; + } + $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_report']}"; + $parseMSG['CurrMSG_buttons'][] = "{$_Lang['mess_delete_single']}"; + } + if(!empty($parseMSG['CurrMSG_buttons'])) + { + $parseMSG['CurrMSG_buttons'] = implode('', $parseMSG['CurrMSG_buttons']); + } + + if(isset($CurMess['isAdditional']) && $CurMess['isAdditional'] === true) + { + $parseMSG['isAdditional'] = true; + } + + $Messages[$CurMess['id']] = $parseMSG; + } + $MsgCache = null; + + if($ReadIDs !== FALSE) + { + $ReadIDs = implode(', ', $ReadIDs); + doquery("UPDATE {{table}} SET `read` = true WHERE `id` IN ({$ReadIDs}) AND `deleted` = false;", 'messages'); + } + + if(!empty($GetMassMsgs)) + { + if($_ThisCategory == 100) + { + $QryGetMassMsg = doquery("SELECT `id`, `type`, `subject`, `text` FROM {{table}} WHERE `id` IN (".implode(', ', $GetMassMsgs).");", 'messages'); + } + else + { + $QryGetMassMsg = doquery("SELECT `id`, `type`, `subject`, `text`, `from` FROM {{table}} WHERE `id` IN (".implode(', ', $GetMassMsgs).");", 'messages'); + } + while($CopyData = mysql_fetch_assoc($QryGetMassMsg)) + { + if($CopyData['type'] == 80 OR $CopyData['type'] == 2) + { + if($_GameConfig['enable_bbcode'] == 1) + { + $CopyData['text'] = bbcode(image($CopyData['text'])); + } + $CopyData['text'] = nl2br($CopyData['text']); + foreach($CopyMsgMap[$CopyData['id']] as $MsgKey) + { + $Messages[$MsgKey]['CurrMSG_subject'] = $CopyData['subject']; + $Messages[$MsgKey]['CurrMSG_text'] = $CopyData['text']; + if($CopyData['type'] == 2) + { + $Messages[$MsgKey]['CurrMSG_from'] .= ' '.$CopyData['from']; + } + } + } + else + { + foreach($CopyMsgMap[$CopyData['id']] as $MsgKey) + { + $Messages[$MsgKey]['CurrMSG_subject'] = $_Lang['msg_const']['subjects']['019']; + $Messages[$MsgKey]['CurrMSG_text'] = sprintf($_Lang['msg_const']['msgs']['err3'], $CopyData['id']); + } + } + } + } + + $MsgTPL = gettemplate('message_mailbox_body'); + $ThreadMsgTPL = gettemplate('message_mailbox_threaded'); + foreach($Messages as $ThisKey => $MessageData) + { + if(isset($MessageData['isAdditional']) && $MessageData['isAdditional'] === true) + { + $ExcludeThreadIDs[$MessageData['Thread_ID']][] = $MessageData['CurrMSG_ID']; + $Messages[$ThreadMap[$MessageData['Thread_ID']]]['AddMSG_parsed'][] = parsetemplate($MsgTPL, $MessageData); + unset($Messages[$ThisKey]); + } + } + foreach($Messages as $MessageData) + { + if($_UseThreads && isset($MessageData['Thread_ID']) && $MessageData['Thread_ID'] > 0) + { + if(!empty($MessageData['AddMSG_parsed'])) + { + $NeededLength = 1 + count($MessageData['AddMSG_parsed']); + } + else + { + $NeededLength = 1; + } + $ThreadParse = array + ( + 'Hidden' => 0, + 'Lang_Expand' => $_Lang['Action_Expand'], + 'Lang_Collapse' => $_Lang['Action_Collapse'], + 'Lang_Loading' => $_Lang['Action_ThreadLoading'], + 'Insert_ThreadID' => $MessageData['Thread_ID'], + 'Insert_MaxMsgID' => $MessageData['CurrMSG_ID'], + 'Insert_CatID' => $_ThisCategory, + 'Insert_ExcludeIDs' => (!empty($ExcludeThreadIDs[$MessageData['Thread_ID']]) ? implode('_', $ExcludeThreadIDs[$MessageData['Thread_ID']]) : ''), + ); + if(!empty($MessageData['AddMSG_parsed'])) + { + $ThreadParse['Insert_Msgs'] = implode('', $MessageData['AddMSG_parsed']); + } + else + { + $ThreadParse['Insert_HideParsed'] = 'hide'; + $ThreadParse['Hidden'] += 1; + } + if($ThreadsLength[$MessageData['Thread_ID']] <= $NeededLength) + { + $ThreadParse['Insert_HideExpand'] = 'hide'; + $ThreadParse['Hidden'] += 1; + } + else + { + $ThreadParse['Insert_Count'] = prettyNumber($ThreadsLength[$MessageData['Thread_ID']]); + } + if($ThreadParse['Hidden'] < 2) + { + $MessageData['AddMSG_parsed'] = parsetemplate($ThreadMsgTPL, $ThreadParse); + } + } + $AllMessages[] = parsetemplate($MsgTPL, $MessageData); + } + $page .= implode('', $AllMessages); + $Messages = null; + $AllMessages = null; + } + else + { + $page .= "{$_Lang['NoMessages']}"; + } + } + else + { + $parse['Hide_headers'] = ' class="hide"'; + $page .= "{$_Lang['NoMessages']}"; + $parse['Hide_NoActions'] = ' style="display: none"'; + } + + if(!empty($MsgInfos)) + { + foreach($MsgInfos as $Data) + { + $MsgBoxData[] = "{$Data}"; + } + } + + $InsertMsgBox = ''; + if(!empty($MsgBoxData)) + { + $InsertMsgBox = ''.implode('
    ', $MsgBoxData).''; + } + $parse['content'] = $page; + $parse['MsgBox'] = $InsertMsgBox; + + $page = parsetemplate($PageTPL, $parse); + + break; + + default: + // Show Message Categories + $GetCounters = doquery("SELECT `type`, `read`, `Thread_ID`, `Thread_IsLast`, COUNT(*) AS `Count` FROM {{table}} WHERE `id_owner` = {$_User['id']} AND `deleted` = false GROUP BY `type`, `read`, `Thread_ID`, `Thread_IsLast` ORDER BY `Thread_IsLast` DESC;", 'messages'); + if(mysql_num_rows($GetCounters) > 0) + { + $SeenThreads = array(); + $ThreadMainTypes = array(); + while($Counter = mysql_fetch_assoc($GetCounters)) + { + // Handler TypeCount + if($_UseThreads AND $Counter['Thread_ID'] > 0) + { + if($Counter['Thread_IsLast'] == 1) + { + $ThreadMainTypes[$Counter['Thread_ID']] = $Counter['type']; + } + else + { + $Counter['type'] = $ThreadMainTypes[$Counter['Thread_ID']]; + } + if(!in_array($Counter['Thread_ID'], $SeenThreads)) + { + $MsgCounter['threaded'][$Counter['type']] += 1; + } + } + else + { + + $MsgCounter['threaded'][$Counter['type']] += $Counter['Count']; + } + $MsgCounter['total'][$Counter['type']] += $Counter['Count']; + if($Counter['read'] == 0) + { + $MsgCounter['unread'][$Counter['type']] += $Counter['Count']; + } + // Handle TotalCount + if($Counter['type'] != 80) + { + $MsgCounter['total'][100] += $Counter['Count']; + if($Counter['read'] == 0) + { + $MsgCounter['unread'][100] += $Counter['Count']; + } + if($_UseThreads AND $Counter['Thread_ID'] > 0) + { + if(!in_array($Counter['Thread_ID'], $SeenThreads)) + { + $MsgCounter['threaded'][100] += 1; + } + } + else + { + $MsgCounter['threaded'][100] += $Counter['Count']; + } + } + + if($_UseThreads AND $Counter['Thread_ID'] > 0) + { + if(!in_array($Counter['Thread_ID'], $SeenThreads)) + { + $SeenThreads[] = $Counter['Thread_ID']; + } + } + } + } + + $TPL_CatList_Body = gettemplate('messages_catlist_body'); + $TPL_CatList_Row = gettemplate('messages_catlist_row'); + + foreach($MessageType as $TypeID) + { + $ThisClass = 'c'.(string)($TypeID + 0); + $parse['Insert_Styles'] .= ".{$ThisClass} { color: {$TitleColor[$TypeID]}; } "; + $ThisArray = array + ( + 'Insert_CatID' => $TypeID, + 'Insert_CatClass' => $ThisClass, + 'Insert_CatName' => $_Lang['type'][$TypeID], + 'Insert_CatUnread' => prettyNumber($MsgCounter['unread'][$TypeID]), + 'Insert_CatTotal' => (($_UseThreads AND in_array($TypeID, $_CanBeThreaded) AND $MsgCounter['threaded'][$TypeID] < $MsgCounter['total'][$TypeID]) ? prettyNumber($MsgCounter['threaded'][$TypeID]).'/' : '').prettyNumber($MsgCounter['total'][$TypeID]), + ); + $parse['Insert_CategoryList'] .= parsetemplate($TPL_CatList_Row, $ThisArray); + } + + if($_UseThreads) + { + $parse['Insert_Hide_ThreadEnabled'] = 'display: none;'; + } + else + { + $parse['Insert_Hide_ThreadDisabled'] = 'display: none;'; + } + + $page = parsetemplate($TPL_CatList_Body, $parse); + + break; +} + +display($CreateSimForms.$page, $SetTitle); + +?> diff --git a/modules/ally.changepact.php b/modules/ally.changepact.php index 2f015dea1..105406a5e 100644 --- a/modules/ally.changepact.php +++ b/modules/ally.changepact.php @@ -1,167 +1,167 @@ - $RankData) - { - foreach($RankData as $DataID => $DataVal) - { - $ParsedRanks[$RankID][$_Vars_AllyRankLabels[$DataID]] = $DataVal; - } - if($ParsedRanks[$RankID]['warnpact'] === true) - { - $RanksID[] = $RankID; - } - } - if(!empty($RanksID)) - { - $RanksID = implode(',', $RanksID); - $Query_GetUsers = ''; - $Query_GetUsers .= "SELECT `id` FROM {{table}} WHERE "; - $Query_GetUsers .= "`ally_id` = {$AllyID} AND `ally_rank_id` IN ({$RanksID})"; - $Query_GetUsers .= "; -- ally.changepact.php|SendNotification|GetUsers"; - $Result_GetUsers = doquery($Query_GetUsers, 'users'); - while($FetchData = mysql_fetch_assoc($Result_GetUsers)) - { - $UserIDs[] = $FetchData['id']; - } - - if(!empty($UserIDs)) - { - Cache_Message($UserIDs, 0, null, 2, $Message['from'], $Message['subject'], $Message['content']); - } - } - } - - if($_ThisUserRank['warnpact'] !== true) - { - message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php', 3); - } - - $Manage_AID = (isset($_GET['aid']) ? intval($_GET['aid']) : 0); - if($Manage_AID <= 0 OR $Manage_AID == $Ally['id']) - { - message($_Lang['Ally_PactChange_BadAID'], $_Lang['Ally_PactChange_Title'], 'alliance.php?mode=pactslist', 3); - } - - $Query_GetPactData = ''; - $Query_GetPactData .= "SELECT `pact`.*, `ally`.`ally_name`, `ally`.`ally_ranks` FROM {{table}} AS `pact` "; - $Query_GetPactData .= "LEFT JOIN `{{prefix}}alliance` AS `ally` ON `ally`.`id` = IF(`pact`.`AllyID_Sender` = {$Ally['id']}, `pact`.`AllyID_Owner`, `pact`.`AllyID_Sender`) "; - $Query_GetPactData .= "WHERE "; - $Query_GetPactData .= "(`pact`.`AllyID_Sender` = {$Ally['id']} AND `pact`.`AllyID_Owner` = {$Manage_AID}) OR "; - $Query_GetPactData .= "(`pact`.`AllyID_Owner` = {$Ally['id']} AND `pact`.`AllyID_Sender` = {$Manage_AID}) "; - $Query_GetPactData .= "LIMIT 1; -- ally.changepact.php|GetPactData"; - $Result_GetPactData = doquery($Query_GetPactData, 'ally_pacts', true); - if(empty($Result_GetPactData['AllyID_Sender'])) - { - message($_Lang['Ally_PactChange_PactDoesntExist'], $_Lang['Ally_PactChange_Title'], 'alliance.php?mode=pactslist', 3); - } - - $Manage_IsSender = ($Result_GetPactData['AllyID_Sender'] == $Ally['id'] ? true : false); - if(($Manage_IsSender && $Result_GetPactData['Change_Sender'] > 0) || (!$Manage_IsSender && $Result_GetPactData['Change_Owner'] > 0)) - { - message($_Lang['Ally_PactChange_PactChangeAwaiting'], $_Lang['Ally_PactChange_Title'], 'alliance.php?mode=pactslist', 3); - } - - $_Lang['Insert_AID'] = $Manage_AID; - $_Lang['Insert_AllyName'] = $Result_GetPactData['ally_name']; - $_Lang['Insert_CurrentOption_'.$Result_GetPactData['Type']] = 'style="color: orange" selected'; - $_Lang['Insert_CurrentType'] = $_Lang['Ally_PactNew_Type_'.$Result_GetPactData['Type']]; - - if(isset($_POST['sent']) && $_POST['sent'] == 1) - { - $NewPact_Msg['color'] = 'red'; - $Manage_NewType = intval($_POST['type']); - if(in_array($Manage_NewType, array(1, 2, 3, 4))) - { - if($Manage_NewType != $Result_GetPactData['Type']) - { - if($Manage_NewType > $Result_GetPactData['Type']) - { - if($Manage_IsSender) - { - $UpdateField = 'Change_Sender'; - $CheckOtherField = 'Change_Owner'; - } - else - { - $UpdateField = 'Change_Owner'; - $CheckOtherField = 'Change_Sender'; - } - if($Result_GetPactData[$CheckOtherField] != $Manage_NewType) - { - $Query_UpdatePactType = ''; - $Query_UpdatePactType .= "UPDATE {{table}} SET "; - $Query_UpdatePactType .= "`{$UpdateField}` = {$Manage_NewType} "; - $Query_UpdatePactType .= "WHERE "; - $Query_UpdatePactType .= "`AllyID_Sender` = {$Result_GetPactData['AllyID_Sender']} AND "; - $Query_UpdatePactType .= "`AllyID_Owner` = {$Result_GetPactData['AllyID_Owner']} "; - $Query_UpdatePactType .= "LIMIT 1; -- ally.changepact.php|UpdatePactType|Higher"; - doquery($Query_UpdatePactType, 'ally_pacts'); - - $Message = array(); - $Message['msg_id'] = '104'; - $Message['args'] = array($Ally['id'], $Ally['ally_name']); - $Message = json_encode($Message); - $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); - SendNotification($Manage_AID, $Result_GetPactData['ally_ranks'], $Message); - - message($_Lang['Ally_PactChange_Msg_Ok_Higher'], $_Lang['Ally_PactChange_Title'], 'alliance.php?mode=pactslist', 3); - } - else - { - $NewPact_Msg['text'] = $_Lang['Ally_PactChange_Msg_TypeAlreadyProposed']; - } - } - else - { - $Query_UpdatePactType = ''; - $Query_UpdatePactType .= "UPDATE {{table}} SET "; - $Query_UpdatePactType .= "`Type` = {$Manage_NewType} "; - $Query_UpdatePactType .= "WHERE "; - $Query_UpdatePactType .= "`AllyID_Sender` = {$Result_GetPactData['AllyID_Sender']} AND "; - $Query_UpdatePactType .= "`AllyID_Owner` = {$Result_GetPactData['AllyID_Owner']} "; - $Query_UpdatePactType .= "LIMIT 1; -- ally.changepact.php|UpdatePactType|Lower"; - doquery($Query_UpdatePactType, 'ally_pacts'); - - $Message = array(); - $Message['msg_id'] = '105'; - $Message['args'] = array($Ally['id'], $Ally['ally_name'], $_Lang['Ally_PactNew_Type_'.$Manage_NewType]); - $Message = json_encode($Message); - $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); - SendNotification($Manage_AID, $Result_GetPactData['ally_ranks'], $Message); - - message($_Lang['Ally_PactChange_Msg_Ok_Lower'], $_Lang['Ally_PactChange_Title'], 'alliance.php?mode=pactslist', 3); - } - } - else - { - $NewPact_Msg['text'] = $_Lang['Ally_PactChange_Msg_TypeSame']; - } - } - else - { - $NewPact_Msg['text'] = $_Lang['Ally_PactChange_Msg_TypeBad']; - } - } - - $_Lang['Insert_MsgBox'] = ''; - if(!empty($NewPact_Msg)) - { - $_Lang['Insert_MsgBox'] .= parsetemplate(gettemplate('_singleRow'), array('Colspan' => 2, 'Classes' => 'pad5 '.$NewPact_Msg['color'], 'Text' => $NewPact_Msg['text'])); - $_Lang['Insert_MsgBox'] .= parsetemplate(gettemplate('_singleRow'), array('Colspan' => 2, 'Classes' => 'inv', 'Text' => '')); - } - - $Page = parsetemplate(gettemplate('alliance_changepact'), $_Lang); - display($Page, $_Lang['Ally_PactChange_Title']); - -?> \ No newline at end of file + $RankData) + { + foreach($RankData as $DataID => $DataVal) + { + $ParsedRanks[$RankID][$_Vars_AllyRankLabels[$DataID]] = $DataVal; + } + if($ParsedRanks[$RankID]['warnpact'] === true) + { + $RanksID[] = $RankID; + } + } + if(!empty($RanksID)) + { + $RanksID = implode(',', $RanksID); + $Query_GetUsers = ''; + $Query_GetUsers .= "SELECT `id` FROM {{table}} WHERE "; + $Query_GetUsers .= "`ally_id` = {$AllyID} AND `ally_rank_id` IN ({$RanksID})"; + $Query_GetUsers .= "; -- ally.changepact.php|SendNotification|GetUsers"; + $Result_GetUsers = doquery($Query_GetUsers, 'users'); + while($FetchData = mysql_fetch_assoc($Result_GetUsers)) + { + $UserIDs[] = $FetchData['id']; + } + + if(!empty($UserIDs)) + { + Cache_Message($UserIDs, 0, null, 2, $Message['from'], $Message['subject'], $Message['content']); + } + } +} + +if($_ThisUserRank['warnpact'] !== true) +{ + message($_Lang['Ally_AccessDenied'], $MsgTitle, 'alliance.php', 3); +} + +$Manage_AID = (isset($_GET['aid']) ? intval($_GET['aid']) : 0); +if($Manage_AID <= 0 OR $Manage_AID == $Ally['id']) +{ + message($_Lang['Ally_PactChange_BadAID'], $_Lang['Ally_PactChange_Title'], 'alliance.php?mode=pactslist', 3); +} + +$Query_GetPactData = ''; +$Query_GetPactData .= "SELECT `pact`.*, `ally`.`ally_name`, `ally`.`ally_ranks` FROM {{table}} AS `pact` "; +$Query_GetPactData .= "LEFT JOIN `{{prefix}}alliance` AS `ally` ON `ally`.`id` = IF(`pact`.`AllyID_Sender` = {$Ally['id']}, `pact`.`AllyID_Owner`, `pact`.`AllyID_Sender`) "; +$Query_GetPactData .= "WHERE "; +$Query_GetPactData .= "(`pact`.`AllyID_Sender` = {$Ally['id']} AND `pact`.`AllyID_Owner` = {$Manage_AID}) OR "; +$Query_GetPactData .= "(`pact`.`AllyID_Owner` = {$Ally['id']} AND `pact`.`AllyID_Sender` = {$Manage_AID}) "; +$Query_GetPactData .= "LIMIT 1; -- ally.changepact.php|GetPactData"; +$Result_GetPactData = doquery($Query_GetPactData, 'ally_pacts', true); +if(empty($Result_GetPactData['AllyID_Sender'])) +{ + message($_Lang['Ally_PactChange_PactDoesntExist'], $_Lang['Ally_PactChange_Title'], 'alliance.php?mode=pactslist', 3); +} + +$Manage_IsSender = ($Result_GetPactData['AllyID_Sender'] == $Ally['id'] ? true : false); +if(($Manage_IsSender && $Result_GetPactData['Change_Sender'] > 0) || (!$Manage_IsSender && $Result_GetPactData['Change_Owner'] > 0)) +{ + message($_Lang['Ally_PactChange_PactChangeAwaiting'], $_Lang['Ally_PactChange_Title'], 'alliance.php?mode=pactslist', 3); +} + +$_Lang['Insert_AID'] = $Manage_AID; +$_Lang['Insert_AllyName'] = $Result_GetPactData['ally_name']; +$_Lang['Insert_CurrentOption_'.$Result_GetPactData['Type']] = 'style="color: orange" selected'; +$_Lang['Insert_CurrentType'] = $_Lang['Ally_PactNew_Type_'.$Result_GetPactData['Type']]; + +if(isset($_POST['sent']) && $_POST['sent'] == 1) +{ + $NewPact_Msg['color'] = 'red'; + $Manage_NewType = intval($_POST['type']); + if(in_array($Manage_NewType, array(1, 2, 3, 4))) + { + if($Manage_NewType != $Result_GetPactData['Type']) + { + if($Manage_NewType > $Result_GetPactData['Type']) + { + if($Manage_IsSender) + { + $UpdateField = 'Change_Sender'; + $CheckOtherField = 'Change_Owner'; + } + else + { + $UpdateField = 'Change_Owner'; + $CheckOtherField = 'Change_Sender'; + } + if($Result_GetPactData[$CheckOtherField] != $Manage_NewType) + { + $Query_UpdatePactType = ''; + $Query_UpdatePactType .= "UPDATE {{table}} SET "; + $Query_UpdatePactType .= "`{$UpdateField}` = {$Manage_NewType} "; + $Query_UpdatePactType .= "WHERE "; + $Query_UpdatePactType .= "`AllyID_Sender` = {$Result_GetPactData['AllyID_Sender']} AND "; + $Query_UpdatePactType .= "`AllyID_Owner` = {$Result_GetPactData['AllyID_Owner']} "; + $Query_UpdatePactType .= "LIMIT 1; -- ally.changepact.php|UpdatePactType|Higher"; + doquery($Query_UpdatePactType, 'ally_pacts'); + + $Message = array(); + $Message['msg_id'] = '104'; + $Message['args'] = array($Ally['id'], $Ally['ally_name']); + $Message = json_encode($Message); + $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); + SendNotification($Manage_AID, $Result_GetPactData['ally_ranks'], $Message); + + message($_Lang['Ally_PactChange_Msg_Ok_Higher'], $_Lang['Ally_PactChange_Title'], 'alliance.php?mode=pactslist', 3); + } + else + { + $NewPact_Msg['text'] = $_Lang['Ally_PactChange_Msg_TypeAlreadyProposed']; + } + } + else + { + $Query_UpdatePactType = ''; + $Query_UpdatePactType .= "UPDATE {{table}} SET "; + $Query_UpdatePactType .= "`Type` = {$Manage_NewType} "; + $Query_UpdatePactType .= "WHERE "; + $Query_UpdatePactType .= "`AllyID_Sender` = {$Result_GetPactData['AllyID_Sender']} AND "; + $Query_UpdatePactType .= "`AllyID_Owner` = {$Result_GetPactData['AllyID_Owner']} "; + $Query_UpdatePactType .= "LIMIT 1; -- ally.changepact.php|UpdatePactType|Lower"; + doquery($Query_UpdatePactType, 'ally_pacts'); + + $Message = array(); + $Message['msg_id'] = '105'; + $Message['args'] = array($Ally['id'], $Ally['ally_name'], $_Lang['Ally_PactNew_Type_'.$Manage_NewType]); + $Message = json_encode($Message); + $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); + SendNotification($Manage_AID, $Result_GetPactData['ally_ranks'], $Message); + + message($_Lang['Ally_PactChange_Msg_Ok_Lower'], $_Lang['Ally_PactChange_Title'], 'alliance.php?mode=pactslist', 3); + } + } + else + { + $NewPact_Msg['text'] = $_Lang['Ally_PactChange_Msg_TypeSame']; + } + } + else + { + $NewPact_Msg['text'] = $_Lang['Ally_PactChange_Msg_TypeBad']; + } +} + +$_Lang['Insert_MsgBox'] = ''; +if(!empty($NewPact_Msg)) +{ + $_Lang['Insert_MsgBox'] .= parsetemplate(gettemplate('_singleRow'), array('Colspan' => 2, 'Classes' => 'pad5 '.$NewPact_Msg['color'], 'Text' => $NewPact_Msg['text'])); + $_Lang['Insert_MsgBox'] .= parsetemplate(gettemplate('_singleRow'), array('Colspan' => 2, 'Classes' => 'inv', 'Text' => '')); +} + +$Page = parsetemplate(gettemplate('alliance_changepact'), $_Lang); +display($Page, $_Lang['Ally_PactChange_Title']); + +?> diff --git a/modules/ally.newpact.php b/modules/ally.newpact.php index 9d6261cb4..571fc565e 100644 --- a/modules/ally.newpact.php +++ b/modules/ally.newpact.php @@ -1,148 +1,148 @@ - 0) - { - $NewPact_AllyID = $Result_NewPact_CheckAlly['id']; - $NewPact_AllyRanks = json_decode($Result_NewPact_CheckAlly['ally_ranks'], true); - - $Query_NewPact_CheckPacts = ''; - $Query_NewPact_CheckPacts .= "("; - $Query_NewPact_CheckPacts .= "SELECT COUNT(*) AS `Count`, 1 AS `Type` FROM `{{prefix}}ally_pacts` WHERE "; - $Query_NewPact_CheckPacts .= "(`AllyID_Sender` = {$Ally['id']} AND `AllyID_Owner` = {$NewPact_AllyID}) OR "; - $Query_NewPact_CheckPacts .= "(`AllyID_Owner` = {$Ally['id']} AND `AllyID_Sender` = {$NewPact_AllyID})"; - $Query_NewPact_CheckPacts .= ")"; - //$Query_NewPact_CheckPacts .= " UNION "; - // Finish this, when AllyWars will be ready - $Query_NewPact_CheckPacts .= "; -- alliance.php|NewPact|CheckPacts"; - $Result_NewPact_CheckPacts = doquery($Query_NewPact_CheckPacts, ''); - while($FetchData = mysql_fetch_assoc($Result_NewPact_CheckPacts)) - { - if($FetchData['Count'] > 0) - { - $CantGoFurther = true; - if($FetchData['Type'] == 1) - { - $NewPact_Msg['text'] = $_Lang['Ally_PactNew_Error_PactAlreadySent']; - } - else - { - $NewPact_Msg['text'] = $_Lang['Ally_PactNew_Error_AllyInWar']; - } - } - } - - if(!isset($CantGoFurther)) - { - $Query_NewPact_CreatePact = ''; - $Query_NewPact_CreatePact .= "INSERT INTO {{table}} SET "; - $Query_NewPact_CreatePact .= "`AllyID_Sender` = {$Ally['id']}, "; - $Query_NewPact_CreatePact .= "`AllyID_Owner` = {$NewPact_AllyID}, "; - $Query_NewPact_CreatePact .= "`Date` = {$Time}, "; - $Query_NewPact_CreatePact .= "`Type` = {$NewPact_Type} "; - $Query_NewPact_CreatePact .= "; -- alliance.php|NewPact|CreatePact"; - doquery($Query_NewPact_CreatePact, 'ally_pacts'); - - foreach($NewPact_AllyRanks as $RankID => $RankData) - { - foreach($RankData as $DataID => $DataVal) - { - $NewPact_AllyRanks_Parsed[$RankID][$_Vars_AllyRankLabels[$DataID]] = $DataVal; - } - if($NewPact_AllyRanks_Parsed[$RankID]['warnpact'] === true) - { - $NewPact_RankIDs[] = $RankID; - } - } - if(!empty($NewPact_RankIDs)) - { - $NewPact_RankIDs = implode(',', $NewPact_RankIDs); - $Query_NewPact_GetUsers = ''; - $Query_NewPact_GetUsers .= "SELECT `id` FROM {{table}} WHERE "; - $Query_NewPact_GetUsers .= "`ally_id` = {$NewPact_AllyID} AND `ally_rank_id` IN ({$NewPact_RankIDs})"; - $Query_NewPact_GetUsers .= "; -- alliance.php|NewPact|GetUsers"; - $Result_NewPact_GetUsers = doquery($Query_NewPact_GetUsers, 'users'); - while($FetchData = mysql_fetch_assoc($Result_NewPact_GetUsers)) - { - $NewPact_UserIDs[] = $FetchData['id']; - } - - if(!empty($NewPact_UserIDs)) - { - $Message = array(); - $Message['msg_id'] = '096'; - $Message['args'] = array($Ally['id'], $Ally['ally_name']); - $Message = json_encode($Message); - Cache_Message($NewPact_UserIDs, 0, $Time, 2, '005', '024', $Message); - } - } - - $NewPact_Msg['color'] = 'lime'; - $NewPact_Msg['text'] = sprintf($_Lang['Ally_PactNew_Success'], $NewPact_AllyID, $NewPact_CheckAlly); - } - } - else - { - $NewPact_Msg['text'] = $_Lang['Ally_PactNew_Error_AllyDoesntExist']; - } - } - else - { - $NewPact_Msg['text'] = $_Lang['Ally_PactNew_Error_BadType']; - } - } - else - { - $NewPact_Msg['text'] = $_Lang['Ally_PactNew_Error_AllySame']; - } - } - else - { - $NewPact_Msg['text'] = $_Lang['Ally_PactNew_Error_BadName']; - } - } - else - { - $NewPact_Msg['text'] = $_Lang['Ally_PactNew_Error_EmptyName']; - } - } - - $_Lang['Insert_MsgBox'] = ''; - if(!empty($NewPact_Msg)) - { - $_Lang['Insert_MsgBox'] .= parsetemplate(gettemplate('_singleRow'), array('Colspan' => 2, 'Classes' => 'pad5 '.$NewPact_Msg['color'], 'Text' => $NewPact_Msg['text'])); - $_Lang['Insert_MsgBox'] .= parsetemplate(gettemplate('_singleRow'), array('Colspan' => 2, 'Classes' => 'inv', 'Text' => '')); - } - - $Page = parsetemplate(gettemplate('alliance_newpact'), $_Lang); - display($Page, $_Lang['Ally_PactNew_Title']); - -?> \ No newline at end of file + 0) + { + $NewPact_AllyID = $Result_NewPact_CheckAlly['id']; + $NewPact_AllyRanks = json_decode($Result_NewPact_CheckAlly['ally_ranks'], true); + + $Query_NewPact_CheckPacts = ''; + $Query_NewPact_CheckPacts .= "("; + $Query_NewPact_CheckPacts .= "SELECT COUNT(*) AS `Count`, 1 AS `Type` FROM `{{prefix}}ally_pacts` WHERE "; + $Query_NewPact_CheckPacts .= "(`AllyID_Sender` = {$Ally['id']} AND `AllyID_Owner` = {$NewPact_AllyID}) OR "; + $Query_NewPact_CheckPacts .= "(`AllyID_Owner` = {$Ally['id']} AND `AllyID_Sender` = {$NewPact_AllyID})"; + $Query_NewPact_CheckPacts .= ")"; + //$Query_NewPact_CheckPacts .= " UNION "; + // Finish this, when AllyWars will be ready + $Query_NewPact_CheckPacts .= "; -- alliance.php|NewPact|CheckPacts"; + $Result_NewPact_CheckPacts = doquery($Query_NewPact_CheckPacts, ''); + while($FetchData = mysql_fetch_assoc($Result_NewPact_CheckPacts)) + { + if($FetchData['Count'] > 0) + { + $CantGoFurther = true; + if($FetchData['Type'] == 1) + { + $NewPact_Msg['text'] = $_Lang['Ally_PactNew_Error_PactAlreadySent']; + } + else + { + $NewPact_Msg['text'] = $_Lang['Ally_PactNew_Error_AllyInWar']; + } + } + } + + if(!isset($CantGoFurther)) + { + $Query_NewPact_CreatePact = ''; + $Query_NewPact_CreatePact .= "INSERT INTO {{table}} SET "; + $Query_NewPact_CreatePact .= "`AllyID_Sender` = {$Ally['id']}, "; + $Query_NewPact_CreatePact .= "`AllyID_Owner` = {$NewPact_AllyID}, "; + $Query_NewPact_CreatePact .= "`Date` = {$Time}, "; + $Query_NewPact_CreatePact .= "`Type` = {$NewPact_Type} "; + $Query_NewPact_CreatePact .= "; -- alliance.php|NewPact|CreatePact"; + doquery($Query_NewPact_CreatePact, 'ally_pacts'); + + foreach($NewPact_AllyRanks as $RankID => $RankData) + { + foreach($RankData as $DataID => $DataVal) + { + $NewPact_AllyRanks_Parsed[$RankID][$_Vars_AllyRankLabels[$DataID]] = $DataVal; + } + if($NewPact_AllyRanks_Parsed[$RankID]['warnpact'] === true) + { + $NewPact_RankIDs[] = $RankID; + } + } + if(!empty($NewPact_RankIDs)) + { + $NewPact_RankIDs = implode(',', $NewPact_RankIDs); + $Query_NewPact_GetUsers = ''; + $Query_NewPact_GetUsers .= "SELECT `id` FROM {{table}} WHERE "; + $Query_NewPact_GetUsers .= "`ally_id` = {$NewPact_AllyID} AND `ally_rank_id` IN ({$NewPact_RankIDs})"; + $Query_NewPact_GetUsers .= "; -- alliance.php|NewPact|GetUsers"; + $Result_NewPact_GetUsers = doquery($Query_NewPact_GetUsers, 'users'); + while($FetchData = mysql_fetch_assoc($Result_NewPact_GetUsers)) + { + $NewPact_UserIDs[] = $FetchData['id']; + } + + if(!empty($NewPact_UserIDs)) + { + $Message = array(); + $Message['msg_id'] = '096'; + $Message['args'] = array($Ally['id'], $Ally['ally_name']); + $Message = json_encode($Message); + Cache_Message($NewPact_UserIDs, 0, $Time, 2, '005', '024', $Message); + } + } + + $NewPact_Msg['color'] = 'lime'; + $NewPact_Msg['text'] = sprintf($_Lang['Ally_PactNew_Success'], $NewPact_AllyID, $NewPact_CheckAlly); + } + } + else + { + $NewPact_Msg['text'] = $_Lang['Ally_PactNew_Error_AllyDoesntExist']; + } + } + else + { + $NewPact_Msg['text'] = $_Lang['Ally_PactNew_Error_BadType']; + } + } + else + { + $NewPact_Msg['text'] = $_Lang['Ally_PactNew_Error_AllySame']; + } + } + else + { + $NewPact_Msg['text'] = $_Lang['Ally_PactNew_Error_BadName']; + } + } + else + { + $NewPact_Msg['text'] = $_Lang['Ally_PactNew_Error_EmptyName']; + } +} + +$_Lang['Insert_MsgBox'] = ''; +if(!empty($NewPact_Msg)) +{ + $_Lang['Insert_MsgBox'] .= parsetemplate(gettemplate('_singleRow'), array('Colspan' => 2, 'Classes' => 'pad5 '.$NewPact_Msg['color'], 'Text' => $NewPact_Msg['text'])); + $_Lang['Insert_MsgBox'] .= parsetemplate(gettemplate('_singleRow'), array('Colspan' => 2, 'Classes' => 'inv', 'Text' => '')); +} + +$Page = parsetemplate(gettemplate('alliance_newpact'), $_Lang); +display($Page, $_Lang['Ally_PactNew_Title']); + +?> diff --git a/modules/ally.pactslist.php b/modules/ally.pactslist.php index f19865411..16d5b9643 100644 --- a/modules/ally.pactslist.php +++ b/modules/ally.pactslist.php @@ -1,502 +1,502 @@ - $RankData) - { - foreach($RankData as $DataID => $DataVal) - { - $ParsedRanks[$RankID][$_Vars_AllyRankLabels[$DataID]] = $DataVal; - } - if($ParsedRanks[$RankID]['warnpact'] === true) - { - $RanksID[] = $RankID; - } - } - if(!empty($RanksID)) - { - $RanksID = implode(',', $RanksID); - $Query_GetUsers = ''; - $Query_GetUsers .= "SELECT `id` FROM {{table}} WHERE "; - $Query_GetUsers .= "`ally_id` = {$AllyID} AND `ally_rank_id` IN ({$RanksID})"; - $Query_GetUsers .= "; -- ally.pactslist.php|SendNotification|GetUsers"; - $Result_GetUsers = doquery($Query_GetUsers, 'users'); - while($FetchData = mysql_fetch_assoc($Result_GetUsers)) - { - $UserIDs[] = $FetchData['id']; - } - - if(!empty($UserIDs)) - { - Cache_Message($UserIDs, 0, null, 2, $Message['from'], $Message['subject'], $Message['content']); - } - } - } - - if(isset($_GET['do'])) - { - $_MsgBox['color'] = 'red'; - if($CanManage) - { - $Manage_CMD = (isset($_GET['cmd']) ? intval($_GET['cmd']) : null); - $Manage_AID = (isset($_GET['aid']) ? intval($_GET['aid']) : null); - if($Manage_AID > 0) - { - if(in_array($Manage_CMD, array(1, 2, 3, 4, 5))) - { - $Query_CheckPact = ''; - $Query_CheckPact .= "SELECT `pact`.*, `ally`.`ally_ranks` FROM {{table}} AS `pact` "; - $Query_CheckPact .= "LEFT JOIN `{{prefix}}alliance` AS `ally` ON "; - $Query_CheckPact .= "`ally`.`id` = IF(`pact`.`AllyID_Sender` = {$Ally['id']}, `pact`.`AllyID_Owner`, `pact`.`AllyID_Sender`) "; - $Query_CheckPact .= "WHERE "; - $Query_CheckPact .= "(`pact`.`AllyID_Sender` = {$Ally['id']} AND `pact`.`AllyID_Owner` = {$Manage_AID}) OR "; - $Query_CheckPact .= "(`pact`.`AllyID_Owner` = {$Ally['id']} AND `pact`.`AllyID_Sender` = {$Manage_AID}) "; - $Query_CheckPact .= "LIMIT 1; -- ally.pactslist.php|CheckPact"; - $Result_CheckPact = doquery($Query_CheckPact, 'ally_pacts', true); - if($Result_CheckPact['AllyID_Sender'] > 0) - { - $Manage_IsSender = ($Result_CheckPact['AllyID_Sender'] == $Ally['id'] ? true : false); - - if($Manage_CMD == 1) - { - // User wants to Remove this Pact - if($Result_CheckPact['Active'] == 1) - { - $Query_RemovePact = ''; - $Query_RemovePact .= "DELETE FROM {{table}} WHERE "; - $Query_RemovePact .= "`AllyID_Sender` = {$Result_CheckPact['AllyID_Sender']} AND "; - $Query_RemovePact .= "`AllyID_Owner` = {$Result_CheckPact['AllyID_Owner']} "; - $Query_RemovePact .= "LIMIT 1; -- ally.pactslist.php|RemovePact"; - doquery($Query_RemovePact, 'ally_pacts'); - - $Message = array(); - $Message['msg_id'] = '102'; - $Message['args'] = array($Ally['id'], $Ally['ally_name']); - $Message = json_encode($Message); - $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); - SendNotification($Manage_AID, $Result_CheckPact['ally_ranks'], $Message); - - $_MsgBox['color'] = 'lime'; - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_OK_Remove']; - } - else - { - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactRemove_NonActive']; - } - } - else if($Manage_CMD == 2) - { - // User wants to RollBack this Pact - if($Manage_IsSender) - { - if($Result_CheckPact['Active'] == 0) - { - $Query_RollbackPact = ''; - $Query_RollbackPact .= "DELETE FROM {{table}} WHERE "; - $Query_RollbackPact .= "`AllyID_Sender` = {$Result_CheckPact['AllyID_Sender']} AND "; - $Query_RollbackPact .= "`AllyID_Owner` = {$Result_CheckPact['AllyID_Owner']} "; - $Query_RollbackPact .= "LIMIT 1; -- ally.pactslist.php|RollbackPact"; - doquery($Query_RollbackPact, 'ally_pacts'); - - $Message = array(); - $Message['msg_id'] = '097'; - $Message['args'] = array($Ally['id'], $Ally['ally_name']); - $Message = json_encode($Message); - $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); - SendNotification($Manage_AID, $Result_CheckPact['ally_ranks'], $Message); - - $_MsgBox['color'] = 'lime'; - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_OK_Rollback']; - } - else - { - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactRollback_Active']; - } - } - else - { - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactRollback_NotSender']; - } - } - elseif($Manage_CMD == 3) - { - // User wants to Remove your (sent by your ally) change type proposal - if($Manage_IsSender) - { - $Manage_CheckField = 'Change_Sender'; - } - else - { - $Manage_CheckField = 'Change_Owner'; - } - if($Result_CheckPact[$Manage_CheckField] > 0) - { - $Query_UpdatePactType = ''; - $Query_UpdatePactType .= "UPDATE {{table}} SET "; - $Query_UpdatePactType .= "`{$Manage_CheckField}` = 0 "; - $Query_UpdatePactType .= "WHERE "; - $Query_UpdatePactType .= "`AllyID_Sender` = {$Result_CheckPact['AllyID_Sender']} AND "; - $Query_UpdatePactType .= "`AllyID_Owner` = {$Result_CheckPact['AllyID_Owner']} "; - $Query_UpdatePactType .= "LIMIT 1; -- ally.pactslist.php|UpdatePactType|StopChange"; - doquery($Query_UpdatePactType, 'ally_pacts'); - - $Message = array(); - $Message['msg_id'] = '103'; - $Message['args'] = array($Ally['id'], $Ally['ally_name']); - $Message = json_encode($Message); - $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); - SendNotification($Manage_AID, $Result_CheckPact['ally_ranks'], $Message); - - $_MsgBox['color'] = 'lime'; - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_OK_StopChange']; - } - else - { - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactChange_NothingToStop']; - } - } - else if($Manage_CMD == 4) - { - // User wants to Accept new Pact proposal or change type proposal - if($Result_CheckPact['Active'] == 0) - { - if(!$Manage_IsSender) - { - // User wants to Accept new Pact proposal - $Query_AcceptNewPact = ''; - $Query_AcceptNewPact .= "UPDATE {{table}} SET "; - $Query_AcceptNewPact .= "`Active` = 1, `Date` = {$Time} "; - $Query_AcceptNewPact .= "WHERE "; - $Query_AcceptNewPact .= "`AllyID_Sender` = {$Result_CheckPact['AllyID_Sender']} AND "; - $Query_AcceptNewPact .= "`AllyID_Owner` = {$Result_CheckPact['AllyID_Owner']} "; - $Query_AcceptNewPact .= "LIMIT 1; -- ally.pactslist.php|AcceptNewPact"; - doquery($Query_AcceptNewPact, 'ally_pacts'); - - $Message = array(); - $Message['msg_id'] = '098'; - $Message['args'] = array($Ally['id'], $Ally['ally_name']); - $Message = json_encode($Message); - $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); - SendNotification($Manage_AID, $Result_CheckPact['ally_ranks'], $Message); - - $_MsgBox['color'] = 'lime'; - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_OK_Accept_NewPact']; - } - else - { - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactAccept_Sender']; - } - } - else - { - // User wants to Accept change type proposal - if($Manage_IsSender) - { - $Manage_NewType = $Result_CheckPact['Change_Owner']; - } - else - { - $Manage_NewType = $Result_CheckPact['Change_Sender']; - } - if($Manage_NewType > 0) - { - $Query_UpdatePactType = ''; - $Query_UpdatePactType .= "UPDATE {{table}} SET "; - $Query_UpdatePactType .= "`Type` = {$Manage_NewType}, "; - $Query_UpdatePactType .= "`Change_Owner` = 0, "; - $Query_UpdatePactType .= "`Change_Sender` = 0 "; - $Query_UpdatePactType .= "WHERE "; - $Query_UpdatePactType .= "`AllyID_Sender` = {$Result_CheckPact['AllyID_Sender']} AND "; - $Query_UpdatePactType .= "`AllyID_Owner` = {$Result_CheckPact['AllyID_Owner']} "; - $Query_UpdatePactType .= "LIMIT 1; -- ally.pactslist.php|UpdatePactType|Accept"; - doquery($Query_UpdatePactType, 'ally_pacts'); - - $Message = array(); - $Message['msg_id'] = '100'; - $Message['args'] = array($Ally['id'], $Ally['ally_name']); - $Message = json_encode($Message); - $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); - SendNotification($Manage_AID, $Result_CheckPact['ally_ranks'], $Message); - - $_MsgBox['color'] = 'lime'; - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_OK_Accept_NewType']; - } - else - { - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactAccept_NothingToAccept']; - } - } - } - else if($Manage_CMD == 5) - { - // User wants to Refuse new Pact proposal or change type proposal - if($Result_CheckPact['Active'] == 0) - { - if(!$Manage_IsSender) - { - // User wants to Refuse new Pact proposal - $Query_RefuseNewPact = ''; - $Query_RefuseNewPact .= "DELETE FROM {{table}} WHERE "; - $Query_RefuseNewPact .= "`AllyID_Sender` = {$Result_CheckPact['AllyID_Sender']} AND "; - $Query_RefuseNewPact .= "`AllyID_Owner` = {$Result_CheckPact['AllyID_Owner']} "; - $Query_RefuseNewPact .= "LIMIT 1; -- ally.pactslist.php|RefuseNewPact"; - doquery($Query_RefuseNewPact, 'ally_pacts'); - - $Message = array(); - $Message['msg_id'] = '099'; - $Message['args'] = array($Ally['id'], $Ally['ally_name']); - $Message = json_encode($Message); - $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); - SendNotification($Manage_AID, $Result_CheckPact['ally_ranks'], $Message); - - $_MsgBox['color'] = 'lime'; - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_OK_Refuse_NewPact']; - } - else - { - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactRefuse_Sender']; - } - } - else - { - // User wants to Refuse change type proposal - if($Manage_IsSender) - { - $Manage_TypeField = 'Change_Owner'; - $Manage_NewType = $Result_CheckPact['Change_Owner']; - } - else - { - $Manage_TypeField = 'Change_Sender'; - $Manage_NewType = $Result_CheckPact['Change_Sender']; - } - if($Manage_NewType > 0) - { - $Query_UpdatePactType = ''; - $Query_UpdatePactType .= "UPDATE {{table}} SET "; - $Query_UpdatePactType .= "`$Manage_TypeField` = 0 "; - $Query_UpdatePactType .= "WHERE "; - $Query_UpdatePactType .= "`AllyID_Sender` = {$Result_CheckPact['AllyID_Sender']} AND "; - $Query_UpdatePactType .= "`AllyID_Owner` = {$Result_CheckPact['AllyID_Owner']} "; - $Query_UpdatePactType .= "LIMIT 1; -- ally.pactslist.php|UpdatePactType|Refuse"; - doquery($Query_UpdatePactType, 'ally_pacts'); - - $Message = array(); - $Message['msg_id'] = '101'; - $Message['args'] = array($Ally['id'], $Ally['ally_name']); - $Message = json_encode($Message); - $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); - SendNotification($Manage_AID, $Result_CheckPact['ally_ranks'], $Message); - - $_MsgBox['color'] = 'lime'; - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_OK_Refuse_NewType']; - } - else - { - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactRefuse_NothingToAccept']; - } - } - } - } - else - { - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactDoesntExist']; - } - } - else - { - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_BadCMD']; - } - } - else - { - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_BadAID']; - } - } - else - { - $_MsgBox['text'] = $_Lang['AllyPacts_Msg_CantManage']; - } - } - - if($CanManage) - { - $ThisRow = gettemplate('alliance_pactslist_manage_row'); - $BodyTPL = gettemplate('alliance_pactslist_manage_body'); - $ThisColspan = 5; - } - else - { - $ThisRow = gettemplate('alliance_pactslist_row'); - $BodyTPL = gettemplate('alliance_pactslist_body'); - $ThisColspan = 4; - } - - $_Lang['Insert_MsgBox'] = ''; - if(!empty($_MsgBox)) - { - $_Lang['Insert_MsgBox'] .= parsetemplate(gettemplate('_singleRow'), array('Colspan' => $ThisColspan, 'Classes' => 'pad5 '.$_MsgBox['color'], 'Text' => $_MsgBox['text'])); - $_Lang['Insert_MsgBox'] .= parsetemplate(gettemplate('_singleRow'), array('Colspan' => $ThisColspan, 'Classes' => 'inv', 'Text' => '')); - } - - $Query_GetPacts = ''; - $Query_GetPacts .= "SELECT `pacts`.*, `ally`.`ally_name` "; - $Query_GetPacts .= "FROM {{table}} AS `pacts` "; - $Query_GetPacts .= "LEFT JOIN `{{prefix}}alliance` AS `ally` "; - $Query_GetPacts .= "ON `ally`.`id` = IF(`pacts`.`AllyID_Sender` = {$Ally['id']}, `pacts`.`AllyID_Owner`, `pacts`.`AllyID_Sender`) "; - $Query_GetPacts .= "WHERE (`AllyID_Sender` = {$Ally['id']} OR `AllyID_Owner` = {$Ally['id']}) "; - $Query_GetPacts .= "; -- ally.pactslist.php|GetPacts"; - $GetPacts = doquery($Query_GetPacts, 'ally_pacts'); - - if(mysql_num_rows($GetPacts) > 0) - { - while($FetchData = mysql_fetch_assoc($GetPacts)) - { - $FetchData['IsSender'] = ($FetchData['AllyID_Sender'] == $Ally['id'] ? true : false); - $FetchData['SecondAllyID'] = ($FetchData['IsSender'] === true ? $FetchData['AllyID_Owner'] : $FetchData['AllyID_Sender']); - if($FetchData['Active'] == 1) - { - if($FetchData['Change_Owner'] > 0) - { - if($FetchData['IsSender'] === false) - { - $FetchData['KeyState'][] = '3'; - $FetchData['Status'][0] = $_Lang['AWNP_States']['active']; - $FetchData['Status'][] = sprintf($_Lang['AWNP_States']['my_2'], $_Lang['AWNP_Types'][$FetchData['Change_Owner']]); - } - else - { - $FetchData['KeyState'][] = '4'; - $FetchData['Status'][0] = $_Lang['AWNP_States']['active']; - $FetchData['Status'][] = sprintf($_Lang['AWNP_States']['their_2'], $_Lang['AWNP_Types'][$FetchData['Change_Owner']]); - } - } - if($FetchData['Change_Sender'] > 0) - { - if($FetchData['IsSender'] === true) - { - $FetchData['KeyState'][] = '3'; - $FetchData['Status'][0] = $_Lang['AWNP_States']['active']; - $FetchData['Status'][] = sprintf($_Lang['AWNP_States']['my_2'], $_Lang['AWNP_Types'][$FetchData['Change_Sender']]); - } - else - { - $FetchData['KeyState'][] = '4'; - $FetchData['Status'][0] = $_Lang['AWNP_States']['active']; - $FetchData['Status'][] = sprintf($_Lang['AWNP_States']['their_2'], $_Lang['AWNP_Types'][$FetchData['Change_Sender']]); - } - } - if(empty($FetchData['KeyState'])) - { - $FetchData['KeyState'][] = '1'; - $FetchData['Status'][] = $_Lang['AWNP_States']['active']; - } - } - else - { - if($FetchData['IsSender'] === true) - { - $FetchData['KeyState'][] = '2'; - $FetchData['Status'][] = $_Lang['AWNP_States']['my_0']; - } - else - { - $FetchData['KeyState'][] = '5'; - $FetchData['Status'][] = $_Lang['AWNP_States']['their_0']; - } - } - - if($CanManage) - { - if(in_array(1, $FetchData['KeyState'])) - { - $FetchData['Actions']['remove'] = array('Class' => 'remove', 'Link' => '?mode=pactslist&do=1&cmd=1&aid='.$FetchData['SecondAllyID']); - $FetchData['Actions']['change'] = array('Class' => 'change', 'Link' => '?mode=changepact&aid='.$FetchData['SecondAllyID']); - } - if(in_array(2, $FetchData['KeyState'])) - { - $FetchData['Actions']['rollback'] = array('Class' => 'rollback', 'Link' => '?mode=pactslist&do=1&cmd=2&aid='.$FetchData['SecondAllyID']); - } - if(in_array(3, $FetchData['KeyState'])) - { - $FetchData['Actions']['remove'] = array('Class' => 'remove', 'Link' => '?mode=pactslist&do=1&cmd=1&aid='.$FetchData['SecondAllyID']); - $FetchData['Actions']['stopchange'] = array('Class' => 'stopchange', 'Link' => '?mode=pactslist&do=1&cmd=3&aid='.$FetchData['SecondAllyID']); - } - if(in_array(4, $FetchData['KeyState'])) - { - $FetchData['Actions']['remove'] = array('Class' => 'remove', 'Link' => '?mode=pactslist&do=1&cmd=1&aid='.$FetchData['SecondAllyID']); - if(!in_array(3, $FetchData['KeyState'])) - { - $FetchData['Actions']['change'] = array('Class' => 'change', 'Link' => '?mode=changepact&aid='.$FetchData['SecondAllyID']); - } - $FetchData['Actions']['accept'] = array('Class' => 'accept', 'Link' => '?mode=pactslist&do=1&cmd=4&aid='.$FetchData['SecondAllyID']); - $FetchData['Actions']['refuse'] = array('Class' => 'refuse', 'Link' => '?mode=pactslist&do=1&cmd=5&aid='.$FetchData['SecondAllyID']); - } - if(in_array(5, $FetchData['KeyState'])) - { - $FetchData['Actions']['accept'] = array('Class' => 'accept', 'Link' => '?mode=pactslist&do=1&cmd=4&aid='.$FetchData['SecondAllyID']); - $FetchData['Actions']['refuse'] = array('Class' => 'refuse', 'Link' => '?mode=pactslist&do=1&cmd=5&aid='.$FetchData['SecondAllyID']); - } - - $TPL_PactsList_Actions = gettemplate('alliance_pactslist_manage_actions'); - foreach($FetchData['Actions'] as &$ThisVal) - { - $ThisVal = parsetemplate($TPL_PactsList_Actions, $ThisVal); - } - $FetchData['Actions'] = implode(' ', $FetchData['Actions']); - } - array_walk($FetchData['Status'], function(&$Value){ $Value = '• '.$Value; }); - $FetchData['Status'] = implode('
    ', $FetchData['Status']); - $FetchData['Key'] = max($FetchData['KeyState']).$FetchData['Date']; - $FetchData['AllyID'] = $FetchData['SecondAllyID']; - $FetchData['AllyName'] = $FetchData['ally_name']; - $FetchData['PactDate'] = prettyDate('d m Y, H:i:s', $FetchData['Date'], 1); - $FetchData['PactType'] = $_Lang['AWNP_Types'][$FetchData['Type']]; - - $PactsList[$FetchData['Key']] = $FetchData; - } - krsort($PactsList, SORT_STRING); - foreach($PactsList as $PactData) - { - $_Lang['ShowPactsList'][] = parsetemplate($ThisRow, $PactData); - } - - $_Lang['ShowPactsList'] = implode('', $_Lang['ShowPactsList']); - } - else - { - $_Lang['ShowPactsList'] = parsetemplate(gettemplate('_singleRow'), array - ( - 'Colspan' => $ThisColspan, - 'Classes' => 'red pad5', - 'Text' => $_Lang['AWNP_NoPacts'] - )); - } - - if($_ThisUserRank['warnpact'] !== true) - { - $_Lang['Insert_HideNewPact'] = 'class="hide"'; - } - - $Page = parsetemplate($BodyTPL, $_Lang); - display($Page, $_Lang['Ally_Pacts_WinTitle']); - -?> \ No newline at end of file + $RankData) + { + foreach($RankData as $DataID => $DataVal) + { + $ParsedRanks[$RankID][$_Vars_AllyRankLabels[$DataID]] = $DataVal; + } + if($ParsedRanks[$RankID]['warnpact'] === true) + { + $RanksID[] = $RankID; + } + } + if(!empty($RanksID)) + { + $RanksID = implode(',', $RanksID); + $Query_GetUsers = ''; + $Query_GetUsers .= "SELECT `id` FROM {{table}} WHERE "; + $Query_GetUsers .= "`ally_id` = {$AllyID} AND `ally_rank_id` IN ({$RanksID})"; + $Query_GetUsers .= "; -- ally.pactslist.php|SendNotification|GetUsers"; + $Result_GetUsers = doquery($Query_GetUsers, 'users'); + while($FetchData = mysql_fetch_assoc($Result_GetUsers)) + { + $UserIDs[] = $FetchData['id']; + } + + if(!empty($UserIDs)) + { + Cache_Message($UserIDs, 0, null, 2, $Message['from'], $Message['subject'], $Message['content']); + } + } +} + +if(isset($_GET['do'])) +{ + $_MsgBox['color'] = 'red'; + if($CanManage) + { + $Manage_CMD = (isset($_GET['cmd']) ? intval($_GET['cmd']) : null); + $Manage_AID = (isset($_GET['aid']) ? intval($_GET['aid']) : null); + if($Manage_AID > 0) + { + if(in_array($Manage_CMD, array(1, 2, 3, 4, 5))) + { + $Query_CheckPact = ''; + $Query_CheckPact .= "SELECT `pact`.*, `ally`.`ally_ranks` FROM {{table}} AS `pact` "; + $Query_CheckPact .= "LEFT JOIN `{{prefix}}alliance` AS `ally` ON "; + $Query_CheckPact .= "`ally`.`id` = IF(`pact`.`AllyID_Sender` = {$Ally['id']}, `pact`.`AllyID_Owner`, `pact`.`AllyID_Sender`) "; + $Query_CheckPact .= "WHERE "; + $Query_CheckPact .= "(`pact`.`AllyID_Sender` = {$Ally['id']} AND `pact`.`AllyID_Owner` = {$Manage_AID}) OR "; + $Query_CheckPact .= "(`pact`.`AllyID_Owner` = {$Ally['id']} AND `pact`.`AllyID_Sender` = {$Manage_AID}) "; + $Query_CheckPact .= "LIMIT 1; -- ally.pactslist.php|CheckPact"; + $Result_CheckPact = doquery($Query_CheckPact, 'ally_pacts', true); + if($Result_CheckPact['AllyID_Sender'] > 0) + { + $Manage_IsSender = ($Result_CheckPact['AllyID_Sender'] == $Ally['id'] ? true : false); + + if($Manage_CMD == 1) + { + // User wants to Remove this Pact + if($Result_CheckPact['Active'] == 1) + { + $Query_RemovePact = ''; + $Query_RemovePact .= "DELETE FROM {{table}} WHERE "; + $Query_RemovePact .= "`AllyID_Sender` = {$Result_CheckPact['AllyID_Sender']} AND "; + $Query_RemovePact .= "`AllyID_Owner` = {$Result_CheckPact['AllyID_Owner']} "; + $Query_RemovePact .= "LIMIT 1; -- ally.pactslist.php|RemovePact"; + doquery($Query_RemovePact, 'ally_pacts'); + + $Message = array(); + $Message['msg_id'] = '102'; + $Message['args'] = array($Ally['id'], $Ally['ally_name']); + $Message = json_encode($Message); + $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); + SendNotification($Manage_AID, $Result_CheckPact['ally_ranks'], $Message); + + $_MsgBox['color'] = 'lime'; + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_OK_Remove']; + } + else + { + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactRemove_NonActive']; + } + } + else if($Manage_CMD == 2) + { + // User wants to RollBack this Pact + if($Manage_IsSender) + { + if($Result_CheckPact['Active'] == 0) + { + $Query_RollbackPact = ''; + $Query_RollbackPact .= "DELETE FROM {{table}} WHERE "; + $Query_RollbackPact .= "`AllyID_Sender` = {$Result_CheckPact['AllyID_Sender']} AND "; + $Query_RollbackPact .= "`AllyID_Owner` = {$Result_CheckPact['AllyID_Owner']} "; + $Query_RollbackPact .= "LIMIT 1; -- ally.pactslist.php|RollbackPact"; + doquery($Query_RollbackPact, 'ally_pacts'); + + $Message = array(); + $Message['msg_id'] = '097'; + $Message['args'] = array($Ally['id'], $Ally['ally_name']); + $Message = json_encode($Message); + $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); + SendNotification($Manage_AID, $Result_CheckPact['ally_ranks'], $Message); + + $_MsgBox['color'] = 'lime'; + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_OK_Rollback']; + } + else + { + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactRollback_Active']; + } + } + else + { + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactRollback_NotSender']; + } + } + elseif($Manage_CMD == 3) + { + // User wants to Remove your (sent by your ally) change type proposal + if($Manage_IsSender) + { + $Manage_CheckField = 'Change_Sender'; + } + else + { + $Manage_CheckField = 'Change_Owner'; + } + if($Result_CheckPact[$Manage_CheckField] > 0) + { + $Query_UpdatePactType = ''; + $Query_UpdatePactType .= "UPDATE {{table}} SET "; + $Query_UpdatePactType .= "`{$Manage_CheckField}` = 0 "; + $Query_UpdatePactType .= "WHERE "; + $Query_UpdatePactType .= "`AllyID_Sender` = {$Result_CheckPact['AllyID_Sender']} AND "; + $Query_UpdatePactType .= "`AllyID_Owner` = {$Result_CheckPact['AllyID_Owner']} "; + $Query_UpdatePactType .= "LIMIT 1; -- ally.pactslist.php|UpdatePactType|StopChange"; + doquery($Query_UpdatePactType, 'ally_pacts'); + + $Message = array(); + $Message['msg_id'] = '103'; + $Message['args'] = array($Ally['id'], $Ally['ally_name']); + $Message = json_encode($Message); + $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); + SendNotification($Manage_AID, $Result_CheckPact['ally_ranks'], $Message); + + $_MsgBox['color'] = 'lime'; + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_OK_StopChange']; + } + else + { + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactChange_NothingToStop']; + } + } + else if($Manage_CMD == 4) + { + // User wants to Accept new Pact proposal or change type proposal + if($Result_CheckPact['Active'] == 0) + { + if(!$Manage_IsSender) + { + // User wants to Accept new Pact proposal + $Query_AcceptNewPact = ''; + $Query_AcceptNewPact .= "UPDATE {{table}} SET "; + $Query_AcceptNewPact .= "`Active` = 1, `Date` = {$Time} "; + $Query_AcceptNewPact .= "WHERE "; + $Query_AcceptNewPact .= "`AllyID_Sender` = {$Result_CheckPact['AllyID_Sender']} AND "; + $Query_AcceptNewPact .= "`AllyID_Owner` = {$Result_CheckPact['AllyID_Owner']} "; + $Query_AcceptNewPact .= "LIMIT 1; -- ally.pactslist.php|AcceptNewPact"; + doquery($Query_AcceptNewPact, 'ally_pacts'); + + $Message = array(); + $Message['msg_id'] = '098'; + $Message['args'] = array($Ally['id'], $Ally['ally_name']); + $Message = json_encode($Message); + $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); + SendNotification($Manage_AID, $Result_CheckPact['ally_ranks'], $Message); + + $_MsgBox['color'] = 'lime'; + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_OK_Accept_NewPact']; + } + else + { + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactAccept_Sender']; + } + } + else + { + // User wants to Accept change type proposal + if($Manage_IsSender) + { + $Manage_NewType = $Result_CheckPact['Change_Owner']; + } + else + { + $Manage_NewType = $Result_CheckPact['Change_Sender']; + } + if($Manage_NewType > 0) + { + $Query_UpdatePactType = ''; + $Query_UpdatePactType .= "UPDATE {{table}} SET "; + $Query_UpdatePactType .= "`Type` = {$Manage_NewType}, "; + $Query_UpdatePactType .= "`Change_Owner` = 0, "; + $Query_UpdatePactType .= "`Change_Sender` = 0 "; + $Query_UpdatePactType .= "WHERE "; + $Query_UpdatePactType .= "`AllyID_Sender` = {$Result_CheckPact['AllyID_Sender']} AND "; + $Query_UpdatePactType .= "`AllyID_Owner` = {$Result_CheckPact['AllyID_Owner']} "; + $Query_UpdatePactType .= "LIMIT 1; -- ally.pactslist.php|UpdatePactType|Accept"; + doquery($Query_UpdatePactType, 'ally_pacts'); + + $Message = array(); + $Message['msg_id'] = '100'; + $Message['args'] = array($Ally['id'], $Ally['ally_name']); + $Message = json_encode($Message); + $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); + SendNotification($Manage_AID, $Result_CheckPact['ally_ranks'], $Message); + + $_MsgBox['color'] = 'lime'; + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_OK_Accept_NewType']; + } + else + { + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactAccept_NothingToAccept']; + } + } + } + else if($Manage_CMD == 5) + { + // User wants to Refuse new Pact proposal or change type proposal + if($Result_CheckPact['Active'] == 0) + { + if(!$Manage_IsSender) + { + // User wants to Refuse new Pact proposal + $Query_RefuseNewPact = ''; + $Query_RefuseNewPact .= "DELETE FROM {{table}} WHERE "; + $Query_RefuseNewPact .= "`AllyID_Sender` = {$Result_CheckPact['AllyID_Sender']} AND "; + $Query_RefuseNewPact .= "`AllyID_Owner` = {$Result_CheckPact['AllyID_Owner']} "; + $Query_RefuseNewPact .= "LIMIT 1; -- ally.pactslist.php|RefuseNewPact"; + doquery($Query_RefuseNewPact, 'ally_pacts'); + + $Message = array(); + $Message['msg_id'] = '099'; + $Message['args'] = array($Ally['id'], $Ally['ally_name']); + $Message = json_encode($Message); + $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); + SendNotification($Manage_AID, $Result_CheckPact['ally_ranks'], $Message); + + $_MsgBox['color'] = 'lime'; + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_OK_Refuse_NewPact']; + } + else + { + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactRefuse_Sender']; + } + } + else + { + // User wants to Refuse change type proposal + if($Manage_IsSender) + { + $Manage_TypeField = 'Change_Owner'; + $Manage_NewType = $Result_CheckPact['Change_Owner']; + } + else + { + $Manage_TypeField = 'Change_Sender'; + $Manage_NewType = $Result_CheckPact['Change_Sender']; + } + if($Manage_NewType > 0) + { + $Query_UpdatePactType = ''; + $Query_UpdatePactType .= "UPDATE {{table}} SET "; + $Query_UpdatePactType .= "`$Manage_TypeField` = 0 "; + $Query_UpdatePactType .= "WHERE "; + $Query_UpdatePactType .= "`AllyID_Sender` = {$Result_CheckPact['AllyID_Sender']} AND "; + $Query_UpdatePactType .= "`AllyID_Owner` = {$Result_CheckPact['AllyID_Owner']} "; + $Query_UpdatePactType .= "LIMIT 1; -- ally.pactslist.php|UpdatePactType|Refuse"; + doquery($Query_UpdatePactType, 'ally_pacts'); + + $Message = array(); + $Message['msg_id'] = '101'; + $Message['args'] = array($Ally['id'], $Ally['ally_name']); + $Message = json_encode($Message); + $Message = array('from' => '005', 'subject' => '024', 'content' => $Message); + SendNotification($Manage_AID, $Result_CheckPact['ally_ranks'], $Message); + + $_MsgBox['color'] = 'lime'; + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_OK_Refuse_NewType']; + } + else + { + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactRefuse_NothingToAccept']; + } + } + } + } + else + { + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_PactDoesntExist']; + } + } + else + { + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_BadCMD']; + } + } + else + { + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_BadAID']; + } + } + else + { + $_MsgBox['text'] = $_Lang['AllyPacts_Msg_CantManage']; + } +} + +if($CanManage) +{ + $ThisRow = gettemplate('alliance_pactslist_manage_row'); + $BodyTPL = gettemplate('alliance_pactslist_manage_body'); + $ThisColspan = 5; +} +else +{ + $ThisRow = gettemplate('alliance_pactslist_row'); + $BodyTPL = gettemplate('alliance_pactslist_body'); + $ThisColspan = 4; +} + +$_Lang['Insert_MsgBox'] = ''; +if(!empty($_MsgBox)) +{ + $_Lang['Insert_MsgBox'] .= parsetemplate(gettemplate('_singleRow'), array('Colspan' => $ThisColspan, 'Classes' => 'pad5 '.$_MsgBox['color'], 'Text' => $_MsgBox['text'])); + $_Lang['Insert_MsgBox'] .= parsetemplate(gettemplate('_singleRow'), array('Colspan' => $ThisColspan, 'Classes' => 'inv', 'Text' => '')); +} + +$Query_GetPacts = ''; +$Query_GetPacts .= "SELECT `pacts`.*, `ally`.`ally_name` "; +$Query_GetPacts .= "FROM {{table}} AS `pacts` "; +$Query_GetPacts .= "LEFT JOIN `{{prefix}}alliance` AS `ally` "; +$Query_GetPacts .= "ON `ally`.`id` = IF(`pacts`.`AllyID_Sender` = {$Ally['id']}, `pacts`.`AllyID_Owner`, `pacts`.`AllyID_Sender`) "; +$Query_GetPacts .= "WHERE (`AllyID_Sender` = {$Ally['id']} OR `AllyID_Owner` = {$Ally['id']}) "; +$Query_GetPacts .= "; -- ally.pactslist.php|GetPacts"; +$GetPacts = doquery($Query_GetPacts, 'ally_pacts'); + +if(mysql_num_rows($GetPacts) > 0) +{ + while($FetchData = mysql_fetch_assoc($GetPacts)) + { + $FetchData['IsSender'] = ($FetchData['AllyID_Sender'] == $Ally['id'] ? true : false); + $FetchData['SecondAllyID'] = ($FetchData['IsSender'] === true ? $FetchData['AllyID_Owner'] : $FetchData['AllyID_Sender']); + if($FetchData['Active'] == 1) + { + if($FetchData['Change_Owner'] > 0) + { + if($FetchData['IsSender'] === false) + { + $FetchData['KeyState'][] = '3'; + $FetchData['Status'][0] = $_Lang['AWNP_States']['active']; + $FetchData['Status'][] = sprintf($_Lang['AWNP_States']['my_2'], $_Lang['AWNP_Types'][$FetchData['Change_Owner']]); + } + else + { + $FetchData['KeyState'][] = '4'; + $FetchData['Status'][0] = $_Lang['AWNP_States']['active']; + $FetchData['Status'][] = sprintf($_Lang['AWNP_States']['their_2'], $_Lang['AWNP_Types'][$FetchData['Change_Owner']]); + } + } + if($FetchData['Change_Sender'] > 0) + { + if($FetchData['IsSender'] === true) + { + $FetchData['KeyState'][] = '3'; + $FetchData['Status'][0] = $_Lang['AWNP_States']['active']; + $FetchData['Status'][] = sprintf($_Lang['AWNP_States']['my_2'], $_Lang['AWNP_Types'][$FetchData['Change_Sender']]); + } + else + { + $FetchData['KeyState'][] = '4'; + $FetchData['Status'][0] = $_Lang['AWNP_States']['active']; + $FetchData['Status'][] = sprintf($_Lang['AWNP_States']['their_2'], $_Lang['AWNP_Types'][$FetchData['Change_Sender']]); + } + } + if(empty($FetchData['KeyState'])) + { + $FetchData['KeyState'][] = '1'; + $FetchData['Status'][] = $_Lang['AWNP_States']['active']; + } + } + else + { + if($FetchData['IsSender'] === true) + { + $FetchData['KeyState'][] = '2'; + $FetchData['Status'][] = $_Lang['AWNP_States']['my_0']; + } + else + { + $FetchData['KeyState'][] = '5'; + $FetchData['Status'][] = $_Lang['AWNP_States']['their_0']; + } + } + + if($CanManage) + { + if(in_array(1, $FetchData['KeyState'])) + { + $FetchData['Actions']['remove'] = array('Class' => 'remove', 'Link' => '?mode=pactslist&do=1&cmd=1&aid='.$FetchData['SecondAllyID']); + $FetchData['Actions']['change'] = array('Class' => 'change', 'Link' => '?mode=changepact&aid='.$FetchData['SecondAllyID']); + } + if(in_array(2, $FetchData['KeyState'])) + { + $FetchData['Actions']['rollback'] = array('Class' => 'rollback', 'Link' => '?mode=pactslist&do=1&cmd=2&aid='.$FetchData['SecondAllyID']); + } + if(in_array(3, $FetchData['KeyState'])) + { + $FetchData['Actions']['remove'] = array('Class' => 'remove', 'Link' => '?mode=pactslist&do=1&cmd=1&aid='.$FetchData['SecondAllyID']); + $FetchData['Actions']['stopchange'] = array('Class' => 'stopchange', 'Link' => '?mode=pactslist&do=1&cmd=3&aid='.$FetchData['SecondAllyID']); + } + if(in_array(4, $FetchData['KeyState'])) + { + $FetchData['Actions']['remove'] = array('Class' => 'remove', 'Link' => '?mode=pactslist&do=1&cmd=1&aid='.$FetchData['SecondAllyID']); + if(!in_array(3, $FetchData['KeyState'])) + { + $FetchData['Actions']['change'] = array('Class' => 'change', 'Link' => '?mode=changepact&aid='.$FetchData['SecondAllyID']); + } + $FetchData['Actions']['accept'] = array('Class' => 'accept', 'Link' => '?mode=pactslist&do=1&cmd=4&aid='.$FetchData['SecondAllyID']); + $FetchData['Actions']['refuse'] = array('Class' => 'refuse', 'Link' => '?mode=pactslist&do=1&cmd=5&aid='.$FetchData['SecondAllyID']); + } + if(in_array(5, $FetchData['KeyState'])) + { + $FetchData['Actions']['accept'] = array('Class' => 'accept', 'Link' => '?mode=pactslist&do=1&cmd=4&aid='.$FetchData['SecondAllyID']); + $FetchData['Actions']['refuse'] = array('Class' => 'refuse', 'Link' => '?mode=pactslist&do=1&cmd=5&aid='.$FetchData['SecondAllyID']); + } + + $TPL_PactsList_Actions = gettemplate('alliance_pactslist_manage_actions'); + foreach($FetchData['Actions'] as &$ThisVal) + { + $ThisVal = parsetemplate($TPL_PactsList_Actions, $ThisVal); + } + $FetchData['Actions'] = implode(' ', $FetchData['Actions']); + } + array_walk($FetchData['Status'], function(&$Value){ $Value = '• '.$Value; }); + $FetchData['Status'] = implode('
    ', $FetchData['Status']); + $FetchData['Key'] = max($FetchData['KeyState']).$FetchData['Date']; + $FetchData['AllyID'] = $FetchData['SecondAllyID']; + $FetchData['AllyName'] = $FetchData['ally_name']; + $FetchData['PactDate'] = prettyDate('d m Y, H:i:s', $FetchData['Date'], 1); + $FetchData['PactType'] = $_Lang['AWNP_Types'][$FetchData['Type']]; + + $PactsList[$FetchData['Key']] = $FetchData; + } + krsort($PactsList, SORT_STRING); + foreach($PactsList as $PactData) + { + $_Lang['ShowPactsList'][] = parsetemplate($ThisRow, $PactData); + } + + $_Lang['ShowPactsList'] = implode('', $_Lang['ShowPactsList']); +} +else +{ + $_Lang['ShowPactsList'] = parsetemplate(gettemplate('_singleRow'), array + ( + 'Colspan' => $ThisColspan, + 'Classes' => 'red pad5', + 'Text' => $_Lang['AWNP_NoPacts'] + )); +} + +if($_ThisUserRank['warnpact'] !== true) +{ + $_Lang['Insert_HideNewPact'] = 'class="hide"'; +} + +$Page = parsetemplate($BodyTPL, $_Lang); +display($Page, $_Lang['Ally_Pacts_WinTitle']); + +?> diff --git a/modules/index.php b/modules/index.php index ee150fd01..bc99142d1 100644 --- a/modules/index.php +++ b/modules/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/moon_sim.php b/moon_sim.php index ae5d795e0..e22bfbe58 100644 --- a/moon_sim.php +++ b/moon_sim.php @@ -1,81 +1,81 @@ - 0 AND $Data['shipcount'] > 0) - { - if($Data['diameter'] < 10000) - { - $_Lang['HideResult'] = ''; - - $MoonChance = (100 - sqrt($Data['diameter'])) * sqrt($Data['shipcount']); - $FleetChance = sqrt($Data['diameter']) / 2; - - if($MoonChance > 100) - { - $MoonChance = 100; - } - else if($MoonChance <= 0) - { - $MoonChance = 0; - } - else - { - $MoonChance = round($MoonChance, 2); - } - - if($FleetChance > 100) - { - $FleetChance = 100; - } - else if($FleetChance <= 0) - { - $FleetChance = 0; - } - else - { - $FleetChance = round($FleetChance, 2); - } - - $_Lang['Input_Diamter'] = prettyNumber($Data['diameter']); - $_Lang['Input_ShipCount'] = prettyNumber($Data['shipcount']); - $_Lang['Input_MoonChance'] = $MoonChance; - $_Lang['Input_FleetChance'] = $FleetChance; - } - else - { - $_Lang['HideError'] = ''; - $_Lang['Input_Error'] = $_Lang['Error_DiameterTooBig']; - } - } - else - { - $_Lang['HideError'] = ''; - $_Lang['Input_Error'] = $_Lang['Error_BadDataGiven']; - } - } - - //Display page - $page = parsetemplate(gettemplate('moon_sim_body'), $_Lang); - - display($page, $_Lang['Title'], false); - -?> \ No newline at end of file + 0 AND $Data['shipcount'] > 0) + { + if($Data['diameter'] < 10000) + { + $_Lang['HideResult'] = ''; + + $MoonChance = (100 - sqrt($Data['diameter'])) * sqrt($Data['shipcount']); + $FleetChance = sqrt($Data['diameter']) / 2; + + if($MoonChance > 100) + { + $MoonChance = 100; + } + else if($MoonChance <= 0) + { + $MoonChance = 0; + } + else + { + $MoonChance = round($MoonChance, 2); + } + + if($FleetChance > 100) + { + $FleetChance = 100; + } + else if($FleetChance <= 0) + { + $FleetChance = 0; + } + else + { + $FleetChance = round($FleetChance, 2); + } + + $_Lang['Input_Diamter'] = prettyNumber($Data['diameter']); + $_Lang['Input_ShipCount'] = prettyNumber($Data['shipcount']); + $_Lang['Input_MoonChance'] = $MoonChance; + $_Lang['Input_FleetChance'] = $FleetChance; + } + else + { + $_Lang['HideError'] = ''; + $_Lang['Input_Error'] = $_Lang['Error_DiameterTooBig']; + } + } + else + { + $_Lang['HideError'] = ''; + $_Lang['Input_Error'] = $_Lang['Error_BadDataGiven']; + } +} + +//Display page +$page = parsetemplate(gettemplate('moon_sim_body'), $_Lang); + +display($page, $_Lang['Title'], false); + +?> diff --git a/morale_info.php b/morale_info.php index ff36f3030..a85a7fca6 100644 --- a/morale_info.php +++ b/morale_info.php @@ -1,84 +1,84 @@ - 0) - { - $_Lang['Insert_MoraleColor'] = 'lime'; - } - else if($_User['morale_level'] <= -50) - { - $_Lang['Insert_MoraleColor'] = 'red'; - } - else if($_User['morale_level'] < 0) - { - $_Lang['Insert_MoraleColor'] = 'orange'; - } - - $PowerUpsDowns = array - ( - 'Table_Bonus_FleetSpeedUp1', - 'Table_Bonus_FleetSpeedUp2', - 'Table_Bonus_FleetPowerUp1', - 'Table_Bonus_FleetShieldPowerUp1', - 'Table_Bonus_IdleResStealRaise1', - 'Table_Bonus_FleetRFAddition1', - 'Table_Penalty_FleetSlowDown1', - 'Table_Penalty_FleetShieldAttenuation1', - 'Table_Penalty_FleetShieldAttenuation2', - 'Table_Penalty_FleetPowerAttenuation1', - 'Table_Penalty_FleetPowerAttenuation2', - 'Table_Penalty_FleetRFRemoval1', - 'Table_Penalty_IdleResStealDrop1', - 'Table_Penalty_AllResStealDrop1', - 'Table_Penalty_SpyReportRevolt', - 'Table_Penalty_OwnResLoseRaise1', - ); - - foreach($PowerUpsDowns as $ThisElement) - { - $ThisElementLevel = $_Lang[$ThisElement.'_Level']; - $ThisIsActive = false; - if($ThisElementLevel > 0) - { - $ThisType = 'Bonus'; - if($_User['morale_level'] >= $ThisElementLevel) - { - $ThisIsActive = true; - } - } - else if($ThisElementLevel < 0) - { - $ThisType = 'Penalty'; - if($_User['morale_level'] <= $ThisElementLevel) - { - $ThisIsActive = true; - } - } - - $_Lang[$ThisElement.'_State'] = sprintf(($ThisIsActive ? $_Lang['Table_State_Active_'.$ThisType] : $_Lang['Table_State_InActive']), $ThisElementLevel); - } - - $_Lang['Table_MoraleStatus'] = sprintf($_Lang['Table_MoraleStatus'], $_Lang['Insert_MoraleColor'], $_User['morale_level']); - - $page = parsetemplate(gettemplate('morale_info_body'), $_Lang); - display($page, $_Lang['PageTitle'], false); - -?> \ No newline at end of file + 0) +{ + $_Lang['Insert_MoraleColor'] = 'lime'; +} +else if($_User['morale_level'] <= -50) +{ + $_Lang['Insert_MoraleColor'] = 'red'; +} +else if($_User['morale_level'] < 0) +{ + $_Lang['Insert_MoraleColor'] = 'orange'; +} + +$PowerUpsDowns = array +( + 'Table_Bonus_FleetSpeedUp1', + 'Table_Bonus_FleetSpeedUp2', + 'Table_Bonus_FleetPowerUp1', + 'Table_Bonus_FleetShieldPowerUp1', + 'Table_Bonus_IdleResStealRaise1', + 'Table_Bonus_FleetRFAddition1', + 'Table_Penalty_FleetSlowDown1', + 'Table_Penalty_FleetShieldAttenuation1', + 'Table_Penalty_FleetShieldAttenuation2', + 'Table_Penalty_FleetPowerAttenuation1', + 'Table_Penalty_FleetPowerAttenuation2', + 'Table_Penalty_FleetRFRemoval1', + 'Table_Penalty_IdleResStealDrop1', + 'Table_Penalty_AllResStealDrop1', + 'Table_Penalty_SpyReportRevolt', + 'Table_Penalty_OwnResLoseRaise1', +); + +foreach($PowerUpsDowns as $ThisElement) +{ + $ThisElementLevel = $_Lang[$ThisElement.'_Level']; + $ThisIsActive = false; + if($ThisElementLevel > 0) + { + $ThisType = 'Bonus'; + if($_User['morale_level'] >= $ThisElementLevel) + { + $ThisIsActive = true; + } + } + else if($ThisElementLevel < 0) + { + $ThisType = 'Penalty'; + if($_User['morale_level'] <= $ThisElementLevel) + { + $ThisIsActive = true; + } + } + + $_Lang[$ThisElement.'_State'] = sprintf(($ThisIsActive ? $_Lang['Table_State_Active_'.$ThisType] : $_Lang['Table_State_InActive']), $ThisElementLevel); +} + +$_Lang['Table_MoraleStatus'] = sprintf($_Lang['Table_MoraleStatus'], $_Lang['Insert_MoraleColor'], $_User['morale_level']); + +$page = parsetemplate(gettemplate('morale_info_body'), $_Lang); +display($page, $_Lang['PageTitle'], false); + +?> diff --git a/notes.php b/notes.php index 1531d1131..21c03051e 100644 --- a/notes.php +++ b/notes.php @@ -1,302 +1,302 @@ - 'lime', 2 => 'orange', 3 => 'red'); - $_Priorities = array(1, 2, 3); - - if(isset($_POST['send']) && $_POST['send'] == 1) - { - $InsertClean['title'] = substr(trim(stripslashes($_POST['title'])), 0, $_MaxLengthTitle); - $InsertClean['priority'] = intval($_POST['priority']); - $InsertClean['text'] = substr(trim(stripslashes($_POST['text'])), 0, $_MaxLengthNote); - - $Insert['title'] = mysql_real_escape_string($InsertClean['title']); - $Insert['priority'] = $InsertClean['priority']; - $Insert['text'] = mysql_real_escape_string($InsertClean['text']); - } - - if($Command == 'show') - { - // Show selected Note - $TPL_Default = gettemplate('notes_form'); - - $GetID = (isset($_GET['id']) ? round($_GET['id']) : 0); - if($GetID <= 0) - { - message($_Lang['Errors_BadIDGiven'], $_Lang['Title'], 'notes.php', 3); - } - - $Get_Row = doquery("SELECT * FROM {{table}} WHERE `id` = {$GetID} LIMIT 1;", 'notes', true); - if(empty($Get_Row)) - { - message($_Lang['Errors_IDNoExist'], $_Lang['Title'], 'notes.php', 3); - } - if($Get_Row['owner'] != $_User['id']) - { - message($_Lang['Errors_NoteNotYour'], $_Lang['Title'], 'notes.php', 3); - } - - if(isset($_POST['send']) && $_POST['send'] == 1) - { - if(!empty($Insert['title'])) - { - $Get_Row['title'] = $InsertClean['title']; - if(in_array($Insert['priority'], $_Priorities)) - { - $Get_Row['priority'] = $InsertClean['priority']; - if(!empty($Insert['text'])) - { - $Get_Row['text'] = $InsertClean['text']; - - $Query_UpdateNote = ''; - $Query_UpdateNote .= "UPDATE {{table}} SET "; - $Query_UpdateNote .= "`title` = '{$Insert['title']}', "; - $Query_UpdateNote .= "`priority` = {$Insert['priority']}, "; - $Query_UpdateNote .= "`text` = '{$Insert['text']}', "; - $Query_UpdateNote .= "`time` = UNIX_TIMESTAMP() "; - $Query_UpdateNote .= "WHERE `id` = {$GetID};"; - doquery($Query_UpdateNote, 'notes'); - - $Parse['Input_MsgText'] = $_Lang['Msg_EditSuccess']; - $Parse['Input_MsgColor'] = 'lime'; - } - else - { - $Parse['Input_MsgText'] = $_Lang['Errors_TextEmpty']; - $Parse['Input_MsgColor'] = 'red'; - } - } - else - { - $Parse['Input_MsgText'] = $_Lang['Errors_BadPriority']; - $Parse['Input_MsgColor'] = 'red'; - } - } - else - { - $Parse['Input_MsgText'] = $_Lang['Errors_TitleEmpty']; - $Parse['Input_MsgColor'] = 'red'; - } - } - - $Parse['Input_Title'] = $Get_Row['title']; - $Parse['Input_PrioritySelect_'.$Get_Row['priority']] = 'selected'; - $Parse['Input_Text'] = $Get_Row['text']; - - $Parse['Input_InsertCMD'] = '?cmd=show&id='.$GetID; - $Parse['Input_InsertTitle'] = $_Lang['Title_EditRow']; - $Parse['Input_MaxTitleLength'] = $_MaxLengthTitle; - $Parse['Input_MaxNoteLength'] = $_MaxLengthNote; - } - else if($Command == 'add') - { - // Add new note - $TPL_Default = gettemplate('notes_form'); - - if(isset($_POST['send']) && $_POST['send'] == 1) - { - if(!empty($Insert['title'])) - { - if(in_array($Insert['priority'], $_Priorities)) - { - if(!empty($Insert['text'])) - { - $Query_InsertNote = ''; - $Query_InsertNote .= "INSERT INTO {{table}} SET "; - $Query_InsertNote .= "`owner` = {$_User['id']}, "; - $Query_InsertNote .= "`time` = UNIX_TIMESTAMP(), "; - $Query_InsertNote .= "`priority` = {$Insert['priority']}, "; - $Query_InsertNote .= "`title` = '{$Insert['title']}', "; - $Query_InsertNote .= "`text` = '{$Insert['text']}';"; - doquery($Query_InsertNote, 'notes'); - - header('Location: ?added=true'); - safeDie(); - } - else - { - $Parse['Input_MsgText'] = $_Lang['Errors_TextEmpty']; - $Parse['Input_MsgColor'] = 'red'; - } - } - else - { - $Parse['Input_MsgText'] = $_Lang['Errors_BadPriority']; - $Parse['Input_MsgColor'] = 'red'; - } - } - else - { - $Parse['Input_MsgText'] = $_Lang['Errors_TitleEmpty']; - $Parse['Input_MsgColor'] = 'red'; - } - } - - if(isset($InsertClean)) - { - $Parse['Input_Title'] = $InsertClean['title']; - $Parse['Input_PrioritySelect_'.$InsertClean['priority']] = 'selected'; - $Parse['Input_Text'] = $InsertClean['text']; - } - - $Parse['Input_InsertCMD'] = '?cmd=add'; - $Parse['Input_InsertTitle'] = $_Lang['Title_AddRow']; - $Parse['Input_MaxTitleLength'] = $_MaxLengthTitle; - $Parse['Input_MaxNoteLength'] = $_MaxLengthNote; - } - else if($Command == 'delete') - { - $Command = ''; - - if(isset($_POST['action']) && $_POST['action'] == 2) - { - // Delete all notes - - doquery("DELETE FROM {{table}} WHERE `owner` = {$_User['id']};", 'notes'); - if(mysql_affected_rows() > 0) - { - $Parse['Input_MsgText'] = $_Lang['Msg_DeleteAllSuccess']; - $Parse['Input_MsgColor'] = 'lime'; - } - else - { - $Parse['Input_MsgText'] = $_Lang['Errors_NothingToDelete']; - $Parse['Input_MsgColor'] = 'red'; - } - } - else - { - // Delete selected notes - if(!empty($_POST['del'])) - { - foreach($_POST['del'] as $Key => $Value) - { - if($Value == 'on') - { - $Key = round($Key); - if($Key > 0) - { - $DeleteIDs[] = $Key; - } - } - } - } - - if(!empty($DeleteIDs)) - { - doquery("DELETE FROM {{table}} WHERE `id` IN (".implode(', ', $DeleteIDs).") AND `owner` = {$_User['id']};", 'notes'); - - if(mysql_affected_rows() > 0) - { - $Parse['Input_MsgText'] = $_Lang['Msg_DeleteSelectedSuccess']; - $Parse['Input_MsgColor'] = 'lime'; - } - else - { - $Parse['Input_MsgText'] = $_Lang['Errors_NothingDeleted']; - $Parse['Input_MsgColor'] = 'red'; - } - } - else - { - $Parse['Input_MsgText'] = $_Lang['Errors_NothingDeleted']; - $Parse['Input_MsgColor'] = 'red'; - } - } - } - else - { - $Command = ''; - } - - if(empty($Command)) - { - // Show list of notes - $TPL_Default = gettemplate('notes_body'); - - $Get_Count = doquery("SELECT COUNT(`id`) AS `Count` FROM {{table}} WHERE `owner` = {$_User['id']};", 'notes', true); - $TotalCount = $Get_Count['Count']; - if($TotalCount > 0) - { - $TPL_List_Row = gettemplate('notes_list_row'); - - $ThisPage = (isset($_GET['page']) ? intval($_GET['page']) : 0); - if($ThisPage < 1) - { - $ThisPage = 1; - } - $SkipCount = ($ThisPage - 1) * $_PerPage; - if($SkipCount >= $TotalCount) - { - $ThisPage = 1; - $SkipCount = 0; - } - - $Query_GetNotes = ''; - $Query_GetNotes .= "SELECT * FROM {{table}} "; - $Query_GetNotes .= "WHERE `owner` = {$_User['id']} "; - $Query_GetNotes .= "ORDER BY `priority` DESC, `time` DESC LIMIT {$SkipCount}, {$_PerPage};"; - $Result_GetNotes = doquery($Query_GetNotes, 'notes'); - while($NoteData = mysql_fetch_assoc($Result_GetNotes)) - { - $NoteData = array - ( - 'ID' => $NoteData['id'], - 'TitleColor' => $_PriorityArray[$NoteData['priority']], - 'Title' => $NoteData['title'], - 'Date' => prettyDate('d m Y, H:i:s', $NoteData['time'], 1) - ); - - $Parse['Input_NotesList'][] = parsetemplate($TPL_List_Row, $NoteData); - } - $Parse['Input_NotesList'] = implode('', $Parse['Input_NotesList']); - - if($TotalCount > $_PerPage) - { - include_once($_EnginePath.'includes/functions/Pagination.php'); - $Pagination = CreatePaginationArray($TotalCount, $_PerPage, $ThisPage, 7); - $PaginationTPL = "{\$ShowValue}"; - $PaginationViewOpt = array('CurrentPage_Classes' => 'orange', 'Breaker_View' => '...'); - $Pagination = ParsePaginationArray($Pagination, $ThisPage, $PaginationTPL, $PaginationViewOpt); - $Parse['Input_Pagination'] = implode(' ', $Pagination); - } - else - { - $Parse['Input_HideAtNoPagination'] = 'hide'; - } - $Parse['Input_HideAtNotes'] = 'hide'; - } - else - { - $Parse['Input_HideAtNoNotes'] = 'hide'; - } - } - - if(isset($_GET['added']) && $_GET['added'] == 'true') - { - $Parse['Input_MsgText'] = $_Lang['Msg_AddSuccess']; - $Parse['Input_MsgColor'] = 'lime'; - } - - if(empty($Parse['Input_MsgText'])) - { - $Parse['Input_HideMsgBox'] = 'hide'; - } - - display(parsetemplate($TPL_Default, $Parse), $Parse['Title'], false); - -?> \ No newline at end of file + 'lime', 2 => 'orange', 3 => 'red'); +$_Priorities = array(1, 2, 3); + +if(isset($_POST['send']) && $_POST['send'] == 1) +{ + $InsertClean['title'] = substr(trim(stripslashes($_POST['title'])), 0, $_MaxLengthTitle); + $InsertClean['priority'] = intval($_POST['priority']); + $InsertClean['text'] = substr(trim(stripslashes($_POST['text'])), 0, $_MaxLengthNote); + + $Insert['title'] = mysql_real_escape_string($InsertClean['title']); + $Insert['priority'] = $InsertClean['priority']; + $Insert['text'] = mysql_real_escape_string($InsertClean['text']); +} + +if($Command == 'show') +{ + // Show selected Note + $TPL_Default = gettemplate('notes_form'); + + $GetID = (isset($_GET['id']) ? round($_GET['id']) : 0); + if($GetID <= 0) + { + message($_Lang['Errors_BadIDGiven'], $_Lang['Title'], 'notes.php', 3); + } + + $Get_Row = doquery("SELECT * FROM {{table}} WHERE `id` = {$GetID} LIMIT 1;", 'notes', true); + if(empty($Get_Row)) + { + message($_Lang['Errors_IDNoExist'], $_Lang['Title'], 'notes.php', 3); + } + if($Get_Row['owner'] != $_User['id']) + { + message($_Lang['Errors_NoteNotYour'], $_Lang['Title'], 'notes.php', 3); + } + + if(isset($_POST['send']) && $_POST['send'] == 1) + { + if(!empty($Insert['title'])) + { + $Get_Row['title'] = $InsertClean['title']; + if(in_array($Insert['priority'], $_Priorities)) + { + $Get_Row['priority'] = $InsertClean['priority']; + if(!empty($Insert['text'])) + { + $Get_Row['text'] = $InsertClean['text']; + + $Query_UpdateNote = ''; + $Query_UpdateNote .= "UPDATE {{table}} SET "; + $Query_UpdateNote .= "`title` = '{$Insert['title']}', "; + $Query_UpdateNote .= "`priority` = {$Insert['priority']}, "; + $Query_UpdateNote .= "`text` = '{$Insert['text']}', "; + $Query_UpdateNote .= "`time` = UNIX_TIMESTAMP() "; + $Query_UpdateNote .= "WHERE `id` = {$GetID};"; + doquery($Query_UpdateNote, 'notes'); + + $Parse['Input_MsgText'] = $_Lang['Msg_EditSuccess']; + $Parse['Input_MsgColor'] = 'lime'; + } + else + { + $Parse['Input_MsgText'] = $_Lang['Errors_TextEmpty']; + $Parse['Input_MsgColor'] = 'red'; + } + } + else + { + $Parse['Input_MsgText'] = $_Lang['Errors_BadPriority']; + $Parse['Input_MsgColor'] = 'red'; + } + } + else + { + $Parse['Input_MsgText'] = $_Lang['Errors_TitleEmpty']; + $Parse['Input_MsgColor'] = 'red'; + } + } + + $Parse['Input_Title'] = $Get_Row['title']; + $Parse['Input_PrioritySelect_'.$Get_Row['priority']] = 'selected'; + $Parse['Input_Text'] = $Get_Row['text']; + + $Parse['Input_InsertCMD'] = '?cmd=show&id='.$GetID; + $Parse['Input_InsertTitle'] = $_Lang['Title_EditRow']; + $Parse['Input_MaxTitleLength'] = $_MaxLengthTitle; + $Parse['Input_MaxNoteLength'] = $_MaxLengthNote; +} +else if($Command == 'add') +{ + // Add new note + $TPL_Default = gettemplate('notes_form'); + + if(isset($_POST['send']) && $_POST['send'] == 1) + { + if(!empty($Insert['title'])) + { + if(in_array($Insert['priority'], $_Priorities)) + { + if(!empty($Insert['text'])) + { + $Query_InsertNote = ''; + $Query_InsertNote .= "INSERT INTO {{table}} SET "; + $Query_InsertNote .= "`owner` = {$_User['id']}, "; + $Query_InsertNote .= "`time` = UNIX_TIMESTAMP(), "; + $Query_InsertNote .= "`priority` = {$Insert['priority']}, "; + $Query_InsertNote .= "`title` = '{$Insert['title']}', "; + $Query_InsertNote .= "`text` = '{$Insert['text']}';"; + doquery($Query_InsertNote, 'notes'); + + header('Location: ?added=true'); + safeDie(); + } + else + { + $Parse['Input_MsgText'] = $_Lang['Errors_TextEmpty']; + $Parse['Input_MsgColor'] = 'red'; + } + } + else + { + $Parse['Input_MsgText'] = $_Lang['Errors_BadPriority']; + $Parse['Input_MsgColor'] = 'red'; + } + } + else + { + $Parse['Input_MsgText'] = $_Lang['Errors_TitleEmpty']; + $Parse['Input_MsgColor'] = 'red'; + } + } + + if(isset($InsertClean)) + { + $Parse['Input_Title'] = $InsertClean['title']; + $Parse['Input_PrioritySelect_'.$InsertClean['priority']] = 'selected'; + $Parse['Input_Text'] = $InsertClean['text']; + } + + $Parse['Input_InsertCMD'] = '?cmd=add'; + $Parse['Input_InsertTitle'] = $_Lang['Title_AddRow']; + $Parse['Input_MaxTitleLength'] = $_MaxLengthTitle; + $Parse['Input_MaxNoteLength'] = $_MaxLengthNote; +} +else if($Command == 'delete') +{ + $Command = ''; + + if(isset($_POST['action']) && $_POST['action'] == 2) + { + // Delete all notes + + doquery("DELETE FROM {{table}} WHERE `owner` = {$_User['id']};", 'notes'); + if(mysql_affected_rows() > 0) + { + $Parse['Input_MsgText'] = $_Lang['Msg_DeleteAllSuccess']; + $Parse['Input_MsgColor'] = 'lime'; + } + else + { + $Parse['Input_MsgText'] = $_Lang['Errors_NothingToDelete']; + $Parse['Input_MsgColor'] = 'red'; + } + } + else + { + // Delete selected notes + if(!empty($_POST['del'])) + { + foreach($_POST['del'] as $Key => $Value) + { + if($Value == 'on') + { + $Key = round($Key); + if($Key > 0) + { + $DeleteIDs[] = $Key; + } + } + } + } + + if(!empty($DeleteIDs)) + { + doquery("DELETE FROM {{table}} WHERE `id` IN (".implode(', ', $DeleteIDs).") AND `owner` = {$_User['id']};", 'notes'); + + if(mysql_affected_rows() > 0) + { + $Parse['Input_MsgText'] = $_Lang['Msg_DeleteSelectedSuccess']; + $Parse['Input_MsgColor'] = 'lime'; + } + else + { + $Parse['Input_MsgText'] = $_Lang['Errors_NothingDeleted']; + $Parse['Input_MsgColor'] = 'red'; + } + } + else + { + $Parse['Input_MsgText'] = $_Lang['Errors_NothingDeleted']; + $Parse['Input_MsgColor'] = 'red'; + } + } +} +else +{ + $Command = ''; +} + +if(empty($Command)) +{ + // Show list of notes + $TPL_Default = gettemplate('notes_body'); + + $Get_Count = doquery("SELECT COUNT(`id`) AS `Count` FROM {{table}} WHERE `owner` = {$_User['id']};", 'notes', true); + $TotalCount = $Get_Count['Count']; + if($TotalCount > 0) + { + $TPL_List_Row = gettemplate('notes_list_row'); + + $ThisPage = (isset($_GET['page']) ? intval($_GET['page']) : 0); + if($ThisPage < 1) + { + $ThisPage = 1; + } + $SkipCount = ($ThisPage - 1) * $_PerPage; + if($SkipCount >= $TotalCount) + { + $ThisPage = 1; + $SkipCount = 0; + } + + $Query_GetNotes = ''; + $Query_GetNotes .= "SELECT * FROM {{table}} "; + $Query_GetNotes .= "WHERE `owner` = {$_User['id']} "; + $Query_GetNotes .= "ORDER BY `priority` DESC, `time` DESC LIMIT {$SkipCount}, {$_PerPage};"; + $Result_GetNotes = doquery($Query_GetNotes, 'notes'); + while($NoteData = mysql_fetch_assoc($Result_GetNotes)) + { + $NoteData = array + ( + 'ID' => $NoteData['id'], + 'TitleColor' => $_PriorityArray[$NoteData['priority']], + 'Title' => $NoteData['title'], + 'Date' => prettyDate('d m Y, H:i:s', $NoteData['time'], 1) + ); + + $Parse['Input_NotesList'][] = parsetemplate($TPL_List_Row, $NoteData); + } + $Parse['Input_NotesList'] = implode('', $Parse['Input_NotesList']); + + if($TotalCount > $_PerPage) + { + include_once($_EnginePath.'includes/functions/Pagination.php'); + $Pagination = CreatePaginationArray($TotalCount, $_PerPage, $ThisPage, 7); + $PaginationTPL = "{\$ShowValue}"; + $PaginationViewOpt = array('CurrentPage_Classes' => 'orange', 'Breaker_View' => '...'); + $Pagination = ParsePaginationArray($Pagination, $ThisPage, $PaginationTPL, $PaginationViewOpt); + $Parse['Input_Pagination'] = implode(' ', $Pagination); + } + else + { + $Parse['Input_HideAtNoPagination'] = 'hide'; + } + $Parse['Input_HideAtNotes'] = 'hide'; + } + else + { + $Parse['Input_HideAtNoNotes'] = 'hide'; + } +} + +if(isset($_GET['added']) && $_GET['added'] == 'true') +{ + $Parse['Input_MsgText'] = $_Lang['Msg_AddSuccess']; + $Parse['Input_MsgColor'] = 'lime'; +} + +if(empty($Parse['Input_MsgText'])) +{ + $Parse['Input_HideMsgBox'] = 'hide'; +} + +display(parsetemplate($TPL_Default, $Parse), $Parse['Title'], false); + +?> diff --git a/officers.php b/officers.php index d66781929..f0db4bbe8 100644 --- a/officers.php +++ b/officers.php @@ -1,124 +1,124 @@ - $Data) - { - foreach($Data['bene'] as &$Value) - { - $Value = '• '.$Value; - } - - $ParseRow = array(); - $ParseRow['Name'] = $Data['name']; - $ParseRow['skinpath'] = $_SkinPath; - $ParseRow['img'] = $Data['img']; - $ParseRow['Info'] = $Data['desc']; - $ParseRow['Benefits'] = $_Lang['Benefits']; - $ParseRow['ParseBenefits'] = implode('
    ', $Data['bene']); - if($Data['type'] == 1) - { - $ThisTimeKey = $Officer.'_time'; - - $ParseRow['OfficerState'] = $_Lang['RentState']; - if($_User[$ThisTimeKey] > $Now) - { - $ParseRow['ThisState'] = $_Lang['RentTill']; - $ParseRow['OfficerVal'] = prettyDate('d m Y H:i:s', $_User[$ThisTimeKey], 1); - $ParseRow['OfficerValColor'] = 'lime'; - $ParseRow['ButtonText'] = $_Lang['RenewRent']; - } - else if($_User[$ThisTimeKey] > 0) - { - $ParseRow['ThisState'] = $_Lang['RentEnded']; - $ParseRow['OfficerVal'] = prettyDate('d m Y H:i:s', $_User[$ThisTimeKey], 1); - $ParseRow['OfficerValColor'] = 'orange'; - $ParseRow['ButtonText'] = $_Lang['RentAgain']; - } - else - { - $ParseRow['ThisState'] = $_Lang['NeverRented']; - $ParseRow['OfficerStateColor'] = 'red'; - $ParseRow['ButtonText'] = $_Lang['FirstRent']; - } - - foreach($Data['price'] as $KeyID => $PriceVal) - { - $ThisTimeVar = '_days'; - if($Data['time'][$KeyID] == 1) - { - $ThisTimeVar = '_day'; - } - $ParseRow['ButtonVars'][$KeyID] = array($Data['time'][$KeyID], $_Lang[$ThisTimeVar]); - $ParseRow['ButtonItems'][$KeyID] = $Data['itemid'][$KeyID]; - } - } - else if($Data['type'] == 2) - { - $ParseRow['OfficerState'] = $_Lang['RentState']; - $ParseRow['ThisState'] = $_Lang[$Data['thisState']]; - - if($_User[$Data['field']] == 0) - { - $ParseRow['ButtonText'] = $_Lang['FirstRent']; - $ParseRow['OfficerValColor'] = 'red'; - } - else - { - $ParseRow['ButtonText'] = $_Lang['RentPlus']; - $ParseRow['OfficerValColor'] = 'lime'; - } - $ParseRow['OfficerVal'] = ($_User[$Data['field']] + 0); - - foreach($Data['price'] as $KeyID => $PriceVal) - { - $ParseRow['ButtonVars'][$KeyID] = array($Data['count'][$KeyID], $_Lang['RentForTransactions']); - $ParseRow['ButtonItems'][$KeyID] = $Data['itemid'][$KeyID]; - } - } - - foreach($Data['price'] as $KeyID => $PriceVal) - { - $BuyParse = array(); - $BuyParse['ButtonText'] = vsprintf($ParseRow['ButtonText'], $ParseRow['ButtonVars'][$KeyID]); - $BuyParse['Cost'] = $_Lang['Cost']; - $BuyParse['CostVal'] = prettyNumber($PriceVal); - $BuyParse['CostUnits'] = $_Lang['DEUnits']; - $BuyParse['ShopItemID'] = $ParseRow['ButtonItems'][$KeyID]; - $ParseRow['BuyButtons'][] = parsetemplate($BuyTPL, $BuyParse); - } - $ParseRow['BuyButtons'] = implode('
    ', $ParseRow['BuyButtons']); - - $_Lang['ParsedOfficers'] .= parsetemplate($RowTPL, $ParseRow); - } - - $_Lang['DarkEnergy_Counter'] = $_User['darkEnergy']; - if($_User['darkEnergy'] >= 15) - { - $_Lang['DarkEnergy_Color'] = 'lime'; - } - else if($_User['darkEnergy'] > 0) - { - $_Lang['DarkEnergy_Color'] = 'orange'; - } - else - { - $_Lang['DarkEnergy_Color'] = 'red'; - } - - $page = parsetemplate(gettemplate('officers'), $_Lang); - display($page, $_Lang['officers'], false); - -?> \ No newline at end of file + $Data) +{ + foreach($Data['bene'] as &$Value) + { + $Value = '• '.$Value; + } + + $ParseRow = array(); + $ParseRow['Name'] = $Data['name']; + $ParseRow['skinpath'] = $_SkinPath; + $ParseRow['img'] = $Data['img']; + $ParseRow['Info'] = $Data['desc']; + $ParseRow['Benefits'] = $_Lang['Benefits']; + $ParseRow['ParseBenefits'] = implode('
    ', $Data['bene']); + if($Data['type'] == 1) + { + $ThisTimeKey = $Officer.'_time'; + + $ParseRow['OfficerState'] = $_Lang['RentState']; + if($_User[$ThisTimeKey] > $Now) + { + $ParseRow['ThisState'] = $_Lang['RentTill']; + $ParseRow['OfficerVal'] = prettyDate('d m Y H:i:s', $_User[$ThisTimeKey], 1); + $ParseRow['OfficerValColor'] = 'lime'; + $ParseRow['ButtonText'] = $_Lang['RenewRent']; + } + else if($_User[$ThisTimeKey] > 0) + { + $ParseRow['ThisState'] = $_Lang['RentEnded']; + $ParseRow['OfficerVal'] = prettyDate('d m Y H:i:s', $_User[$ThisTimeKey], 1); + $ParseRow['OfficerValColor'] = 'orange'; + $ParseRow['ButtonText'] = $_Lang['RentAgain']; + } + else + { + $ParseRow['ThisState'] = $_Lang['NeverRented']; + $ParseRow['OfficerStateColor'] = 'red'; + $ParseRow['ButtonText'] = $_Lang['FirstRent']; + } + + foreach($Data['price'] as $KeyID => $PriceVal) + { + $ThisTimeVar = '_days'; + if($Data['time'][$KeyID] == 1) + { + $ThisTimeVar = '_day'; + } + $ParseRow['ButtonVars'][$KeyID] = array($Data['time'][$KeyID], $_Lang[$ThisTimeVar]); + $ParseRow['ButtonItems'][$KeyID] = $Data['itemid'][$KeyID]; + } + } + else if($Data['type'] == 2) + { + $ParseRow['OfficerState'] = $_Lang['RentState']; + $ParseRow['ThisState'] = $_Lang[$Data['thisState']]; + + if($_User[$Data['field']] == 0) + { + $ParseRow['ButtonText'] = $_Lang['FirstRent']; + $ParseRow['OfficerValColor'] = 'red'; + } + else + { + $ParseRow['ButtonText'] = $_Lang['RentPlus']; + $ParseRow['OfficerValColor'] = 'lime'; + } + $ParseRow['OfficerVal'] = ($_User[$Data['field']] + 0); + + foreach($Data['price'] as $KeyID => $PriceVal) + { + $ParseRow['ButtonVars'][$KeyID] = array($Data['count'][$KeyID], $_Lang['RentForTransactions']); + $ParseRow['ButtonItems'][$KeyID] = $Data['itemid'][$KeyID]; + } + } + + foreach($Data['price'] as $KeyID => $PriceVal) + { + $BuyParse = array(); + $BuyParse['ButtonText'] = vsprintf($ParseRow['ButtonText'], $ParseRow['ButtonVars'][$KeyID]); + $BuyParse['Cost'] = $_Lang['Cost']; + $BuyParse['CostVal'] = prettyNumber($PriceVal); + $BuyParse['CostUnits'] = $_Lang['DEUnits']; + $BuyParse['ShopItemID'] = $ParseRow['ButtonItems'][$KeyID]; + $ParseRow['BuyButtons'][] = parsetemplate($BuyTPL, $BuyParse); + } + $ParseRow['BuyButtons'] = implode('
    ', $ParseRow['BuyButtons']); + + $_Lang['ParsedOfficers'] .= parsetemplate($RowTPL, $ParseRow); +} + +$_Lang['DarkEnergy_Counter'] = $_User['darkEnergy']; +if($_User['darkEnergy'] >= 15) +{ + $_Lang['DarkEnergy_Color'] = 'lime'; +} +else if($_User['darkEnergy'] > 0) +{ + $_Lang['DarkEnergy_Color'] = 'orange'; +} +else +{ + $_Lang['DarkEnergy_Color'] = 'red'; +} + +$page = parsetemplate(gettemplate('officers'), $_Lang); +display($page, $_Lang['officers'], false); + +?> diff --git a/other/index.php b/other/index.php index ee150fd01..bc99142d1 100644 --- a/other/index.php +++ b/other/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/overview.php b/overview.php index 4bfb20c25..9a884cd66 100644 --- a/overview.php +++ b/overview.php @@ -1,1151 +1,1151 @@ - 0) - { - // Update Referrer Tasks - if(empty($GlobalParsedTasks[$_User['referred']]['tasks_done_parsed'])) - { - $GetUserTasksDone = doquery("SELECT `id`, `tasks_done` FROM {{table}} WHERE `id` = {$_User['referred']} LIMIT 1;", 'users', true); - if($GetUserTasksDone['id'] == $_User['referred']) - { - unset($GetUserTasksDone['id']); - Tasks_CheckUservar($GetUserTasksDone); - $GlobalParsedTasks[$_User['referred']] = $GetUserTasksDone; - $ThisTaskUser = $GlobalParsedTasks[$_User['referred']]; - $ThisTaskUser['id'] = $_User['referred']; - } - } - else - { - $ThisTaskUser = $GlobalParsedTasks[$_User['referred']]; - $ThisTaskUser['id'] = $_User['referred']; - } - - if(!empty($ThisTaskUser)) - { - Tasks_TriggerTask($ThisTaskUser, 'NEWUSER_REGISTER', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use (&$ThisTaskUser) - { - $Return = Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); - $ThisTaskUser['TaskData'][] = array - ( - 'TaskID' => $TaskID, - 'TaskStatus' => $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID], - 'TaskLimit' => $JobArray[$JobArray['statusField']] - ); - return $Return; - } - )); - } - - // Check IP Intersection - $_Included_AlertSystemUtilities = true; - include($_EnginePath.'includes/functions/AlertSystemUtilities.php'); - $CheckIntersection = AlertUtils_IPIntersect($_User['id'], $_User['referred'], array - ( - 'LastTimeDiff' => (TIME_DAY * 60), - 'ThisTimeDiff' => (TIME_DAY * 60), - 'ThisTimeStamp' => ($Now - SERVER_MAINOPEN_TSTAMP) - )); - if($CheckIntersection !== false) - { - $FiltersData = array(); - $FiltersData['place'] = 4; - $FiltersData['alertsender'] = 4; - $FiltersData['users'] = array($_User['id'], $_User['referred']); - $FiltersData['ips'] = $CheckIntersection['Intersect']; - $FiltersData['newuser'] = $_User['id']; - $FiltersData['referrer'] = $_User['referred']; - foreach($CheckIntersection['Intersect'] as $IP) - { - $FiltersData['logcount'][$IP][$_User['id']] = $CheckIntersection['IPLogData'][$_User['id']][$IP]['Count']; - $FiltersData['logcount'][$IP][$_User['referred']] = $CheckIntersection['IPLogData'][$_User['referred']][$IP]['Count']; - } - - $FilterResult = AlertUtils_CheckFilters($FiltersData, array('Save' => true)); - if($FilterResult['SendAlert']) - { - $_Alert['Data']['ReferrerID'] = $_User['referred']; - foreach($CheckIntersection['Intersect'] as $ThisIPID) - { - $_Alert['Data']['Intersect'][] = array - ( - 'IPID' => $ThisIPID, - 'NewUser' => $CheckIntersection['IPLogData'][$_User['id']][$ThisIPID], - 'OldUser' => $CheckIntersection['IPLogData'][$_User['referred']][$ThisIPID] - ); - } - if(!empty($ThisTaskUser['TaskData'])) - { - $_Alert['Data']['Tasks'] = $ThisTaskUser['TaskData']; - } - - $Query_AlertOtherUsers .= "SELECT DISTINCT `User_ID` FROM {{table}} WHERE "; - $Query_AlertOtherUsers .= "`User_ID` NOT IN ({$_User['id']}, {$_User['referred']}) AND "; - $Query_AlertOtherUsers .= "`IP_ID` IN (".implode(', ', $CheckIntersection['Intersect']).") AND "; - $Query_AlertOtherUsers .= "`Count` > `FailCount`;"; - $Result_AlertOtherUsers = doquery($Query_AlertOtherUsers, 'user_enterlog'); - if(mysql_num_rows($Result_AlertOtherUsers) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_AlertOtherUsers)) - { - $_Alert['Data']['OtherUsers'][] = $FetchData['User_ID']; - } - } - - Alerts_Add(4, $Now, 1, 2, 8, $_User['id'], $_Alert['Data']); - } - } - } - - // Check, if this IP is Proxy - $IPHash = md5($_SERVER['REMOTE_ADDR']); - $Query_CheckProxy = "SELECT `ID`, `isProxy` FROM {{table}} WHERE `ValueHash` = '{$IPHash}' LIMIT 1;"; - $Result_CheckProxy = doquery($Query_CheckProxy, 'used_ip_and_ua', true); - if($Result_CheckProxy['ID'] > 0 AND $Result_CheckProxy['isProxy'] == 1) - { - if(!isset($_Included_AlertSystemUtilities)) - { - include($_EnginePath.'includes/functions/AlertSystemUtilities.php'); - $_Included_AlertSystemUtilities = true; - } - $FiltersData = array(); - $FiltersData['place'] = 4; - $FiltersData['alertsender'] = 5; - $FiltersData['users'] = array($_User['id']); - $FiltersData['ips'] = array($Result_CheckProxy['ID']); - - $FilterResult = AlertUtils_CheckFilters($FiltersData, array('DontLoad' => true, 'DontLoad_OnlyIfCacheEmpty' => true)); - if($FilterResult['SendAlert']) - { - $_Alert['Data']['IPID'] = $Result_CheckProxy['ID']; - if($_SERVER['REMOTE_ADDR'] == $_User['ip_at_reg']) - { - $_Alert['Data']['RegIP'] = true; - } - - Alerts_Add(5, $Now, 1, 3, 8, $_User['id'], $_Alert['Data']); - } - } - - // Give Free ProAccount for 7 days - //doquery("INSERT INTO {{table}} VALUES (NULL, {$_User['id']}, UNIX_TIMESTAMP(), 0, 0, 11, 0);", 'premium_free'); - - // Create DevLog Dump - define('IN_USERFIRSTLOGIN', true); - $InnerUIDSet = $_User['id']; - $SkipDumpMsg = true; - include($_EnginePath.'admin/scripts/script.createUserDevDump.php'); - - display(parsetemplate($TPL, $_Lang), $_Lang['FirstLogin_Title'], false); - } - - $mode = (isset($_GET['mode']) ? $_GET['mode'] : ''); - - includeLang('resources'); - includeLang('overview'); - - switch($mode) - { - case 'rename': - // --- Rename Planet Page --- - $parse = $_Lang; - - $parse['Rename_Ins_MsgHide'] = 'style="display: none;"'; - $parse['Rename_Ins_MsgTxt'] = false; - - if($_Planet['planet_type'] == 1) - { - $parse['Rename_CurrentName'] = sprintf($parse['Rename_CurrentName'], $parse['Rename_Planet']); - } - else - { - $parse['Rename_CurrentName'] = sprintf($parse['Rename_CurrentName'], $parse['Rename_Moon']); - } - - if(isset($_POST['action']) && $_POST['action'] == 'do') - { - // User wants to change planets name - $NewName = trim($_POST['set_newname']); - if(!empty($NewName)) - { - // Update only, when name is not the same as old - if($_Planet['name'] != $NewName) - { - // Check if planet new name is correct - $NewNameLength = strlen($NewName); - if($NewNameLength < 3) - { - $parse['Rename_Ins_MsgColor'] = 'red'; - $parse['Rename_Ins_MsgTxt'] = $_Lang['RenamePlanet_TooShort']; - } - elseif($NewNameLength > 20) - { - $parse['Rename_Ins_MsgColor'] = 'red'; - $parse['Rename_Ins_MsgTxt'] = $_Lang['RenamePlanet_TooLong']; - } - elseif(!preg_match(REGEXP_PLANETNAME_ABSOLUTE, $NewName)) - { - $parse['Rename_Ins_MsgColor'] = 'red'; - $parse['Rename_Ins_MsgTxt'] = $_Lang['RenamePlanet_BadSigns']; - } - if($parse['Rename_Ins_MsgTxt'] === false) - { - //Save the new name in Script Memory - $_Planet['name'] = $NewName; - //Now save it in DataBase - doquery("UPDATE {{table}} SET `name` = '{$NewName}' WHERE `id` = {$_User['current_planet']} LIMIT 1;", 'planets'); - $parse['Rename_Ins_MsgColor'] = 'lime'; - $parse['Rename_Ins_MsgTxt'] = $_Lang['RenamePlanet_NameSaved']; - } - } - else - { - $parse['Rename_Ins_MsgColor'] = 'orange'; - $parse['Rename_Ins_MsgTxt'] = $_Lang['RenamePlanet_SameName']; - } - } - else - { - $parse['Rename_Ins_MsgColor'] = 'red'; - $parse['Rename_Ins_MsgTxt'] = $_Lang['RenamePlanet_0Lenght']; - } - } - - if($parse['Rename_Ins_MsgTxt'] !== false) - { - $parse['Rename_Ins_MsgHide'] = ''; - } - - $parse['Rename_Ins_CurrentName'] = "{$_Planet['name']} [{$_Planet['galaxy']}:{$_Planet['system']}:{$_Planet['planet']}]"; - - $page = parsetemplate(gettemplate('overview_rename'), $parse); - display($page, $_Lang['Rename_TitleMain']); - break; - case 'abandon': - // --- Abandon Colony --- - if(isOnVacation()) - { - message($_Lang['Vacation_WarnMsg'], $_Lang['Vacation']); - } - - $parse = $_Lang; - $parse['Abandon_Ins_MsgHide'] = 'style="display: none;"'; - $parse['Abandon_Ins_MsgTxt'] = false; - - if(isset($_POST['action']) && $_POST['action'] == 'do') - { - $parse['Abandon_Ins_MsgColor'] = 'red'; - // Check if given password is good - if(!empty($_POST['give_passwd'])) - { - if(md5($_POST['give_passwd']) == $_User['password']) - { - if($_User['id_planet'] != $_User['current_planet']) - { - if($_Planet['planet_type'] == 1 OR $_Planet['planet_type'] == 3) - { - include($_EnginePath.'includes/functions/DeleteSelectedPlanetorMoon.php'); - $DeleteResult = DeleteSelectedPlanetorMoon(); - if($DeleteResult['result'] === true) - { - // Prevent abandoning Planet to make mission faster - Tasks_TriggerTask($_User, 'COLONIZE_PLANET', array - ( - 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($_User) - { - global $UserTasksUpdate; - if(!empty($UserTasksUpdate[$_User['id']]['status'][$ThisCat][$TaskID][$JobID])) - { - $_User['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$_User['id']]['status'][$ThisCat][$TaskID][$JobID]; - } - if($_User['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] <= 0) - { - return true; - } - $_User['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] -= 1; - $UserTasksUpdate[$_User['id']]['status'][$ThisCat][$TaskID][$JobID] = $_User['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; - return true; - } - )); - - // User Development Log - $UserDev_Log[] = array('PlanetID' => $_Planet['id'], 'Date' => $Now, 'Place' => 25, 'Code' => '0', 'ElementID' => '0'); - if(count($DeleteResult['ids']) > 1) - { - $UserDev_Log[] = array('PlanetID' => $DeleteResult['ids'][1], 'Date' => $Now, 'Place' => 25, 'Code' => '0', 'ElementID' => '0'); - } - - header('Location: overview.php?showmsg=abandon'); - safeDie(); - } - else - { - if($DeleteResult['reason'] == 'tech') - { - $parse['Abandon_Ins_MsgTxt'] = $_Lang['Abandon_TechHere']; - } - elseif($DeleteResult['reason'] == 'sql') - { - $parse['Abandon_Ins_MsgTxt'] = $_Lang['Abandon_SQLError']; - } - elseif($DeleteResult['reason'] == 'fleet_current') - { - $parse['Abandon_Ins_MsgTxt'] = $_Lang['Abandon_FlyingFleetsHere']; - } - elseif($DeleteResult['reason'] == 'fleet_moon') - { - $parse['Abandon_Ins_MsgTxt'] = $_Lang['Abandon_FlyingFleetsMoon']; - } - } - } - else - { - $parse['Abandon_Ins_MsgTxt'] = $_Lang['Abandon_BadPlanetrowData']; - } - } - else - { - $parse['Abandon_Ins_MsgTxt'] = $_Lang['Abandon_CantAbandonMother']; - } - } - else - { - $parse['Abandon_Ins_MsgTxt'] = $_Lang['Abandon_BadPassword']; - } - } - else - { - $parse['Abandon_Ins_MsgTxt'] = $_Lang['Abandon_NoPassword']; - } - } - - if($parse['Abandon_Ins_MsgTxt'] !== false) - { - $parse['Abandon_Ins_MsgHide'] = ''; - } - $parse['Abandon_Desc'] = sprintf($parse['Abandon_Desc'], ($_Planet['planet_type'] == 1 ? $_Lang['Abandon_Planet'] : $_Lang['Abandon_Moon']), $_Planet['name'], "[{$_Planet['galaxy']}:{$_Planet['system']}:{$_Planet['planet']}]"); - $parse['Abandon_Ins_Pass'] = $_User['password']; - - $page = parsetemplate(gettemplate('overview_deleteplanet'), $parse); - display($page, $_Lang['Abandon_TitleMain']); - break; - default: - $parse = &$_Lang; - include($_EnginePath.'includes/functions/InsertJavaScriptChronoApplet.php'); - InsertJavaScriptChronoApplet(false, false, false); - $InsertJSChronoApplet_GlobalIncluded = true; - - // --- Vacation Mode Box - if(isOnVacation()) - { - $parse['VacationModeBox'] = ''.$_Lang['VacationModeBox_Text'].' '; - } - - // --- Activation Box - if(!empty($_User['activation_code'])) - { - $parse['ActivationInfoBox'] = ''.$_Lang['ActivationInfo_Text'].' '; - } - - // --- New User Protection Box - if($_User['NoobProtection_EndTime'] > $Now) - { - if(isset($_GET['cancelprotection']) && $_GET['cancelprotection'] == '1') - { - $_User['NoobProtection_EndTime'] = $Now; - $Query_UpdateUser = "UPDATE {{table}} SET `NoobProtection_EndTime` = {$Now} WHERE `id` = {$_User['id']} LIMIT 1;"; - doquery($Query_UpdateUser, 'users'); - - $parse['NewUserBox'] = ''.$_Lang['NewUserProtection_Canceled'].' '; - } - else - { - $ProtectTimeLeft = $_User['NoobProtection_EndTime'] - $Now; - $parse['NewUserBox'] = InsertJavaScriptChronoApplet('newprotect', '', $ProtectTimeLeft).''.sprintf($_Lang['NewUserProtection_Text'], pretty_time($ProtectTimeLeft, true, 'dhms')).' '; - } - } - - // --- Admin Info Box ------------------------------------------------------------------------------------ - if(CheckAuth('supportadmin')) - { - $Query_AdminBoxCheck[] = "SELECT COUNT(*) AS `Count`, 1 AS `Type` FROM `{{prefix}}reports` WHERE `status` = 0"; - $Query_AdminBoxCheck[] = "SELECT COUNT(*) AS `Count`, 2 AS `Type` FROM `{{prefix}}declarations` WHERE `status` = 0"; - $Query_AdminBoxCheck[] = "SELECT COUNT(*) AS `Count`, 3 AS `Type` FROM `{{prefix}}system_alerts` WHERE `status` = 0"; - $Query_AdminBoxCheck = implode(' UNION ', $Query_AdminBoxCheck); - $Result_AdminBoxCheck = doquery($Query_AdminBoxCheck, ''); - - $AdminBoxTotalCount = 0; - while($AdminBoxData = mysql_fetch_assoc($Result_AdminBoxCheck)) - { - $AdminBox[$AdminBoxData['Type']] = $AdminBoxData['Count']; - $AdminBoxTotalCount += $AdminBoxData['Count']; - } - if($AdminBoxTotalCount > 0) - { - $AdminAlerts = sprintf($_Lang['AdminAlertsBox'], $AdminBox[1], $AdminBox[2], $AdminBox[3]); - $parse['AdminInfoBox'] = ''.$AdminAlerts.' '; - } - } - - // --- MailChange Box ------------------------------------------------------------------------------------ - $parse['MailChange_Hide'] = 'display: none;'; - if($_User['email'] != $_User['email_2']) - { - $MailChange = doquery("SELECT * FROM {{table}} WHERE `UserID` = {$_User['id']} AND `ConfirmType` = 0 LIMIT 1;", 'mailchange', true); - if($MailChange['ID'] > 0) - { - $ChangeTime = $MailChange['Date'] + (TIME_DAY * 7); - - $parse['MailChange_Hide'] = ''; - $parse['MailChange_Box'] = sprintf($_Lang['MailChange_Text']); - if($MailChange['ConfirmHashNew'] == '') - { - if($ChangeTime < $Now) - { - $parse['MailChange_Box'] .= "

    "; - } - else - { - $parse['MailChange_Box'] .= "

    ".sprintf($_Lang['MailChange_Inf2'], date('d.m.Y H:i:s', $ChangeTime)); - } - } - else - { - $parse['MailChange_Box'] .= "

    {$_Lang['MailChange_Inf1']}"; - } - } - } - - // Fleet Blockade Info (here, only for Global Block) - $GetSFBData = doquery("SELECT `ID`, `EndTime`, `BlockMissions`, `DontBlockIfIdle`, `Reason` FROM {{table}} WHERE `Type` = 1 AND `StartTime` <= UNIX_TIMESTAMP() AND (`EndTime` > UNIX_TIMESTAMP() OR `PostEndTime` > UNIX_TIMESTAMP()) ORDER BY `EndTime` DESC LIMIT 1;", 'smart_fleet_blockade', true); - if($GetSFBData['ID'] > 0) - { - // Fleet Blockade is Active - include($_EnginePath.'includes/functions/CreateSFBInfobox.php'); - $parse['P_SFBInfobox'] = CreateSFBInfobox($GetSFBData, array('standAlone' => true, 'Width' => 750, 'MarginBottom' => 10)); - } - - // --- Free Premium Items Info Box ----------------------------------------------------------------------- - $GetFreeItems = doquery("SELECT COUNT(`ID`) as `Count` FROM {{table}} WHERE `UserID` = {$_User['id']} AND `Used` = false;", 'premium_free', true); - if($GetFreeItems['Count'] > 0) - { - $parse['FreePremiumItemsBox'] = ''.sprintf($_Lang['FreePremItem_Text'], $GetFreeItems['Count']).''; - } - - // --- System Messages Box ------------------------------------------------------------------------------- - if(!empty($_GET['showmsg'])) - { - $SysMsgLoop = 0; - if($_GET['showmsg'] == 'abandon') - { - $ShowSystemMsg[$SysMsgLoop]['txt'] = $_Lang['Abandon_ColonyAbandoned']; - $ShowSystemMsg[$SysMsgLoop]['col'] = 'lime'; - $SysMsgLoop += 1; - } - } - - if(!empty($ShowSystemMsg)) - { - $parse['SystemMsgBox'] = ''; - foreach($ShowSystemMsg as $SystemMsg) - { - $parse['SystemMsgBox'] .= ''.$SystemMsg['txt'].''; - } - } - - // --- New Messages Information Box ---------------------------------------------------------------------- - $NewMsg = doquery("SELECT COUNT(`id`) as `count` FROM {{table}} WHERE `deleted` = false AND `read` = false AND `id_owner` = {$_User['id']};", 'messages', true); - if($NewMsg['count'] > 0) - { - if($NewMsg['count'] == 1) - { - $MsgBox_NewSurfix = $_Lang['MsgBox_New_1']; - $MsgBox_UnreadenSurfix= $_Lang['MsgBox_Unreaden_1']; - $MsgBox_Msg_s = $_Lang['MsgBox_Msg']; - } - elseif($NewMsg['count'] > 1 AND $NewMsg['count'] < 5) - { - $MsgBox_NewSurfix = $_Lang['MsgBox_New_2_4']; - $MsgBox_UnreadenSurfix= $_Lang['MsgBox_Unreaden_2_4']; - $MsgBox_Msg_s = $_Lang['MsgBox_Msgs']; - } - else - { - $MsgBox_NewSurfix = $_Lang['MsgBox_New_5']; - $MsgBox_UnreadenSurfix= $_Lang['MsgBox_Unreaden_5']; - $MsgBox_Msg_s = $_Lang['MsgBox_Msgs']; - } - $MsgBoxText = $_Lang['MsgBox_YouHave'].' '.prettyNumber($NewMsg['count']).' '.$_Lang['MsgBox_New'].$MsgBox_NewSurfix.', '.$_Lang['MsgBox_Unreaden'].$MsgBox_UnreadenSurfix.' '.$MsgBox_Msg_s.'!'; - - $NewMsgBox = ''.$MsgBoxText.''; - $parse['NewMsgBox'] = $NewMsgBox; - } - - // --- New Polls Information Box ------------------------------------------------------------------------- - $Polls = doquery("SELECT {{table}}.`id`, `votes`.`id` AS `vote_id` FROM {{table}} LEFT JOIN {{prefix}}poll_votes AS `votes` ON `votes`.`poll_id` = {{table}}.id AND `votes`.`user_id` = {$_User['id']} WHERE {{table}}.`open` = 1 ORDER BY {{table}}.`time` DESC;", 'polls'); - if(mysql_num_rows($Polls) > 0) - { - $AvailablePolls = 0; - while($PollData = mysql_fetch_assoc($Polls)) - { - if($PollData['vote_id'] <= 0) - { - $AvailablePolls += 1; - } - } - if($AvailablePolls > 0) - { - $parse['NewPollsBox'] = ''.vsprintf($_Lang['PollBox_You_can_vote_in_new_polls'], ($AvailablePolls > 1) ? $_Lang['PollBox_More'] : $_Lang['PollBox_One']).''; - } - } - - // --- Get users activity informations ----------------------------------------------------------- - $TodaysStartTimeStamp = mktime(0, 0, 0); - $OnlineUsers = doquery("SELECT IF(`onlinetime` >= (UNIX_TIMESTAMP() - (".TIME_ONLINE.")), 1, 0) AS `current_online` FROM {{table}} WHERE `onlinetime` >= {$TodaysStartTimeStamp};", 'users'); - $TodayActive = mysql_num_rows($OnlineUsers); - $CurrentOnline = 0; - if($TodayActive > 0) - { - while($ActiveData = mysql_fetch_assoc($OnlineUsers)) - { - if($ActiveData['current_online'] == 1) - { - $CurrentOnline += 1; - } - } - } - $parse['CurrentOnline'] = prettyNumber($CurrentOnline); - $parse['TodayOnline'] = prettyNumber($TodayActive); - $parse['TotalPlayerCount'] = prettyNumber($_GameConfig['users_amount']); - $parse['ServerRecord'] = prettyNumber($_GameConfig['rekord']); - - // --- Get last Stats and Records UpdateTime ----------------------------------------------------- - $parse['LastStatsRecount'] = date('d.m.Y H:i:s', $_GameConfig['last_update']); - - // --- MoraleSystem Box --- - if(MORALE_ENABLED) - { - Morale_ReCalculate($_User); - $UserMoraleLevel = $_User['morale_level']; - - $parse['Insert_Morale_Level'] = $UserMoraleLevel; - if($UserMoraleLevel > 0) - { - $parse['Insert_Morale_Color'] = 'lime'; - } - else if($UserMoraleLevel < 0) - { - if($UserMoraleLevel <= -50) - { - $parse['Insert_Morale_Color'] = 'red'; - } - else - { - $parse['Insert_Morale_Color'] = 'orange'; - } - } - - if($UserMoraleLevel == 0) - { - $parse['Insert_Morale_Status'] = $_Lang['Box_Morale_NoChanges']; - } - else - { - if($UserMoraleLevel > 0) - { - $Temp_MoraleStatus = 'Pos'; - } - else - { - $Temp_MoraleStatus = 'Neg'; - } - if($_User['morale_droptime'] > $Now) - { - GlobalTemplate_AppendToAfterBody(InsertJavaScriptChronoApplet('morale', '', $_User['morale_droptime'], true)); - $parse['Insert_Morale_Status'] = sprintf($_Lang['Box_Morale_DropStartIn_'.$Temp_MoraleStatus], pretty_time($_User['morale_droptime'] - $Now, true, 'D')); - } - else - { - if($UserMoraleLevel > 0) - { - $Temp_MoraleDropInterval = MORALE_DROPINTERVAL_POSITIVE; - } - else - { - $Temp_MoraleDropInterval = MORALE_DROPINTERVAL_NEGATIVE; - } - if($_User['morale_lastupdate'] == 0) - { - $Temp_MoraleNextDrop = $_User['morale_droptime'] + $Temp_MoraleDropInterval; - } - else - { - $Temp_MoraleNextDrop = $_User['morale_lastupdate'] + $Temp_MoraleDropInterval; - } - GlobalTemplate_AppendToAfterBody(InsertJavaScriptChronoApplet('morale', '', $Temp_MoraleNextDrop, true)); - $parse['Insert_Morale_Status'] = sprintf($_Lang['Box_Morale_Dropping_'.$Temp_MoraleStatus], pretty_time($Temp_MoraleNextDrop - $Now, true, 'D')); - } - } - $_Lang['Box_Morale_Points'] = sprintf($_Lang['Box_Morale_Points'], prettyNumber($_User['morale_points'])); - - $parse['Insert_MoraleBox'] = parsetemplate(gettemplate('overview_body_morale'), $parse); - } - - // --- Get Register Date - - $RegisterDays = floor(($Now - $_User['register_time']) / (24*60*60)); - if($RegisterDays == 1) - { - $parse['RegisterDaysTxt'] = $parse['_youPlaySince_1day']; - } - else - { - $parse['RegisterDaysTxt'] = $parse['_youPlaySince_2days']; - } - $parse['RegisterDays'] = prettyNumber($RegisterDays); - $parse['RegisterDate'] = date('d.m.Y', $_User['register_time']); - - // --- ProAccount Box --- - $parse['ProAccountInfoText'] = ($_User['pro_time'] > $Now) ? $_Lang['ProAccTill'].''.date("d.m.Y\<\b\\r\/\>H:i:s", $_User['pro_time']).'' : (($_User['pro_time'] == 0) ? $_Lang['NoProAccEver'] : $_Lang['NoProAccSince'].''.date("d.m.Y\<\b\\r\/\>H:i:s", $_User['pro_time']).''); - $parse['ProAccLink'] = ($_User['pro_time'] > $Now) ? $_Lang['ProAccBuyMore'] : (($_User['pro_time'] == 0) ? $_Lang['ProAccBuyFirst'] : $_Lang['ProAccBuyNext']); - - // --- Get Reffered Count -- - $Referred = doquery("SELECT COUNT(`id`) as `count` FROM {{table}} WHERE `referrer_id` = {$_User['id']};", 'referring_table', true); - $parse['RefferedCounter'] = prettyNumber((($Referred['count'] > 0) ? $Referred['count'] : '0')); - - // --- Get UserStats --- - $StatRecord = doquery("SELECT * FROM {{table}} WHERE `stat_type` = '1' AND `id_owner` = {$_User['id']} LIMIT 1;", 'statpoints', true); - $parse['user_points'] = prettyNumber($StatRecord['build_points']); - $parse['user_fleet'] = prettyNumber($StatRecord['fleet_points']); - $parse['user_defs'] = prettyNumber($StatRecord['defs_points']); - $parse['player_points_tech'] = prettyNumber($StatRecord['tech_points']); - $parse['total_points'] = prettyNumber($StatRecord['total_points']); - - // Total Rank changes - if($StatRecord['total_rank'] > 0) - { - $ile = $StatRecord['total_old_rank'] - $StatRecord['total_rank']; - if($ile > 0) - { - $ile = "(+{$ile})"; - } - elseif($ile < 0) - { - $ile = "({$ile})"; - } - else - { - $ile = '(*)'; - } - $parse['user_total_rank'] = ''.$StatRecord['total_rank'].' '.$ile; - } - else - { - $parse['user_total_rank'] = 0; - $StatRecord['total_rank'] = '0'; - } - $parse['set_user_total_rank'] = $StatRecord['total_rank']; - - // Build Rank changes - if(isset($StatRecord['build_rank']) && $StatRecord['build_rank'] > 0) - { - $ile = $StatRecord['build_old_rank'] - $StatRecord['build_rank']; - if($ile > 0) - { - $ile = "(+{$ile})"; - } - elseif($ile < 0) - { - $ile = "({$ile})"; - } - else - { - $ile = '(*)'; - } - $parse['user_br'] = ''.$StatRecord['build_rank'].' '.$ile; - } - else - { - $parse['user_br'] = 0; - $StatRecord['build_rank'] = '0'; - } - $parse['set_user_br'] = $StatRecord['build_rank']; - - // Fleet rank changes - if(isset($StatRecord['fleet_rank']) && $StatRecord['fleet_rank'] > 0) - { - $ile = $StatRecord['fleet_old_rank'] - $StatRecord['fleet_rank']; - if($ile > 0) - { - $ile = "(+{$ile})"; - } - else if($ile < 0) - { - $ile = "({$ile})"; - } - else - { - $ile = '(*)'; - } - $parse['user_fr'] = ''.$StatRecord['fleet_rank'].' '.$ile; - } - else - { - $parse['user_fr'] = 0; - $StatRecord['fleet_rank'] = '0'; - } - $parse['set_user_fr'] = $StatRecord['fleet_rank']; - - // Defense rank changes - if(isset($StatRecord['defs_rank']) && $StatRecord['defs_rank'] > 0) - { - $ile = $StatRecord['defs_old_rank'] - $StatRecord['defs_rank']; - if($ile > 0) - { - $ile = "(+{$ile})"; - } - else if($ile < 0) - { - $ile = "({$ile})"; - } - else - { - $ile = '(*)'; - } - $parse['user_dr'] = ''.$StatRecord['defs_rank'].' '.$ile; - } - else - { - $parse['user_dr'] = 0; - $StatRecord['defs_rank'] = '0'; - } - $parse['set_user_dr'] = $StatRecord['defs_rank']; - - // Research rank changes - if(isset($StatRecord['tech_rank']) && $StatRecord['tech_rank'] > 0) - { - $ile = $StatRecord['tech_old_rank'] - $StatRecord['tech_rank']; - if($ile > 0) - { - $ile = "(+{$ile})"; - } - else if($ile < 0) - { - $ile = "({$ile})"; - } - else - { - $ile = '(*)'; - } - $parse['user_tr'] = ''.$StatRecord['tech_rank'].' '.$ile; - } - else - { - $parse['user_tr'] = 0; - $StatRecord['tech_rank'] = '0'; - } - $parse['set_user_tr'] = $StatRecord['tech_rank']; - - // Get User Achievements - $GetStats_Fields = '`ustat_raids_won`, `ustat_raids_draw`, `ustat_raids_lost`, `ustat_raids_acs_won`, `ustat_raids_inAlly`, `ustat_raids_missileAttack`'; - $GetStats = doquery("SELECT {$GetStats_Fields} FROM {{table}} WHERE `A_UserID` = {$_User['id']} LIMIT 1;", 'achievements_stats', true); - $parse['raids'] = prettyNumber($GetStats['ustat_raids_won'] + $GetStats['ustat_raids_draw'] + $GetStats['ustat_raids_lost'] + $GetStats['ustat_raids_inAlly']); - $parse['raidswin'] = prettyNumber($GetStats['ustat_raids_won']); - $parse['raidsdraw'] = prettyNumber($GetStats['ustat_raids_draw']); - $parse['raidsloose'] = prettyNumber($GetStats['ustat_raids_lost']); - $parse['raidacswin'] = prettyNumber($GetStats['ustat_raids_acs_won']); - $parse['raidsinally'] = prettyNumber($GetStats['ustat_raids_inAlly']); - $parse['raidsmissileattacks'] = prettyNumber($GetStats['ustat_raids_missileAttack']); - - // --- Planet Data --------- - if($_Planet['planet_type'] == 1) - { - $parse['ShowWhatsOnOrbit'] = ''.$_Lang['_emptyOrbit'].''; - if($_GalaxyRow['id_moon'] > 0) - { - $MoonRow = doquery("SELECT `id`, `name` FROM {{table}} WHERE `id` = {$_GalaxyRow['id_moon']} LIMIT 1;", 'planets', true); - if($MoonRow['id'] > 0) - { - $parse['ShowWhatsOnOrbit'] = "{$MoonRow['name']}"; - } - } - } - else - { - $PlanetData = doquery("SELECT `id`, `name` FROM {{table}} WHERE `id` = {$_GalaxyRow['id_planet']} LIMIT 1;", 'planets', true); - $parse['ShowWhatsOnOrbit'] = "{$PlanetData['name']}"; - $DontShowPlanet[] = $PlanetData['id']; - } - if(empty($parse['onOrbit_img'])) - { - $parse['hide_orbit_view'] = 'style="display: none;"'; - } - - $MaxPlanetFields = CalculateMaxPlanetFields($_Planet); - $parse['skinpath'] = $_SkinPath; - $parse['planet_image'] = $_Planet['image']; - $parse['planet_name'] = $_Planet['name']; - $parse['planet_diameter'] = prettyNumber($_Planet['diameter']); - $parse['planet_field_current'] = $_Planet['field_current']; - $parse['planet_field_max']= $MaxPlanetFields; - $parse['planet_temp_min'] = $_Planet['temp_min']; - $parse['planet_temp_max'] = $_Planet['temp_max']; - $parse['galaxy_galaxy'] = $_Planet['galaxy']; - $parse['galaxy_planet'] = $_Planet['planet']; - $parse['galaxy_system'] = $_Planet['system']; - if($_Planet['id'] == $_User['id_planet']) - { - $parse['HideAbandonLink'] = ' style="display: none"'; - } - $parse['_planetData_type'] = ($_Planet['planet_type'] == 1) ? $parse['_planetData_planet'] : $parse['_planetData_moon']; - $parse['overvier_type'] = ($_Planet['planet_type'] == 1) ? $parse['_overview_planet'] : $parse['_overview_moon']; - $parse['planet_field_used_percent'] = round(($_Planet['field_current'] / $MaxPlanetFields) * 100); - $parse['metal_debris'] = prettyNumber($_GalaxyRow['metal']); - $parse['crystal_debris'] = prettyNumber($_GalaxyRow['crystal']); - if($_GalaxyRow['metal'] <= 0 AND $_GalaxyRow['crystal'] <= 0) - { - $parse['hide_debris'] = 'style="display: none;"'; - } - else - { - $parse['hide_nodebris'] = 'display: none;'; - } - - // --- Transporters ---------------------------- - $SmallRequired = ceil(($_Planet['metal'] + $_Planet['crystal'] + $_Planet['deuterium']) / $_Vars_Prices[202]['capacity']); - $BigRequired = ceil(($_Planet['metal'] + $_Planet['crystal'] + $_Planet['deuterium']) / $_Vars_Prices[203]['capacity']); - $MegaRequired = ceil(($_Planet['metal'] + $_Planet['crystal'] + $_Planet['deuterium']) / $_Vars_Prices[217]['capacity']); - - $SmallMissStay = -($SmallRequired - $_Planet[$_Vars_GameElements[202]]); - $BigMissStay = -($BigRequired - $_Planet[$_Vars_GameElements[203]]); - $MegaMissStay = -($MegaRequired - $_Planet[$_Vars_GameElements[217]]); - - $parse['small_cargo_count'] = prettyNumber($SmallRequired);//Small cargo ship - $parse['big_cargo_count'] = prettyNumber($BigRequired);//Big cargo ship - $parse['mega_cargo_count'] = prettyNumber($MegaRequired); //Mega cargo ship - - $parse['small_cargo_miss_stay'] = str_replace('-', '', prettyColorNumber($SmallMissStay, true)); - $parse['big_cargo_miss_stay'] = str_replace('-', '', prettyColorNumber($BigMissStay, true)); - $parse['mega_cargo_miss_stay'] = str_replace('-', '', prettyColorNumber($MegaMissStay, true)); - - $parse['small_trans'] = $_Lang['tech'][202]; - $parse['big_trans'] = $_Lang['tech'][203]; - $parse['mega_trans'] = $_Lang['tech'][217]; - - if(isPro() AND $_User['current_planet'] != $_User['settings_mainPlanetID']) - { - $GetQuickResPlanet = doquery("SELECT `name`, `galaxy`, `system`, `planet` FROM {{table}} WHERE `id` = {$_User['settings_mainPlanetID']};", 'planets', true); - $parse['QuickResSend_Button'] = sprintf($_Lang['QuickResSend_Button'], $GetQuickResPlanet['name'], $GetQuickResPlanet['galaxy'], $GetQuickResPlanet['system'], $GetQuickResPlanet['planet']); - } - else - { - $parse['Hide_QuickResButton'] = ' style="display: none;"'; - } - - // --- Flying Fleets Table --- - $Query_GetFleets = ''; - $Query_GetFleets .= "SELECT `fl`.*, `pl1`.`name` AS `start_name`, `pl2`.`name` AS `end_name`, `acs`.`fleets_id`, `usr`.`username` AS `owner_name` "; - $Query_GetFleets .= "FROM {{table}} AS `fl`"; - $Query_GetFleets .= "LEFT JOIN `{{prefix}}planets` AS `pl1` ON `pl1`.`id` = `fl`.`fleet_start_id` "; - $Query_GetFleets .= "LEFT JOIN `{{prefix}}planets` AS `pl2` ON `pl2`.`id` = `fl`.`fleet_end_id` "; - $Query_GetFleets .= "LEFT JOIN `{{prefix}}users` AS `usr` ON `usr`.`id` = `fl`.`fleet_owner` "; - $Query_GetFleets .= "LEFT JOIN `{{prefix}}acs` AS `acs` ON `acs`.`main_fleet_id` = `fl`.`fleet_id` "; - $Query_GetFleets .= "WHERE `fl`.`fleet_owner` = '{$_User['id']}' OR `fl`.`fleet_target_owner` = '{$_User['id']}';"; - $Result_GetFleets = doquery($Query_GetFleets, 'fleets'); - - $FleetIndex1 = 0; - $FleetIndex2 = 2000; - if(mysql_num_rows($Result_GetFleets) > 0) - { - include($_EnginePath.'includes/functions/BuildFleetEventTable.php'); - while($FleetRow = mysql_fetch_assoc($Result_GetFleets)) - { - if($FleetRow['fleet_owner'] == $_User['id']) - { - $FleetIndex1 += 1; - - $StartTime = $FleetRow['fleet_start_time']; - $StayTime = $FleetRow['fleet_end_stay']; - $EndTime = $FleetRow['fleet_end_time']; - // If this is ACS Fleet, change Mission (for AttackLeader Fleet) - if(!empty($FleetRow['fleets_id'])) - { - $FleetRow['fleet_mission'] = 2; - } - - if($StartTime > $Now) - { - $Fleets[$StartTime.'_'.$FleetRow['fleet_id']] = BuildFleetEventTable($FleetRow, 0, true, 'fs', $FleetIndex1); - } - - if($FleetRow['fleet_mission'] != 4 OR ($StartTime < $Now AND $FleetRow['fleet_mission'] == 4 AND $EndTime > $Now)) - { - if($FleetRow['fleet_mission'] != 4) - { - if($StayTime > $Now) - { - $Fleets[$StayTime.'_'.$FleetRow['fleet_id']] = BuildFleetEventTable($FleetRow, 1, true, 'ft', $FleetIndex1); - } - } - if($FleetRow['fleet_mission'] == 7 AND $FleetRow['fleet_mess'] == 0 AND $FleetRow['fleet_amount'] == 1) - { - // Dont show ComeBack when this is a colonization mission - } - else - { - if($EndTime > $Now) - { - $Fleets[$EndTime.'_'.$FleetRow['fleet_id']] = BuildFleetEventTable($FleetRow, 2, true, 'fe', $FleetIndex1); - } - } - } - } - else - { - if($FleetRow['fleet_mission'] != 8) - { - $FleetIndex2 += 1; - $StartTime = $FleetRow['fleet_start_time']; - $StayTime = $FleetRow['fleet_end_stay']; - if(!empty($FleetRow['fleets_id'])) - { - $FleetRow['fleet_mission'] = 2; - } - - if($StartTime > $Now) - { - $Fleets[$StartTime.'_'.$FleetRow['fleet_id']] = BuildFleetEventTable($FleetRow, 0, false, 'ofs', $FleetIndex2); - } - if($FleetRow['fleet_mission'] == 5) - { - if($StayTime > $Now) - { - $Fleets[$StayTime.'_'.$FleetRow['fleet_id']] = BuildFleetEventTable($FleetRow, 1, false, 'oft', $FleetIndex2); - } - } - } - } - } - } - if(!empty($Fleets)) - { - ksort($Fleets); - $parse['fleet_list'] = implode('', $Fleets); - } - - // --- Create other planets thumbnails --- - $Results['planets'] = array(); - - $Order = ($_User['planet_sort_order'] == 1) ? 'DESC' : 'ASC' ; - $Sort = $_User['planet_sort']; - - $QryPlanets = "SELECT * FROM {{table}} WHERE `id_owner` = {$_User['id']} AND `id` != {$_Planet['id']} AND `planet_type` != 3 ORDER BY "; - if($Sort == 0) - { - $QryPlanets .= "`id` {$Order}"; - } - else if($Sort == 1) - { - $QryPlanets .= "`galaxy`, `system`, `planet`, `planet_type` {$Order}"; - } - else if($Sort == 2) - { - $QryPlanets .= "`name` {$Order}"; - } - $parse['OtherPlanets'] = ''; - $AllOtherPlanets = doquery($QryPlanets, 'planets'); - if(mysql_num_rows($AllOtherPlanets) > 0) - { - $InCurrentRow = 0; - $InNextRow = false; - - while($PlanetsData = mysql_fetch_assoc($AllOtherPlanets)) - { - // Show Planet on List - if(empty($DontShowPlanet) OR !in_array($PlanetsData['id'], $DontShowPlanet)) - { - $DontShowThisPlanet = false; - } - else - { - $DontShowThisPlanet = true; - } - if($DontShowThisPlanet === false) - { - if($InCurrentRow == 0) - { - $parse['OtherPlanets'] .= ''; - } - $parse['OtherPlanets'] .= ''.$PlanetsData['name'].'
    '; - $parse['OtherPlanets'] .= "
    "; - $parse['OtherPlanets'] .= '
    '; - } - // Update Planet - Building Queue - if(HandlePlanetUpdate($PlanetsData, $_User, $Now, true) === true) - { - $Results['planets'][] = $PlanetsData; - } - if($PlanetsData['buildQueue_firstEndTime'] > 0) - { - if($DontShowThisPlanet === false) - { - $BuildQueue = $PlanetsData['buildQueue']; - $QueueArray = explode (';', $BuildQueue); - $CurrentBuild = explode (',', $QueueArray[0]); - $BuildElement = $CurrentBuild[0]; - $BuildLevel = $CurrentBuild[1]; - $BuildRestTime = pretty_time($CurrentBuild[3] - $Now); - - $parse['OtherPlanets'] .= $_Lang['tech'][$BuildElement].' ('.$BuildLevel.')'; - $parse['OtherPlanets'] .= '
    ('.$BuildRestTime.')'; - } - } - else - { - if($DontShowThisPlanet === false) - { - $parse['OtherPlanets'] .= $_Lang['Free'].'
     '; - } - } - - if($DontShowThisPlanet === false) - { - $parse['OtherPlanets'] .= '
    '; - } - - if($DontShowThisPlanet === false) - { - $InCurrentRow += 1; - if($InCurrentRow >= 5) - { - $InCurrentRow = 0; - $InNextRow = true; - if($DontShowThisPlanet == false) - { - $parse['OtherPlanets'] .= ''; - } - } - } - } - - if($InNextRow === true AND $InCurrentRow > 0) - { - $Difference = 5 - $InCurrentRow; - for($i = 0; $i < $Difference; $i += 1) - { - $parse['OtherPlanets'] .= ' '; - } - $parse['OtherPlanets'] .= ''; - } - } - else - { - $parse['hide_other_planets'] = 'style="display: none;"'; - } - - // Update this planet (if necessary) - if(HandlePlanetUpdate($_Planet, $_User, $Now, true) === true) - { - $Results['planets'][] = $_Planet; - } - if($_Planet['buildQueue_firstEndTime'] > 0) - { - $BuildQueue = explode(';', $_Planet['buildQueue']); - $CurrBuild = explode(',', $BuildQueue[0]); - $RestTime = $_Planet['buildQueue_firstEndTime'] - $Now; - $PlanetID = $_Planet['id']; - - $Build = ''; - $Build .= InsertJavaScriptChronoApplet('pl', 'this', $RestTime, false, false, 'function() { SetTimer = \"'.$_Lang['BuildJS_Complete'].'\"; document.getElementById(\"dlink\").innerHTML = \''.$_Lang['BuildJS_Continue'].'\'; window.setTimeout(\'document.location.href=\"overview.php?planet='.$PlanetID.'\";\', 1000); }'); - $Build .= $_Lang['tech'][$CurrBuild[0]].' ('.$CurrBuild[1].')'; - $Build .= '
    '.pretty_time($RestTime, true).'
    '; - if(isset($_Vars_PremiumBuildings[$CurrBuild[0]]) && $_Vars_PremiumBuildings[$CurrBuild[0]] == 1) - { - $Build .= ''; - } - else - { - $Build .= ''; - } - - $parse['building'] = $Build; - } - else - { - $parse['building'] = $_Lang['Free']; - } - - // Now update all the planets (if it's necessary) - HandlePlanetUpdate_MultiUpdate($Results, $_User); - - // News Frame ... - if($_GameConfig['OverviewNewsFrame'] == '1') - { - $parse['FromAdmins'] = nl2br($_GameConfig['OverviewNewsText']); - } - if($_GameConfig['OverviewBanner'] == '1') - { - $parse['TopLists_box'] = nl2br($_GameConfig['OverviewClickBanner']); - } - - $parse['referralLink2'] = GAMEURL.'index.php?r='.$_User['id']; - $parse['referralLink1'] = '[url='.$parse['referralLink2'].'][img]'.GAMEURL.'generate_sig.php?uid='.$_User['id'].'[/img][/url]'; - $parse['UserUID'] = $_User['id']; - - $page = parsetemplate(gettemplate('overview_body'), $parse); - display($page, $_Lang['Overview']); - break; - } - -?> \ No newline at end of file + 0) + { + // Update Referrer Tasks + if(empty($GlobalParsedTasks[$_User['referred']]['tasks_done_parsed'])) + { + $GetUserTasksDone = doquery("SELECT `id`, `tasks_done` FROM {{table}} WHERE `id` = {$_User['referred']} LIMIT 1;", 'users', true); + if($GetUserTasksDone['id'] == $_User['referred']) + { + unset($GetUserTasksDone['id']); + Tasks_CheckUservar($GetUserTasksDone); + $GlobalParsedTasks[$_User['referred']] = $GetUserTasksDone; + $ThisTaskUser = $GlobalParsedTasks[$_User['referred']]; + $ThisTaskUser['id'] = $_User['referred']; + } + } + else + { + $ThisTaskUser = $GlobalParsedTasks[$_User['referred']]; + $ThisTaskUser['id'] = $_User['referred']; + } + + if(!empty($ThisTaskUser)) + { + Tasks_TriggerTask($ThisTaskUser, 'NEWUSER_REGISTER', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use (&$ThisTaskUser) + { + $Return = Tasks_TriggerTask_MainCheck_Progressive($JobArray, $ThisCat, $TaskID, $JobID, $ThisTaskUser, 1); + $ThisTaskUser['TaskData'][] = array + ( + 'TaskID' => $TaskID, + 'TaskStatus' => $ThisTaskUser['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID], + 'TaskLimit' => $JobArray[$JobArray['statusField']] + ); + return $Return; + } + )); + } + + // Check IP Intersection + $_Included_AlertSystemUtilities = true; + include($_EnginePath.'includes/functions/AlertSystemUtilities.php'); + $CheckIntersection = AlertUtils_IPIntersect($_User['id'], $_User['referred'], array + ( + 'LastTimeDiff' => (TIME_DAY * 60), + 'ThisTimeDiff' => (TIME_DAY * 60), + 'ThisTimeStamp' => ($Now - SERVER_MAINOPEN_TSTAMP) + )); + if($CheckIntersection !== false) + { + $FiltersData = array(); + $FiltersData['place'] = 4; + $FiltersData['alertsender'] = 4; + $FiltersData['users'] = array($_User['id'], $_User['referred']); + $FiltersData['ips'] = $CheckIntersection['Intersect']; + $FiltersData['newuser'] = $_User['id']; + $FiltersData['referrer'] = $_User['referred']; + foreach($CheckIntersection['Intersect'] as $IP) + { + $FiltersData['logcount'][$IP][$_User['id']] = $CheckIntersection['IPLogData'][$_User['id']][$IP]['Count']; + $FiltersData['logcount'][$IP][$_User['referred']] = $CheckIntersection['IPLogData'][$_User['referred']][$IP]['Count']; + } + + $FilterResult = AlertUtils_CheckFilters($FiltersData, array('Save' => true)); + if($FilterResult['SendAlert']) + { + $_Alert['Data']['ReferrerID'] = $_User['referred']; + foreach($CheckIntersection['Intersect'] as $ThisIPID) + { + $_Alert['Data']['Intersect'][] = array + ( + 'IPID' => $ThisIPID, + 'NewUser' => $CheckIntersection['IPLogData'][$_User['id']][$ThisIPID], + 'OldUser' => $CheckIntersection['IPLogData'][$_User['referred']][$ThisIPID] + ); + } + if(!empty($ThisTaskUser['TaskData'])) + { + $_Alert['Data']['Tasks'] = $ThisTaskUser['TaskData']; + } + + $Query_AlertOtherUsers .= "SELECT DISTINCT `User_ID` FROM {{table}} WHERE "; + $Query_AlertOtherUsers .= "`User_ID` NOT IN ({$_User['id']}, {$_User['referred']}) AND "; + $Query_AlertOtherUsers .= "`IP_ID` IN (".implode(', ', $CheckIntersection['Intersect']).") AND "; + $Query_AlertOtherUsers .= "`Count` > `FailCount`;"; + $Result_AlertOtherUsers = doquery($Query_AlertOtherUsers, 'user_enterlog'); + if(mysql_num_rows($Result_AlertOtherUsers) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_AlertOtherUsers)) + { + $_Alert['Data']['OtherUsers'][] = $FetchData['User_ID']; + } + } + + Alerts_Add(4, $Now, 1, 2, 8, $_User['id'], $_Alert['Data']); + } + } + } + + // Check, if this IP is Proxy + $IPHash = md5($_SERVER['REMOTE_ADDR']); + $Query_CheckProxy = "SELECT `ID`, `isProxy` FROM {{table}} WHERE `ValueHash` = '{$IPHash}' LIMIT 1;"; + $Result_CheckProxy = doquery($Query_CheckProxy, 'used_ip_and_ua', true); + if($Result_CheckProxy['ID'] > 0 AND $Result_CheckProxy['isProxy'] == 1) + { + if(!isset($_Included_AlertSystemUtilities)) + { + include($_EnginePath.'includes/functions/AlertSystemUtilities.php'); + $_Included_AlertSystemUtilities = true; + } + $FiltersData = array(); + $FiltersData['place'] = 4; + $FiltersData['alertsender'] = 5; + $FiltersData['users'] = array($_User['id']); + $FiltersData['ips'] = array($Result_CheckProxy['ID']); + + $FilterResult = AlertUtils_CheckFilters($FiltersData, array('DontLoad' => true, 'DontLoad_OnlyIfCacheEmpty' => true)); + if($FilterResult['SendAlert']) + { + $_Alert['Data']['IPID'] = $Result_CheckProxy['ID']; + if($_SERVER['REMOTE_ADDR'] == $_User['ip_at_reg']) + { + $_Alert['Data']['RegIP'] = true; + } + + Alerts_Add(5, $Now, 1, 3, 8, $_User['id'], $_Alert['Data']); + } + } + + // Give Free ProAccount for 7 days + //doquery("INSERT INTO {{table}} VALUES (NULL, {$_User['id']}, UNIX_TIMESTAMP(), 0, 0, 11, 0);", 'premium_free'); + + // Create DevLog Dump + define('IN_USERFIRSTLOGIN', true); + $InnerUIDSet = $_User['id']; + $SkipDumpMsg = true; + include($_EnginePath.'admin/scripts/script.createUserDevDump.php'); + + display(parsetemplate($TPL, $_Lang), $_Lang['FirstLogin_Title'], false); +} + +$mode = (isset($_GET['mode']) ? $_GET['mode'] : ''); + +includeLang('resources'); +includeLang('overview'); + +switch($mode) +{ + case 'rename': + // --- Rename Planet Page --- + $parse = $_Lang; + + $parse['Rename_Ins_MsgHide'] = 'style="display: none;"'; + $parse['Rename_Ins_MsgTxt'] = false; + + if($_Planet['planet_type'] == 1) + { + $parse['Rename_CurrentName'] = sprintf($parse['Rename_CurrentName'], $parse['Rename_Planet']); + } + else + { + $parse['Rename_CurrentName'] = sprintf($parse['Rename_CurrentName'], $parse['Rename_Moon']); + } + + if(isset($_POST['action']) && $_POST['action'] == 'do') + { + // User wants to change planets name + $NewName = trim($_POST['set_newname']); + if(!empty($NewName)) + { + // Update only, when name is not the same as old + if($_Planet['name'] != $NewName) + { + // Check if planet new name is correct + $NewNameLength = strlen($NewName); + if($NewNameLength < 3) + { + $parse['Rename_Ins_MsgColor'] = 'red'; + $parse['Rename_Ins_MsgTxt'] = $_Lang['RenamePlanet_TooShort']; + } + elseif($NewNameLength > 20) + { + $parse['Rename_Ins_MsgColor'] = 'red'; + $parse['Rename_Ins_MsgTxt'] = $_Lang['RenamePlanet_TooLong']; + } + elseif(!preg_match(REGEXP_PLANETNAME_ABSOLUTE, $NewName)) + { + $parse['Rename_Ins_MsgColor'] = 'red'; + $parse['Rename_Ins_MsgTxt'] = $_Lang['RenamePlanet_BadSigns']; + } + if($parse['Rename_Ins_MsgTxt'] === false) + { + //Save the new name in Script Memory + $_Planet['name'] = $NewName; + //Now save it in DataBase + doquery("UPDATE {{table}} SET `name` = '{$NewName}' WHERE `id` = {$_User['current_planet']} LIMIT 1;", 'planets'); + $parse['Rename_Ins_MsgColor'] = 'lime'; + $parse['Rename_Ins_MsgTxt'] = $_Lang['RenamePlanet_NameSaved']; + } + } + else + { + $parse['Rename_Ins_MsgColor'] = 'orange'; + $parse['Rename_Ins_MsgTxt'] = $_Lang['RenamePlanet_SameName']; + } + } + else + { + $parse['Rename_Ins_MsgColor'] = 'red'; + $parse['Rename_Ins_MsgTxt'] = $_Lang['RenamePlanet_0Lenght']; + } + } + + if($parse['Rename_Ins_MsgTxt'] !== false) + { + $parse['Rename_Ins_MsgHide'] = ''; + } + + $parse['Rename_Ins_CurrentName'] = "{$_Planet['name']} [{$_Planet['galaxy']}:{$_Planet['system']}:{$_Planet['planet']}]"; + + $page = parsetemplate(gettemplate('overview_rename'), $parse); + display($page, $_Lang['Rename_TitleMain']); + break; + case 'abandon': + // --- Abandon Colony --- + if(isOnVacation()) + { + message($_Lang['Vacation_WarnMsg'], $_Lang['Vacation']); + } + + $parse = $_Lang; + $parse['Abandon_Ins_MsgHide'] = 'style="display: none;"'; + $parse['Abandon_Ins_MsgTxt'] = false; + + if(isset($_POST['action']) && $_POST['action'] == 'do') + { + $parse['Abandon_Ins_MsgColor'] = 'red'; + // Check if given password is good + if(!empty($_POST['give_passwd'])) + { + if(md5($_POST['give_passwd']) == $_User['password']) + { + if($_User['id_planet'] != $_User['current_planet']) + { + if($_Planet['planet_type'] == 1 OR $_Planet['planet_type'] == 3) + { + include($_EnginePath.'includes/functions/DeleteSelectedPlanetorMoon.php'); + $DeleteResult = DeleteSelectedPlanetorMoon(); + if($DeleteResult['result'] === true) + { + // Prevent abandoning Planet to make mission faster + Tasks_TriggerTask($_User, 'COLONIZE_PLANET', array + ( + 'mainCheck' => function($JobArray, $ThisCat, $TaskID, $JobID) use ($_User) + { + global $UserTasksUpdate; + if(!empty($UserTasksUpdate[$_User['id']]['status'][$ThisCat][$TaskID][$JobID])) + { + $_User['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] = $UserTasksUpdate[$_User['id']]['status'][$ThisCat][$TaskID][$JobID]; + } + if($_User['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] <= 0) + { + return true; + } + $_User['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID] -= 1; + $UserTasksUpdate[$_User['id']]['status'][$ThisCat][$TaskID][$JobID] = $_User['tasks_done_parsed']['status'][$ThisCat][$TaskID][$JobID]; + return true; + } + )); + + // User Development Log + $UserDev_Log[] = array('PlanetID' => $_Planet['id'], 'Date' => $Now, 'Place' => 25, 'Code' => '0', 'ElementID' => '0'); + if(count($DeleteResult['ids']) > 1) + { + $UserDev_Log[] = array('PlanetID' => $DeleteResult['ids'][1], 'Date' => $Now, 'Place' => 25, 'Code' => '0', 'ElementID' => '0'); + } + + header('Location: overview.php?showmsg=abandon'); + safeDie(); + } + else + { + if($DeleteResult['reason'] == 'tech') + { + $parse['Abandon_Ins_MsgTxt'] = $_Lang['Abandon_TechHere']; + } + elseif($DeleteResult['reason'] == 'sql') + { + $parse['Abandon_Ins_MsgTxt'] = $_Lang['Abandon_SQLError']; + } + elseif($DeleteResult['reason'] == 'fleet_current') + { + $parse['Abandon_Ins_MsgTxt'] = $_Lang['Abandon_FlyingFleetsHere']; + } + elseif($DeleteResult['reason'] == 'fleet_moon') + { + $parse['Abandon_Ins_MsgTxt'] = $_Lang['Abandon_FlyingFleetsMoon']; + } + } + } + else + { + $parse['Abandon_Ins_MsgTxt'] = $_Lang['Abandon_BadPlanetrowData']; + } + } + else + { + $parse['Abandon_Ins_MsgTxt'] = $_Lang['Abandon_CantAbandonMother']; + } + } + else + { + $parse['Abandon_Ins_MsgTxt'] = $_Lang['Abandon_BadPassword']; + } + } + else + { + $parse['Abandon_Ins_MsgTxt'] = $_Lang['Abandon_NoPassword']; + } + } + + if($parse['Abandon_Ins_MsgTxt'] !== false) + { + $parse['Abandon_Ins_MsgHide'] = ''; + } + $parse['Abandon_Desc'] = sprintf($parse['Abandon_Desc'], ($_Planet['planet_type'] == 1 ? $_Lang['Abandon_Planet'] : $_Lang['Abandon_Moon']), $_Planet['name'], "[{$_Planet['galaxy']}:{$_Planet['system']}:{$_Planet['planet']}]"); + $parse['Abandon_Ins_Pass'] = $_User['password']; + + $page = parsetemplate(gettemplate('overview_deleteplanet'), $parse); + display($page, $_Lang['Abandon_TitleMain']); + break; + default: + $parse = &$_Lang; + include($_EnginePath.'includes/functions/InsertJavaScriptChronoApplet.php'); + InsertJavaScriptChronoApplet(false, false, false); + $InsertJSChronoApplet_GlobalIncluded = true; + + // --- Vacation Mode Box + if(isOnVacation()) + { + $parse['VacationModeBox'] = ''.$_Lang['VacationModeBox_Text'].' '; + } + + // --- Activation Box + if(!empty($_User['activation_code'])) + { + $parse['ActivationInfoBox'] = ''.$_Lang['ActivationInfo_Text'].' '; + } + + // --- New User Protection Box + if($_User['NoobProtection_EndTime'] > $Now) + { + if(isset($_GET['cancelprotection']) && $_GET['cancelprotection'] == '1') + { + $_User['NoobProtection_EndTime'] = $Now; + $Query_UpdateUser = "UPDATE {{table}} SET `NoobProtection_EndTime` = {$Now} WHERE `id` = {$_User['id']} LIMIT 1;"; + doquery($Query_UpdateUser, 'users'); + + $parse['NewUserBox'] = ''.$_Lang['NewUserProtection_Canceled'].' '; + } + else + { + $ProtectTimeLeft = $_User['NoobProtection_EndTime'] - $Now; + $parse['NewUserBox'] = InsertJavaScriptChronoApplet('newprotect', '', $ProtectTimeLeft).''.sprintf($_Lang['NewUserProtection_Text'], pretty_time($ProtectTimeLeft, true, 'dhms')).' '; + } + } + + // --- Admin Info Box ------------------------------------------------------------------------------------ + if(CheckAuth('supportadmin')) + { + $Query_AdminBoxCheck[] = "SELECT COUNT(*) AS `Count`, 1 AS `Type` FROM `{{prefix}}reports` WHERE `status` = 0"; + $Query_AdminBoxCheck[] = "SELECT COUNT(*) AS `Count`, 2 AS `Type` FROM `{{prefix}}declarations` WHERE `status` = 0"; + $Query_AdminBoxCheck[] = "SELECT COUNT(*) AS `Count`, 3 AS `Type` FROM `{{prefix}}system_alerts` WHERE `status` = 0"; + $Query_AdminBoxCheck = implode(' UNION ', $Query_AdminBoxCheck); + $Result_AdminBoxCheck = doquery($Query_AdminBoxCheck, ''); + + $AdminBoxTotalCount = 0; + while($AdminBoxData = mysql_fetch_assoc($Result_AdminBoxCheck)) + { + $AdminBox[$AdminBoxData['Type']] = $AdminBoxData['Count']; + $AdminBoxTotalCount += $AdminBoxData['Count']; + } + if($AdminBoxTotalCount > 0) + { + $AdminAlerts = sprintf($_Lang['AdminAlertsBox'], $AdminBox[1], $AdminBox[2], $AdminBox[3]); + $parse['AdminInfoBox'] = ''.$AdminAlerts.' '; + } + } + + // --- MailChange Box ------------------------------------------------------------------------------------ + $parse['MailChange_Hide'] = 'display: none;'; + if($_User['email'] != $_User['email_2']) + { + $MailChange = doquery("SELECT * FROM {{table}} WHERE `UserID` = {$_User['id']} AND `ConfirmType` = 0 LIMIT 1;", 'mailchange', true); + if($MailChange['ID'] > 0) + { + $ChangeTime = $MailChange['Date'] + (TIME_DAY * 7); + + $parse['MailChange_Hide'] = ''; + $parse['MailChange_Box'] = sprintf($_Lang['MailChange_Text']); + if($MailChange['ConfirmHashNew'] == '') + { + if($ChangeTime < $Now) + { + $parse['MailChange_Box'] .= "

    "; + } + else + { + $parse['MailChange_Box'] .= "

    ".sprintf($_Lang['MailChange_Inf2'], date('d.m.Y H:i:s', $ChangeTime)); + } + } + else + { + $parse['MailChange_Box'] .= "

    {$_Lang['MailChange_Inf1']}"; + } + } + } + + // Fleet Blockade Info (here, only for Global Block) + $GetSFBData = doquery("SELECT `ID`, `EndTime`, `BlockMissions`, `DontBlockIfIdle`, `Reason` FROM {{table}} WHERE `Type` = 1 AND `StartTime` <= UNIX_TIMESTAMP() AND (`EndTime` > UNIX_TIMESTAMP() OR `PostEndTime` > UNIX_TIMESTAMP()) ORDER BY `EndTime` DESC LIMIT 1;", 'smart_fleet_blockade', true); + if($GetSFBData['ID'] > 0) + { + // Fleet Blockade is Active + include($_EnginePath.'includes/functions/CreateSFBInfobox.php'); + $parse['P_SFBInfobox'] = CreateSFBInfobox($GetSFBData, array('standAlone' => true, 'Width' => 750, 'MarginBottom' => 10)); + } + + // --- Free Premium Items Info Box ----------------------------------------------------------------------- + $GetFreeItems = doquery("SELECT COUNT(`ID`) as `Count` FROM {{table}} WHERE `UserID` = {$_User['id']} AND `Used` = false;", 'premium_free', true); + if($GetFreeItems['Count'] > 0) + { + $parse['FreePremiumItemsBox'] = ''.sprintf($_Lang['FreePremItem_Text'], $GetFreeItems['Count']).''; + } + + // --- System Messages Box ------------------------------------------------------------------------------- + if(!empty($_GET['showmsg'])) + { + $SysMsgLoop = 0; + if($_GET['showmsg'] == 'abandon') + { + $ShowSystemMsg[$SysMsgLoop]['txt'] = $_Lang['Abandon_ColonyAbandoned']; + $ShowSystemMsg[$SysMsgLoop]['col'] = 'lime'; + $SysMsgLoop += 1; + } + } + + if(!empty($ShowSystemMsg)) + { + $parse['SystemMsgBox'] = ''; + foreach($ShowSystemMsg as $SystemMsg) + { + $parse['SystemMsgBox'] .= ''.$SystemMsg['txt'].''; + } + } + + // --- New Messages Information Box ---------------------------------------------------------------------- + $NewMsg = doquery("SELECT COUNT(`id`) as `count` FROM {{table}} WHERE `deleted` = false AND `read` = false AND `id_owner` = {$_User['id']};", 'messages', true); + if($NewMsg['count'] > 0) + { + if($NewMsg['count'] == 1) + { + $MsgBox_NewSurfix = $_Lang['MsgBox_New_1']; + $MsgBox_UnreadenSurfix= $_Lang['MsgBox_Unreaden_1']; + $MsgBox_Msg_s = $_Lang['MsgBox_Msg']; + } + elseif($NewMsg['count'] > 1 AND $NewMsg['count'] < 5) + { + $MsgBox_NewSurfix = $_Lang['MsgBox_New_2_4']; + $MsgBox_UnreadenSurfix= $_Lang['MsgBox_Unreaden_2_4']; + $MsgBox_Msg_s = $_Lang['MsgBox_Msgs']; + } + else + { + $MsgBox_NewSurfix = $_Lang['MsgBox_New_5']; + $MsgBox_UnreadenSurfix= $_Lang['MsgBox_Unreaden_5']; + $MsgBox_Msg_s = $_Lang['MsgBox_Msgs']; + } + $MsgBoxText = $_Lang['MsgBox_YouHave'].' '.prettyNumber($NewMsg['count']).' '.$_Lang['MsgBox_New'].$MsgBox_NewSurfix.', '.$_Lang['MsgBox_Unreaden'].$MsgBox_UnreadenSurfix.' '.$MsgBox_Msg_s.'!'; + + $NewMsgBox = ''.$MsgBoxText.''; + $parse['NewMsgBox'] = $NewMsgBox; + } + + // --- New Polls Information Box ------------------------------------------------------------------------- + $Polls = doquery("SELECT {{table}}.`id`, `votes`.`id` AS `vote_id` FROM {{table}} LEFT JOIN {{prefix}}poll_votes AS `votes` ON `votes`.`poll_id` = {{table}}.id AND `votes`.`user_id` = {$_User['id']} WHERE {{table}}.`open` = 1 ORDER BY {{table}}.`time` DESC;", 'polls'); + if(mysql_num_rows($Polls) > 0) + { + $AvailablePolls = 0; + while($PollData = mysql_fetch_assoc($Polls)) + { + if($PollData['vote_id'] <= 0) + { + $AvailablePolls += 1; + } + } + if($AvailablePolls > 0) + { + $parse['NewPollsBox'] = ''.vsprintf($_Lang['PollBox_You_can_vote_in_new_polls'], ($AvailablePolls > 1) ? $_Lang['PollBox_More'] : $_Lang['PollBox_One']).''; + } + } + + // --- Get users activity informations ----------------------------------------------------------- + $TodaysStartTimeStamp = mktime(0, 0, 0); + $OnlineUsers = doquery("SELECT IF(`onlinetime` >= (UNIX_TIMESTAMP() - (".TIME_ONLINE.")), 1, 0) AS `current_online` FROM {{table}} WHERE `onlinetime` >= {$TodaysStartTimeStamp};", 'users'); + $TodayActive = mysql_num_rows($OnlineUsers); + $CurrentOnline = 0; + if($TodayActive > 0) + { + while($ActiveData = mysql_fetch_assoc($OnlineUsers)) + { + if($ActiveData['current_online'] == 1) + { + $CurrentOnline += 1; + } + } + } + $parse['CurrentOnline'] = prettyNumber($CurrentOnline); + $parse['TodayOnline'] = prettyNumber($TodayActive); + $parse['TotalPlayerCount'] = prettyNumber($_GameConfig['users_amount']); + $parse['ServerRecord'] = prettyNumber($_GameConfig['rekord']); + + // --- Get last Stats and Records UpdateTime ----------------------------------------------------- + $parse['LastStatsRecount'] = date('d.m.Y H:i:s', $_GameConfig['last_update']); + + // --- MoraleSystem Box --- + if(MORALE_ENABLED) + { + Morale_ReCalculate($_User); + $UserMoraleLevel = $_User['morale_level']; + + $parse['Insert_Morale_Level'] = $UserMoraleLevel; + if($UserMoraleLevel > 0) + { + $parse['Insert_Morale_Color'] = 'lime'; + } + else if($UserMoraleLevel < 0) + { + if($UserMoraleLevel <= -50) + { + $parse['Insert_Morale_Color'] = 'red'; + } + else + { + $parse['Insert_Morale_Color'] = 'orange'; + } + } + + if($UserMoraleLevel == 0) + { + $parse['Insert_Morale_Status'] = $_Lang['Box_Morale_NoChanges']; + } + else + { + if($UserMoraleLevel > 0) + { + $Temp_MoraleStatus = 'Pos'; + } + else + { + $Temp_MoraleStatus = 'Neg'; + } + if($_User['morale_droptime'] > $Now) + { + GlobalTemplate_AppendToAfterBody(InsertJavaScriptChronoApplet('morale', '', $_User['morale_droptime'], true)); + $parse['Insert_Morale_Status'] = sprintf($_Lang['Box_Morale_DropStartIn_'.$Temp_MoraleStatus], pretty_time($_User['morale_droptime'] - $Now, true, 'D')); + } + else + { + if($UserMoraleLevel > 0) + { + $Temp_MoraleDropInterval = MORALE_DROPINTERVAL_POSITIVE; + } + else + { + $Temp_MoraleDropInterval = MORALE_DROPINTERVAL_NEGATIVE; + } + if($_User['morale_lastupdate'] == 0) + { + $Temp_MoraleNextDrop = $_User['morale_droptime'] + $Temp_MoraleDropInterval; + } + else + { + $Temp_MoraleNextDrop = $_User['morale_lastupdate'] + $Temp_MoraleDropInterval; + } + GlobalTemplate_AppendToAfterBody(InsertJavaScriptChronoApplet('morale', '', $Temp_MoraleNextDrop, true)); + $parse['Insert_Morale_Status'] = sprintf($_Lang['Box_Morale_Dropping_'.$Temp_MoraleStatus], pretty_time($Temp_MoraleNextDrop - $Now, true, 'D')); + } + } + $_Lang['Box_Morale_Points'] = sprintf($_Lang['Box_Morale_Points'], prettyNumber($_User['morale_points'])); + + $parse['Insert_MoraleBox'] = parsetemplate(gettemplate('overview_body_morale'), $parse); + } + + // --- Get Register Date - + $RegisterDays = floor(($Now - $_User['register_time']) / (24*60*60)); + if($RegisterDays == 1) + { + $parse['RegisterDaysTxt'] = $parse['_youPlaySince_1day']; + } + else + { + $parse['RegisterDaysTxt'] = $parse['_youPlaySince_2days']; + } + $parse['RegisterDays'] = prettyNumber($RegisterDays); + $parse['RegisterDate'] = date('d.m.Y', $_User['register_time']); + + // --- ProAccount Box --- + $parse['ProAccountInfoText'] = ($_User['pro_time'] > $Now) ? $_Lang['ProAccTill'].''.date("d.m.Y\<\b\\r\/\>H:i:s", $_User['pro_time']).'' : (($_User['pro_time'] == 0) ? $_Lang['NoProAccEver'] : $_Lang['NoProAccSince'].''.date("d.m.Y\<\b\\r\/\>H:i:s", $_User['pro_time']).''); + $parse['ProAccLink'] = ($_User['pro_time'] > $Now) ? $_Lang['ProAccBuyMore'] : (($_User['pro_time'] == 0) ? $_Lang['ProAccBuyFirst'] : $_Lang['ProAccBuyNext']); + + // --- Get Reffered Count -- + $Referred = doquery("SELECT COUNT(`id`) as `count` FROM {{table}} WHERE `referrer_id` = {$_User['id']};", 'referring_table', true); + $parse['RefferedCounter'] = prettyNumber((($Referred['count'] > 0) ? $Referred['count'] : '0')); + + // --- Get UserStats --- + $StatRecord = doquery("SELECT * FROM {{table}} WHERE `stat_type` = '1' AND `id_owner` = {$_User['id']} LIMIT 1;", 'statpoints', true); + $parse['user_points'] = prettyNumber($StatRecord['build_points']); + $parse['user_fleet'] = prettyNumber($StatRecord['fleet_points']); + $parse['user_defs'] = prettyNumber($StatRecord['defs_points']); + $parse['player_points_tech'] = prettyNumber($StatRecord['tech_points']); + $parse['total_points'] = prettyNumber($StatRecord['total_points']); + + // Total Rank changes + if($StatRecord['total_rank'] > 0) + { + $ile = $StatRecord['total_old_rank'] - $StatRecord['total_rank']; + if($ile > 0) + { + $ile = "(+{$ile})"; + } + elseif($ile < 0) + { + $ile = "({$ile})"; + } + else + { + $ile = '(*)'; + } + $parse['user_total_rank'] = ''.$StatRecord['total_rank'].' '.$ile; + } + else + { + $parse['user_total_rank'] = 0; + $StatRecord['total_rank'] = '0'; + } + $parse['set_user_total_rank'] = $StatRecord['total_rank']; + + // Build Rank changes + if(isset($StatRecord['build_rank']) && $StatRecord['build_rank'] > 0) + { + $ile = $StatRecord['build_old_rank'] - $StatRecord['build_rank']; + if($ile > 0) + { + $ile = "(+{$ile})"; + } + elseif($ile < 0) + { + $ile = "({$ile})"; + } + else + { + $ile = '(*)'; + } + $parse['user_br'] = ''.$StatRecord['build_rank'].' '.$ile; + } + else + { + $parse['user_br'] = 0; + $StatRecord['build_rank'] = '0'; + } + $parse['set_user_br'] = $StatRecord['build_rank']; + + // Fleet rank changes + if(isset($StatRecord['fleet_rank']) && $StatRecord['fleet_rank'] > 0) + { + $ile = $StatRecord['fleet_old_rank'] - $StatRecord['fleet_rank']; + if($ile > 0) + { + $ile = "(+{$ile})"; + } + else if($ile < 0) + { + $ile = "({$ile})"; + } + else + { + $ile = '(*)'; + } + $parse['user_fr'] = ''.$StatRecord['fleet_rank'].' '.$ile; + } + else + { + $parse['user_fr'] = 0; + $StatRecord['fleet_rank'] = '0'; + } + $parse['set_user_fr'] = $StatRecord['fleet_rank']; + + // Defense rank changes + if(isset($StatRecord['defs_rank']) && $StatRecord['defs_rank'] > 0) + { + $ile = $StatRecord['defs_old_rank'] - $StatRecord['defs_rank']; + if($ile > 0) + { + $ile = "(+{$ile})"; + } + else if($ile < 0) + { + $ile = "({$ile})"; + } + else + { + $ile = '(*)'; + } + $parse['user_dr'] = ''.$StatRecord['defs_rank'].' '.$ile; + } + else + { + $parse['user_dr'] = 0; + $StatRecord['defs_rank'] = '0'; + } + $parse['set_user_dr'] = $StatRecord['defs_rank']; + + // Research rank changes + if(isset($StatRecord['tech_rank']) && $StatRecord['tech_rank'] > 0) + { + $ile = $StatRecord['tech_old_rank'] - $StatRecord['tech_rank']; + if($ile > 0) + { + $ile = "(+{$ile})"; + } + else if($ile < 0) + { + $ile = "({$ile})"; + } + else + { + $ile = '(*)'; + } + $parse['user_tr'] = ''.$StatRecord['tech_rank'].' '.$ile; + } + else + { + $parse['user_tr'] = 0; + $StatRecord['tech_rank'] = '0'; + } + $parse['set_user_tr'] = $StatRecord['tech_rank']; + + // Get User Achievements + $GetStats_Fields = '`ustat_raids_won`, `ustat_raids_draw`, `ustat_raids_lost`, `ustat_raids_acs_won`, `ustat_raids_inAlly`, `ustat_raids_missileAttack`'; + $GetStats = doquery("SELECT {$GetStats_Fields} FROM {{table}} WHERE `A_UserID` = {$_User['id']} LIMIT 1;", 'achievements_stats', true); + $parse['raids'] = prettyNumber($GetStats['ustat_raids_won'] + $GetStats['ustat_raids_draw'] + $GetStats['ustat_raids_lost'] + $GetStats['ustat_raids_inAlly']); + $parse['raidswin'] = prettyNumber($GetStats['ustat_raids_won']); + $parse['raidsdraw'] = prettyNumber($GetStats['ustat_raids_draw']); + $parse['raidsloose'] = prettyNumber($GetStats['ustat_raids_lost']); + $parse['raidacswin'] = prettyNumber($GetStats['ustat_raids_acs_won']); + $parse['raidsinally'] = prettyNumber($GetStats['ustat_raids_inAlly']); + $parse['raidsmissileattacks'] = prettyNumber($GetStats['ustat_raids_missileAttack']); + + // --- Planet Data --------- + if($_Planet['planet_type'] == 1) + { + $parse['ShowWhatsOnOrbit'] = ''.$_Lang['_emptyOrbit'].''; + if($_GalaxyRow['id_moon'] > 0) + { + $MoonRow = doquery("SELECT `id`, `name` FROM {{table}} WHERE `id` = {$_GalaxyRow['id_moon']} LIMIT 1;", 'planets', true); + if($MoonRow['id'] > 0) + { + $parse['ShowWhatsOnOrbit'] = "{$MoonRow['name']}"; + } + } + } + else + { + $PlanetData = doquery("SELECT `id`, `name` FROM {{table}} WHERE `id` = {$_GalaxyRow['id_planet']} LIMIT 1;", 'planets', true); + $parse['ShowWhatsOnOrbit'] = "{$PlanetData['name']}"; + $DontShowPlanet[] = $PlanetData['id']; + } + if(empty($parse['onOrbit_img'])) + { + $parse['hide_orbit_view'] = 'style="display: none;"'; + } + + $MaxPlanetFields = CalculateMaxPlanetFields($_Planet); + $parse['skinpath'] = $_SkinPath; + $parse['planet_image'] = $_Planet['image']; + $parse['planet_name'] = $_Planet['name']; + $parse['planet_diameter'] = prettyNumber($_Planet['diameter']); + $parse['planet_field_current'] = $_Planet['field_current']; + $parse['planet_field_max']= $MaxPlanetFields; + $parse['planet_temp_min'] = $_Planet['temp_min']; + $parse['planet_temp_max'] = $_Planet['temp_max']; + $parse['galaxy_galaxy'] = $_Planet['galaxy']; + $parse['galaxy_planet'] = $_Planet['planet']; + $parse['galaxy_system'] = $_Planet['system']; + if($_Planet['id'] == $_User['id_planet']) + { + $parse['HideAbandonLink'] = ' style="display: none"'; + } + $parse['_planetData_type'] = ($_Planet['planet_type'] == 1) ? $parse['_planetData_planet'] : $parse['_planetData_moon']; + $parse['overvier_type'] = ($_Planet['planet_type'] == 1) ? $parse['_overview_planet'] : $parse['_overview_moon']; + $parse['planet_field_used_percent'] = round(($_Planet['field_current'] / $MaxPlanetFields) * 100); + $parse['metal_debris'] = prettyNumber($_GalaxyRow['metal']); + $parse['crystal_debris'] = prettyNumber($_GalaxyRow['crystal']); + if($_GalaxyRow['metal'] <= 0 AND $_GalaxyRow['crystal'] <= 0) + { + $parse['hide_debris'] = 'style="display: none;"'; + } + else + { + $parse['hide_nodebris'] = 'display: none;'; + } + + // --- Transporters ---------------------------- + $SmallRequired = ceil(($_Planet['metal'] + $_Planet['crystal'] + $_Planet['deuterium']) / $_Vars_Prices[202]['capacity']); + $BigRequired = ceil(($_Planet['metal'] + $_Planet['crystal'] + $_Planet['deuterium']) / $_Vars_Prices[203]['capacity']); + $MegaRequired = ceil(($_Planet['metal'] + $_Planet['crystal'] + $_Planet['deuterium']) / $_Vars_Prices[217]['capacity']); + + $SmallMissStay = -($SmallRequired - $_Planet[$_Vars_GameElements[202]]); + $BigMissStay = -($BigRequired - $_Planet[$_Vars_GameElements[203]]); + $MegaMissStay = -($MegaRequired - $_Planet[$_Vars_GameElements[217]]); + + $parse['small_cargo_count'] = prettyNumber($SmallRequired);//Small cargo ship + $parse['big_cargo_count'] = prettyNumber($BigRequired);//Big cargo ship + $parse['mega_cargo_count'] = prettyNumber($MegaRequired); //Mega cargo ship + + $parse['small_cargo_miss_stay'] = str_replace('-', '', prettyColorNumber($SmallMissStay, true)); + $parse['big_cargo_miss_stay'] = str_replace('-', '', prettyColorNumber($BigMissStay, true)); + $parse['mega_cargo_miss_stay'] = str_replace('-', '', prettyColorNumber($MegaMissStay, true)); + + $parse['small_trans'] = $_Lang['tech'][202]; + $parse['big_trans'] = $_Lang['tech'][203]; + $parse['mega_trans'] = $_Lang['tech'][217]; + + if(isPro() AND $_User['current_planet'] != $_User['settings_mainPlanetID']) + { + $GetQuickResPlanet = doquery("SELECT `name`, `galaxy`, `system`, `planet` FROM {{table}} WHERE `id` = {$_User['settings_mainPlanetID']};", 'planets', true); + $parse['QuickResSend_Button'] = sprintf($_Lang['QuickResSend_Button'], $GetQuickResPlanet['name'], $GetQuickResPlanet['galaxy'], $GetQuickResPlanet['system'], $GetQuickResPlanet['planet']); + } + else + { + $parse['Hide_QuickResButton'] = ' style="display: none;"'; + } + + // --- Flying Fleets Table --- + $Query_GetFleets = ''; + $Query_GetFleets .= "SELECT `fl`.*, `pl1`.`name` AS `start_name`, `pl2`.`name` AS `end_name`, `acs`.`fleets_id`, `usr`.`username` AS `owner_name` "; + $Query_GetFleets .= "FROM {{table}} AS `fl`"; + $Query_GetFleets .= "LEFT JOIN `{{prefix}}planets` AS `pl1` ON `pl1`.`id` = `fl`.`fleet_start_id` "; + $Query_GetFleets .= "LEFT JOIN `{{prefix}}planets` AS `pl2` ON `pl2`.`id` = `fl`.`fleet_end_id` "; + $Query_GetFleets .= "LEFT JOIN `{{prefix}}users` AS `usr` ON `usr`.`id` = `fl`.`fleet_owner` "; + $Query_GetFleets .= "LEFT JOIN `{{prefix}}acs` AS `acs` ON `acs`.`main_fleet_id` = `fl`.`fleet_id` "; + $Query_GetFleets .= "WHERE `fl`.`fleet_owner` = '{$_User['id']}' OR `fl`.`fleet_target_owner` = '{$_User['id']}';"; + $Result_GetFleets = doquery($Query_GetFleets, 'fleets'); + + $FleetIndex1 = 0; + $FleetIndex2 = 2000; + if(mysql_num_rows($Result_GetFleets) > 0) + { + include($_EnginePath.'includes/functions/BuildFleetEventTable.php'); + while($FleetRow = mysql_fetch_assoc($Result_GetFleets)) + { + if($FleetRow['fleet_owner'] == $_User['id']) + { + $FleetIndex1 += 1; + + $StartTime = $FleetRow['fleet_start_time']; + $StayTime = $FleetRow['fleet_end_stay']; + $EndTime = $FleetRow['fleet_end_time']; + // If this is ACS Fleet, change Mission (for AttackLeader Fleet) + if(!empty($FleetRow['fleets_id'])) + { + $FleetRow['fleet_mission'] = 2; + } + + if($StartTime > $Now) + { + $Fleets[$StartTime.'_'.$FleetRow['fleet_id']] = BuildFleetEventTable($FleetRow, 0, true, 'fs', $FleetIndex1); + } + + if($FleetRow['fleet_mission'] != 4 OR ($StartTime < $Now AND $FleetRow['fleet_mission'] == 4 AND $EndTime > $Now)) + { + if($FleetRow['fleet_mission'] != 4) + { + if($StayTime > $Now) + { + $Fleets[$StayTime.'_'.$FleetRow['fleet_id']] = BuildFleetEventTable($FleetRow, 1, true, 'ft', $FleetIndex1); + } + } + if($FleetRow['fleet_mission'] == 7 AND $FleetRow['fleet_mess'] == 0 AND $FleetRow['fleet_amount'] == 1) + { + // Dont show ComeBack when this is a colonization mission + } + else + { + if($EndTime > $Now) + { + $Fleets[$EndTime.'_'.$FleetRow['fleet_id']] = BuildFleetEventTable($FleetRow, 2, true, 'fe', $FleetIndex1); + } + } + } + } + else + { + if($FleetRow['fleet_mission'] != 8) + { + $FleetIndex2 += 1; + $StartTime = $FleetRow['fleet_start_time']; + $StayTime = $FleetRow['fleet_end_stay']; + if(!empty($FleetRow['fleets_id'])) + { + $FleetRow['fleet_mission'] = 2; + } + + if($StartTime > $Now) + { + $Fleets[$StartTime.'_'.$FleetRow['fleet_id']] = BuildFleetEventTable($FleetRow, 0, false, 'ofs', $FleetIndex2); + } + if($FleetRow['fleet_mission'] == 5) + { + if($StayTime > $Now) + { + $Fleets[$StayTime.'_'.$FleetRow['fleet_id']] = BuildFleetEventTable($FleetRow, 1, false, 'oft', $FleetIndex2); + } + } + } + } + } + } + if(!empty($Fleets)) + { + ksort($Fleets); + $parse['fleet_list'] = implode('', $Fleets); + } + + // --- Create other planets thumbnails --- + $Results['planets'] = array(); + + $Order = ($_User['planet_sort_order'] == 1) ? 'DESC' : 'ASC' ; + $Sort = $_User['planet_sort']; + + $QryPlanets = "SELECT * FROM {{table}} WHERE `id_owner` = {$_User['id']} AND `id` != {$_Planet['id']} AND `planet_type` != 3 ORDER BY "; + if($Sort == 0) + { + $QryPlanets .= "`id` {$Order}"; + } + else if($Sort == 1) + { + $QryPlanets .= "`galaxy`, `system`, `planet`, `planet_type` {$Order}"; + } + else if($Sort == 2) + { + $QryPlanets .= "`name` {$Order}"; + } + $parse['OtherPlanets'] = ''; + $AllOtherPlanets = doquery($QryPlanets, 'planets'); + if(mysql_num_rows($AllOtherPlanets) > 0) + { + $InCurrentRow = 0; + $InNextRow = false; + + while($PlanetsData = mysql_fetch_assoc($AllOtherPlanets)) + { + // Show Planet on List + if(empty($DontShowPlanet) OR !in_array($PlanetsData['id'], $DontShowPlanet)) + { + $DontShowThisPlanet = false; + } + else + { + $DontShowThisPlanet = true; + } + if($DontShowThisPlanet === false) + { + if($InCurrentRow == 0) + { + $parse['OtherPlanets'] .= ''; + } + $parse['OtherPlanets'] .= ''.$PlanetsData['name'].'
    '; + $parse['OtherPlanets'] .= "
    "; + $parse['OtherPlanets'] .= '
    '; + } + // Update Planet - Building Queue + if(HandlePlanetUpdate($PlanetsData, $_User, $Now, true) === true) + { + $Results['planets'][] = $PlanetsData; + } + if($PlanetsData['buildQueue_firstEndTime'] > 0) + { + if($DontShowThisPlanet === false) + { + $BuildQueue = $PlanetsData['buildQueue']; + $QueueArray = explode (';', $BuildQueue); + $CurrentBuild = explode (',', $QueueArray[0]); + $BuildElement = $CurrentBuild[0]; + $BuildLevel = $CurrentBuild[1]; + $BuildRestTime = pretty_time($CurrentBuild[3] - $Now); + + $parse['OtherPlanets'] .= $_Lang['tech'][$BuildElement].' ('.$BuildLevel.')'; + $parse['OtherPlanets'] .= '
    ('.$BuildRestTime.')'; + } + } + else + { + if($DontShowThisPlanet === false) + { + $parse['OtherPlanets'] .= $_Lang['Free'].'
     '; + } + } + + if($DontShowThisPlanet === false) + { + $parse['OtherPlanets'] .= '
    '; + } + + if($DontShowThisPlanet === false) + { + $InCurrentRow += 1; + if($InCurrentRow >= 5) + { + $InCurrentRow = 0; + $InNextRow = true; + if($DontShowThisPlanet == false) + { + $parse['OtherPlanets'] .= ''; + } + } + } + } + + if($InNextRow === true AND $InCurrentRow > 0) + { + $Difference = 5 - $InCurrentRow; + for($i = 0; $i < $Difference; $i += 1) + { + $parse['OtherPlanets'] .= ' '; + } + $parse['OtherPlanets'] .= ''; + } + } + else + { + $parse['hide_other_planets'] = 'style="display: none;"'; + } + + // Update this planet (if necessary) + if(HandlePlanetUpdate($_Planet, $_User, $Now, true) === true) + { + $Results['planets'][] = $_Planet; + } + if($_Planet['buildQueue_firstEndTime'] > 0) + { + $BuildQueue = explode(';', $_Planet['buildQueue']); + $CurrBuild = explode(',', $BuildQueue[0]); + $RestTime = $_Planet['buildQueue_firstEndTime'] - $Now; + $PlanetID = $_Planet['id']; + + $Build = ''; + $Build .= InsertJavaScriptChronoApplet('pl', 'this', $RestTime, false, false, 'function() { SetTimer = \"'.$_Lang['BuildJS_Complete'].'\"; document.getElementById(\"dlink\").innerHTML = \''.$_Lang['BuildJS_Continue'].'\'; window.setTimeout(\'document.location.href=\"overview.php?planet='.$PlanetID.'\";\', 1000); }'); + $Build .= $_Lang['tech'][$CurrBuild[0]].' ('.$CurrBuild[1].')'; + $Build .= '
    '.pretty_time($RestTime, true).'
    '; + if(isset($_Vars_PremiumBuildings[$CurrBuild[0]]) && $_Vars_PremiumBuildings[$CurrBuild[0]] == 1) + { + $Build .= ''; + } + else + { + $Build .= ''; + } + + $parse['building'] = $Build; + } + else + { + $parse['building'] = $_Lang['Free']; + } + + // Now update all the planets (if it's necessary) + HandlePlanetUpdate_MultiUpdate($Results, $_User); + + // News Frame ... + if($_GameConfig['OverviewNewsFrame'] == '1') + { + $parse['FromAdmins'] = nl2br($_GameConfig['OverviewNewsText']); + } + if($_GameConfig['OverviewBanner'] == '1') + { + $parse['TopLists_box'] = nl2br($_GameConfig['OverviewClickBanner']); + } + + $parse['referralLink2'] = GAMEURL.'index.php?r='.$_User['id']; + $parse['referralLink1'] = '[url='.$parse['referralLink2'].'][img]'.GAMEURL.'generate_sig.php?uid='.$_User['id'].'[/img][/url]'; + $parse['UserUID'] = $_User['id']; + + $page = parsetemplate(gettemplate('overview_body'), $parse); + display($page, $_Lang['Overview']); + break; +} + +?> diff --git a/phalanx.php b/phalanx.php index 82d5ad741..0ea0e104c 100644 --- a/phalanx.php +++ b/phalanx.php @@ -1,239 +1,239 @@ - 0) - { - $parse = $_Lang; - $ThisCoords = array - ( - 'galaxy' => $ThisMoon['galaxy'], - 'system' => $ThisMoon['system'], - 'planet' => $ThisMoon['planet'] - ); - $ThisPhalanx = $ThisMoon['sensor_phalanx']; - $TargetData = array - ( - 'galaxy' => (isset($_GET['galaxy']) ? intval($_GET['galaxy']) : 0), - 'system' => (isset($_GET['system']) ? intval($_GET['system']) : 0), - 'planet' => (isset($_GET['planet']) ? intval($_GET['planet']) : 0) - ); - - include($_EnginePath.'includes/functions/GetPhalanxRange.php'); - $RangeDown = $ThisCoords['system'] - GetPhalanxRange($ThisPhalanx); - $RangeUp = $ThisCoords['system'] + GetPhalanxRange($ThisPhalanx); - - $DenyScan = false; - if($TargetData['galaxy'] < 1 OR $TargetData['galaxy'] > MAX_GALAXY_IN_WORLD OR $TargetData['system'] < 1 OR $TargetData['system'] > MAX_SYSTEM_IN_GALAXY OR $TargetData['planet'] < 1 OR $TargetData['planet'] > MAX_PLANET_IN_SYSTEM) - { - $DenyScan = true; - $WhyDoNotScan = $_Lang['PhalanxError_BadCoordinates']; - } - if($TargetData['galaxy'] != $ThisCoords['galaxy']) - { - $DenyScan = true; - $WhyDoNotScan = $_Lang['PhalanxError_GalaxyOutOfRange']; - } - if($TargetData['system'] > $RangeUp OR $TargetData['system'] < $RangeDown) - { - $DenyScan = true; - $WhyDoNotScan = $_Lang['PhalanxError_TargetOutOfRange']; - } - if(CheckAuth('supportadmin')) - { - $DenyScan = false; - } - - if($DenyScan !== true) - { - $Query_GetTarget = ''; - $Query_GetTarget .= "SELECT `pl`.`id`, `pl`.`id_owner`, `pl`.`name`, `pl`.`galaxy`, `pl`.`system`, `pl`.`planet`, `users`.`username` "; - $Query_GetTarget .= "FROM {{table}} AS `pl` "; - $Query_GetTarget .= "LEFT JOIN {{prefix}}users AS `users` ON `users`.`id` = `pl`.`id_owner` "; - $Query_GetTarget .= "WHERE "; - $Query_GetTarget .= "`pl`.`galaxy` = {$TargetData['galaxy']} AND "; - $Query_GetTarget .= "`pl`.`system` = {$TargetData['system']} AND "; - $Query_GetTarget .= "`pl`.`planet` = {$TargetData['planet']} AND "; - $Query_GetTarget .= "`pl`.`planet_type` = 1 "; - $Query_GetTarget .= "LIMIT 1; -- Phalanx|GetTarget"; - $Result_GetTarget = doquery($Query_GetTarget, 'planets', true); - - $TargetName = $Result_GetTarget['name']; - $TargetID = $Result_GetTarget['id']; - if($TargetID > 0) - { - // Calculate Fleets - FlyingFleetHandler($ThisMoon, array($TargetID)); - $_DontShowMenus = true; - if($ThisMoon['id'] > 0) - { - if($ThisMoon['deuterium'] >= $ScanCost) - { - if($ScanCost > 0) - { - $ThisMoon['deuterium'] -= $ScanCost; - doquery("UPDATE {{table}} SET `deuterium` = `deuterium` - {$ScanCost} WHERE `id` = {$_User['current_planet']};", 'planets'); - - $UserDev_Log[] = array('PlanetID' => $ThisMoon['id'], 'Date' => $Now, 'Place' => 29, 'Code' => '0', 'ElementID' => '0', 'AdditionalData' => ''); - } - - $parse['Insert_Coord_Galaxy'] = $Result_GetTarget['galaxy']; - $parse['Insert_Coord_System'] = $Result_GetTarget['system']; - $parse['Insert_Coord_Planet'] = $Result_GetTarget['planet']; - if($Result_GetTarget['id_owner'] > 0) - { - $parse['Insert_OwnerName'] = "({$Result_GetTarget['username']})"; - $parse['Insert_TargetName'] = $TargetName; - } - else - { - $parse['Table_Title2'] = ''; - $parse['Insert_TargetName'] = "{$_Lang['Abandoned_planet']}"; - } - $parse['Insert_My_Galaxy'] = $ThisCoords['galaxy']; - $parse['Insert_My_System'] = $ThisCoords['system']; - $parse['Insert_My_Planet'] = $ThisCoords['planet']; - $parse['Insert_MyMoonName'] = $ThisMoon['name']; - $parse['Insert_DeuteriumAmount'] = prettyNumber($ThisMoon['deuterium']); - if($ThisMoon['deuterium'] >= $ScanCost) - { - $parse['Insert_DeuteriumColor'] = 'lime'; - } - else - { - $parse['Insert_DeuteriumColor'] = 'red'; - } - $parse['skinpath'] = $_SkinPath; - - $JoinStartNames = "LEFT JOIN {{prefix}}planets AS `planet1` ON `planet1`.`id` = {{table}}.`fleet_start_id` "; - $JoinEndNames = "LEFT JOIN {{prefix}}planets AS `planet2` ON `planet2`.`id` = {{table}}.`fleet_end_id` "; - $JoinOwnerName = "LEFT JOIN {{prefix}}users AS `usr` ON `usr`.`id` = {{table}}.`fleet_owner`"; - $JoinACS = "LEFT JOIN {{prefix}}acs AS `get_acs` ON `main_fleet_id` = `fleet_id`"; - - $Query_GetFleets = ''; - $Query_GetFleets .= "SELECT {{table}}.*, `planet1`.`name` as `start_name`, `planet2`.`name` as `end_name`, `get_acs`.`fleets_id`, `usr`.`username` AS `owner_name` "; - $Query_GetFleets .= "FROM {{table}} "; - $Query_GetFleets .= "{$JoinStartNames} {$JoinEndNames} {$JoinOwnerName} {$JoinACS} "; - $Query_GetFleets .= "WHERE "; - $Query_GetFleets .= "`fleet_start_id` = {$TargetID} OR `fleet_end_id` = {$TargetID} "; - $Query_GetFleets .= "; -- Phalanx|GetFleets"; - $Result_GetFleets = doquery($Query_GetFleets, 'fleets'); - - $parse['phl_fleets_table'] = $_Lang['PhalanxInfo_NoMovements']; - if(mysql_num_rows($Result_GetFleets) > 0) - { - include($_EnginePath.'includes/functions/BuildFleetEventTable.php'); - $Record = 0; - while($FleetRow = mysql_fetch_assoc($Result_GetFleets)) - { - $Record += 1; - - $StartTime = $FleetRow['fleet_start_time']; - $StayTime = $FleetRow['fleet_end_stay']; - $EndTime = $FleetRow['fleet_end_time']; - - if($FleetRow['fleet_owner'] == $Result_GetTarget['id_owner']) - { - $FleetType = true; - } - else - { - $FleetType = false; - } - - $FleetRow['fleet_resource_metal'] = 0; - $FleetRow['fleet_resource_crystal'] = 0; - $FleetRow['fleet_resource_deuterium'] = 0; - if(!empty($FleetRow['fleets_id'])) - { - $FleetRow['fleet_mission'] = 2; - } - if($StartTime > $Now) - { - $Label = 'fs'; - $fpage[$StartTime.str_pad($FleetRow['fleet_id'], 20, '0', STR_PAD_LEFT)] = BuildFleetEventTable($FleetRow, 0, $FleetType, $Label, $Record, true); - } - if($FleetRow['fleet_mission'] != 4) - { - $Label = 'ft'; - if($StayTime > $Now) - { - $fpage[$StayTime.str_pad($FleetRow['fleet_id'], 20, '0', STR_PAD_LEFT)] = BuildFleetEventTable($FleetRow, 1, $FleetType, $Label, $Record, true); - } - if($FleetType == true) - { - $Label = 'fe'; - if($EndTime > $Now) - { - $fpage[$EndTime.str_pad($FleetRow['fleet_id'], 20, '0', STR_PAD_LEFT)] = BuildFleetEventTable($FleetRow, 2, $FleetType, $Label, $Record, true); - } - } - } - } - if(!empty($fpage)) - { - ksort($fpage, SORT_STRING); - $parse['phl_fleets_table'] = implode('', $fpage); - } - } - $page = parsetemplate($PageTPL, $parse); - } - else - { - message(sprintf($_Lang['PhalanxError_NoEnoughFuel'], prettyNumber($ScanCost)), $PageTitle); - } - } - else - { - message($_Lang['PhalanxError_MoonDestroyed'], $PageTitle); - } - } - else - { - message($_Lang['PhalanxError_CoordsEmpty'], $PageTitle); - } - } - else - { - message($WhyDoNotScan, $PageTitle); - } - } - else - { - message($_Lang['PhalanxError_NoPhalanxHere'], $PageTitle); - } - } - else - { - message($_Lang['PhalanxError_ScanOnlyFromMoon'], $PageTitle); - } - - display($page, $PageTitle, false); - -?> \ No newline at end of file + 0) + { + $parse = $_Lang; + $ThisCoords = array + ( + 'galaxy' => $ThisMoon['galaxy'], + 'system' => $ThisMoon['system'], + 'planet' => $ThisMoon['planet'] + ); + $ThisPhalanx = $ThisMoon['sensor_phalanx']; + $TargetData = array + ( + 'galaxy' => (isset($_GET['galaxy']) ? intval($_GET['galaxy']) : 0), + 'system' => (isset($_GET['system']) ? intval($_GET['system']) : 0), + 'planet' => (isset($_GET['planet']) ? intval($_GET['planet']) : 0) + ); + + include($_EnginePath.'includes/functions/GetPhalanxRange.php'); + $RangeDown = $ThisCoords['system'] - GetPhalanxRange($ThisPhalanx); + $RangeUp = $ThisCoords['system'] + GetPhalanxRange($ThisPhalanx); + + $DenyScan = false; + if($TargetData['galaxy'] < 1 OR $TargetData['galaxy'] > MAX_GALAXY_IN_WORLD OR $TargetData['system'] < 1 OR $TargetData['system'] > MAX_SYSTEM_IN_GALAXY OR $TargetData['planet'] < 1 OR $TargetData['planet'] > MAX_PLANET_IN_SYSTEM) + { + $DenyScan = true; + $WhyDoNotScan = $_Lang['PhalanxError_BadCoordinates']; + } + if($TargetData['galaxy'] != $ThisCoords['galaxy']) + { + $DenyScan = true; + $WhyDoNotScan = $_Lang['PhalanxError_GalaxyOutOfRange']; + } + if($TargetData['system'] > $RangeUp OR $TargetData['system'] < $RangeDown) + { + $DenyScan = true; + $WhyDoNotScan = $_Lang['PhalanxError_TargetOutOfRange']; + } + if(CheckAuth('supportadmin')) + { + $DenyScan = false; + } + + if($DenyScan !== true) + { + $Query_GetTarget = ''; + $Query_GetTarget .= "SELECT `pl`.`id`, `pl`.`id_owner`, `pl`.`name`, `pl`.`galaxy`, `pl`.`system`, `pl`.`planet`, `users`.`username` "; + $Query_GetTarget .= "FROM {{table}} AS `pl` "; + $Query_GetTarget .= "LEFT JOIN {{prefix}}users AS `users` ON `users`.`id` = `pl`.`id_owner` "; + $Query_GetTarget .= "WHERE "; + $Query_GetTarget .= "`pl`.`galaxy` = {$TargetData['galaxy']} AND "; + $Query_GetTarget .= "`pl`.`system` = {$TargetData['system']} AND "; + $Query_GetTarget .= "`pl`.`planet` = {$TargetData['planet']} AND "; + $Query_GetTarget .= "`pl`.`planet_type` = 1 "; + $Query_GetTarget .= "LIMIT 1; -- Phalanx|GetTarget"; + $Result_GetTarget = doquery($Query_GetTarget, 'planets', true); + + $TargetName = $Result_GetTarget['name']; + $TargetID = $Result_GetTarget['id']; + if($TargetID > 0) + { + // Calculate Fleets + FlyingFleetHandler($ThisMoon, array($TargetID)); + $_DontShowMenus = true; + if($ThisMoon['id'] > 0) + { + if($ThisMoon['deuterium'] >= $ScanCost) + { + if($ScanCost > 0) + { + $ThisMoon['deuterium'] -= $ScanCost; + doquery("UPDATE {{table}} SET `deuterium` = `deuterium` - {$ScanCost} WHERE `id` = {$_User['current_planet']};", 'planets'); + + $UserDev_Log[] = array('PlanetID' => $ThisMoon['id'], 'Date' => $Now, 'Place' => 29, 'Code' => '0', 'ElementID' => '0', 'AdditionalData' => ''); + } + + $parse['Insert_Coord_Galaxy'] = $Result_GetTarget['galaxy']; + $parse['Insert_Coord_System'] = $Result_GetTarget['system']; + $parse['Insert_Coord_Planet'] = $Result_GetTarget['planet']; + if($Result_GetTarget['id_owner'] > 0) + { + $parse['Insert_OwnerName'] = "({$Result_GetTarget['username']})"; + $parse['Insert_TargetName'] = $TargetName; + } + else + { + $parse['Table_Title2'] = ''; + $parse['Insert_TargetName'] = "{$_Lang['Abandoned_planet']}"; + } + $parse['Insert_My_Galaxy'] = $ThisCoords['galaxy']; + $parse['Insert_My_System'] = $ThisCoords['system']; + $parse['Insert_My_Planet'] = $ThisCoords['planet']; + $parse['Insert_MyMoonName'] = $ThisMoon['name']; + $parse['Insert_DeuteriumAmount'] = prettyNumber($ThisMoon['deuterium']); + if($ThisMoon['deuterium'] >= $ScanCost) + { + $parse['Insert_DeuteriumColor'] = 'lime'; + } + else + { + $parse['Insert_DeuteriumColor'] = 'red'; + } + $parse['skinpath'] = $_SkinPath; + + $JoinStartNames = "LEFT JOIN {{prefix}}planets AS `planet1` ON `planet1`.`id` = {{table}}.`fleet_start_id` "; + $JoinEndNames = "LEFT JOIN {{prefix}}planets AS `planet2` ON `planet2`.`id` = {{table}}.`fleet_end_id` "; + $JoinOwnerName = "LEFT JOIN {{prefix}}users AS `usr` ON `usr`.`id` = {{table}}.`fleet_owner`"; + $JoinACS = "LEFT JOIN {{prefix}}acs AS `get_acs` ON `main_fleet_id` = `fleet_id`"; + + $Query_GetFleets = ''; + $Query_GetFleets .= "SELECT {{table}}.*, `planet1`.`name` as `start_name`, `planet2`.`name` as `end_name`, `get_acs`.`fleets_id`, `usr`.`username` AS `owner_name` "; + $Query_GetFleets .= "FROM {{table}} "; + $Query_GetFleets .= "{$JoinStartNames} {$JoinEndNames} {$JoinOwnerName} {$JoinACS} "; + $Query_GetFleets .= "WHERE "; + $Query_GetFleets .= "`fleet_start_id` = {$TargetID} OR `fleet_end_id` = {$TargetID} "; + $Query_GetFleets .= "; -- Phalanx|GetFleets"; + $Result_GetFleets = doquery($Query_GetFleets, 'fleets'); + + $parse['phl_fleets_table'] = $_Lang['PhalanxInfo_NoMovements']; + if(mysql_num_rows($Result_GetFleets) > 0) + { + include($_EnginePath.'includes/functions/BuildFleetEventTable.php'); + $Record = 0; + while($FleetRow = mysql_fetch_assoc($Result_GetFleets)) + { + $Record += 1; + + $StartTime = $FleetRow['fleet_start_time']; + $StayTime = $FleetRow['fleet_end_stay']; + $EndTime = $FleetRow['fleet_end_time']; + + if($FleetRow['fleet_owner'] == $Result_GetTarget['id_owner']) + { + $FleetType = true; + } + else + { + $FleetType = false; + } + + $FleetRow['fleet_resource_metal'] = 0; + $FleetRow['fleet_resource_crystal'] = 0; + $FleetRow['fleet_resource_deuterium'] = 0; + if(!empty($FleetRow['fleets_id'])) + { + $FleetRow['fleet_mission'] = 2; + } + if($StartTime > $Now) + { + $Label = 'fs'; + $fpage[$StartTime.str_pad($FleetRow['fleet_id'], 20, '0', STR_PAD_LEFT)] = BuildFleetEventTable($FleetRow, 0, $FleetType, $Label, $Record, true); + } + if($FleetRow['fleet_mission'] != 4) + { + $Label = 'ft'; + if($StayTime > $Now) + { + $fpage[$StayTime.str_pad($FleetRow['fleet_id'], 20, '0', STR_PAD_LEFT)] = BuildFleetEventTable($FleetRow, 1, $FleetType, $Label, $Record, true); + } + if($FleetType == true) + { + $Label = 'fe'; + if($EndTime > $Now) + { + $fpage[$EndTime.str_pad($FleetRow['fleet_id'], 20, '0', STR_PAD_LEFT)] = BuildFleetEventTable($FleetRow, 2, $FleetType, $Label, $Record, true); + } + } + } + } + if(!empty($fpage)) + { + ksort($fpage, SORT_STRING); + $parse['phl_fleets_table'] = implode('', $fpage); + } + } + $page = parsetemplate($PageTPL, $parse); + } + else + { + message(sprintf($_Lang['PhalanxError_NoEnoughFuel'], prettyNumber($ScanCost)), $PageTitle); + } + } + else + { + message($_Lang['PhalanxError_MoonDestroyed'], $PageTitle); + } + } + else + { + message($_Lang['PhalanxError_CoordsEmpty'], $PageTitle); + } + } + else + { + message($WhyDoNotScan, $PageTitle); + } + } + else + { + message($_Lang['PhalanxError_NoPhalanxHere'], $PageTitle); + } +} +else +{ + message($_Lang['PhalanxError_ScanOnlyFromMoon'], $PageTitle); +} + +display($page, $PageTitle, false); + +?> diff --git a/phpcs.xml b/phpcs.xml index 39bd69507..1a5448c52 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -2,6 +2,12 @@ Created with the PHP Coding Standard Generator. http://edorian.github.com/php-coding-standard-generator/ +*/class/Smarty/* +*/includes/phpmailer/* +*/action_logs/* +*/cache/* +*/tmp/* +*/vendor/* diff --git a/polls.php b/polls.php index d9515bfd3..9929e5859 100644 --- a/polls.php +++ b/polls.php @@ -1,321 +1,321 @@ - 0) - { - $Query_PollData = ''; - $Query_PollData .= "SELECT `poll`.*, `votes`.`id` AS `vote_id`, `votes`.`answer` "; - $Query_PollData .= "FROM {{table}} AS `poll` "; - $Query_PollData .= "LEFT JOIN `{{prefix}}poll_votes` AS `votes` ON `votes`.`poll_id` = `poll`.`id` AND `votes`.`user_id` = {$_User['id']} "; - $Query_PollData .= "WHERE `poll`.`id` = {$PollID} LIMIT 1; -- Polls|PollData"; - $SelectPoll = doquery($Query_PollData, 'polls', true); - - if($SelectPoll['id'] != $PollID) - { - message($_Lang['Poll_doesnt_exist'], $_Lang['Title'], $_BackLink, 3); - } - if($SelectPoll['open'] != 1 AND $SelectPoll['show_results'] != 1) - { - message($_Lang['Poll_is_closed_for_view'], $_Lang['Title'], $_BackLink, 3); - } - - $Answers = explode(';', $SelectPoll['answers']); - foreach($Answers as $Key => $Value) - { - if(!empty($Value)) - { - $AvailableAnswers[] = $Key; - $AnswersArray[$Key] = $Value; - } - } - if(empty($AvailableAnswers)) - { - message($_Lang['Error_NoAnswers'], $_Lang['Title'], $_BackLink, 3); - } - - if(isset($_POST['send']) && $_POST['send'] == 1) - { - $_BackLink = 'polls.php?pid='.$PollID; - if($SelectPoll['open'] != 1) - { - message($_Lang['Poll_is_closed'], $_Lang['Title'], $_BackLink, 3); - } - if(isset($_POST['vote']) && $_POST['vote'] != null) - { - if($SelectPoll['Opt_Multivote'] == 0) - { - $Vote = intval($_POST['vote']); - if(!in_array($Vote, $AvailableAnswers)) - { - message($_Lang['No_selected_answer'], $_Lang['Title'], $_BackLink, 3); - } - } - else - { - if(!empty($_POST['vote'])) - { - foreach($_POST['vote'] as $Key => $Value) - { - if($Value == 'on' AND in_array($Key, $AvailableAnswers)) - { - $Votes[] = $Key; - } - } - } - if(empty($Votes)) - { - message($_Lang['Error_BadSelection_Multi'], $_Lang['Title'], $_BackLink, 3); - } - $Vote = implode(',', $Votes); - } - - if($SelectPoll['vote_id'] == null) - { - doquery("INSERT INTO {{table}} VALUES (NULL, {$PollID}, {$_User['id']}, '{$Vote}', UNIX_TIMESTAMP());", 'poll_votes'); - message($_Lang['Thx_for_voting'], $_Lang['Title'], $_BackLink, 3); - } - else - { - doquery("UPDATE {{table}} SET `answer` = '{$Vote}', `time` = UNIX_TIMESTAMP() WHERE `id` = {$SelectPoll['vote_id']};", 'poll_votes'); - message($_Lang['Thx_for_chaning_vote'], $_Lang['Title'], $_BackLink, 3); - } - } - else - { - message($_Lang['Error_NoOptionSelected'], $_Lang['Title'], $_BackLink, 3); - } - } - else - { - $IsOpen = ($SelectPoll['open'] == 1 ? true : false); - $AllVotes = 0; - - if($SelectPoll['show_results'] == 1 OR CheckAuth('supportadmin')) - { - $ShowResult = true; - - if(CheckAuth('supportadmin')) - { - $TPL_Voting_Username = gettemplate('polls_voting_username'); - $Query_GetVotes = ''; - $Query_GetVotes .= "SELECT `votes`.`answer`, `votes`.`user_id` AS `uid`, `users`.`username` "; - $Query_GetVotes .= "FROM {{table}} AS `votes` "; - $Query_GetVotes .= "LEFT JOIN `{{prefix}}users` AS `users` ON `votes`.`user_id` = `users`.`id` "; - $Query_GetVotes .= "WHERE `votes`.`poll_id` = {$PollID}; -- Polls|GetVotes|Admin"; - $SelectVotes = doquery($Query_GetVotes, 'poll_votes'); - while($Votes = mysql_fetch_assoc($SelectVotes)) - { - $Votes['answer'] = explode(',', $Votes['answer']); - foreach($Votes['answer'] as $ThisAnswer) - { - if(!isset($Results[$ThisAnswer])) - { - $Results[$ThisAnswer] = 0; - } - $Results[$ThisAnswer] += 1; - $AllVotes += 1; - if(empty($Votes['username'])) - { - $Votes['username'] = "{$_Lang['User_Deleted']}"; - } - $UserVotes[$ThisAnswer][] = parsetemplate($TPL_Voting_Username, array('UID' => $Votes['uid'], 'Username' => $Votes['username'])); - } - } - } - else - { - $Query_GetVotes = ''; - $Query_GetVotes .= "SELECT `answer`, COUNT(*) AS `Count` "; - $Query_GetVotes .= "FROM {{table}} "; - $Query_GetVotes .= "WHERE `poll_id` = {$PollID} "; - $Query_GetVotes .= "GROUP BY `answer`; "; - $Query_GetVotes .= "-- Polls|GetVotes|User"; - $SelectVotes = doquery($Query_GetVotes, 'poll_votes'); - - if($SelectPoll['Opt_Multivote'] == 0) - { - while($Votes = mysql_fetch_assoc($SelectVotes)) - { - if(!isset($Results[$Votes['answer']])) - { - $Results[$Votes['answer']] = 0; - } - $Results[$Votes['answer']] += $Votes['Count']; - $AllVotes += $Votes['Count']; - } - } - else - { - while($Votes = mysql_fetch_assoc($SelectVotes)) - { - $Votes['answer'] = explode(',', $Votes['answer']); - foreach($Votes['answer'] as $ThisAnswer) - { - if(!isset($Results[$ThisAnswer])) - { - $Results[$ThisAnswer] = 0; - } - $Results[$ThisAnswer] += $Votes['Count']; - $AllVotes += $Votes['Count']; - } - } - } - } - } - else - { - $_Lang['PollResultsInfo'] = parsetemplate(gettemplate('_singleRow'), array('Classes' => 'orange pad5', 'Colspan' => '3', 'Text' => $_Lang['ResultsAreHidden'])); - } - - $_Lang['PollID'] = $PollID; - $_Lang['PollName'] = $SelectPoll['name']; - if(!empty($SelectPoll['desc'])) - { - $_Lang['PollDesc'] = $SelectPoll['desc']; - } - else - { - $_Lang['PollDescHide'] = ' style="display: none;"'; - } - if($SelectPoll['open'] == 1) - { - if($SelectPoll['vote_id'] == null) - { - $_Lang['Vote_or_change'] = $_Lang['Vote_now']; - $_Lang['Insert_SubmitColor'] = 'lime'; - } - else - { - $_Lang['Vote_or_change'] = $_Lang['Change_vote']; - $_Lang['Insert_SubmitColor'] = 'orange'; - } - } - else - { - $_Lang['Vote_or_change'] = $_Lang['Submit_PollLocked']; - $_Lang['Insert_SubmitColor'] = 'red'; - $_Lang['Insert_SubmitDisable'] = 'disabled'; - } - - $TPL_Voting_Row_Template = ($SelectPoll['Opt_Multivote'] == 1 ? 'polls_voting_row_multi' : 'polls_voting_row_single'); - $TPL_Voting_Row = gettemplate($TPL_Voting_Row_Template); - $SelectPoll['userAnswers'] = explode(',', $SelectPoll['answer']); - foreach($AnswersArray as $Key => $Value) - { - $Key = (string)($Key + 0); - $ThisValue = array(); - - $VotingResult = ''; - if($ShowResult === true) - { - $ThisValue['voteResult_Count'] = (isset($Results[$Key]) && $Results[$Key] > 0 ? $Results[$Key] : '0'); - $ThisValue['voteResult_Percent'] = ((isset($Results[$Key]) && $AllVotes > 0) ? round(($Results[$Key] / $AllVotes) * 100, 1) : '0'); - if($SelectPoll['vote_id'] > 0 AND in_array($Key, $SelectPoll['userAnswers'])) - { - $ThisValue['voteResult_Color'] = 'orange'; - } - } - else - { - $VotingResult = '-'; - } - $ThisValue['voteNo'] = $Key; - if(!$IsOpen) - { - $ThisValue['voteDisable'] = 'disabled'; - } - if($SelectPoll['vote_id'] > 0 AND in_array($Key, $SelectPoll['userAnswers'])) - { - $ThisValue['voteCheck'] = 'checked'; - } - $ThisValue['voteAnswerName'] = $Value; - if(!empty($UserVotes[$Key])) - { - $ThisValue['voteResult_Usernames'] = implode('
    ', $UserVotes[$Key]); - } - - $_Lang['Insert_PollAnswers'][] = parsetemplate($TPL_Voting_Row, $ThisValue); - } - $_Lang['Insert_PollAnswers'] = implode('', $_Lang['Insert_PollAnswers']); - } - - if(CheckAuth('supportadmin')) - { - $_Lang['ShowUsersLink'] = ' ['.$_Lang['ShowUsers'].']'; - } - - $page = parsetemplate(gettemplate('polls_voting'), $_Lang); - } - else - { - $Query_GetPolls = ''; - $Query_GetPolls .= "SELECT `poll`.`id`, `poll`.`name`, `poll`.`time`, `poll`.`open`, `poll`.`show_results`, `poll`.`obligatory`, `votes`.`id` AS `vote_id` "; - $Query_GetPolls .= "FROM `{{table}}` AS `poll` "; - $Query_GetPolls .= "LEFT JOIN `{{prefix}}poll_votes` AS `votes` ON `votes`.`poll_id` = `poll`.`id` AND `votes`.`user_id` = {$_User['id']} "; - $Query_GetPolls .= "WHERE `open` = 1 OR `show_results` = 1 "; - $Query_GetPolls .= "; -- Polls|GetPolls"; - $Result_GetPolls = doquery($Query_GetPolls, 'polls'); - - if(mysql_num_rows($Result_GetPolls) > 0) - { - $TPL_List_Row = gettemplate('polls_list_row'); - while($FetchData = mysql_fetch_assoc($Result_GetPolls)) - { - $CreateKey = (($FetchData['vote_id'] > 0 OR $FetchData['open'] == 0) ? '1' : '2').($FetchData['obligatory'] == 0 ? '1' : '2').($FetchData['open'] == 0 ? '1' : '2').$FetchData['time'].str_pad($FetchData['id'], 10, '0', STR_PAD_LEFT); - $FetchData['Insert_PollID'] = $FetchData['id']; - $FetchData['Insert_PollName'] = $FetchData['name']; - - if($FetchData['open'] == 0) - { - $FetchData['Insert_StateClass'][] = 'locked'; - $FetchData['Insert_PollState'][] = $_Lang['State_IsClosed']; - } - if($FetchData['vote_id'] > 0) - { - $FetchData['Insert_StateClass'][] = 'voted'; - $FetchData['Insert_PollState'][] = $_Lang['State_IsVoted']; - } - if($FetchData['obligatory'] == 1 AND $FetchData['open'] == 1 AND $FetchData['vote_id'] == null) - { - $FetchData['Insert_StateClass'][] = 'obligatory orange'; - $FetchData['Insert_PollState'][] = $_Lang['State_IsObligatory']; - } - if(!empty($FetchData['Insert_StateClass'])) - { - $FetchData['Insert_StateClass'] = implode(' ', $FetchData['Insert_StateClass']); - } - if(!empty($FetchData['Insert_PollState'])) - { - $FetchData['Insert_PollState'] = implode(' ', $FetchData['Insert_PollState']); - } - - $_Lang['Insert_PollRows'][$CreateKey] = parsetemplate($TPL_List_Row, $FetchData); - } - krsort($_Lang['Insert_PollRows'], SORT_STRING); - $_Lang['Insert_PollRows'] = implode('', $_Lang['Insert_PollRows']); - } - else - { - $_Lang['Insert_PollRows'] = parsetemplate(gettemplate('_singleRow'), array('Classes' => 'pad5 orange info', 'Text' => $_Lang['no_polls'])); - } - - $page = parsetemplate(gettemplate('polls_list_body'), $_Lang); - } - - display($page,$_Lang['Title'], false); - -?> \ No newline at end of file + 0) +{ + $Query_PollData = ''; + $Query_PollData .= "SELECT `poll`.*, `votes`.`id` AS `vote_id`, `votes`.`answer` "; + $Query_PollData .= "FROM {{table}} AS `poll` "; + $Query_PollData .= "LEFT JOIN `{{prefix}}poll_votes` AS `votes` ON `votes`.`poll_id` = `poll`.`id` AND `votes`.`user_id` = {$_User['id']} "; + $Query_PollData .= "WHERE `poll`.`id` = {$PollID} LIMIT 1; -- Polls|PollData"; + $SelectPoll = doquery($Query_PollData, 'polls', true); + + if($SelectPoll['id'] != $PollID) + { + message($_Lang['Poll_doesnt_exist'], $_Lang['Title'], $_BackLink, 3); + } + if($SelectPoll['open'] != 1 AND $SelectPoll['show_results'] != 1) + { + message($_Lang['Poll_is_closed_for_view'], $_Lang['Title'], $_BackLink, 3); + } + + $Answers = explode(';', $SelectPoll['answers']); + foreach($Answers as $Key => $Value) + { + if(!empty($Value)) + { + $AvailableAnswers[] = $Key; + $AnswersArray[$Key] = $Value; + } + } + if(empty($AvailableAnswers)) + { + message($_Lang['Error_NoAnswers'], $_Lang['Title'], $_BackLink, 3); + } + + if(isset($_POST['send']) && $_POST['send'] == 1) + { + $_BackLink = 'polls.php?pid='.$PollID; + if($SelectPoll['open'] != 1) + { + message($_Lang['Poll_is_closed'], $_Lang['Title'], $_BackLink, 3); + } + if(isset($_POST['vote']) && $_POST['vote'] != null) + { + if($SelectPoll['Opt_Multivote'] == 0) + { + $Vote = intval($_POST['vote']); + if(!in_array($Vote, $AvailableAnswers)) + { + message($_Lang['No_selected_answer'], $_Lang['Title'], $_BackLink, 3); + } + } + else + { + if(!empty($_POST['vote'])) + { + foreach($_POST['vote'] as $Key => $Value) + { + if($Value == 'on' AND in_array($Key, $AvailableAnswers)) + { + $Votes[] = $Key; + } + } + } + if(empty($Votes)) + { + message($_Lang['Error_BadSelection_Multi'], $_Lang['Title'], $_BackLink, 3); + } + $Vote = implode(',', $Votes); + } + + if($SelectPoll['vote_id'] == null) + { + doquery("INSERT INTO {{table}} VALUES (NULL, {$PollID}, {$_User['id']}, '{$Vote}', UNIX_TIMESTAMP());", 'poll_votes'); + message($_Lang['Thx_for_voting'], $_Lang['Title'], $_BackLink, 3); + } + else + { + doquery("UPDATE {{table}} SET `answer` = '{$Vote}', `time` = UNIX_TIMESTAMP() WHERE `id` = {$SelectPoll['vote_id']};", 'poll_votes'); + message($_Lang['Thx_for_chaning_vote'], $_Lang['Title'], $_BackLink, 3); + } + } + else + { + message($_Lang['Error_NoOptionSelected'], $_Lang['Title'], $_BackLink, 3); + } + } + else + { + $IsOpen = ($SelectPoll['open'] == 1 ? true : false); + $AllVotes = 0; + + if($SelectPoll['show_results'] == 1 OR CheckAuth('supportadmin')) + { + $ShowResult = true; + + if(CheckAuth('supportadmin')) + { + $TPL_Voting_Username = gettemplate('polls_voting_username'); + $Query_GetVotes = ''; + $Query_GetVotes .= "SELECT `votes`.`answer`, `votes`.`user_id` AS `uid`, `users`.`username` "; + $Query_GetVotes .= "FROM {{table}} AS `votes` "; + $Query_GetVotes .= "LEFT JOIN `{{prefix}}users` AS `users` ON `votes`.`user_id` = `users`.`id` "; + $Query_GetVotes .= "WHERE `votes`.`poll_id` = {$PollID}; -- Polls|GetVotes|Admin"; + $SelectVotes = doquery($Query_GetVotes, 'poll_votes'); + while($Votes = mysql_fetch_assoc($SelectVotes)) + { + $Votes['answer'] = explode(',', $Votes['answer']); + foreach($Votes['answer'] as $ThisAnswer) + { + if(!isset($Results[$ThisAnswer])) + { + $Results[$ThisAnswer] = 0; + } + $Results[$ThisAnswer] += 1; + $AllVotes += 1; + if(empty($Votes['username'])) + { + $Votes['username'] = "{$_Lang['User_Deleted']}"; + } + $UserVotes[$ThisAnswer][] = parsetemplate($TPL_Voting_Username, array('UID' => $Votes['uid'], 'Username' => $Votes['username'])); + } + } + } + else + { + $Query_GetVotes = ''; + $Query_GetVotes .= "SELECT `answer`, COUNT(*) AS `Count` "; + $Query_GetVotes .= "FROM {{table}} "; + $Query_GetVotes .= "WHERE `poll_id` = {$PollID} "; + $Query_GetVotes .= "GROUP BY `answer`; "; + $Query_GetVotes .= "-- Polls|GetVotes|User"; + $SelectVotes = doquery($Query_GetVotes, 'poll_votes'); + + if($SelectPoll['Opt_Multivote'] == 0) + { + while($Votes = mysql_fetch_assoc($SelectVotes)) + { + if(!isset($Results[$Votes['answer']])) + { + $Results[$Votes['answer']] = 0; + } + $Results[$Votes['answer']] += $Votes['Count']; + $AllVotes += $Votes['Count']; + } + } + else + { + while($Votes = mysql_fetch_assoc($SelectVotes)) + { + $Votes['answer'] = explode(',', $Votes['answer']); + foreach($Votes['answer'] as $ThisAnswer) + { + if(!isset($Results[$ThisAnswer])) + { + $Results[$ThisAnswer] = 0; + } + $Results[$ThisAnswer] += $Votes['Count']; + $AllVotes += $Votes['Count']; + } + } + } + } + } + else + { + $_Lang['PollResultsInfo'] = parsetemplate(gettemplate('_singleRow'), array('Classes' => 'orange pad5', 'Colspan' => '3', 'Text' => $_Lang['ResultsAreHidden'])); + } + + $_Lang['PollID'] = $PollID; + $_Lang['PollName'] = $SelectPoll['name']; + if(!empty($SelectPoll['desc'])) + { + $_Lang['PollDesc'] = $SelectPoll['desc']; + } + else + { + $_Lang['PollDescHide'] = ' style="display: none;"'; + } + if($SelectPoll['open'] == 1) + { + if($SelectPoll['vote_id'] == null) + { + $_Lang['Vote_or_change'] = $_Lang['Vote_now']; + $_Lang['Insert_SubmitColor'] = 'lime'; + } + else + { + $_Lang['Vote_or_change'] = $_Lang['Change_vote']; + $_Lang['Insert_SubmitColor'] = 'orange'; + } + } + else + { + $_Lang['Vote_or_change'] = $_Lang['Submit_PollLocked']; + $_Lang['Insert_SubmitColor'] = 'red'; + $_Lang['Insert_SubmitDisable'] = 'disabled'; + } + + $TPL_Voting_Row_Template = ($SelectPoll['Opt_Multivote'] == 1 ? 'polls_voting_row_multi' : 'polls_voting_row_single'); + $TPL_Voting_Row = gettemplate($TPL_Voting_Row_Template); + $SelectPoll['userAnswers'] = explode(',', $SelectPoll['answer']); + foreach($AnswersArray as $Key => $Value) + { + $Key = (string)($Key + 0); + $ThisValue = array(); + + $VotingResult = ''; + if($ShowResult === true) + { + $ThisValue['voteResult_Count'] = (isset($Results[$Key]) && $Results[$Key] > 0 ? $Results[$Key] : '0'); + $ThisValue['voteResult_Percent'] = ((isset($Results[$Key]) && $AllVotes > 0) ? round(($Results[$Key] / $AllVotes) * 100, 1) : '0'); + if($SelectPoll['vote_id'] > 0 AND in_array($Key, $SelectPoll['userAnswers'])) + { + $ThisValue['voteResult_Color'] = 'orange'; + } + } + else + { + $VotingResult = '-'; + } + $ThisValue['voteNo'] = $Key; + if(!$IsOpen) + { + $ThisValue['voteDisable'] = 'disabled'; + } + if($SelectPoll['vote_id'] > 0 AND in_array($Key, $SelectPoll['userAnswers'])) + { + $ThisValue['voteCheck'] = 'checked'; + } + $ThisValue['voteAnswerName'] = $Value; + if(!empty($UserVotes[$Key])) + { + $ThisValue['voteResult_Usernames'] = implode('
    ', $UserVotes[$Key]); + } + + $_Lang['Insert_PollAnswers'][] = parsetemplate($TPL_Voting_Row, $ThisValue); + } + $_Lang['Insert_PollAnswers'] = implode('', $_Lang['Insert_PollAnswers']); + } + + if(CheckAuth('supportadmin')) + { + $_Lang['ShowUsersLink'] = ' ['.$_Lang['ShowUsers'].']'; + } + + $page = parsetemplate(gettemplate('polls_voting'), $_Lang); +} +else +{ + $Query_GetPolls = ''; + $Query_GetPolls .= "SELECT `poll`.`id`, `poll`.`name`, `poll`.`time`, `poll`.`open`, `poll`.`show_results`, `poll`.`obligatory`, `votes`.`id` AS `vote_id` "; + $Query_GetPolls .= "FROM `{{table}}` AS `poll` "; + $Query_GetPolls .= "LEFT JOIN `{{prefix}}poll_votes` AS `votes` ON `votes`.`poll_id` = `poll`.`id` AND `votes`.`user_id` = {$_User['id']} "; + $Query_GetPolls .= "WHERE `open` = 1 OR `show_results` = 1 "; + $Query_GetPolls .= "; -- Polls|GetPolls"; + $Result_GetPolls = doquery($Query_GetPolls, 'polls'); + + if(mysql_num_rows($Result_GetPolls) > 0) + { + $TPL_List_Row = gettemplate('polls_list_row'); + while($FetchData = mysql_fetch_assoc($Result_GetPolls)) + { + $CreateKey = (($FetchData['vote_id'] > 0 OR $FetchData['open'] == 0) ? '1' : '2').($FetchData['obligatory'] == 0 ? '1' : '2').($FetchData['open'] == 0 ? '1' : '2').$FetchData['time'].str_pad($FetchData['id'], 10, '0', STR_PAD_LEFT); + $FetchData['Insert_PollID'] = $FetchData['id']; + $FetchData['Insert_PollName'] = $FetchData['name']; + + if($FetchData['open'] == 0) + { + $FetchData['Insert_StateClass'][] = 'locked'; + $FetchData['Insert_PollState'][] = $_Lang['State_IsClosed']; + } + if($FetchData['vote_id'] > 0) + { + $FetchData['Insert_StateClass'][] = 'voted'; + $FetchData['Insert_PollState'][] = $_Lang['State_IsVoted']; + } + if($FetchData['obligatory'] == 1 AND $FetchData['open'] == 1 AND $FetchData['vote_id'] == null) + { + $FetchData['Insert_StateClass'][] = 'obligatory orange'; + $FetchData['Insert_PollState'][] = $_Lang['State_IsObligatory']; + } + if(!empty($FetchData['Insert_StateClass'])) + { + $FetchData['Insert_StateClass'] = implode(' ', $FetchData['Insert_StateClass']); + } + if(!empty($FetchData['Insert_PollState'])) + { + $FetchData['Insert_PollState'] = implode(' ', $FetchData['Insert_PollState']); + } + + $_Lang['Insert_PollRows'][$CreateKey] = parsetemplate($TPL_List_Row, $FetchData); + } + krsort($_Lang['Insert_PollRows'], SORT_STRING); + $_Lang['Insert_PollRows'] = implode('', $_Lang['Insert_PollRows']); + } + else + { + $_Lang['Insert_PollRows'] = parsetemplate(gettemplate('_singleRow'), array('Classes' => 'pad5 orange info', 'Text' => $_Lang['no_polls'])); + } + + $page = parsetemplate(gettemplate('polls_list_body'), $_Lang); +} + +display($page,$_Lang['Title'], false); + +?> diff --git a/profile.php b/profile.php index 0d9d9622d..385938b7c 100644 --- a/profile.php +++ b/profile.php @@ -1,281 +1,281 @@ - 0) - { - $GetAlly = doquery("SELECT * FROM {{table}} WHERE `id` = {$GetUser['ally_id']};", 'alliance', true); - $GetAlly['ally_ranks'] = json_decode($GetAlly['ally_ranks'], true); - } - $UserIsBuddy = false; - $IsIgnored = false; - if($UserID == $_User['id']) - { - $UserIsBuddy = true; - $_Lang['HideIgnore'] = $_Lang['HideReport'] = $_Lang['HideBuddy'] = $_Lang['HideAllyInvite'] = $Hide; - } - else - { - $CheckBuddy = doquery("SELECT `active` FROM {{table}} WHERE (`sender` = {$_User['id']} AND `owner` = {$UserID}) OR (`owner` = {$_User['id']} AND `sender` = {$UserID}) LIMIT 1;", 'buddy', true); - if($CheckBuddy['active'] == 1) - { - $UserIsBuddy = true; - } - $CheckIgnore = doquery("SELECT COUNT(*) AS `Count` FROM {{table}} WHERE `OwnerID` = {$_User['id']} AND `IgnoredID` = {$UserID};", 'ignoresystem', true); - if($CheckIgnore['Count'] > 0) - { - $IsIgnored = true; - } - - if($_User['ally_id'] <= 0 OR $GetUser['ally_id'] > 0) - { - $_Lang['HideAllyInvite'] = $Hide; - } - } - if(CheckAuth('go')) - { - if(CheckAuth('sgo')) - { - $_Lang['HideReport'] = $Hide; - } - $_Lang['Insert_AdminInfoLink'] = ''.$_Lang['Table_AdminInfo'].''; - } - - $SelectAchievements = doquery("SELECT * FROM {{table}} WHERE `A_UserID` = {$UserID} LIMIT 1;", 'achievements_stats', true); - $GetStats = doquery("SELECT * FROM {{table}} WHERE `id_owner` = {$UserID} AND `stat_type` = 1;", 'statpoints', true); - - if(empty($GetUser['avatar'])) - { - $_Lang['User_Avatar'] = $_EnginePath.'images/noavatar.png'; - } - else - { - $_Lang['User_Avatar'] = $GetUser['avatar']; - $_Lang['HideNoAvatar'] = $Hide; - } - $_Lang['User_ID'] = $UserID; - $_Lang['User_Username'] = $GetUser['username']; - $_Lang['User_Gamerank'] = $_Lang['msg_const']['senders']['rangs'][GetAuthLabel($GetUser)]; - $_Lang['User_Allyname'] = (!empty($GetAlly['ally_name']) ? "{$GetAlly['ally_name']} [{$GetAlly['ally_tag']}]" : '-'); - $_Lang['User_Allyrank'] = (!empty($GetAlly['ally_ranks'][$GetUser['ally_rank_id']][0]) ? $GetAlly['ally_ranks'][$GetUser['ally_rank_id']][0] : '-'); - $_Lang['User_PlanetGalaxy'] = $GetUser['galaxy']; - $_Lang['User_PlanetSystem'] = $GetUser['system']; - $_Lang['User_PlanetPlanet'] = $GetUser['planet']; - $_Lang['User_MotherPlanet'] = $GetMotherPlanet['name']; - if($UserIsBuddy) - { - if($GetUser['onlinetime'] >= ($Now - TIME_ONLINE)) - { - $_Lang['User_ShowBuddyOption'] = $_Lang['Table_Buddy'].' '.$_Lang['Table_Online'].''; - } - else - { - $_Lang['User_ShowBuddyOption'] = $_Lang['Table_Buddy'].' '.$_Lang['Table_Offline'].''; - } - } - else - { - $_Lang['User_ShowBuddyOption'] = "{$_Lang['Table_Add2Buddy']}"; - } - if(!$IsIgnored) - { - $_Lang['User_IgnoreLink'] = 'ignoreadd='.$UserID; - $_Lang['User_IgnoreText'] = $_Lang['Table_Ignore']; - } - else - { - $_Lang['User_IgnoreLink'] = 'tab=5'; - $_Lang['User_IgnoreText'] = $_Lang['Table_UnIgnore']; - } - if(!isOnVacation($GetUser)) - { - $_Lang['HideVacations'] = $Hide; - } - if($GetUser['is_banned'] != 1) - { - $_Lang['HideBanned'] = $Hide; - } - $TotalFightsNumber = $SelectAchievements['ustat_raids_won'] + $SelectAchievements['ustat_raids_draw'] + $SelectAchievements['ustat_raids_lost'] + $SelectAchievements['ustat_raids_inAlly']; - $_Lang['User_FightsTotal'] = prettyNumber($TotalFightsNumber); - $_Lang['User_FightsWon'] = prettyNumber($SelectAchievements['ustat_raids_won']); - $_Lang['User_FightsWonACS'] = prettyNumber($SelectAchievements['ustat_raids_acs_won']); - $_Lang['User_FightsDraw'] = prettyNumber($SelectAchievements['ustat_raids_draw']); - $_Lang['User_FightsLost'] = prettyNumber($SelectAchievements['ustat_raids_lost']); - $_Lang['User_FightsInAlly'] = prettyNumber($SelectAchievements['ustat_raids_inAlly']); - if($TotalFightsNumber > 0) - { - $_Lang['User_FightsWonP'] = intval(($SelectAchievements['ustat_raids_won'] / $TotalFightsNumber) * 100); - $_Lang['User_FightsWonACSP'] = intval(($SelectAchievements['ustat_raids_acs_won'] / $TotalFightsNumber) * 100); - $_Lang['User_FightsDrawP'] = intval(($SelectAchievements['ustat_raids_draw'] / $TotalFightsNumber) * 100); - $_Lang['User_FightsLostP'] = intval(($SelectAchievements['ustat_raids_lost'] / $TotalFightsNumber) * 100); - $_Lang['User_FightsInAllyP'] = intval(($SelectAchievements['ustat_raids_inAlly'] / $TotalFightsNumber) * 100); - } - else - { - $_Lang['User_FightsWonP'] = '0'; - $_Lang['User_FightsWonACSP'] = '0'; - $_Lang['User_FightsDrawP'] = '0'; - $_Lang['User_FightsLostP'] = '0'; - $_Lang['User_FightsInAllyP'] = '0'; - } - $_Lang['User_MissileAttacks'] = prettyNumber($SelectAchievements['ustat_raids_missileAttack']); - $_Lang['User_MoonsCreated'] = prettyNumber($SelectAchievements['ustat_moons_created']); - $_Lang['User_MoonsDestroyed'] = prettyNumber($SelectAchievements['ustat_moons_destroyed']); - - $_Lang['User_ShotDownUnits'] = ''; - $_Lang['User_LostUnits'] = ''; - $_Lang['User_WarBalance'] = ''; - - if(!empty($SelectAchievements)) - { - foreach($SelectAchievements as $Key => $Value) - { - if(strstr($Key, 'destroyed_') !== false) - { - $UnitID = str_replace('destroyed_', '', $Key); - $_Lang['User_ShotDownUnits'] += $Value; - $_Lang['User_WarBalance'] += (($_Vars_Prices[$UnitID]['metal'] + $_Vars_Prices[$UnitID]['crystal'] + $_Vars_Prices[$UnitID]['deuterium']) * $Value) / 1000; - } - else if(strstr($Key, 'lost_') !== false) - { - $UnitID = str_replace('lost_', '', $Key); - $_Lang['User_LostUnits'] += $Value; - $_Lang['User_WarBalance'] -= (($_Vars_Prices[$UnitID]['metal'] + $_Vars_Prices[$UnitID]['crystal'] + $_Vars_Prices[$UnitID]['deuterium']) * $Value) / 1000; - } - } - } - if($_Lang['User_WarBalance'] == 0) - { - $_Lang['User_WarBalanceColor'] = 'orange'; - $_Lang['User_WarBalance'] = prettyNumber($_Lang['User_WarBalance']); - } - else if($_Lang['User_WarBalance'] > 0) - { - $_Lang['User_WarBalanceColor'] = 'lime'; - $_Lang['User_WarBalance'] = '+ '.prettyNumber($_Lang['User_WarBalance']); - } - else - { - $_Lang['User_WarBalanceColor'] = 'red'; - $_Lang['User_WarBalance'] = '- '.prettyNumber($_Lang['User_WarBalance'] * -1); - } - $_Lang['User_ShotDownUnits'] = prettyNumber($_Lang['User_ShotDownUnits']); - $_Lang['User_LostUnits'] = prettyNumber($_Lang['User_LostUnits']); - - if($GetStats['total_rank'] <= 0) - { - $_Lang['User_StatRange'] = '0'; - $_Lang['User_GlobalPosition']= $_Lang['Table_PosZero']; - } - else - { - $_Lang['User_StatRange'] = $GetStats['total_rank']; - $_Lang['User_GlobalPosition'] = prettyNumber($GetStats['total_rank']); - } - $_Lang['User_Points']= prettyNumber($GetStats['total_points']); - - if(MORALE_ENABLED) - { - $_Lang['User_MoralePoints'] = prettyNumber($GetUser['morale_points']); - } - else - { - $_Lang['Insert_MoraleHide'] = 'hide'; - } - - if($GetStats['fleet_rank'] <= 0) - { - $_Lang['User_FleetsRange'] = '0'; - $_Lang['User_FleetsPosition'] = $_Lang['Table_PosZero']; - } - else - { - $_Lang['User_FleetsRange'] = $GetStats['fleet_rank']; - $_Lang['User_FleetsPosition'] = prettyNumber($GetStats['fleet_rank']); - } - $_Lang['User_PointsFleets'] = prettyNumber($GetStats['fleet_points']); - - if($GetStats['tech_rank'] <= 0) - { - $_Lang['User_ResearchRange'] = '0'; - $_Lang['User_ResearchPosition'] = $_Lang['Table_PosZero']; - } - else - { - $_Lang['User_ResearchRange'] = $GetStats['tech_rank']; - $_Lang['User_ResearchPosition'] = prettyNumber($GetStats['tech_rank']); - } - $_Lang['User_PointsResearch'] = prettyNumber($GetStats['tech_points']); - - if($GetStats['build_rank'] <= 0) - { - $_Lang['User_BuildingsRange'] = '0'; - $_Lang['User_BuildingsPosition'] = $_Lang['Table_PosZero']; - } - else - { - $_Lang['User_BuildingsRange'] = $GetStats['build_rank']; - $_Lang['User_BuildingsPosition'] = prettyNumber($GetStats['build_rank']); - } - $_Lang['User_PointsBuildings'] = prettyNumber($GetStats['build_points']); - - if($GetStats['defs_rank'] <= 0) - { - $_Lang['User_DefenseRange'] = '0'; - $_Lang['User_DefensePosition'] = $_Lang['Table_PosZero']; - } - else - { - $_Lang['User_DefenseRange'] = $GetStats['defs_rank']; - $_Lang['User_DefensePosition'] = prettyNumber($GetStats['defs_rank']); - } - $_Lang['User_PointsDefense'] = prettyNumber($GetStats['defs_points']); - - $Page = parsetemplate($BodyTPL, $_Lang); - - display($Page, $PageTitle, false); - -?> \ No newline at end of file + 0) +{ + $GetAlly = doquery("SELECT * FROM {{table}} WHERE `id` = {$GetUser['ally_id']};", 'alliance', true); + $GetAlly['ally_ranks'] = json_decode($GetAlly['ally_ranks'], true); +} +$UserIsBuddy = false; +$IsIgnored = false; +if($UserID == $_User['id']) +{ + $UserIsBuddy = true; + $_Lang['HideIgnore'] = $_Lang['HideReport'] = $_Lang['HideBuddy'] = $_Lang['HideAllyInvite'] = $Hide; +} +else +{ + $CheckBuddy = doquery("SELECT `active` FROM {{table}} WHERE (`sender` = {$_User['id']} AND `owner` = {$UserID}) OR (`owner` = {$_User['id']} AND `sender` = {$UserID}) LIMIT 1;", 'buddy', true); + if($CheckBuddy['active'] == 1) + { + $UserIsBuddy = true; + } + $CheckIgnore = doquery("SELECT COUNT(*) AS `Count` FROM {{table}} WHERE `OwnerID` = {$_User['id']} AND `IgnoredID` = {$UserID};", 'ignoresystem', true); + if($CheckIgnore['Count'] > 0) + { + $IsIgnored = true; + } + + if($_User['ally_id'] <= 0 OR $GetUser['ally_id'] > 0) + { + $_Lang['HideAllyInvite'] = $Hide; + } +} +if(CheckAuth('go')) +{ + if(CheckAuth('sgo')) + { + $_Lang['HideReport'] = $Hide; + } + $_Lang['Insert_AdminInfoLink'] = ''.$_Lang['Table_AdminInfo'].''; +} + +$SelectAchievements = doquery("SELECT * FROM {{table}} WHERE `A_UserID` = {$UserID} LIMIT 1;", 'achievements_stats', true); +$GetStats = doquery("SELECT * FROM {{table}} WHERE `id_owner` = {$UserID} AND `stat_type` = 1;", 'statpoints', true); + +if(empty($GetUser['avatar'])) +{ + $_Lang['User_Avatar'] = $_EnginePath.'images/noavatar.png'; +} +else +{ + $_Lang['User_Avatar'] = $GetUser['avatar']; + $_Lang['HideNoAvatar'] = $Hide; +} +$_Lang['User_ID'] = $UserID; +$_Lang['User_Username'] = $GetUser['username']; +$_Lang['User_Gamerank'] = $_Lang['msg_const']['senders']['rangs'][GetAuthLabel($GetUser)]; +$_Lang['User_Allyname'] = (!empty($GetAlly['ally_name']) ? "{$GetAlly['ally_name']} [{$GetAlly['ally_tag']}]" : '-'); +$_Lang['User_Allyrank'] = (!empty($GetAlly['ally_ranks'][$GetUser['ally_rank_id']][0]) ? $GetAlly['ally_ranks'][$GetUser['ally_rank_id']][0] : '-'); +$_Lang['User_PlanetGalaxy'] = $GetUser['galaxy']; +$_Lang['User_PlanetSystem'] = $GetUser['system']; +$_Lang['User_PlanetPlanet'] = $GetUser['planet']; +$_Lang['User_MotherPlanet'] = $GetMotherPlanet['name']; +if($UserIsBuddy) +{ + if($GetUser['onlinetime'] >= ($Now - TIME_ONLINE)) + { + $_Lang['User_ShowBuddyOption'] = $_Lang['Table_Buddy'].' '.$_Lang['Table_Online'].''; + } + else + { + $_Lang['User_ShowBuddyOption'] = $_Lang['Table_Buddy'].' '.$_Lang['Table_Offline'].''; + } +} +else +{ + $_Lang['User_ShowBuddyOption'] = "{$_Lang['Table_Add2Buddy']}"; +} +if(!$IsIgnored) +{ + $_Lang['User_IgnoreLink'] = 'ignoreadd='.$UserID; + $_Lang['User_IgnoreText'] = $_Lang['Table_Ignore']; +} +else +{ + $_Lang['User_IgnoreLink'] = 'tab=5'; + $_Lang['User_IgnoreText'] = $_Lang['Table_UnIgnore']; +} +if(!isOnVacation($GetUser)) +{ + $_Lang['HideVacations'] = $Hide; +} +if($GetUser['is_banned'] != 1) +{ + $_Lang['HideBanned'] = $Hide; +} +$TotalFightsNumber = $SelectAchievements['ustat_raids_won'] + $SelectAchievements['ustat_raids_draw'] + $SelectAchievements['ustat_raids_lost'] + $SelectAchievements['ustat_raids_inAlly']; +$_Lang['User_FightsTotal'] = prettyNumber($TotalFightsNumber); +$_Lang['User_FightsWon'] = prettyNumber($SelectAchievements['ustat_raids_won']); +$_Lang['User_FightsWonACS'] = prettyNumber($SelectAchievements['ustat_raids_acs_won']); +$_Lang['User_FightsDraw'] = prettyNumber($SelectAchievements['ustat_raids_draw']); +$_Lang['User_FightsLost'] = prettyNumber($SelectAchievements['ustat_raids_lost']); +$_Lang['User_FightsInAlly'] = prettyNumber($SelectAchievements['ustat_raids_inAlly']); +if($TotalFightsNumber > 0) +{ + $_Lang['User_FightsWonP'] = intval(($SelectAchievements['ustat_raids_won'] / $TotalFightsNumber) * 100); + $_Lang['User_FightsWonACSP'] = intval(($SelectAchievements['ustat_raids_acs_won'] / $TotalFightsNumber) * 100); + $_Lang['User_FightsDrawP'] = intval(($SelectAchievements['ustat_raids_draw'] / $TotalFightsNumber) * 100); + $_Lang['User_FightsLostP'] = intval(($SelectAchievements['ustat_raids_lost'] / $TotalFightsNumber) * 100); + $_Lang['User_FightsInAllyP'] = intval(($SelectAchievements['ustat_raids_inAlly'] / $TotalFightsNumber) * 100); +} +else +{ + $_Lang['User_FightsWonP'] = '0'; + $_Lang['User_FightsWonACSP'] = '0'; + $_Lang['User_FightsDrawP'] = '0'; + $_Lang['User_FightsLostP'] = '0'; + $_Lang['User_FightsInAllyP'] = '0'; +} +$_Lang['User_MissileAttacks'] = prettyNumber($SelectAchievements['ustat_raids_missileAttack']); +$_Lang['User_MoonsCreated'] = prettyNumber($SelectAchievements['ustat_moons_created']); +$_Lang['User_MoonsDestroyed'] = prettyNumber($SelectAchievements['ustat_moons_destroyed']); + +$_Lang['User_ShotDownUnits'] = ''; +$_Lang['User_LostUnits'] = ''; +$_Lang['User_WarBalance'] = ''; + +if(!empty($SelectAchievements)) +{ + foreach($SelectAchievements as $Key => $Value) + { + if(strstr($Key, 'destroyed_') !== false) + { + $UnitID = str_replace('destroyed_', '', $Key); + $_Lang['User_ShotDownUnits'] += $Value; + $_Lang['User_WarBalance'] += (($_Vars_Prices[$UnitID]['metal'] + $_Vars_Prices[$UnitID]['crystal'] + $_Vars_Prices[$UnitID]['deuterium']) * $Value) / 1000; + } + else if(strstr($Key, 'lost_') !== false) + { + $UnitID = str_replace('lost_', '', $Key); + $_Lang['User_LostUnits'] += $Value; + $_Lang['User_WarBalance'] -= (($_Vars_Prices[$UnitID]['metal'] + $_Vars_Prices[$UnitID]['crystal'] + $_Vars_Prices[$UnitID]['deuterium']) * $Value) / 1000; + } + } +} +if($_Lang['User_WarBalance'] == 0) +{ + $_Lang['User_WarBalanceColor'] = 'orange'; + $_Lang['User_WarBalance'] = prettyNumber($_Lang['User_WarBalance']); +} +else if($_Lang['User_WarBalance'] > 0) +{ + $_Lang['User_WarBalanceColor'] = 'lime'; + $_Lang['User_WarBalance'] = '+ '.prettyNumber($_Lang['User_WarBalance']); +} +else +{ + $_Lang['User_WarBalanceColor'] = 'red'; + $_Lang['User_WarBalance'] = '- '.prettyNumber($_Lang['User_WarBalance'] * -1); +} +$_Lang['User_ShotDownUnits'] = prettyNumber($_Lang['User_ShotDownUnits']); +$_Lang['User_LostUnits'] = prettyNumber($_Lang['User_LostUnits']); + +if($GetStats['total_rank'] <= 0) +{ + $_Lang['User_StatRange'] = '0'; + $_Lang['User_GlobalPosition']= $_Lang['Table_PosZero']; +} +else +{ + $_Lang['User_StatRange'] = $GetStats['total_rank']; + $_Lang['User_GlobalPosition'] = prettyNumber($GetStats['total_rank']); +} +$_Lang['User_Points']= prettyNumber($GetStats['total_points']); + +if(MORALE_ENABLED) +{ + $_Lang['User_MoralePoints'] = prettyNumber($GetUser['morale_points']); +} +else +{ + $_Lang['Insert_MoraleHide'] = 'hide'; +} + +if($GetStats['fleet_rank'] <= 0) +{ + $_Lang['User_FleetsRange'] = '0'; + $_Lang['User_FleetsPosition'] = $_Lang['Table_PosZero']; +} +else +{ + $_Lang['User_FleetsRange'] = $GetStats['fleet_rank']; + $_Lang['User_FleetsPosition'] = prettyNumber($GetStats['fleet_rank']); +} +$_Lang['User_PointsFleets'] = prettyNumber($GetStats['fleet_points']); + +if($GetStats['tech_rank'] <= 0) +{ + $_Lang['User_ResearchRange'] = '0'; + $_Lang['User_ResearchPosition'] = $_Lang['Table_PosZero']; +} +else +{ + $_Lang['User_ResearchRange'] = $GetStats['tech_rank']; + $_Lang['User_ResearchPosition'] = prettyNumber($GetStats['tech_rank']); +} +$_Lang['User_PointsResearch'] = prettyNumber($GetStats['tech_points']); + +if($GetStats['build_rank'] <= 0) +{ + $_Lang['User_BuildingsRange'] = '0'; + $_Lang['User_BuildingsPosition'] = $_Lang['Table_PosZero']; +} +else +{ + $_Lang['User_BuildingsRange'] = $GetStats['build_rank']; + $_Lang['User_BuildingsPosition'] = prettyNumber($GetStats['build_rank']); +} +$_Lang['User_PointsBuildings'] = prettyNumber($GetStats['build_points']); + +if($GetStats['defs_rank'] <= 0) +{ + $_Lang['User_DefenseRange'] = '0'; + $_Lang['User_DefensePosition'] = $_Lang['Table_PosZero']; +} +else +{ + $_Lang['User_DefenseRange'] = $GetStats['defs_rank']; + $_Lang['User_DefensePosition'] = prettyNumber($GetStats['defs_rank']); +} +$_Lang['User_PointsDefense'] = prettyNumber($GetStats['defs_points']); + +$Page = parsetemplate($BodyTPL, $_Lang); + +display($Page, $PageTitle, false); + +?> diff --git a/records.php b/records.php index 7d87343a6..e54950b5a 100644 --- a/records.php +++ b/records.php @@ -1,88 +1,88 @@ - 0) - { - while($Rec = mysql_fetch_assoc($Records)) - { - $Row = array(); - - $Element = $Rec['element']; - $UserID = $Rec['id_owner']; - $UserName = $Rec['username']; - $Count = $Rec['count']; - $Row['ElementID'] = $Element; - $Row['winner'] = ($UserID != 0) ? "{$UserName}" : $_Lang['rec_rien']; - $Row['element'] = $_Lang['tech'][$Element]; - $Row['count'] = ($Count > 0) ? prettyNumber($Count) : $_Lang['rec_rien']; - - if($Element >= 1 && $Element <= 39 || $Element == 44) - { - // Buildings (normal) - $parse['building'] .= parsetemplate($TableRows, $Row); - } - else if($Element >= 41 && $Element <= 99 && $Element != 44 && $Element != 50) - { - // Buildings (special) - $parse['buildspe'] .= parsetemplate($TableRows, $Row); - } - else if($Element >= 101 && $Element <= 199) - { - // Technology - $parse['research'] .= parsetemplate($TableRows, $Row); - } - else if($Element >= 201 && $Element <= 399) - { - // Ships - $parse['fleet'].= parsetemplate($TableRows, $Row); - } - else if($Element >= 401 && $Element <= 599 AND $Element != 407 AND $Element != 408) - { - // Defense - $parse['defenses'] .= parsetemplate($TableRows, $Row); - } - } - } - - $page = parsetemplate( $RecordTpl, $parse ); - display($page, $_Lang['rec_title']); - -?> \ No newline at end of file + 0) +{ + while($Rec = mysql_fetch_assoc($Records)) + { + $Row = array(); + + $Element = $Rec['element']; + $UserID = $Rec['id_owner']; + $UserName = $Rec['username']; + $Count = $Rec['count']; + $Row['ElementID'] = $Element; + $Row['winner'] = ($UserID != 0) ? "{$UserName}" : $_Lang['rec_rien']; + $Row['element'] = $_Lang['tech'][$Element]; + $Row['count'] = ($Count > 0) ? prettyNumber($Count) : $_Lang['rec_rien']; + + if($Element >= 1 && $Element <= 39 || $Element == 44) + { + // Buildings (normal) + $parse['building'] .= parsetemplate($TableRows, $Row); + } + else if($Element >= 41 && $Element <= 99 && $Element != 44 && $Element != 50) + { + // Buildings (special) + $parse['buildspe'] .= parsetemplate($TableRows, $Row); + } + else if($Element >= 101 && $Element <= 199) + { + // Technology + $parse['research'] .= parsetemplate($TableRows, $Row); + } + else if($Element >= 201 && $Element <= 399) + { + // Ships + $parse['fleet'].= parsetemplate($TableRows, $Row); + } + else if($Element >= 401 && $Element <= 599 AND $Element != 407 AND $Element != 408) + { + // Defense + $parse['defenses'] .= parsetemplate($TableRows, $Row); + } + } +} + +$page = parsetemplate( $RecordTpl, $parse ); +display($page, $_Lang['rec_title']); + +?> diff --git a/redirect.php b/redirect.php index 503045095..bd93f2ab6 100644 --- a/redirect.php +++ b/redirect.php @@ -1,30 +1,26 @@ - \ No newline at end of file + diff --git a/ref_table.php b/ref_table.php index 03221aa23..6eb0e14b0 100644 --- a/ref_table.php +++ b/ref_table.php @@ -1,53 +1,53 @@ - 0) - { - $RowTPL = gettemplate('ref_table_row'); - - while($NewUser = mysql_fetch_assoc($Result_SelectRows)) - { - if(!empty($NewUser['username'])) - { - $NewUser['Username'] = $NewUser['username']; - } - else - { - $NewUser['Username'] = "{$_Lang['UserDeleted']}"; - } - $NewUser['RegDate'] = prettyDate('d m Y - H:i:s', $NewUser['time'], 1); - $NewUser['Provision'] = "{$NewUser['provisions_granted']} {$_Lang['DEUnits']}"; - - $_Lang['Rows'] .= parsetemplate($RowTPL, $NewUser); - } - } - else - { - $_Lang['Rows'] = "{$_Lang['referred_noone']}"; - } - - $page = parsetemplate(gettemplate('ref_table_body'), $_Lang); - display($page, $_Lang['reftable'], false); - -?> \ No newline at end of file + 0) +{ + $RowTPL = gettemplate('ref_table_row'); + + while($NewUser = mysql_fetch_assoc($Result_SelectRows)) + { + if(!empty($NewUser['username'])) + { + $NewUser['Username'] = $NewUser['username']; + } + else + { + $NewUser['Username'] = "{$_Lang['UserDeleted']}"; + } + $NewUser['RegDate'] = prettyDate('d m Y - H:i:s', $NewUser['time'], 1); + $NewUser['Provision'] = "{$NewUser['provisions_granted']} {$_Lang['DEUnits']}"; + + $_Lang['Rows'] .= parsetemplate($RowTPL, $NewUser); + } +} +else +{ + $_Lang['Rows'] = "{$_Lang['referred_noone']}"; +} + +$page = parsetemplate(gettemplate('ref_table_body'), $_Lang); +display($page, $_Lang['reftable'], false); + +?> diff --git a/reg_ajax.php b/reg_ajax.php index cfb3a8d25..3d512c4d8 100644 --- a/reg_ajax.php +++ b/reg_ajax.php @@ -1,476 +1,476 @@ - 64) - { - // Username is too long - $JSONResponse['Errors'][] = 2; - $JSONResponse['BadFields'][] = 'username'; - } - else if(!preg_match(REGEXP_USERNAME_ABSOLUTE, $Username)) - { - // Username has illegal signs - $JSONResponse['Errors'][] = 3; - $JSONResponse['BadFields'][] = 'username'; - } - else - { - $UsernameGood = true; - } - - // Check if Password is correct - if(strlen($Password) < 4) - { - // Password is too short - $JSONResponse['Errors'][] = 4; - $JSONResponse['BadFields'][] = 'password'; - } - - // Check if EMail is correct - $EmailGood = false; - $BannedDomains = str_replace('.', '\.', $_GameConfig['BannedMailDomains']); - if(empty($Email)) - { - // EMail is empty - $JSONResponse['Errors'][] = 5; - $JSONResponse['BadFields'][] = 'email'; - } - else if($Email != $CheckEmail) - { - // EMail has illegal signs - $JSONResponse['Errors'][] = 6; - $JSONResponse['BadFields'][] = 'email'; - } - else if(!is_email($Email)) - { - // EMail is incorrect - $JSONResponse['Errors'][] = 7; - $JSONResponse['BadFields'][] = 'email'; - } - else if(!empty($BannedDomains) && preg_match('#('.$BannedDomains.')+#si', $Email)) - { - // EMail is on banned domains list - $JSONResponse['Errors'][] = 8; - $JSONResponse['BadFields'][] = 'email'; - } - else - { - $EmailGood = true; - } - - // PreCheck Galaxy - if($GalaxyNo < 1) - { - // Galaxy not given - $JSONResponse['Errors'][] = 13; - $JSONResponse['BadFields'][] = 'galaxy'; - } - else if($GalaxyNo > MAX_GALAXY_IN_WORLD) - { - // GalaxyNo is too high - $JSONResponse['Errors'][] = 14; - $JSONResponse['BadFields'][] = 'galaxy'; - } - - // Check if Rules has been accepted - if($Rules != 'on') - { - // Rules are not accepted - $JSONResponse['Errors'][] = 9; - } - - if(REGISTER_RECAPTCHA_ENABLE) - { - // Check if reCaptcha is correct - if(!isset($_GET['recaptcha_challenge_field'])) - { - $_GET['recaptcha_challenge_field'] = null; - } - if(!isset($_GET['recaptcha_response_field'])) - { - $_GET['recaptcha_response_field'] = null; - } - $resp = recaptcha_check_answer(REGISTER_RECAPTCHA_PRIVATEKEY, $_SERVER['REMOTE_ADDR'], $_GET['recaptcha_challenge_field'], $_GET['recaptcha_response_field']); - if(!$resp->is_valid) - { - // ReCaptcha Code is not valid - $JSONResponse['Errors'][] = 10; - } - } - - if($EmailGood === true AND $UsernameGood === true) - { - $Query_CheckExistance = ''; - $Query_CheckExistance .= "SELECT `username`, `email` FROM {{table}} "; - $Query_CheckExistance .= "WHERE `username` = '{$Username}' OR `email` = '{$Email}' LIMIT 2;"; - $Result_CheckExistance = doquery($Query_CheckExistance, 'users'); - if(mysql_num_rows($Result_CheckExistance) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_CheckExistance)) - { - if(strtolower($FetchData['username']) == strtolower($Username)) - { - // Username is used - $JSONResponse['Errors'][] = 11; - $JSONResponse['BadFields'][] = 'username'; - } - else - { - // EMail is used - $JSONResponse['Errors'][] = 12; - $JSONResponse['BadFields'][] = 'email'; - } - } - } - } - - if(empty($JSONResponse['Errors'])) - { - unset($JSONResponse['Errors']); - - // Check Galaxy - $SystemsRange = 25; - $SystemRandom = mt_rand(1, MAX_SYSTEM_IN_GALAXY); - if(($SystemRandom + $SystemsRange) >= MAX_SYSTEM_IN_GALAXY) - { - $System_Lower = $SystemRandom - $SystemsRange; - } - else - { - $System_Lower = $SystemRandom; - } - $System_Higher = $System_Lower + $SystemsRange; - $Planet_Lower = 4; - $Planet_Higher = 12; - - // - Step 1: check random range of solar systems - $PosFound = false; - $Position_NonFree = array(); - $Position_NonFreeCount = 0; - $Position_TotalCount = (($System_Higher - $System_Lower) + 1) * (($Planet_Higher - $Planet_Lower) + 1); - - $Query_CheckGalaxy1 = ''; - $Query_CheckGalaxy1 .= "SELECT `system`, `planet` FROM {{table}} "; - $Query_CheckGalaxy1 .= "WHERE `galaxy` = {$GalaxyNo} AND "; - $Query_CheckGalaxy1 .= "`system` BETWEEN {$System_Lower} AND {$System_Higher} AND "; - $Query_CheckGalaxy1 .= "`planet` BETWEEN {$Planet_Lower} AND {$Planet_Higher};"; - $Result_CheckGalaxy1 = doquery($Query_CheckGalaxy1, 'galaxy'); - if(mysql_num_rows($Result_CheckGalaxy1) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_CheckGalaxy1)) - { - $Position_NonFree["{$FetchData['system']}:{$FetchData['planet']}"] = true; - } - $Position_NonFreeCount = count($Position_NonFree); - } - if($Position_NonFreeCount < $Position_TotalCount) - { - while(!$PosFound) - { - $System = mt_rand($System_Lower, $System_Higher); - $Planet = mt_rand($Planet_Lower, $Planet_Higher); - if(!isset($Position_NonFree["{$System}:{$Planet}"])) - { - $PosFound = true; - } - } - } - else - { - // - Step 2: check whole galaxy, if space not found earlier - $Position_NonFree = array(); - $Position_NonFreeCount = 0; - $Position_TotalCount = MAX_SYSTEM_IN_GALAXY * (($Planet_Higher - $Planet_Lower) + 1); - - $Query_CheckGalaxy2 = ''; - $Query_CheckGalaxy2 .= "SELECT `system`, `planet` FROM {{table}} "; - $Query_CheckGalaxy2 .= "WHERE `galaxy` = {$GalaxyNo} AND "; - $Query_CheckGalaxy2 .= "`planet` BETWEEN {$Planet_Lower} AND {$Planet_Higher};"; - $Result_CheckGalaxy2 = doquery($Query_CheckGalaxy2, 'galaxy'); - if(mysql_num_rows($Result_CheckGalaxy2) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_CheckGalaxy2)) - { - $Position_NonFree["{$FetchData['system']}:{$FetchData['planet']}"] = true; - } - $Position_NonFreeCount = count($Position_NonFree); - } - if($Position_NonFreeCount < $Position_TotalCount) - { - while(!$PosFound) - { - $System = mt_rand(1, MAX_SYSTEM_IN_GALAXY); - $Planet = mt_rand($Planet_Lower, $Planet_Higher); - if(!isset($Position_NonFree["{$System}:{$Planet}"])) - { - $PosFound = true; - } - } - } - else - { - // - Step 3: check whole galaxy and all slots which has not been checked - $Position_NonFree = array(); - $Position_NonFreeCount = 0; - for($i = 1; $i < $Planet_Lower; $i += 1) - { - $Planet_PosArray[] = $i; - } - for($i = $Planet_Higher; $i < MAX_PLANET_IN_SYSTEM; $i += 1) - { - $Planet_PosArray[] = $i; - } - $Position_TotalCount = MAX_SYSTEM_IN_GALAXY * count($Planet_PosArray); - - $Query_CheckGalaxy3 = ''; - $Query_CheckGalaxy3 .= "SELECT `system`, `planet` FROM {{table}} "; - $Query_CheckGalaxy3 .= "WHERE `galaxy` = {$GalaxyNo} AND "; - $Query_CheckGalaxy3 .= "`planet` NOT BETWEEN {$Planet_Lower} AND {$Planet_Higher};"; - $Result_CheckGalaxy3 = doquery($Query_CheckGalaxy3, 'galaxy'); - if(mysql_num_rows($Result_CheckGalaxy3) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_CheckGalaxy3)) - { - $Position_NonFree["{$FetchData['system']}:{$FetchData['planet']}"] = true; - } - $Position_NonFreeCount = count($Position_NonFree); - } - if($Position_NonFreeCount < $Position_TotalCount) - { - while(!$PosFound) - { - $System = mt_rand(1, MAX_SYSTEM_IN_GALAXY); - $Planet = $Planet_PosArray[array_rand($Planet_PosArray)]; - if(!isset($Position_NonFree["{$System}:{$Planet}"])) - { - $PosFound = true; - } - } - } - } - } - - if($PosFound) - { - $Query_InsertUser = ''; - $Query_InsertUser .= "INSERT INTO {{table}} SET "; - $Query_InsertUser .= "`username` = '{$Username}', "; - $Query_InsertUser .= "`email` = '{$Email}', "; - $Query_InsertUser .= "`email_2` = '{$Email}', "; - $Query_InsertUser .= "`ip_at_reg` = '{$_SERVER['REMOTE_ADDR']}', "; - $Query_InsertUser .= "`id_planet` = 0, "; - $Query_InsertUser .= "`register_time` = {$Now}, "; - $Query_InsertUser .= "`onlinetime` = {$Now} - (24*60*60), "; - $Query_InsertUser .= "`rules_accept_stamp` = {$Now}, "; - $Query_InsertUser .= "`password` = MD5('{$Password}');"; - doquery($Query_InsertUser, 'users'); - - // Get UserID - $Query_GetUserID = "SELECT LAST_INSERT_ID() AS `ID`;"; - $Result_GetUserID = doquery($Query_GetUserID, '', true); - $UserID = $Result_GetUserID['ID']; - - // Update all MailChanges - doquery("UPDATE {{table}} SET `ConfirmType` = 4 WHERE `NewMail` = '{$Email}' AND `ConfirmType` = 0;", 'mailchange'); - - // Create a Planet for User - include($_EnginePath.'includes/functions/CreateOnePlanetRecord.php'); - $Galaxy = $GalaxyNo; - $PlanetID = CreateOnePlanetRecord($Galaxy, $System, $Planet, $UserID, $_Lang['MotherPlanet'], true); - - // Update Config - $_GameConfig['users_amount'] += 1; - $Query_UpdateConfig = ''; - $Query_UpdateConfig .= "UPDATE {{table}} "; - $Query_UpdateConfig .= "SET `config_value` = {$_GameConfig['users_amount']} "; - $Query_UpdateConfig .= "WHERE `config_name` = 'users_amount';"; - doquery($Query_UpdateConfig, 'config'); - $_MemCache->GameConfig = $_GameConfig; - - // Update User with new data - if(isset($_COOKIE[REFERING_COOKIENAME]) && $_COOKIE[REFERING_COOKIENAME] > 0) - { - $RefID = round($_COOKIE[REFERING_COOKIENAME]); - if($RefID > 0) - { - $Query_SelectReferrer = "SELECT `id` FROM {{table}} WHERE `id` = {$RefID} LIMIT 1;"; - $Result_SelectReferrer = doquery($Query_SelectReferrer, 'users', true); - if($Result_SelectReferrer['id'] > 0) - { - $UserIPs['r'] = trim($_SERVER['REMOTE_ADDR']); - $UserIPs['p'] = preg_replace('#[^a-zA-Z0-9\.\,\:\ ]{1,}#si', '', trim($_SERVER['HTTP_X_FORWARDED_FOR'])); - if(empty($UserIPs['p'])) - { - unset($UserIPs['p']); - } - foreach($UserIPs as $Key => $Data) - { - $CreateRegIP[] = "{$Key},{$Data}"; - $UserIPs[$Key] = "'{$Data}'"; - } - $CreateRegIP = implode(';', $CreateRegIP); - - $Query_InsertRefData_Matches = 'null'; - - $Query_SelectIPMatches = "SELECT `ID` FROM {{table}} WHERE `Type` = 'ip' AND `Value` IN (".implode(',', $UserIPs).");"; - $Result_SelectIPMatches = doquery($Query_SelectIPMatches, 'used_ip_and_ua'); - if(mysql_num_rows($Result_SelectIPMatches) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_SelectIPMatches)) - { - $MatchedIPIDs[] = $FetchData['ID']; - } - - $Query_SelectEnterLogMatches = "SELECT `ID` FROM {{table}} WHERE `IP_ID` IN (".implode(',', $MatchedIPIDs).");"; - $Result_SelectEnterLogMatches = doquery($Query_SelectEnterLogMatches, 'user_enterlog'); - if(mysql_num_rows($Result_SelectEnterLogMatches) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_SelectEnterLogMatches)) - { - $MatchedEnterLogIDs[] = $FetchData['ID']; - } - - $Query_InsertRefData_Matches = '\''.implode(',', $MatchedEnterLogIDs).'\''; - } - } - - $Query_InsertRefData = ''; - $Query_InsertRefData .= "INSERT INTO {{table}} SET "; - $Query_InsertRefData .= "`referrer_id` = {$RefID}, "; - $Query_InsertRefData .= "`newuser_id` = {$UserID}, "; - $Query_InsertRefData .= "`time` = {$Now}, "; - $Query_InsertRefData .= "`reg_ip` = '{$CreateRegIP}', "; - $Query_InsertRefData .= "`matches_found` = {$Query_InsertRefData_Matches};"; - doquery($Query_InsertRefData, 'referring_table'); - - $Message = false; - $Message['msg_id'] = '038'; - $Message['args'] = array(''); - $Message = json_encode($Message); - - SendSimpleMessage($RefID, 0, $Now, 70, '007', '016', $Message); - - $Query_UpdateUser_Fields[] = "`referred` = {$RefID}"; - } - } - } - - $ActivationCode = md5(mt_rand(0, 99999999999)); - - $Query_UpdateUser_Fields[] = "`id_planet` = {$PlanetID}"; - $Query_UpdateUser_Fields[] = "`settings_mainPlanetID` = {$PlanetID}"; - $Query_UpdateUser_Fields[] = "`current_planet` = {$PlanetID}"; - $Query_UpdateUser_Fields[] = "`galaxy` = {$Galaxy}"; - $Query_UpdateUser_Fields[] = "`system` = {$System}"; - $Query_UpdateUser_Fields[] = "`planet` = {$Planet}"; - if(REGISTER_REQUIRE_EMAILCONFIRM) - { - $Query_UpdateUser_Fields[] = "`activation_code` = '{$ActivationCode}'"; - } - else - { - $Query_UpdateUser_Fields[] = "`activation_code` = ''"; - } - - $Query_UpdateUser = ''; - $Query_UpdateUser .= "UPDATE {{table}} SET "; - $Query_UpdateUser .= implode(', ', $Query_UpdateUser_Fields); - $Query_UpdateUser .= " WHERE `id` = {$UserID} LIMIT 1;"; - doquery($Query_UpdateUser, 'users'); - - // Send a invitation private msg - $Message = false; - $Message['msg_id'] = '022'; - $Message['args'] = array(''); - $Message = json_encode($Message); - - SendSimpleMessage($UserID, 0, $Now, 70, '004', '009', $Message); - - if(REGISTER_REQUIRE_EMAILCONFIRM) - { - include($_EnginePath.'includes/functions/SendMail.php'); - $MailParse['login'] = $Username; - $MailParse['password'] = $Password; - $MailParse['Universe'] = $_Lang['RegMail_UniName']; - $MailParse['activationlink'] = ''.GAMEURL.'activate.php?code='.$ActivationCode.''; - $MailParse['UserRefLink'] = ''.GAMEURL.'index.php?r='.$UserID.''; - $MailParsed = parsetemplate($_Lang['mail_template'], $MailParse); - SendMail($Email, $_Lang['mail_title'], $MailParsed); - } - - if(SERVER_MAINOPEN_TSTAMP <= $Now) - { - if(LOCALHOST) - { - require($_EnginePath.'config.localhost.php'); - } - else if(TESTSERVER) - { - require($_EnginePath.'config.testserver.php'); - } - else - { - require($_EnginePath.'config.php'); - } - $cookie = $UserID.'/%/'.$Username.'/%/'.md5(md5($Password).'--'.$__ServerConnectionSettings['secretword']).'/%/0'; - $JSONResponse['Code'] = 1; - $JSONResponse['Cookie'][] = array('Name' => $_GameConfig['COOKIE_NAME'], 'Value' => $cookie); - $JSONResponse['Redirect'] = GAMEURL_UNISTRICT.'/overview.php'; - } - else - { - $JSONResponse['Code'] = 2; - } - } - else - { - $JSONResponse['Errors'][] = 15; - $JSONResponse['BadFields'][] = 'email'; - } - } - die('regCallback('.json_encode($JSONResponse).');'); - } - else - { - header('Location: index.php'); - die('regCallback({});'); - } - -?> \ No newline at end of file + 64) + { + // Username is too long + $JSONResponse['Errors'][] = 2; + $JSONResponse['BadFields'][] = 'username'; + } + else if(!preg_match(REGEXP_USERNAME_ABSOLUTE, $Username)) + { + // Username has illegal signs + $JSONResponse['Errors'][] = 3; + $JSONResponse['BadFields'][] = 'username'; + } + else + { + $UsernameGood = true; + } + + // Check if Password is correct + if(strlen($Password) < 4) + { + // Password is too short + $JSONResponse['Errors'][] = 4; + $JSONResponse['BadFields'][] = 'password'; + } + + // Check if EMail is correct + $EmailGood = false; + $BannedDomains = str_replace('.', '\.', $_GameConfig['BannedMailDomains']); + if(empty($Email)) + { + // EMail is empty + $JSONResponse['Errors'][] = 5; + $JSONResponse['BadFields'][] = 'email'; + } + else if($Email != $CheckEmail) + { + // EMail has illegal signs + $JSONResponse['Errors'][] = 6; + $JSONResponse['BadFields'][] = 'email'; + } + else if(!is_email($Email)) + { + // EMail is incorrect + $JSONResponse['Errors'][] = 7; + $JSONResponse['BadFields'][] = 'email'; + } + else if(!empty($BannedDomains) && preg_match('#('.$BannedDomains.')+#si', $Email)) + { + // EMail is on banned domains list + $JSONResponse['Errors'][] = 8; + $JSONResponse['BadFields'][] = 'email'; + } + else + { + $EmailGood = true; + } + + // PreCheck Galaxy + if($GalaxyNo < 1) + { + // Galaxy not given + $JSONResponse['Errors'][] = 13; + $JSONResponse['BadFields'][] = 'galaxy'; + } + else if($GalaxyNo > MAX_GALAXY_IN_WORLD) + { + // GalaxyNo is too high + $JSONResponse['Errors'][] = 14; + $JSONResponse['BadFields'][] = 'galaxy'; + } + + // Check if Rules has been accepted + if($Rules != 'on') + { + // Rules are not accepted + $JSONResponse['Errors'][] = 9; + } + + if(REGISTER_RECAPTCHA_ENABLE) + { + // Check if reCaptcha is correct + if(!isset($_GET['recaptcha_challenge_field'])) + { + $_GET['recaptcha_challenge_field'] = null; + } + if(!isset($_GET['recaptcha_response_field'])) + { + $_GET['recaptcha_response_field'] = null; + } + $resp = recaptcha_check_answer(REGISTER_RECAPTCHA_PRIVATEKEY, $_SERVER['REMOTE_ADDR'], $_GET['recaptcha_challenge_field'], $_GET['recaptcha_response_field']); + if(!$resp->is_valid) + { + // ReCaptcha Code is not valid + $JSONResponse['Errors'][] = 10; + } + } + + if($EmailGood === true AND $UsernameGood === true) + { + $Query_CheckExistance = ''; + $Query_CheckExistance .= "SELECT `username`, `email` FROM {{table}} "; + $Query_CheckExistance .= "WHERE `username` = '{$Username}' OR `email` = '{$Email}' LIMIT 2;"; + $Result_CheckExistance = doquery($Query_CheckExistance, 'users'); + if(mysql_num_rows($Result_CheckExistance) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_CheckExistance)) + { + if(strtolower($FetchData['username']) == strtolower($Username)) + { + // Username is used + $JSONResponse['Errors'][] = 11; + $JSONResponse['BadFields'][] = 'username'; + } + else + { + // EMail is used + $JSONResponse['Errors'][] = 12; + $JSONResponse['BadFields'][] = 'email'; + } + } + } + } + + if(empty($JSONResponse['Errors'])) + { + unset($JSONResponse['Errors']); + + // Check Galaxy + $SystemsRange = 25; + $SystemRandom = mt_rand(1, MAX_SYSTEM_IN_GALAXY); + if(($SystemRandom + $SystemsRange) >= MAX_SYSTEM_IN_GALAXY) + { + $System_Lower = $SystemRandom - $SystemsRange; + } + else + { + $System_Lower = $SystemRandom; + } + $System_Higher = $System_Lower + $SystemsRange; + $Planet_Lower = 4; + $Planet_Higher = 12; + + // - Step 1: check random range of solar systems + $PosFound = false; + $Position_NonFree = array(); + $Position_NonFreeCount = 0; + $Position_TotalCount = (($System_Higher - $System_Lower) + 1) * (($Planet_Higher - $Planet_Lower) + 1); + + $Query_CheckGalaxy1 = ''; + $Query_CheckGalaxy1 .= "SELECT `system`, `planet` FROM {{table}} "; + $Query_CheckGalaxy1 .= "WHERE `galaxy` = {$GalaxyNo} AND "; + $Query_CheckGalaxy1 .= "`system` BETWEEN {$System_Lower} AND {$System_Higher} AND "; + $Query_CheckGalaxy1 .= "`planet` BETWEEN {$Planet_Lower} AND {$Planet_Higher};"; + $Result_CheckGalaxy1 = doquery($Query_CheckGalaxy1, 'galaxy'); + if(mysql_num_rows($Result_CheckGalaxy1) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_CheckGalaxy1)) + { + $Position_NonFree["{$FetchData['system']}:{$FetchData['planet']}"] = true; + } + $Position_NonFreeCount = count($Position_NonFree); + } + if($Position_NonFreeCount < $Position_TotalCount) + { + while(!$PosFound) + { + $System = mt_rand($System_Lower, $System_Higher); + $Planet = mt_rand($Planet_Lower, $Planet_Higher); + if(!isset($Position_NonFree["{$System}:{$Planet}"])) + { + $PosFound = true; + } + } + } + else + { + // - Step 2: check whole galaxy, if space not found earlier + $Position_NonFree = array(); + $Position_NonFreeCount = 0; + $Position_TotalCount = MAX_SYSTEM_IN_GALAXY * (($Planet_Higher - $Planet_Lower) + 1); + + $Query_CheckGalaxy2 = ''; + $Query_CheckGalaxy2 .= "SELECT `system`, `planet` FROM {{table}} "; + $Query_CheckGalaxy2 .= "WHERE `galaxy` = {$GalaxyNo} AND "; + $Query_CheckGalaxy2 .= "`planet` BETWEEN {$Planet_Lower} AND {$Planet_Higher};"; + $Result_CheckGalaxy2 = doquery($Query_CheckGalaxy2, 'galaxy'); + if(mysql_num_rows($Result_CheckGalaxy2) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_CheckGalaxy2)) + { + $Position_NonFree["{$FetchData['system']}:{$FetchData['planet']}"] = true; + } + $Position_NonFreeCount = count($Position_NonFree); + } + if($Position_NonFreeCount < $Position_TotalCount) + { + while(!$PosFound) + { + $System = mt_rand(1, MAX_SYSTEM_IN_GALAXY); + $Planet = mt_rand($Planet_Lower, $Planet_Higher); + if(!isset($Position_NonFree["{$System}:{$Planet}"])) + { + $PosFound = true; + } + } + } + else + { + // - Step 3: check whole galaxy and all slots which has not been checked + $Position_NonFree = array(); + $Position_NonFreeCount = 0; + for($i = 1; $i < $Planet_Lower; $i += 1) + { + $Planet_PosArray[] = $i; + } + for($i = $Planet_Higher; $i < MAX_PLANET_IN_SYSTEM; $i += 1) + { + $Planet_PosArray[] = $i; + } + $Position_TotalCount = MAX_SYSTEM_IN_GALAXY * count($Planet_PosArray); + + $Query_CheckGalaxy3 = ''; + $Query_CheckGalaxy3 .= "SELECT `system`, `planet` FROM {{table}} "; + $Query_CheckGalaxy3 .= "WHERE `galaxy` = {$GalaxyNo} AND "; + $Query_CheckGalaxy3 .= "`planet` NOT BETWEEN {$Planet_Lower} AND {$Planet_Higher};"; + $Result_CheckGalaxy3 = doquery($Query_CheckGalaxy3, 'galaxy'); + if(mysql_num_rows($Result_CheckGalaxy3) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_CheckGalaxy3)) + { + $Position_NonFree["{$FetchData['system']}:{$FetchData['planet']}"] = true; + } + $Position_NonFreeCount = count($Position_NonFree); + } + if($Position_NonFreeCount < $Position_TotalCount) + { + while(!$PosFound) + { + $System = mt_rand(1, MAX_SYSTEM_IN_GALAXY); + $Planet = $Planet_PosArray[array_rand($Planet_PosArray)]; + if(!isset($Position_NonFree["{$System}:{$Planet}"])) + { + $PosFound = true; + } + } + } + } + } + + if($PosFound) + { + $Query_InsertUser = ''; + $Query_InsertUser .= "INSERT INTO {{table}} SET "; + $Query_InsertUser .= "`username` = '{$Username}', "; + $Query_InsertUser .= "`email` = '{$Email}', "; + $Query_InsertUser .= "`email_2` = '{$Email}', "; + $Query_InsertUser .= "`ip_at_reg` = '{$_SERVER['REMOTE_ADDR']}', "; + $Query_InsertUser .= "`id_planet` = 0, "; + $Query_InsertUser .= "`register_time` = {$Now}, "; + $Query_InsertUser .= "`onlinetime` = {$Now} - (24*60*60), "; + $Query_InsertUser .= "`rules_accept_stamp` = {$Now}, "; + $Query_InsertUser .= "`password` = MD5('{$Password}');"; + doquery($Query_InsertUser, 'users'); + + // Get UserID + $Query_GetUserID = "SELECT LAST_INSERT_ID() AS `ID`;"; + $Result_GetUserID = doquery($Query_GetUserID, '', true); + $UserID = $Result_GetUserID['ID']; + + // Update all MailChanges + doquery("UPDATE {{table}} SET `ConfirmType` = 4 WHERE `NewMail` = '{$Email}' AND `ConfirmType` = 0;", 'mailchange'); + + // Create a Planet for User + include($_EnginePath.'includes/functions/CreateOnePlanetRecord.php'); + $Galaxy = $GalaxyNo; + $PlanetID = CreateOnePlanetRecord($Galaxy, $System, $Planet, $UserID, $_Lang['MotherPlanet'], true); + + // Update Config + $_GameConfig['users_amount'] += 1; + $Query_UpdateConfig = ''; + $Query_UpdateConfig .= "UPDATE {{table}} "; + $Query_UpdateConfig .= "SET `config_value` = {$_GameConfig['users_amount']} "; + $Query_UpdateConfig .= "WHERE `config_name` = 'users_amount';"; + doquery($Query_UpdateConfig, 'config'); + $_MemCache->GameConfig = $_GameConfig; + + // Update User with new data + if(isset($_COOKIE[REFERING_COOKIENAME]) && $_COOKIE[REFERING_COOKIENAME] > 0) + { + $RefID = round($_COOKIE[REFERING_COOKIENAME]); + if($RefID > 0) + { + $Query_SelectReferrer = "SELECT `id` FROM {{table}} WHERE `id` = {$RefID} LIMIT 1;"; + $Result_SelectReferrer = doquery($Query_SelectReferrer, 'users', true); + if($Result_SelectReferrer['id'] > 0) + { + $UserIPs['r'] = trim($_SERVER['REMOTE_ADDR']); + $UserIPs['p'] = preg_replace('#[^a-zA-Z0-9\.\,\:\ ]{1,}#si', '', trim($_SERVER['HTTP_X_FORWARDED_FOR'])); + if(empty($UserIPs['p'])) + { + unset($UserIPs['p']); + } + foreach($UserIPs as $Key => $Data) + { + $CreateRegIP[] = "{$Key},{$Data}"; + $UserIPs[$Key] = "'{$Data}'"; + } + $CreateRegIP = implode(';', $CreateRegIP); + + $Query_InsertRefData_Matches = 'null'; + + $Query_SelectIPMatches = "SELECT `ID` FROM {{table}} WHERE `Type` = 'ip' AND `Value` IN (".implode(',', $UserIPs).");"; + $Result_SelectIPMatches = doquery($Query_SelectIPMatches, 'used_ip_and_ua'); + if(mysql_num_rows($Result_SelectIPMatches) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_SelectIPMatches)) + { + $MatchedIPIDs[] = $FetchData['ID']; + } + + $Query_SelectEnterLogMatches = "SELECT `ID` FROM {{table}} WHERE `IP_ID` IN (".implode(',', $MatchedIPIDs).");"; + $Result_SelectEnterLogMatches = doquery($Query_SelectEnterLogMatches, 'user_enterlog'); + if(mysql_num_rows($Result_SelectEnterLogMatches) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_SelectEnterLogMatches)) + { + $MatchedEnterLogIDs[] = $FetchData['ID']; + } + + $Query_InsertRefData_Matches = '\''.implode(',', $MatchedEnterLogIDs).'\''; + } + } + + $Query_InsertRefData = ''; + $Query_InsertRefData .= "INSERT INTO {{table}} SET "; + $Query_InsertRefData .= "`referrer_id` = {$RefID}, "; + $Query_InsertRefData .= "`newuser_id` = {$UserID}, "; + $Query_InsertRefData .= "`time` = {$Now}, "; + $Query_InsertRefData .= "`reg_ip` = '{$CreateRegIP}', "; + $Query_InsertRefData .= "`matches_found` = {$Query_InsertRefData_Matches};"; + doquery($Query_InsertRefData, 'referring_table'); + + $Message = false; + $Message['msg_id'] = '038'; + $Message['args'] = array(''); + $Message = json_encode($Message); + + SendSimpleMessage($RefID, 0, $Now, 70, '007', '016', $Message); + + $Query_UpdateUser_Fields[] = "`referred` = {$RefID}"; + } + } + } + + $ActivationCode = md5(mt_rand(0, 99999999999)); + + $Query_UpdateUser_Fields[] = "`id_planet` = {$PlanetID}"; + $Query_UpdateUser_Fields[] = "`settings_mainPlanetID` = {$PlanetID}"; + $Query_UpdateUser_Fields[] = "`current_planet` = {$PlanetID}"; + $Query_UpdateUser_Fields[] = "`galaxy` = {$Galaxy}"; + $Query_UpdateUser_Fields[] = "`system` = {$System}"; + $Query_UpdateUser_Fields[] = "`planet` = {$Planet}"; + if(REGISTER_REQUIRE_EMAILCONFIRM) + { + $Query_UpdateUser_Fields[] = "`activation_code` = '{$ActivationCode}'"; + } + else + { + $Query_UpdateUser_Fields[] = "`activation_code` = ''"; + } + + $Query_UpdateUser = ''; + $Query_UpdateUser .= "UPDATE {{table}} SET "; + $Query_UpdateUser .= implode(', ', $Query_UpdateUser_Fields); + $Query_UpdateUser .= " WHERE `id` = {$UserID} LIMIT 1;"; + doquery($Query_UpdateUser, 'users'); + + // Send a invitation private msg + $Message = false; + $Message['msg_id'] = '022'; + $Message['args'] = array(''); + $Message = json_encode($Message); + + SendSimpleMessage($UserID, 0, $Now, 70, '004', '009', $Message); + + if(REGISTER_REQUIRE_EMAILCONFIRM) + { + include($_EnginePath.'includes/functions/SendMail.php'); + $MailParse['login'] = $Username; + $MailParse['password'] = $Password; + $MailParse['Universe'] = $_Lang['RegMail_UniName']; + $MailParse['activationlink'] = ''.GAMEURL.'activate.php?code='.$ActivationCode.''; + $MailParse['UserRefLink'] = ''.GAMEURL.'index.php?r='.$UserID.''; + $MailParsed = parsetemplate($_Lang['mail_template'], $MailParse); + SendMail($Email, $_Lang['mail_title'], $MailParsed); + } + + if(SERVER_MAINOPEN_TSTAMP <= $Now) + { + if(LOCALHOST) + { + require($_EnginePath.'config.localhost.php'); + } + else if(TESTSERVER) + { + require($_EnginePath.'config.testserver.php'); + } + else + { + require($_EnginePath.'config.php'); + } + $cookie = $UserID.'/%/'.$Username.'/%/'.md5(md5($Password).'--'.$__ServerConnectionSettings['secretword']).'/%/0'; + $JSONResponse['Code'] = 1; + $JSONResponse['Cookie'][] = array('Name' => $_GameConfig['COOKIE_NAME'], 'Value' => $cookie); + $JSONResponse['Redirect'] = GAMEURL_UNISTRICT.'/overview.php'; + } + else + { + $JSONResponse['Code'] = 2; + } + } + else + { + $JSONResponse['Errors'][] = 15; + $JSONResponse['BadFields'][] = 'email'; + } + } + die('regCallback('.json_encode($JSONResponse).');'); +} +else +{ + header('Location: index.php'); + die('regCallback({});'); +} + +?> diff --git a/reg_mainpage.php b/reg_mainpage.php index 648a5d271..fc28f1edd 100644 --- a/reg_mainpage.php +++ b/reg_mainpage.php @@ -1,92 +1,92 @@ - array - ( - // If you want to place your Universum on another domain (or subdomain), - // regscripturl is absolute path (with http://) to your Universum reg_ajax.php file - 'regscripturl' => './reg_ajax.php', - 'gamespeed' => 1, - 'resspeed' => 1, - 'fleetspeed' => 1, - 'start' => 0, - 'galaxycount' => 9, - 'acs' => true, - 'rapid' => true, - 'fleetdeb' => 0, - 'defdeb' => '0', - 'mother' => 1, - ), - ); - - if(REGISTER_RECAPTCHA_ENABLE) - { - require($_EnginePath.'includes/recaptchalib.php'); - } - - // Create registry form - $parse = $_Lang; - - $TPL_UniInfoBox = gettemplate('reg_uniinfo_box'); - $TPL_UniSelector = gettemplate('reg_uniselector'); - $TPLInfo_UniInfoBoxWidth = 700; - - $UniIterator = 0; - foreach($UniData as $UniNo => $This) - { - $ThisInfobox = $_Lang; - $ThisInfobox['Insert_UniID'] = $UniNo; - $ThisInfobox['Insert_GameSpeed'] = prettyNumber($This['gamespeed']); - $ThisInfobox['Insert_ResSpeed'] = prettyNumber($This['resspeed']); - $ThisInfobox['Insert_FleetSpeed'] = prettyNumber($This['fleetspeed']); - $ThisInfobox['Insert_UniStart'] = prettyDate('d m Y - H:i', $This['start'], 1); - $ThisInfobox['Insert_WorldSize'] = $This['galaxycount']; - $ThisInfobox['Insert_GameACS'] = ($This['acs'] === true ? $_Lang['UniOpt_Active'] : $_Lang['UniOpt_InActive']); - $ThisInfobox['Insert_GameACS_Color'] = ($This['acs'] === true ? 'lime' : 'red'); - $ThisInfobox['Insert_GameRapidFire'] = ($This['rapid'] === true ? $_Lang['UniOpt_Active'] : $_Lang['UniOpt_InActive']); - $ThisInfobox['Insert_GameRapidFire_Color'] = ($This['rapid'] === true ? 'lime' : 'red'); - $ThisInfobox['Insert_GameFleetDebris'] = $This['fleetdeb']; - $ThisInfobox['Insert_GameDefenseDebris'] = $This['defdeb']; - $ThisInfobox['Insert_MotherSize'] = prettyNumber($This['mother']); - - $ThisInfobox['Insert_UniVal'] = $This['regscripturl']; - if($UniNo == $RecommendedUni) - { - $ThisInfobox['Insert_Selected'] = 'selected'; - $parse['Insert_UniInfo_Holder_LeftPos'] = -($UniIterator * $TPLInfo_UniInfoBoxWidth); - } - if(empty($This['name'])) - { - $ThisInfobox['Insert_UniName'] = $UniNo; - } - - $parse['Insert_UniInfo_Boxes'] = parsetemplate($TPL_UniInfoBox, $ThisInfobox); - $parse['Insert_UniSelectors'] = parsetemplate($TPL_UniSelector, $ThisInfobox); - - $UniIterator += 1; - } - - $parse['GameURL'] = GAMEURL_STRICT; - $parse['GameName'] = $_GameConfig['game_name']; - $parse['Insert_JSLang'] = json_encode($_Lang['JSLang']); - if(REGISTER_RECAPTCHA_ENABLE) - { - $parse['ReCaptchaCode'] = recaptcha_get_html(REGISTER_RECAPTCHA_PUBLICKEY); - } - $page = parsetemplate(gettemplate('registry_form'), $parse); - - display($page, $_Lang['Title'], false); - -?> \ No newline at end of file + array + ( + // If you want to place your Universum on another domain (or subdomain), + // regscripturl is absolute path (with http://) to your Universum reg_ajax.php file + 'regscripturl' => './reg_ajax.php', + 'gamespeed' => 1, + 'resspeed' => 1, + 'fleetspeed' => 1, + 'start' => 0, + 'galaxycount' => 9, + 'acs' => true, + 'rapid' => true, + 'fleetdeb' => 0, + 'defdeb' => '0', + 'mother' => 1, + ), +); + +if(REGISTER_RECAPTCHA_ENABLE) +{ + require($_EnginePath.'includes/recaptchalib.php'); +} + +// Create registry form +$parse = $_Lang; + +$TPL_UniInfoBox = gettemplate('reg_uniinfo_box'); +$TPL_UniSelector = gettemplate('reg_uniselector'); +$TPLInfo_UniInfoBoxWidth = 700; + +$UniIterator = 0; +foreach($UniData as $UniNo => $This) +{ + $ThisInfobox = $_Lang; + $ThisInfobox['Insert_UniID'] = $UniNo; + $ThisInfobox['Insert_GameSpeed'] = prettyNumber($This['gamespeed']); + $ThisInfobox['Insert_ResSpeed'] = prettyNumber($This['resspeed']); + $ThisInfobox['Insert_FleetSpeed'] = prettyNumber($This['fleetspeed']); + $ThisInfobox['Insert_UniStart'] = prettyDate('d m Y - H:i', $This['start'], 1); + $ThisInfobox['Insert_WorldSize'] = $This['galaxycount']; + $ThisInfobox['Insert_GameACS'] = ($This['acs'] === true ? $_Lang['UniOpt_Active'] : $_Lang['UniOpt_InActive']); + $ThisInfobox['Insert_GameACS_Color'] = ($This['acs'] === true ? 'lime' : 'red'); + $ThisInfobox['Insert_GameRapidFire'] = ($This['rapid'] === true ? $_Lang['UniOpt_Active'] : $_Lang['UniOpt_InActive']); + $ThisInfobox['Insert_GameRapidFire_Color'] = ($This['rapid'] === true ? 'lime' : 'red'); + $ThisInfobox['Insert_GameFleetDebris'] = $This['fleetdeb']; + $ThisInfobox['Insert_GameDefenseDebris'] = $This['defdeb']; + $ThisInfobox['Insert_MotherSize'] = prettyNumber($This['mother']); + + $ThisInfobox['Insert_UniVal'] = $This['regscripturl']; + if($UniNo == $RecommendedUni) + { + $ThisInfobox['Insert_Selected'] = 'selected'; + $parse['Insert_UniInfo_Holder_LeftPos'] = -($UniIterator * $TPLInfo_UniInfoBoxWidth); + } + if(empty($This['name'])) + { + $ThisInfobox['Insert_UniName'] = $UniNo; + } + + $parse['Insert_UniInfo_Boxes'] = parsetemplate($TPL_UniInfoBox, $ThisInfobox); + $parse['Insert_UniSelectors'] = parsetemplate($TPL_UniSelector, $ThisInfobox); + + $UniIterator += 1; +} + +$parse['GameURL'] = GAMEURL_STRICT; +$parse['GameName'] = $_GameConfig['game_name']; +$parse['Insert_JSLang'] = json_encode($_Lang['JSLang']); +if(REGISTER_RECAPTCHA_ENABLE) +{ + $parse['ReCaptchaCode'] = recaptcha_get_html(REGISTER_RECAPTCHA_PUBLICKEY); +} +$page = parsetemplate(gettemplate('registry_form'), $parse); + +display($page, $_Lang['Title'], false); + +?> diff --git a/report.php b/report.php index 2cc3b87df..1dda3b867 100644 --- a/report.php +++ b/report.php @@ -1,172 +1,172 @@ - 0 AND !in_array($ReportType, $NeedUsername) AND !in_array($ReportType, $CanHaveUsername)) - { - $UserID = '0'; - } - if($ElementID > 0 AND !in_array($ReportType, $NeedElement)) - { - $ElementID = '0'; - } - - $Query_SendReport = ''; - $Query_SendReport .= "INSERT INTO {{table}} SET "; - $Query_SendReport .= "`date` = UNIX_TIMESTAMP(), "; - $Query_SendReport .= "`sender_id` = {$_User['id']}, "; - $Query_SendReport .= "`report_type` = ".($TypesFlip[$ReportType] + 1).", "; - $Query_SendReport .= "`report_element` = {$ElementID}, "; - $Query_SendReport .= "`report_user` = {$UserID}, "; - $Query_SendReport .= "`user_info` = '".trim(mysql_real_escape_string(strip_tags(stripslashes($_POST['user_info']))))."';"; - doquery($Query_SendReport, 'reports'); - - $Sent = true; - } - } - } - } - - if($Sent === false) - { - $Parse['post_user_info'] = $_POST['user_info']; - $Parse['post_reported_username'] = $_POST['reported_username']; - $Parse['post_eid'] = $_POST['eid']; - $Parse['select_type_'.$ReportType] = 'selected'; - $Parse['Report_send_result'] = '
    '.$ShowMSG.'
     '; - } - else - { - $Parse['Report_send_result'] = '
    '.$_Lang['Report_sent'].'
     '; - } - } - else - { - if(!empty($_GET['eid'])) - { - $Parse['get_eid'] = round($_GET['eid']); - } - if(!empty($_GET['uid'])) - { - $UID = intval($_GET['uid']); - $SelectUIDData = doquery("SELECT `username` FROM {{table}} WHERE `id` = {$UID} LIMIT 1;", 'users', true); - if(!empty($SelectUIDData['username'])) - { - $Parse['get_uid'] = $SelectUIDData['username']; - } - } - $Type = 0; - if(!empty($_GET['type'])) - { - $Type = intval($_GET['type']); - $Parse['select_type_'.$AllowedTypes[($Type - 1)]] = 'selected'; - } - if(!empty($_GET['info'])) - { - $Parse['post_user_info'] = $_GET['info']; - } - - if(($Type != 1 && $Type != 9) || $Parse['get_eid'] <= 0) - { - $Parse['Input_HideType1'] = ' disabled'; - $Parse['select_type_'.$AllowedTypes[0]] = ''; - } - } - - $Page = parsetemplate($PageTPL, $Parse); - display($Page, $_Lang['Title'], false); - -?> \ No newline at end of file + 0 AND !in_array($ReportType, $NeedUsername) AND !in_array($ReportType, $CanHaveUsername)) + { + $UserID = '0'; + } + if($ElementID > 0 AND !in_array($ReportType, $NeedElement)) + { + $ElementID = '0'; + } + + $Query_SendReport = ''; + $Query_SendReport .= "INSERT INTO {{table}} SET "; + $Query_SendReport .= "`date` = UNIX_TIMESTAMP(), "; + $Query_SendReport .= "`sender_id` = {$_User['id']}, "; + $Query_SendReport .= "`report_type` = ".($TypesFlip[$ReportType] + 1).", "; + $Query_SendReport .= "`report_element` = {$ElementID}, "; + $Query_SendReport .= "`report_user` = {$UserID}, "; + $Query_SendReport .= "`user_info` = '".trim(mysql_real_escape_string(strip_tags(stripslashes($_POST['user_info']))))."';"; + doquery($Query_SendReport, 'reports'); + + $Sent = true; + } + } + } + } + + if($Sent === false) + { + $Parse['post_user_info'] = $_POST['user_info']; + $Parse['post_reported_username'] = $_POST['reported_username']; + $Parse['post_eid'] = $_POST['eid']; + $Parse['select_type_'.$ReportType] = 'selected'; + $Parse['Report_send_result'] = '
    '.$ShowMSG.'
     '; + } + else + { + $Parse['Report_send_result'] = '
    '.$_Lang['Report_sent'].'
     '; + } +} +else +{ + if(!empty($_GET['eid'])) + { + $Parse['get_eid'] = round($_GET['eid']); + } + if(!empty($_GET['uid'])) + { + $UID = intval($_GET['uid']); + $SelectUIDData = doquery("SELECT `username` FROM {{table}} WHERE `id` = {$UID} LIMIT 1;", 'users', true); + if(!empty($SelectUIDData['username'])) + { + $Parse['get_uid'] = $SelectUIDData['username']; + } + } + $Type = 0; + if(!empty($_GET['type'])) + { + $Type = intval($_GET['type']); + $Parse['select_type_'.$AllowedTypes[($Type - 1)]] = 'selected'; + } + if(!empty($_GET['info'])) + { + $Parse['post_user_info'] = $_GET['info']; + } + + if(($Type != 1 && $Type != 9) || $Parse['get_eid'] <= 0) + { + $Parse['Input_HideType1'] = ' disabled'; + $Parse['select_type_'.$AllowedTypes[0]] = ''; + } +} + +$Page = parsetemplate($PageTPL, $Parse); +display($Page, $_Lang['Title'], false); + +?> diff --git a/resources.php b/resources.php index 803544019..7abc15857 100644 --- a/resources.php +++ b/resources.php @@ -1,491 +1,491 @@ - $Value) - { - if($Field == 'setUsage2All') - { - if($Value == 'on') - { - $Post_SetUsage2All = true; - } - continue; - } - if(preg_match('/^[a-zA-Z\_]{1,}$/D', $Field)) - { - $FieldName = $Field.'_workpercent'; - if(isset($CurrentPlanet[$FieldName])) - { - if(!in_array($Value, $ValidList['percent'])) - { - message($_Lang['Hacking_attempt'], $_Lang['Warning'], 'resources.php', 3); - } - $Value = $Value / 10; - if($CurrentPlanet[$FieldName] != $Value || $Post_SetUsage2All) - { - $SetPercents[$CurrentPlanet['id']][$FieldName] = array('old' => $CurrentPlanet[$FieldName], 'new' => $Value); - $CurrentPlanet[$FieldName] = $Value; - $UpdatePlanet[] = "`{$FieldName}` = '{$Value}'"; - $FieldName = str_replace('_workpercent', '', $FieldName); - $InsertDevLog[] = "{$FieldName},{$Value}"; - } - } - } - else - { - message($_Lang['Hacking_attempt'], $_Lang['Warning'], 'resources.php', 3); - } - } - if(!empty($UpdatePlanet)) - { - $UpdatePercentIDs[] = $CurrentPlanet['id']; - if($Post_SetUsage2All) - { - $SelectOtherPlanets = doquery("SELECT * FROM {{table}} WHERE `id_owner` = {$CurrentUser['id']} AND `planet_type` = 1 AND `id` != {$CurrentPlanet['id']};", 'planets'); - if(mysql_num_rows($SelectOtherPlanets) > 0) - { - $CopySetPercents = $SetPercents; - $SetPercents = null; - - $Results['planets'] = array(); - while($PlanetData = mysql_fetch_assoc($SelectOtherPlanets)) - { - if(HandlePlanetUpdate($PlanetData, $CurrentUser, $Now, true) === true) - { - $Results['planets'][] = $PlanetData; - } - - $UpdatePercentIDs[] = $PlanetData['id']; - } - HandlePlanetUpdate_MultiUpdate($Results, $CurrentUser); - - $SetPercents = $CopySetPercents; - } - else - { - $Post_SetUsage2All = false; - $_POST['setUsage2All'] = 'off'; - } - } - $QryUpdatePlanet = "UPDATE {{table}} SET "; - $QryUpdatePlanet .= implode(', ', $UpdatePlanet); - $QryUpdatePlanet .= " WHERE "; - if($Post_SetUsage2All) - { - $SetCode = 2; - } - else - { - $SetCode = 1; - } - $QryUpdatePlanet .= "`id` IN (".implode(', ', $UpdatePercentIDs).");"; - doquery($QryUpdatePlanet, 'planets'); - - $UserDev_Log[] = array('PlanetID' => $CurrentPlanet['id'], 'Date' => $Now, 'Place' => 22, 'Code' => $SetCode, 'ElementID' => '0', 'AdditionalData' => implode(';', $InsertDevLog)); - } - } - - $parse = $_Lang; - - // ------------------------------------------------------------------------------------------------------- - // Calculate Storage - $CurrentPlanet['metal_max'] = floor(BASE_STORAGE_SIZE * pow (1.7, $CurrentPlanet[$_Vars_GameElements[22]])); - $CurrentPlanet['crystal_max'] = floor(BASE_STORAGE_SIZE * pow (1.7, $CurrentPlanet[$_Vars_GameElements[23]])); - $CurrentPlanet['deuterium_max'] = floor(BASE_STORAGE_SIZE * pow (1.7, $CurrentPlanet[$_Vars_GameElements[24]])); - - // ------------------------------------------------------------------------------------------------------- - $parse['resource_row'] = ''; - $CurrentPlanet['metal_perhour'] = 0; - $CurrentPlanet['crystal_perhour'] = 0; - $CurrentPlanet['deuterium_perhour'] = 0; - $CurrentPlanet['energy_max'] = 0; - $CurrentPlanet['energy_used'] = 0; - $BuildTemp = $CurrentPlanet['temp_max']; - $Loop = 0; - foreach($_Vars_ElementCategories['prod'] as $ProdID) - { - if(isset($_Vars_ResProduction[$ProdID])) - { - if($CurrentPlanet[$_Vars_GameElements[$ProdID]] <= 0) - { - $CurrRow[$Loop]['zero_level'] = ' class="red"'; - } - - $BuildLevelFactor = $CurrentPlanet[$_Vars_GameElements[$ProdID].'_workpercent']; - $BuildLevel = $CurrentPlanet[$_Vars_GameElements[$ProdID]]; - - $metal = abs(floor( eval ( $_Vars_ResProduction[$ProdID]['formule']['metal'] ) * ( $_GameConfig['resource_multiplier'] ) * (($CurrentUser['geologist_time'] > $Now) ? 1.15 : 1) ) ); - $crystal = abs(floor( eval ( $_Vars_ResProduction[$ProdID]['formule']['crystal'] ) * ( $_GameConfig['resource_multiplier'] ) * (($CurrentUser['geologist_time'] > $Now) ? 1.15 : 1) ) ); - if($ProdID != 12) - { - $deuterium = floor( eval ( $_Vars_ResProduction[$ProdID]['formule']['deuterium'] ) * ( $_GameConfig['resource_multiplier'] ) * (($CurrentUser['geologist_time'] > $Now) ? 1.15 : 1) ); - } - else - { - $deuterium = floor( eval ( $_Vars_ResProduction[$ProdID]['formule']['deuterium'] ) * ( $_GameConfig['resource_multiplier'] ) ); - } - - // Calculate Energy - if($ProdID < 4) - { - $energy = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy'])); - } - else - { - if($ProdID != 12) - { - $energy = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * (($CurrentUser['engineer_time'] > $Now) ? 1.10 : 1)); - } - else - { - $MineDeuteriumUse = floor(eval($_Vars_ResProduction[$ProdID]['formule']['deuterium']) * ($_GameConfig['resource_multiplier'])) * (-1); - if($MineDeuteriumUse > 0) - { - if($CurrentPlanet['deuterium'] <= 0) - { - if(($CurrentPlanet['deuterium_perhour'] + $deuterium) == ($MineDeuteriumUse * (-1))) - { - // If no enough + production of deuterium - $energy = 0; - } - else - { - // If there is still some deuterium in + production to use - $FusionReactorMulti = $CurrentPlanet['deuterium_perhour'] / $MineDeuteriumUse; - if($FusionReactorMulti > 1) - { - $FusionReactorMulti = 1; - } - $energy = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $FusionReactorMulti * (($CurrentUser['engineer_time'] > $Now) ? 1.10 : 1)); - } - } - else - { - $FusionReactorMulti = $CurrentPlanet['deuterium'] / ($MineDeuteriumUse / 3600); - if($FusionReactorMulti > 1) - { - $FusionReactorMulti = 1; - } - - $energy = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $FusionReactorMulti * (($CurrentUser['engineer_time'] > $Now) ? 1.10 : 1)); - } - } - else - { - $energy = 0; - } - } - } - - if($energy > 0) - { - $CurrentPlanet['energy_max']+= $energy; - } - else - { - $CurrentPlanet['energy_used'] += $energy; - } - $CurrentPlanet['metal_perhour'] += $metal; - $CurrentPlanet['crystal_perhour'] += $crystal; - $CurrentPlanet['deuterium_perhour'] += $deuterium; - - $Field = $_Vars_GameElements[$ProdID]."_workpercent"; - $CurrRow[$Loop]['name'] = $_Vars_GameElements[$ProdID]; - $CurrRow[$Loop]['workpercent'] = $CurrentPlanet[$Field]; - $CurrRow[$Loop]['option'] = ''; - for($Option = 10; $Option >= 0; $Option -= 1) - { - $OptValue = $Option * 10; - if($Option == $CurrRow[$Loop]['workpercent']) - { - $OptSelected = ' selected=selected'; - } - else - { - $OptSelected = ''; - } - $CurrRow[$Loop]['option'] .= ""; - } - $CurrRow[$Loop]['ID'] = $ProdID; - $CurrRow[$Loop]['type'] = $_Lang['tech'][$ProdID]; - $CurrRow[$Loop]['level'] = ($ProdID > 200) ? $_Lang['quantity'] : $_Lang['level']; - $CurrRow[$Loop]['level_type'] = $CurrentPlanet[ $_Vars_GameElements[$ProdID] ]; - if($ProdID > 200) - { - $CurrRow[$Loop]['level_type'] = prettyNumber($CurrRow[$Loop]['level_type']); - } - $CurrRow[$Loop]['metal_type'] = $metal; - $CurrRow[$Loop]['crystal_type'] = $crystal; - $CurrRow[$Loop]['deuterium_type'] = $deuterium; - $CurrRow[$Loop]['energy_type'] = $energy; - - $Loop += 1; - } - } - - $parse['Production_of_resources_in_the_planet'] = str_replace('%s', (($CurrentPlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']).' '.$CurrentPlanet['name'], $_Lang['Production_of_resources_in_the_planet']); - if($CurrentPlanet['energy_max'] == 0 AND abs($CurrentPlanet['energy_used']) > 0) - { - $parse['production_level'] = 0; - } - else if($CurrentPlanet['energy_max'] > 0 AND abs($CurrentPlanet['energy_used']) > $CurrentPlanet['energy_max']) - { - $parse['production_level'] = floor(($CurrentPlanet['energy_max'] * 100) / abs($CurrentPlanet['energy_used'])); - } - else - { - $parse['production_level'] = 100; - } - if($parse['production_level'] > 100) - { - $parse['production_level'] = 100; - } - - if(!empty($CurrRow)) - { - foreach($CurrRow as $val) - { - if($val['ID'] < 4) - { - $val['metal_type'] = prettyColorNumber($val['metal_type'] * 0.01 * $parse['production_level']); - $val['crystal_type'] = prettyColorNumber($val['crystal_type'] * 0.01 * $parse['production_level']); - $val['deuterium_type'] = prettyColorNumber($val['deuterium_type'] * 0.01 * $parse['production_level']); - } - else - { - $val['metal_type'] = prettyColorNumber($val['metal_type']); - $val['crystal_type'] = prettyColorNumber($val['crystal_type']); - $val['deuterium_type'] = prettyColorNumber($val['deuterium_type']); - } - $val['energy_type'] = prettyColorNumber($val['energy_type'], true); - $parse['resource_row'] .= parsetemplate ( $RessRowTPL, $val ); - } - } - - $parse['metal_basic_income'] = $_GameConfig['metal_basic_income'] * $_GameConfig['resource_multiplier']; - $parse['crystal_basic_income'] = $_GameConfig['crystal_basic_income'] * $_GameConfig['resource_multiplier']; - $parse['deuterium_basic_income'] = $_GameConfig['deuterium_basic_income'] * $_GameConfig['resource_multiplier']; - $parse['energy_basic_income'] = $_GameConfig['energy_basic_income']; - - if($CurrentPlanet['metal_max'] < $CurrentPlanet['metal']) - { - $parse['metal_max'] = ''; - } - else - { - $parse['metal_max'] = ''; - } - $parse['metal_max'] .= prettyNumber($CurrentPlanet['metal_max'] / 1000) ." {$_Lang['k']}"; - - if($CurrentPlanet['crystal_max'] < $CurrentPlanet['crystal']) - { - $parse['crystal_max'] = ''; - } - else - { - $parse['crystal_max'] = ''; - } - $parse['crystal_max'] .= prettyNumber($CurrentPlanet['crystal_max'] / 1000) ." {$_Lang['k']}"; - - if($CurrentPlanet['deuterium_max'] < $CurrentPlanet['deuterium']) - { - $parse['deuterium_max'] = ''; - } - else - { - $parse['deuterium_max'] = ''; - } - $parse['deuterium_max'] .= prettyNumber($CurrentPlanet['deuterium_max'] / 1000) ." {$_Lang['k']}"; - - $parse['metal_total'] = prettyColorNumber(floor(($CurrentPlanet['metal_perhour'] * 0.01 * $parse['production_level']) + ($_GameConfig['metal_basic_income'] * $_GameConfig['resource_multiplier']))); - $parse['crystal_total'] = prettyColorNumber(floor(($CurrentPlanet['crystal_perhour'] * 0.01 * $parse['production_level']) + ($_GameConfig['crystal_basic_income'] * $_GameConfig['resource_multiplier']))); - $parse['deuterium_total'] = prettyColorNumber(floor(($CurrentPlanet['deuterium_perhour'] * 0.01 * $parse['production_level']) + ($_GameConfig['deuterium_basic_income'] * $_GameConfig['resource_multiplier']))); - $parse['energy_total'] = prettyColorNumber(floor(($CurrentPlanet['energy_max'] + $_GameConfig['energy_basic_income']) + $CurrentPlanet['energy_used'])); - - $parse['daily_metal'] = floor(($CurrentPlanet['metal_perhour'] * 24* 0.01 * $parse['production_level']) + ($parse['metal_basic_income'] * 24)); - $parse['weekly_metal'] = floor(($CurrentPlanet['metal_perhour'] * 24 * 7* 0.01 * $parse['production_level']) + ($parse['metal_basic_income'] * 24 * 7)); - $parse['monthly_metal'] = floor(($CurrentPlanet['metal_perhour'] * 24 * 30 * 0.01 * $parse['production_level']) + ($parse['metal_basic_income'] * 24 * 30 )); - - $parse['daily_crystal'] = floor(($CurrentPlanet['crystal_perhour'] * 24* 0.01 * $parse['production_level']) + ($parse['crystal_basic_income'] * 24)); - $parse['weekly_crystal'] = floor(($CurrentPlanet['crystal_perhour'] * 24 * 7* 0.01 * $parse['production_level']) + ($parse['crystal_basic_income'] * 24 * 7)); - $parse['monthly_crystal'] = floor(($CurrentPlanet['crystal_perhour'] * 24 * 30 * 0.01 * $parse['production_level']) + ($parse['crystal_basic_income'] * 24 * 30 )); - - $parse['daily_deuterium'] = floor(($CurrentPlanet['deuterium_perhour'] * 24* 0.01 * $parse['production_level']) + ($parse['deuterium_basic_income'] * 24)); - $parse['weekly_deuterium'] = floor(($CurrentPlanet['deuterium_perhour'] * 24 * 7* 0.01 * $parse['production_level']) + ($parse['deuterium_basic_income'] * 24 * 7)); - $parse['monthly_deuterium'] = floor(($CurrentPlanet['deuterium_perhour'] * 24 * 30 * 0.01 * $parse['production_level']) + ($parse['deuterium_basic_income'] * 24 * 30 )); - - $parse['daily_metal'] = prettyColorNumber($parse['daily_metal']); - $parse['weekly_metal'] = prettyColorNumber($parse['weekly_metal']); - $parse['monthly_metal'] = prettyColorNumber($parse['monthly_metal']); - - $parse['daily_crystal'] = prettyColorNumber($parse['daily_crystal']); - $parse['weekly_crystal'] = prettyColorNumber($parse['weekly_crystal']); - $parse['monthly_crystal'] = prettyColorNumber($parse['monthly_crystal']); - - $parse['daily_deuterium'] = prettyColorNumber($parse['daily_deuterium']); - $parse['weekly_deuterium'] = prettyColorNumber($parse['weekly_deuterium']); - $parse['monthly_deuterium'] = prettyColorNumber($parse['monthly_deuterium']); - - $parse['metal_storage'] = prettyNumber(floor($CurrentPlanet['metal'] / $CurrentPlanet['metal_max'] * 100)) . $_Lang['o/o']; - $parse['crystal_storage'] = prettyNumber(floor($CurrentPlanet['crystal'] / $CurrentPlanet['crystal_max'] * 100)) . $_Lang['o/o']; - $parse['deuterium_storage'] = prettyNumber(floor($CurrentPlanet['deuterium'] / $CurrentPlanet['deuterium_max'] * 100)) . $_Lang['o/o']; - $parse['metal_storage_bar'] = floor(($CurrentPlanet['metal'] / $CurrentPlanet['metal_max'] * 100) * 2.5); - $parse['crystal_storage_bar'] = floor(($CurrentPlanet['crystal'] / $CurrentPlanet['crystal_max'] * 100) * 2.5); - $parse['deuterium_storage_bar'] = floor(($CurrentPlanet['deuterium'] / $CurrentPlanet['deuterium_max'] * 100) * 2.5); - - if($parse['metal_storage_bar'] > (100 * 2.5)) - { - $parse['metal_storage_bar'] = 250; - $parse['metal_storage_barcolor'] = 'red'; - } - else if($parse['metal_storage_bar'] > (80 * 2.5)) - { - $parse['metal_storage_barcolor'] = 'orange'; - } - else - { - $parse['metal_storage_barcolor'] = 'lime'; - } - - if($parse['crystal_storage_bar'] > (100 * 2.5)) - { - $parse['crystal_storage_bar'] = 250; - $parse['crystal_storage_barcolor'] = 'red'; - } - else if($parse['crystal_storage_bar'] > (80 * 2.5)) - { - $parse['crystal_storage_barcolor'] = 'orange'; - } - else - { - $parse['crystal_storage_barcolor'] = 'lime'; - } - - if($parse['deuterium_storage_bar'] > (100 * 2.5)) - { - $parse['deuterium_storage_bar'] = 250; - $parse['deuterium_storage_barcolor'] = 'red'; - } - else if($parse['deuterium_storage_bar'] > (80 * 2.5)) - { - $parse['deuterium_storage_barcolor'] = 'orange'; - } - else - { - $parse['deuterium_storage_barcolor'] = 'lime'; - } - - if(isOnVacation($CurrentUser)) - { - $parse['production_level'] = 0; - } - - if($parse['production_level'] > 50) - { - $parse['production_level_barcolor'] = 'lime'; - } - else if($parse['production_level'] > 25) - { - $parse['production_level_barcolor'] = 'orange'; - } - else - { - $parse['production_level_barcolor'] = 'red'; - } - - $parse['production_level_bar'] = $parse['production_level'] * 2.5; - $parse['production_level'] = $parse['production_level'].'%'; - if(isOnVacation($CurrentUser)) - { - $parse['production_level'] .= '
    '.$_Lang['VacationMode']; - } - - //----------------------------------------- - $NeedenSmallCargo = ceil(($CurrentPlanet['metal'] + $CurrentPlanet['crystal'] + $CurrentPlanet['deuterium']) / $_Vars_Prices[202]['capacity']); - $NeedenBigCargo = ceil(($CurrentPlanet['metal'] + $CurrentPlanet['crystal'] + $CurrentPlanet['deuterium']) / $_Vars_Prices[203]['capacity']); - $NeedenMegaCargo = ceil(($CurrentPlanet['metal'] + $CurrentPlanet['crystal'] + $CurrentPlanet['deuterium']) / $_Vars_Prices[217]['capacity']); - // Calculate how many is missing - $MissingSmallCargo = $NeedenSmallCargo - $CurrentPlanet['small_cargo_ship']; - $MissingBigCargo = $NeedenBigCargo - $CurrentPlanet['big_cargo_ship']; - $MissingMegaCargo = $NeedenMegaCargo - $CurrentPlanet['mega_cargo_ship']; - // Show us pretty numbers - $NoNeedMoreTransport = ''.$_Lang['no_need_more_transporters'].''; - $parse['missing_s'] = ($MissingSmallCargo > 0) ? prettyNumber($MissingSmallCargo) : $NoNeedMoreTransport; - $parse['missing_b'] = ($MissingBigCargo > 0) ? prettyNumber($MissingBigCargo) : $NoNeedMoreTransport; - $parse['missing_m'] = ($MissingMegaCargo > 0) ? prettyNumber($MissingMegaCargo) : $NoNeedMoreTransport; - - $parse['have_s'] = prettyNumber($CurrentPlanet['small_cargo_ship']); - $parse['have_b'] = prettyNumber($CurrentPlanet['big_cargo_ship']); - $parse['have_m'] = prettyNumber($CurrentPlanet['mega_cargo_ship']); - - $parse['planet_type_res'] = ($CurrentPlanet['planet_type'] == 1) ? $_Lang['from_planet'] : $_Lang['from_moon']; - $parse['nazwa'] = $CurrentPlanet['name']; - $parse['trans_s'] = prettyNumber($NeedenSmallCargo); - $parse['trans_b'] = prettyNumber($NeedenBigCargo); - $parse['trans_m'] = prettyNumber($NeedenMegaCargo); - - $parse['small_cargo_name'] = $_Lang['tech'][202]; - $parse['big_cargo_name'] = $_Lang['tech'][203]; - $parse['mega_cargo_name'] = $_Lang['tech'][217]; - - $parse['metal_basic_income'] = prettyNumber($parse['metal_basic_income']); - $parse['crystal_basic_income'] = prettyNumber($parse['crystal_basic_income']); - $parse['deuterium_basic_income'] = prettyNumber($parse['deuterium_basic_income']); - $parse['energy_basic_income']= prettyNumber($parse['energy_basic_income']); - - if($CurrentUser['geologist_time'] > $Now) - { - $parse['GeologistBonusPercent'] = '15'; - } - else - { - $parse['GeologistBonusPercent'] = '0'; - } - - $page = parsetemplate($RessBodyTPL, $parse); - - return $page; - } - - $Page = BuildRessourcePage($_User, $_Planet); - display($Page, $_Lang['Resources']); - -?> \ No newline at end of file + $Value) + { + if($Field == 'setUsage2All') + { + if($Value == 'on') + { + $Post_SetUsage2All = true; + } + continue; + } + if(preg_match('/^[a-zA-Z\_]{1,}$/D', $Field)) + { + $FieldName = $Field.'_workpercent'; + if(isset($CurrentPlanet[$FieldName])) + { + if(!in_array($Value, $ValidList['percent'])) + { + message($_Lang['Hacking_attempt'], $_Lang['Warning'], 'resources.php', 3); + } + $Value = $Value / 10; + if($CurrentPlanet[$FieldName] != $Value || $Post_SetUsage2All) + { + $SetPercents[$CurrentPlanet['id']][$FieldName] = array('old' => $CurrentPlanet[$FieldName], 'new' => $Value); + $CurrentPlanet[$FieldName] = $Value; + $UpdatePlanet[] = "`{$FieldName}` = '{$Value}'"; + $FieldName = str_replace('_workpercent', '', $FieldName); + $InsertDevLog[] = "{$FieldName},{$Value}"; + } + } + } + else + { + message($_Lang['Hacking_attempt'], $_Lang['Warning'], 'resources.php', 3); + } + } + if(!empty($UpdatePlanet)) + { + $UpdatePercentIDs[] = $CurrentPlanet['id']; + if($Post_SetUsage2All) + { + $SelectOtherPlanets = doquery("SELECT * FROM {{table}} WHERE `id_owner` = {$CurrentUser['id']} AND `planet_type` = 1 AND `id` != {$CurrentPlanet['id']};", 'planets'); + if(mysql_num_rows($SelectOtherPlanets) > 0) + { + $CopySetPercents = $SetPercents; + $SetPercents = null; + + $Results['planets'] = array(); + while($PlanetData = mysql_fetch_assoc($SelectOtherPlanets)) + { + if(HandlePlanetUpdate($PlanetData, $CurrentUser, $Now, true) === true) + { + $Results['planets'][] = $PlanetData; + } + + $UpdatePercentIDs[] = $PlanetData['id']; + } + HandlePlanetUpdate_MultiUpdate($Results, $CurrentUser); + + $SetPercents = $CopySetPercents; + } + else + { + $Post_SetUsage2All = false; + $_POST['setUsage2All'] = 'off'; + } + } + $QryUpdatePlanet = "UPDATE {{table}} SET "; + $QryUpdatePlanet .= implode(', ', $UpdatePlanet); + $QryUpdatePlanet .= " WHERE "; + if($Post_SetUsage2All) + { + $SetCode = 2; + } + else + { + $SetCode = 1; + } + $QryUpdatePlanet .= "`id` IN (".implode(', ', $UpdatePercentIDs).");"; + doquery($QryUpdatePlanet, 'planets'); + + $UserDev_Log[] = array('PlanetID' => $CurrentPlanet['id'], 'Date' => $Now, 'Place' => 22, 'Code' => $SetCode, 'ElementID' => '0', 'AdditionalData' => implode(';', $InsertDevLog)); + } + } + + $parse = $_Lang; + + // ------------------------------------------------------------------------------------------------------- + // Calculate Storage + $CurrentPlanet['metal_max'] = floor(BASE_STORAGE_SIZE * pow (1.7, $CurrentPlanet[$_Vars_GameElements[22]])); + $CurrentPlanet['crystal_max'] = floor(BASE_STORAGE_SIZE * pow (1.7, $CurrentPlanet[$_Vars_GameElements[23]])); + $CurrentPlanet['deuterium_max'] = floor(BASE_STORAGE_SIZE * pow (1.7, $CurrentPlanet[$_Vars_GameElements[24]])); + + // ------------------------------------------------------------------------------------------------------- + $parse['resource_row'] = ''; + $CurrentPlanet['metal_perhour'] = 0; + $CurrentPlanet['crystal_perhour'] = 0; + $CurrentPlanet['deuterium_perhour'] = 0; + $CurrentPlanet['energy_max'] = 0; + $CurrentPlanet['energy_used'] = 0; + $BuildTemp = $CurrentPlanet['temp_max']; + $Loop = 0; + foreach($_Vars_ElementCategories['prod'] as $ProdID) + { + if(isset($_Vars_ResProduction[$ProdID])) + { + if($CurrentPlanet[$_Vars_GameElements[$ProdID]] <= 0) + { + $CurrRow[$Loop]['zero_level'] = ' class="red"'; + } + + $BuildLevelFactor = $CurrentPlanet[$_Vars_GameElements[$ProdID].'_workpercent']; + $BuildLevel = $CurrentPlanet[$_Vars_GameElements[$ProdID]]; + + $metal = abs(floor( eval ( $_Vars_ResProduction[$ProdID]['formule']['metal'] ) * ( $_GameConfig['resource_multiplier'] ) * (($CurrentUser['geologist_time'] > $Now) ? 1.15 : 1) ) ); + $crystal = abs(floor( eval ( $_Vars_ResProduction[$ProdID]['formule']['crystal'] ) * ( $_GameConfig['resource_multiplier'] ) * (($CurrentUser['geologist_time'] > $Now) ? 1.15 : 1) ) ); + if($ProdID != 12) + { + $deuterium = floor( eval ( $_Vars_ResProduction[$ProdID]['formule']['deuterium'] ) * ( $_GameConfig['resource_multiplier'] ) * (($CurrentUser['geologist_time'] > $Now) ? 1.15 : 1) ); + } + else + { + $deuterium = floor( eval ( $_Vars_ResProduction[$ProdID]['formule']['deuterium'] ) * ( $_GameConfig['resource_multiplier'] ) ); + } + + // Calculate Energy + if($ProdID < 4) + { + $energy = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy'])); + } + else + { + if($ProdID != 12) + { + $energy = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * (($CurrentUser['engineer_time'] > $Now) ? 1.10 : 1)); + } + else + { + $MineDeuteriumUse = floor(eval($_Vars_ResProduction[$ProdID]['formule']['deuterium']) * ($_GameConfig['resource_multiplier'])) * (-1); + if($MineDeuteriumUse > 0) + { + if($CurrentPlanet['deuterium'] <= 0) + { + if(($CurrentPlanet['deuterium_perhour'] + $deuterium) == ($MineDeuteriumUse * (-1))) + { + // If no enough + production of deuterium + $energy = 0; + } + else + { + // If there is still some deuterium in + production to use + $FusionReactorMulti = $CurrentPlanet['deuterium_perhour'] / $MineDeuteriumUse; + if($FusionReactorMulti > 1) + { + $FusionReactorMulti = 1; + } + $energy = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $FusionReactorMulti * (($CurrentUser['engineer_time'] > $Now) ? 1.10 : 1)); + } + } + else + { + $FusionReactorMulti = $CurrentPlanet['deuterium'] / ($MineDeuteriumUse / 3600); + if($FusionReactorMulti > 1) + { + $FusionReactorMulti = 1; + } + + $energy = floor(eval($_Vars_ResProduction[$ProdID]['formule']['energy']) * $FusionReactorMulti * (($CurrentUser['engineer_time'] > $Now) ? 1.10 : 1)); + } + } + else + { + $energy = 0; + } + } + } + + if($energy > 0) + { + $CurrentPlanet['energy_max']+= $energy; + } + else + { + $CurrentPlanet['energy_used'] += $energy; + } + $CurrentPlanet['metal_perhour'] += $metal; + $CurrentPlanet['crystal_perhour'] += $crystal; + $CurrentPlanet['deuterium_perhour'] += $deuterium; + + $Field = $_Vars_GameElements[$ProdID]."_workpercent"; + $CurrRow[$Loop]['name'] = $_Vars_GameElements[$ProdID]; + $CurrRow[$Loop]['workpercent'] = $CurrentPlanet[$Field]; + $CurrRow[$Loop]['option'] = ''; + for($Option = 10; $Option >= 0; $Option -= 1) + { + $OptValue = $Option * 10; + if($Option == $CurrRow[$Loop]['workpercent']) + { + $OptSelected = ' selected=selected'; + } + else + { + $OptSelected = ''; + } + $CurrRow[$Loop]['option'] .= ""; + } + $CurrRow[$Loop]['ID'] = $ProdID; + $CurrRow[$Loop]['type'] = $_Lang['tech'][$ProdID]; + $CurrRow[$Loop]['level'] = ($ProdID > 200) ? $_Lang['quantity'] : $_Lang['level']; + $CurrRow[$Loop]['level_type'] = $CurrentPlanet[ $_Vars_GameElements[$ProdID] ]; + if($ProdID > 200) + { + $CurrRow[$Loop]['level_type'] = prettyNumber($CurrRow[$Loop]['level_type']); + } + $CurrRow[$Loop]['metal_type'] = $metal; + $CurrRow[$Loop]['crystal_type'] = $crystal; + $CurrRow[$Loop]['deuterium_type'] = $deuterium; + $CurrRow[$Loop]['energy_type'] = $energy; + + $Loop += 1; + } + } + + $parse['Production_of_resources_in_the_planet'] = str_replace('%s', (($CurrentPlanet['planet_type'] == 1) ? $_Lang['on_planet'] : $_Lang['on_moon']).' '.$CurrentPlanet['name'], $_Lang['Production_of_resources_in_the_planet']); + if($CurrentPlanet['energy_max'] == 0 AND abs($CurrentPlanet['energy_used']) > 0) + { + $parse['production_level'] = 0; + } + else if($CurrentPlanet['energy_max'] > 0 AND abs($CurrentPlanet['energy_used']) > $CurrentPlanet['energy_max']) + { + $parse['production_level'] = floor(($CurrentPlanet['energy_max'] * 100) / abs($CurrentPlanet['energy_used'])); + } + else + { + $parse['production_level'] = 100; + } + if($parse['production_level'] > 100) + { + $parse['production_level'] = 100; + } + + if(!empty($CurrRow)) + { + foreach($CurrRow as $val) + { + if($val['ID'] < 4) + { + $val['metal_type'] = prettyColorNumber($val['metal_type'] * 0.01 * $parse['production_level']); + $val['crystal_type'] = prettyColorNumber($val['crystal_type'] * 0.01 * $parse['production_level']); + $val['deuterium_type'] = prettyColorNumber($val['deuterium_type'] * 0.01 * $parse['production_level']); + } + else + { + $val['metal_type'] = prettyColorNumber($val['metal_type']); + $val['crystal_type'] = prettyColorNumber($val['crystal_type']); + $val['deuterium_type'] = prettyColorNumber($val['deuterium_type']); + } + $val['energy_type'] = prettyColorNumber($val['energy_type'], true); + $parse['resource_row'] .= parsetemplate ( $RessRowTPL, $val ); + } + } + + $parse['metal_basic_income'] = $_GameConfig['metal_basic_income'] * $_GameConfig['resource_multiplier']; + $parse['crystal_basic_income'] = $_GameConfig['crystal_basic_income'] * $_GameConfig['resource_multiplier']; + $parse['deuterium_basic_income'] = $_GameConfig['deuterium_basic_income'] * $_GameConfig['resource_multiplier']; + $parse['energy_basic_income'] = $_GameConfig['energy_basic_income']; + + if($CurrentPlanet['metal_max'] < $CurrentPlanet['metal']) + { + $parse['metal_max'] = ''; + } + else + { + $parse['metal_max'] = ''; + } + $parse['metal_max'] .= prettyNumber($CurrentPlanet['metal_max'] / 1000) ." {$_Lang['k']}"; + + if($CurrentPlanet['crystal_max'] < $CurrentPlanet['crystal']) + { + $parse['crystal_max'] = ''; + } + else + { + $parse['crystal_max'] = ''; + } + $parse['crystal_max'] .= prettyNumber($CurrentPlanet['crystal_max'] / 1000) ." {$_Lang['k']}"; + + if($CurrentPlanet['deuterium_max'] < $CurrentPlanet['deuterium']) + { + $parse['deuterium_max'] = ''; + } + else + { + $parse['deuterium_max'] = ''; + } + $parse['deuterium_max'] .= prettyNumber($CurrentPlanet['deuterium_max'] / 1000) ." {$_Lang['k']}"; + + $parse['metal_total'] = prettyColorNumber(floor(($CurrentPlanet['metal_perhour'] * 0.01 * $parse['production_level']) + ($_GameConfig['metal_basic_income'] * $_GameConfig['resource_multiplier']))); + $parse['crystal_total'] = prettyColorNumber(floor(($CurrentPlanet['crystal_perhour'] * 0.01 * $parse['production_level']) + ($_GameConfig['crystal_basic_income'] * $_GameConfig['resource_multiplier']))); + $parse['deuterium_total'] = prettyColorNumber(floor(($CurrentPlanet['deuterium_perhour'] * 0.01 * $parse['production_level']) + ($_GameConfig['deuterium_basic_income'] * $_GameConfig['resource_multiplier']))); + $parse['energy_total'] = prettyColorNumber(floor(($CurrentPlanet['energy_max'] + $_GameConfig['energy_basic_income']) + $CurrentPlanet['energy_used'])); + + $parse['daily_metal'] = floor(($CurrentPlanet['metal_perhour'] * 24* 0.01 * $parse['production_level']) + ($parse['metal_basic_income'] * 24)); + $parse['weekly_metal'] = floor(($CurrentPlanet['metal_perhour'] * 24 * 7* 0.01 * $parse['production_level']) + ($parse['metal_basic_income'] * 24 * 7)); + $parse['monthly_metal'] = floor(($CurrentPlanet['metal_perhour'] * 24 * 30 * 0.01 * $parse['production_level']) + ($parse['metal_basic_income'] * 24 * 30 )); + + $parse['daily_crystal'] = floor(($CurrentPlanet['crystal_perhour'] * 24* 0.01 * $parse['production_level']) + ($parse['crystal_basic_income'] * 24)); + $parse['weekly_crystal'] = floor(($CurrentPlanet['crystal_perhour'] * 24 * 7* 0.01 * $parse['production_level']) + ($parse['crystal_basic_income'] * 24 * 7)); + $parse['monthly_crystal'] = floor(($CurrentPlanet['crystal_perhour'] * 24 * 30 * 0.01 * $parse['production_level']) + ($parse['crystal_basic_income'] * 24 * 30 )); + + $parse['daily_deuterium'] = floor(($CurrentPlanet['deuterium_perhour'] * 24* 0.01 * $parse['production_level']) + ($parse['deuterium_basic_income'] * 24)); + $parse['weekly_deuterium'] = floor(($CurrentPlanet['deuterium_perhour'] * 24 * 7* 0.01 * $parse['production_level']) + ($parse['deuterium_basic_income'] * 24 * 7)); + $parse['monthly_deuterium'] = floor(($CurrentPlanet['deuterium_perhour'] * 24 * 30 * 0.01 * $parse['production_level']) + ($parse['deuterium_basic_income'] * 24 * 30 )); + + $parse['daily_metal'] = prettyColorNumber($parse['daily_metal']); + $parse['weekly_metal'] = prettyColorNumber($parse['weekly_metal']); + $parse['monthly_metal'] = prettyColorNumber($parse['monthly_metal']); + + $parse['daily_crystal'] = prettyColorNumber($parse['daily_crystal']); + $parse['weekly_crystal'] = prettyColorNumber($parse['weekly_crystal']); + $parse['monthly_crystal'] = prettyColorNumber($parse['monthly_crystal']); + + $parse['daily_deuterium'] = prettyColorNumber($parse['daily_deuterium']); + $parse['weekly_deuterium'] = prettyColorNumber($parse['weekly_deuterium']); + $parse['monthly_deuterium'] = prettyColorNumber($parse['monthly_deuterium']); + + $parse['metal_storage'] = prettyNumber(floor($CurrentPlanet['metal'] / $CurrentPlanet['metal_max'] * 100)) . $_Lang['o/o']; + $parse['crystal_storage'] = prettyNumber(floor($CurrentPlanet['crystal'] / $CurrentPlanet['crystal_max'] * 100)) . $_Lang['o/o']; + $parse['deuterium_storage'] = prettyNumber(floor($CurrentPlanet['deuterium'] / $CurrentPlanet['deuterium_max'] * 100)) . $_Lang['o/o']; + $parse['metal_storage_bar'] = floor(($CurrentPlanet['metal'] / $CurrentPlanet['metal_max'] * 100) * 2.5); + $parse['crystal_storage_bar'] = floor(($CurrentPlanet['crystal'] / $CurrentPlanet['crystal_max'] * 100) * 2.5); + $parse['deuterium_storage_bar'] = floor(($CurrentPlanet['deuterium'] / $CurrentPlanet['deuterium_max'] * 100) * 2.5); + + if($parse['metal_storage_bar'] > (100 * 2.5)) + { + $parse['metal_storage_bar'] = 250; + $parse['metal_storage_barcolor'] = 'red'; + } + else if($parse['metal_storage_bar'] > (80 * 2.5)) + { + $parse['metal_storage_barcolor'] = 'orange'; + } + else + { + $parse['metal_storage_barcolor'] = 'lime'; + } + + if($parse['crystal_storage_bar'] > (100 * 2.5)) + { + $parse['crystal_storage_bar'] = 250; + $parse['crystal_storage_barcolor'] = 'red'; + } + else if($parse['crystal_storage_bar'] > (80 * 2.5)) + { + $parse['crystal_storage_barcolor'] = 'orange'; + } + else + { + $parse['crystal_storage_barcolor'] = 'lime'; + } + + if($parse['deuterium_storage_bar'] > (100 * 2.5)) + { + $parse['deuterium_storage_bar'] = 250; + $parse['deuterium_storage_barcolor'] = 'red'; + } + else if($parse['deuterium_storage_bar'] > (80 * 2.5)) + { + $parse['deuterium_storage_barcolor'] = 'orange'; + } + else + { + $parse['deuterium_storage_barcolor'] = 'lime'; + } + + if(isOnVacation($CurrentUser)) + { + $parse['production_level'] = 0; + } + + if($parse['production_level'] > 50) + { + $parse['production_level_barcolor'] = 'lime'; + } + else if($parse['production_level'] > 25) + { + $parse['production_level_barcolor'] = 'orange'; + } + else + { + $parse['production_level_barcolor'] = 'red'; + } + + $parse['production_level_bar'] = $parse['production_level'] * 2.5; + $parse['production_level'] = $parse['production_level'].'%'; + if(isOnVacation($CurrentUser)) + { + $parse['production_level'] .= '
    '.$_Lang['VacationMode']; + } + + //----------------------------------------- + $NeedenSmallCargo = ceil(($CurrentPlanet['metal'] + $CurrentPlanet['crystal'] + $CurrentPlanet['deuterium']) / $_Vars_Prices[202]['capacity']); + $NeedenBigCargo = ceil(($CurrentPlanet['metal'] + $CurrentPlanet['crystal'] + $CurrentPlanet['deuterium']) / $_Vars_Prices[203]['capacity']); + $NeedenMegaCargo = ceil(($CurrentPlanet['metal'] + $CurrentPlanet['crystal'] + $CurrentPlanet['deuterium']) / $_Vars_Prices[217]['capacity']); + // Calculate how many is missing + $MissingSmallCargo = $NeedenSmallCargo - $CurrentPlanet['small_cargo_ship']; + $MissingBigCargo = $NeedenBigCargo - $CurrentPlanet['big_cargo_ship']; + $MissingMegaCargo = $NeedenMegaCargo - $CurrentPlanet['mega_cargo_ship']; + // Show us pretty numbers + $NoNeedMoreTransport = ''.$_Lang['no_need_more_transporters'].''; + $parse['missing_s'] = ($MissingSmallCargo > 0) ? prettyNumber($MissingSmallCargo) : $NoNeedMoreTransport; + $parse['missing_b'] = ($MissingBigCargo > 0) ? prettyNumber($MissingBigCargo) : $NoNeedMoreTransport; + $parse['missing_m'] = ($MissingMegaCargo > 0) ? prettyNumber($MissingMegaCargo) : $NoNeedMoreTransport; + + $parse['have_s'] = prettyNumber($CurrentPlanet['small_cargo_ship']); + $parse['have_b'] = prettyNumber($CurrentPlanet['big_cargo_ship']); + $parse['have_m'] = prettyNumber($CurrentPlanet['mega_cargo_ship']); + + $parse['planet_type_res'] = ($CurrentPlanet['planet_type'] == 1) ? $_Lang['from_planet'] : $_Lang['from_moon']; + $parse['nazwa'] = $CurrentPlanet['name']; + $parse['trans_s'] = prettyNumber($NeedenSmallCargo); + $parse['trans_b'] = prettyNumber($NeedenBigCargo); + $parse['trans_m'] = prettyNumber($NeedenMegaCargo); + + $parse['small_cargo_name'] = $_Lang['tech'][202]; + $parse['big_cargo_name'] = $_Lang['tech'][203]; + $parse['mega_cargo_name'] = $_Lang['tech'][217]; + + $parse['metal_basic_income'] = prettyNumber($parse['metal_basic_income']); + $parse['crystal_basic_income'] = prettyNumber($parse['crystal_basic_income']); + $parse['deuterium_basic_income'] = prettyNumber($parse['deuterium_basic_income']); + $parse['energy_basic_income']= prettyNumber($parse['energy_basic_income']); + + if($CurrentUser['geologist_time'] > $Now) + { + $parse['GeologistBonusPercent'] = '15'; + } + else + { + $parse['GeologistBonusPercent'] = '0'; + } + + $page = parsetemplate($RessBodyTPL, $parse); + + return $page; +} + +$Page = BuildRessourcePage($_User, $_Planet); +display($Page, $_Lang['Resources']); + +?> diff --git a/rocket_simulator.php b/rocket_simulator.php index 91490acea..af78b91f6 100644 --- a/rocket_simulator.php +++ b/rocket_simulator.php @@ -1,267 +1,267 @@ - $Value) - { - if($Item == 'tech') - { - $DefTech = intval($Value); - if($DefTech < 0) - { - $DefTech = 0; - } - } - else if($Item == '502') - { - $ICMissiles = round(floatval($Value)); - if($ICMissiles < 0) - { - $ICMissiles = 0; - } - } - else if($Item == 'sys') - { - foreach($Value as $ID => $Count) - { - if($ID > 400 AND $ID < 500 AND !empty($_Vars_GameElements[$ID])) - { - $Count = round(floatval($Count)); - if($Count > 0) - { - $PlanetDefSys[$ID] = $Count; - $TotalDefsCount += $Count; - } - } - } - } - } - - foreach($_POST['atk'] as $Item => $Value) - { - if($Item == 'tech') - { - $AtkTech = intval($Value); - if($AtkTech < 0) - { - $AtkTech = 0; - } - } - else if($Item == '503') - { - $IPMissiles = round(floatval($Value)); - if($IPMissiles < 0) - { - $IPMissiles = 0; - } - $IPMissilesOrg = $IPMissiles; - } - else if($Item == 'target') - { - $Value = intval($Value); - if($Value <= 0) - { - $Target = 0; - } - else - { - if($Value < 100 AND !empty($_Vars_GameElements[($Value + 400)])) - { - $Target = $Value; - } - else - { - $Target = 0; - } - } - } - } - - if($IPMissiles == 0) - { - $FatalError = $_Lang['No_IPM_Given']; - } - if($TotalDefsCount == 0) - { - if($FatalError !== false) - { - $FatalError .= '
    '; - } - $FatalError .= $_Lang['No_Defs_Given']; - } - - if($FatalError === false) - { - if($IPMissiles <= $ICMissiles) - { - $ResultContent = ''.$_Lang['IPMissiles_Destroyed'].''; - } - else - { - if($ICMissiles > 0) - { - $IPMissiles -= $ICMissiles; - $ResultContent = ''.sprintf($_Lang['IPMissiles_CapturedX'], $ICMissiles).''; - } - - include('includes/functions/CalcInterplanetaryAttack.php'); - - $Attack = CalcInterplanetaryAttack($DefTech, $AtkTech, $IPMissiles, $PlanetDefSys, $Target); - - if($Attack['DestroyedTotal'] > 0) - { - $ResultTables['left'][] = $_Lang['Destroyed_Sys']; - $ResultTables['left'][] = ''; - foreach($Attack['Destroyed'] as $key => $val) - { - if($val > 0) - { - $ResultTables['left'][] = $_Lang['tech'][$key].' ( -'.prettyNumber($val).')';; - } - } - $ResultTables['left'][] = ''; - $ResultTables['left'][] = $_Lang['Destroyed_Sys_Count'].' '.prettyNumber($Attack['DestroyedTotal']); - $ResultTables['left'][] = ''; - $ResultTables['left'][] = $_Lang['Lost_units_Sys']; - $ResultTables['left'][] = prettyNumber($Attack['Metal_loss']).' '.$_Lang['units'].' '.$_Lang['Metal_rec']; - $ResultTables['left'][] = prettyNumber($Attack['Crystal_loss']).' '.$_Lang['units'].' '.$_Lang['Crystal_rec']; - $ResultTables['left'][] = prettyNumber($Attack['Deuterium_loss']).' '.$_Lang['units'].' '.$_Lang['Deuterium_rec']; - } - else - { - $ResultTables['left'][] = $_Lang['Nothing_destroyed']; - $ResultTables['left'][] = ''; - } - $ResultTables['right'][] = $_Lang['Range']; - $ResultTables['right'][] = prettyNumber($Attack['IPM_Range']).' '.$_Lang['SquareMeters']; - if($_GameConfig['Debris_Def_Rocket'] > 0) - { - $ResultTables['right'][] = ''; - $ResultTables['right'][] = $_Lang['DefDebris']; - $ResultTables['right'][] = prettyNumber($Attack['Debris']['metal']).' '.$_Lang['units'].' '.$_Lang['Metal_rec']; - $ResultTables['right'][] = prettyNumber($Attack['Debris']['crystal']).' '.$_Lang['units'].' '.$_Lang['Crystal_rec']; - } - } - if($ICMissiles > 0) - { - if(!empty($ResultTables['left'])) - { - $ResultTables['left'][] = ''; - } - if($ICMissiles >= $IPMissilesOrg) - { - $ICMissilesUsed = $IPMissiles; - } - else - { - $ICMissilesUsed = $ICMissiles; - } - $_Lang['LostICM'] = '-'.prettyNumber($ICMissilesUsed).''; - $ResultTables['left'][] = $_Lang['Lost_units_ICM']; - $ResultTables['left'][] = prettyNumber($ICMissilesUsed * $_Vars_Prices[502]['metal']).' '.$_Lang['units'].' '.$_Lang['Metal_rec']; - $ResultTables['left'][] = prettyNumber($ICMissilesUsed * $_Vars_Prices[502]['deuterium']).' '.$_Lang['units'].' '.$_Lang['Deuterium_rec']; - } - if(!empty($ResultTables['right'])) - { - $ResultTables['right'][] = ''; - } - $ResultTables['right'][] = $_Lang['Lost_units_IPM']; - $ResultTables['right'][] = prettyNumber($IPMissilesOrg * $_Vars_Prices[503]['metal']).' '.$_Lang['units'].' '.$_Lang['Metal_rec']; - $ResultTables['right'][] = prettyNumber($IPMissilesOrg * $_Vars_Prices[503]['crystal']).' '.$_Lang['units'].' '.$_Lang['Crystal_rec']; - $ResultTables['right'][] = prettyNumber($IPMissilesOrg * $_Vars_Prices[503]['deuterium']).' '.$_Lang['units'].' '.$_Lang['Deuterium_rec']; - } - else - { - $ResultContent = ''.$FatalError.''; - } - - $_Lang['Result'] = ''.$_Lang['Sim_Result'].''; - if(!empty($ResultContent)) - { - $_Lang['Result'] .= ''.$ResultContent.''; - } - if(!empty($ResultTables)) - { - $_Lang['Result'] .= ''.implode('
    ', $ResultTables['left']).''.implode('
    ', $ResultTables['right']).''; - } - $_Lang['Result'] .= ''; - - } - - $_Lang['DefTech']= $_Lang['tech'][111]; - $_Lang['AtkTech']= $_Lang['tech'][109]; - - $PrepareTargetList = ''; - - if($DefTech > 0) - { - $_Lang['SetDefTech'] = $DefTech; - } - if($AtkTech > 0) - { - $_Lang['SetAtkTech'] = $AtkTech; - } - if($IPMissilesOrg > 0) - { - $_Lang['SetIPM'] = $IPMissilesOrg; - } - if($ICMissiles > 0) - { - $_Lang['SetICM'] = $ICMissiles; - } - - $_Lang['DefenceRows'] = ''; - foreach($_Vars_GameElements as $ID => $DBName) - { - if(!empty($DBName)) - { - if($ID > 400 AND $ID < 500 AND !empty($_Lang['tech'][$ID])) - { - $ThisRow_InsertValue = null; - if(isset($PlanetDefSys[$ID]) && $PlanetDefSys[$ID] > 0) - { - $ThisRow_InsertValue = ' value="'.$PlanetDefSys[$ID].'"'; - } - - $_Lang['DefenceRows'] .= ''.$_Lang['tech'][$ID].': '.((isset($Attack['Destroyed'][$ID]) && $Attack['Destroyed'][$ID] > 0) ? ('-'.prettyNumber($Attack['Destroyed'][$ID]).'') : '').''; - if(!isset($TargetSel)) - { - $_Lang['DefenceRows'] .= ''.$_Lang['MainTarget'].''; - $TargetSel = true; - } - else - { - $_Lang['DefenceRows'] .= ' '; - } - $_Lang['DefenceRows'] .= ''; - $PrepareTargetList .= ''; - } - } - } - $_Lang['DefenceRows'] = str_replace('{$PrepareTargetList}', $PrepareTargetList, $_Lang['DefenceRows']); - - //Display page - $page = parsetemplate(gettemplate('rocket_simulator'), $_Lang); - - display($page, $_Lang['Title'], false); - -?> \ No newline at end of file + $Value) + { + if($Item == 'tech') + { + $DefTech = intval($Value); + if($DefTech < 0) + { + $DefTech = 0; + } + } + else if($Item == '502') + { + $ICMissiles = round(floatval($Value)); + if($ICMissiles < 0) + { + $ICMissiles = 0; + } + } + else if($Item == 'sys') + { + foreach($Value as $ID => $Count) + { + if($ID > 400 AND $ID < 500 AND !empty($_Vars_GameElements[$ID])) + { + $Count = round(floatval($Count)); + if($Count > 0) + { + $PlanetDefSys[$ID] = $Count; + $TotalDefsCount += $Count; + } + } + } + } + } + + foreach($_POST['atk'] as $Item => $Value) + { + if($Item == 'tech') + { + $AtkTech = intval($Value); + if($AtkTech < 0) + { + $AtkTech = 0; + } + } + else if($Item == '503') + { + $IPMissiles = round(floatval($Value)); + if($IPMissiles < 0) + { + $IPMissiles = 0; + } + $IPMissilesOrg = $IPMissiles; + } + else if($Item == 'target') + { + $Value = intval($Value); + if($Value <= 0) + { + $Target = 0; + } + else + { + if($Value < 100 AND !empty($_Vars_GameElements[($Value + 400)])) + { + $Target = $Value; + } + else + { + $Target = 0; + } + } + } + } + + if($IPMissiles == 0) + { + $FatalError = $_Lang['No_IPM_Given']; + } + if($TotalDefsCount == 0) + { + if($FatalError !== false) + { + $FatalError .= '
    '; + } + $FatalError .= $_Lang['No_Defs_Given']; + } + + if($FatalError === false) + { + if($IPMissiles <= $ICMissiles) + { + $ResultContent = ''.$_Lang['IPMissiles_Destroyed'].''; + } + else + { + if($ICMissiles > 0) + { + $IPMissiles -= $ICMissiles; + $ResultContent = ''.sprintf($_Lang['IPMissiles_CapturedX'], $ICMissiles).''; + } + + include('includes/functions/CalcInterplanetaryAttack.php'); + + $Attack = CalcInterplanetaryAttack($DefTech, $AtkTech, $IPMissiles, $PlanetDefSys, $Target); + + if($Attack['DestroyedTotal'] > 0) + { + $ResultTables['left'][] = $_Lang['Destroyed_Sys']; + $ResultTables['left'][] = ''; + foreach($Attack['Destroyed'] as $key => $val) + { + if($val > 0) + { + $ResultTables['left'][] = $_Lang['tech'][$key].' ( -'.prettyNumber($val).')';; + } + } + $ResultTables['left'][] = ''; + $ResultTables['left'][] = $_Lang['Destroyed_Sys_Count'].' '.prettyNumber($Attack['DestroyedTotal']); + $ResultTables['left'][] = ''; + $ResultTables['left'][] = $_Lang['Lost_units_Sys']; + $ResultTables['left'][] = prettyNumber($Attack['Metal_loss']).' '.$_Lang['units'].' '.$_Lang['Metal_rec']; + $ResultTables['left'][] = prettyNumber($Attack['Crystal_loss']).' '.$_Lang['units'].' '.$_Lang['Crystal_rec']; + $ResultTables['left'][] = prettyNumber($Attack['Deuterium_loss']).' '.$_Lang['units'].' '.$_Lang['Deuterium_rec']; + } + else + { + $ResultTables['left'][] = $_Lang['Nothing_destroyed']; + $ResultTables['left'][] = ''; + } + $ResultTables['right'][] = $_Lang['Range']; + $ResultTables['right'][] = prettyNumber($Attack['IPM_Range']).' '.$_Lang['SquareMeters']; + if($_GameConfig['Debris_Def_Rocket'] > 0) + { + $ResultTables['right'][] = ''; + $ResultTables['right'][] = $_Lang['DefDebris']; + $ResultTables['right'][] = prettyNumber($Attack['Debris']['metal']).' '.$_Lang['units'].' '.$_Lang['Metal_rec']; + $ResultTables['right'][] = prettyNumber($Attack['Debris']['crystal']).' '.$_Lang['units'].' '.$_Lang['Crystal_rec']; + } + } + if($ICMissiles > 0) + { + if(!empty($ResultTables['left'])) + { + $ResultTables['left'][] = ''; + } + if($ICMissiles >= $IPMissilesOrg) + { + $ICMissilesUsed = $IPMissiles; + } + else + { + $ICMissilesUsed = $ICMissiles; + } + $_Lang['LostICM'] = '-'.prettyNumber($ICMissilesUsed).''; + $ResultTables['left'][] = $_Lang['Lost_units_ICM']; + $ResultTables['left'][] = prettyNumber($ICMissilesUsed * $_Vars_Prices[502]['metal']).' '.$_Lang['units'].' '.$_Lang['Metal_rec']; + $ResultTables['left'][] = prettyNumber($ICMissilesUsed * $_Vars_Prices[502]['deuterium']).' '.$_Lang['units'].' '.$_Lang['Deuterium_rec']; + } + if(!empty($ResultTables['right'])) + { + $ResultTables['right'][] = ''; + } + $ResultTables['right'][] = $_Lang['Lost_units_IPM']; + $ResultTables['right'][] = prettyNumber($IPMissilesOrg * $_Vars_Prices[503]['metal']).' '.$_Lang['units'].' '.$_Lang['Metal_rec']; + $ResultTables['right'][] = prettyNumber($IPMissilesOrg * $_Vars_Prices[503]['crystal']).' '.$_Lang['units'].' '.$_Lang['Crystal_rec']; + $ResultTables['right'][] = prettyNumber($IPMissilesOrg * $_Vars_Prices[503]['deuterium']).' '.$_Lang['units'].' '.$_Lang['Deuterium_rec']; + } + else + { + $ResultContent = ''.$FatalError.''; + } + + $_Lang['Result'] = ''.$_Lang['Sim_Result'].''; + if(!empty($ResultContent)) + { + $_Lang['Result'] .= ''.$ResultContent.''; + } + if(!empty($ResultTables)) + { + $_Lang['Result'] .= ''.implode('
    ', $ResultTables['left']).''.implode('
    ', $ResultTables['right']).''; + } + $_Lang['Result'] .= ''; + +} + +$_Lang['DefTech']= $_Lang['tech'][111]; +$_Lang['AtkTech']= $_Lang['tech'][109]; + +$PrepareTargetList = ''; + +if($DefTech > 0) +{ + $_Lang['SetDefTech'] = $DefTech; +} +if($AtkTech > 0) +{ + $_Lang['SetAtkTech'] = $AtkTech; +} +if($IPMissilesOrg > 0) +{ + $_Lang['SetIPM'] = $IPMissilesOrg; +} +if($ICMissiles > 0) +{ + $_Lang['SetICM'] = $ICMissiles; +} + +$_Lang['DefenceRows'] = ''; +foreach($_Vars_GameElements as $ID => $DBName) +{ + if(!empty($DBName)) + { + if($ID > 400 AND $ID < 500 AND !empty($_Lang['tech'][$ID])) + { + $ThisRow_InsertValue = null; + if(isset($PlanetDefSys[$ID]) && $PlanetDefSys[$ID] > 0) + { + $ThisRow_InsertValue = ' value="'.$PlanetDefSys[$ID].'"'; + } + + $_Lang['DefenceRows'] .= ''.$_Lang['tech'][$ID].': '.((isset($Attack['Destroyed'][$ID]) && $Attack['Destroyed'][$ID] > 0) ? ('-'.prettyNumber($Attack['Destroyed'][$ID]).'') : '').''; + if(!isset($TargetSel)) + { + $_Lang['DefenceRows'] .= ''.$_Lang['MainTarget'].''; + $TargetSel = true; + } + else + { + $_Lang['DefenceRows'] .= ' '; + } + $_Lang['DefenceRows'] .= ''; + $PrepareTargetList .= ''; + } + } +} +$_Lang['DefenceRows'] = str_replace('{$PrepareTargetList}', $PrepareTargetList, $_Lang['DefenceRows']); + +//Display page +$page = parsetemplate(gettemplate('rocket_simulator'), $_Lang); + +display($page, $_Lang['Title'], false); + +?> diff --git a/rules.php b/rules.php index 7dc8f9542..33faf5098 100644 --- a/rules.php +++ b/rules.php @@ -10,54 +10,54 @@ $_EnginePath = './'; include($_EnginePath.'common.php'); - includeLang('rules'); - $TPL = gettemplate('rules_body'); - - if(isLogged() && isset($_ForceRulesAcceptBox) && $_ForceRulesAcceptBox === true) - { - $IsInDelete = ($_User['is_ondeletion'] == 1 ? true : false); - - if(isset($_GET['cmd'])) - { - if($_GET['cmd'] == 'decline') - { - if($IsInDelete !== true) - { - $_User['deletion_endtime'] = time() + (ACCOUNT_DELETION_TIME * TIME_DAY); - doquery("UPDATE {{table}} SET `is_ondeletion` = 1, `deletion_endtime` = {$_User['deletion_endtime']} WHERE `id` = {$_User['id']} LIMIT 1;", 'users'); - $IsInDelete = true; - $_User['is_ondeletion'] = 1; - } - } - else if($_GET['cmd'] == 'accept') - { - $AddToUpdate = ''; - if($IsInDelete === true) - { - $AddToUpdate = ", `is_ondeletion` = 0, `deletion_endtime` = 0"; - } - doquery("UPDATE {{table}} SET `rules_accept_stamp` = {$_GameConfig['last_rules_changes']} {$AddToUpdate} WHERE `id` = {$_User['id']} LIMIT 1;", 'users'); - header('Location: overview.php'); - safeDie(); - } - } - - if($_User['is_ondeletion'] == 1) - { - $_Lang['AcceptBox_Option_Accept'] = $_Lang['AcceptBox_Option_Accept1']; - $_Lang['AcceptBox_Option_Decline'] = $_Lang['AcceptBox_Option_Decline1']; - $_Lang['AcceptBox_InsertDeleteTime'] = sprintf($_Lang['AcceptBox_DeleteTime'], prettyDate('d m Y \o H:i:s', intval($_User['deletion_endtime']), 1)); - } - else - { - $_Lang['AcceptBox_Option_Accept'] = $_Lang['AcceptBox_Option_Accept0']; - $_Lang['AcceptBox_Option_Decline'] = $_Lang['AcceptBox_Option_Decline0']; - } - $_Lang['AcceptBox_Info'] = sprintf($_Lang['AcceptBox_Info'], prettyDate('d m Y, H:i:s', $_GameConfig['last_rules_changes'], 1)); - - $TPL = str_replace('{InsertRulesAcceptanceBox}', gettemplate('rules_acceptbox'), $TPL); - } - - display(parsetemplate($TPL, $_Lang), $_Lang['Page_Title'], false); - -?> \ No newline at end of file +includeLang('rules'); +$TPL = gettemplate('rules_body'); + +if(isLogged() && isset($_ForceRulesAcceptBox) && $_ForceRulesAcceptBox === true) +{ + $IsInDelete = ($_User['is_ondeletion'] == 1 ? true : false); + + if(isset($_GET['cmd'])) + { + if($_GET['cmd'] == 'decline') + { + if($IsInDelete !== true) + { + $_User['deletion_endtime'] = time() + (ACCOUNT_DELETION_TIME * TIME_DAY); + doquery("UPDATE {{table}} SET `is_ondeletion` = 1, `deletion_endtime` = {$_User['deletion_endtime']} WHERE `id` = {$_User['id']} LIMIT 1;", 'users'); + $IsInDelete = true; + $_User['is_ondeletion'] = 1; + } + } + else if($_GET['cmd'] == 'accept') + { + $AddToUpdate = ''; + if($IsInDelete === true) + { + $AddToUpdate = ", `is_ondeletion` = 0, `deletion_endtime` = 0"; + } + doquery("UPDATE {{table}} SET `rules_accept_stamp` = {$_GameConfig['last_rules_changes']} {$AddToUpdate} WHERE `id` = {$_User['id']} LIMIT 1;", 'users'); + header('Location: overview.php'); + safeDie(); + } + } + + if($_User['is_ondeletion'] == 1) + { + $_Lang['AcceptBox_Option_Accept'] = $_Lang['AcceptBox_Option_Accept1']; + $_Lang['AcceptBox_Option_Decline'] = $_Lang['AcceptBox_Option_Decline1']; + $_Lang['AcceptBox_InsertDeleteTime'] = sprintf($_Lang['AcceptBox_DeleteTime'], prettyDate('d m Y \o H:i:s', intval($_User['deletion_endtime']), 1)); + } + else + { + $_Lang['AcceptBox_Option_Accept'] = $_Lang['AcceptBox_Option_Accept0']; + $_Lang['AcceptBox_Option_Decline'] = $_Lang['AcceptBox_Option_Decline0']; + } + $_Lang['AcceptBox_Info'] = sprintf($_Lang['AcceptBox_Info'], prettyDate('d m Y, H:i:s', $_GameConfig['last_rules_changes'], 1)); + + $TPL = str_replace('{InsertRulesAcceptanceBox}', gettemplate('rules_acceptbox'), $TPL); +} + +display(parsetemplate($TPL, $_Lang), $_Lang['Page_Title'], false); + +?> diff --git a/scripts/index.php b/scripts/index.php index b0c9fceef..bc99142d1 100644 --- a/scripts/index.php +++ b/scripts/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/search.php b/search.php index b81e17188..1b9ccd8fb 100644 --- a/search.php +++ b/search.php @@ -1,202 +1,202 @@ -0'; - - // Generate Queries - switch($Type) - { - case 'playername': - { - $table = gettemplate('search_user_table'); - $row = gettemplate('search_user_row'); - $NeedenFields = "`ally`.`ally_name`, `planet`.`name`, `stat`.`total_rank` AS `rank`"; - $Query_Get = "SELECT {{table}}.*, {$NeedenFields} FROM {{table}} "; - $Query_Get .= "LEFT JOIN {{prefix}}alliance AS `ally` ON {{table}}.ally_id = `ally`.`id` "; - $Query_Get .= "LEFT JOIN {{prefix}}planets AS `planet` ON {{table}}.id_planet = `planet`.`id` "; - $Query_Get .= "LEFT JOIN {{prefix}}statpoints AS `stat` ON {{table}}.id = `stat`.`id_owner` AND `stat_type` = '1' "; - $Query_Get .= "WHERE `username` LIKE '%{\$SearchVar}%' LIMIT {\$QueryStart}, {$PerPage};"; - $Query_Count = "SELECT COUNT(`id`) as `count` FROM {{table}} WHERE `username` LIKE '%{\$SearchVar}%';"; - $Query_Table = 'users'; - $Search_CheckRegExp = REGEXP_USERNAME; - break; - } - case 'allytag': - { - $table = gettemplate('search_ally_table'); - $row = gettemplate('search_ally_row'); - $NeedenFields = "`stat`.`total_points` AS `ally_points`"; - $Query_Get = "SELECT {{table}}.*, {$NeedenFields} FROM {{table}} "; - $Query_Get .= "LEFT JOIN {{prefix}}statpoints AS `stat` ON `stat`.`id_owner` = `{{table}}`.`id` AND `stat_type` = '2' "; - $Query_Get .= "WHERE `ally_tag` LIKE '%{\$SearchVar}%' LIMIT {\$QueryStart}, {$PerPage};"; - $Query_Count = "SELECT COUNT(`id`) as `count` FROM {{table}} WHERE `ally_tag` LIKE '%{\$SearchVar}%';"; - $Query_Table = 'alliance'; - $Search_CheckRegExp = REGEXP_ALLYNAMEANDTAG; - break; - } - case 'allyname': - { - $table = gettemplate('search_ally_table'); - $row = gettemplate('search_ally_row'); - $NeedenFields = "`stat`.`total_points` AS `ally_points`"; - $Query_Get = "SELECT {{table}}.*, {$NeedenFields} FROM {{table}} "; - $Query_Get .= "LEFT JOIN {{prefix}}statpoints AS `stat` ON `stat`.`id_owner` = `{{table}}`.`id` AND `stat_type` = '2' "; - $Query_Get .= "WHERE `ally_name` LIKE '%{\$SearchVar}%' LIMIT {\$QueryStart}, {$PerPage};"; - $Query_Count = "SELECT COUNT(`id`) as `count` FROM {{table}} WHERE `ally_name` LIKE '%{\$SearchVar}%';"; - $Query_Table = 'alliance'; - $Search_CheckRegExp = REGEXP_ALLYNAMEANDTAG; - break; - } - } - - $Results = null; - if(!empty($Search_Value)) - { - if(empty($Search_CheckRegExp) OR preg_match($Search_CheckRegExp, $Search_Value)) - { - $Search_Value = preg_replace(REGEXP_SANITIZELIKE_SEARCH, REGEXP_SANITIZELIKE_REPLACE, $Search_Value); - - $Query_Count = str_replace('{$SearchVar}', $Search_Value, $Query_Count); - $Get_Count = doquery($Query_Count, $Query_Table, true); - if($Get_Count['count'] > 0) - { - if($QueryStart >= $Get_Count['count']) - { - $QueryStart = 0; - $ThisPage = 1; - } - $Query_Get = str_replace(array('{$SearchVar}', '{$QueryStart}'), array($Search_Value, $QueryStart), $Query_Get); - $Get_Rows = doquery($Query_Get, $Query_Table); - - while($RowData = mysql_fetch_assoc($Get_Rows)) - { - if($Type == 'playername') - { - $RowData['planet_name'] = $RowData['name']; - if($RowData['old_username_expire'] > $Now){ - $RowData['username'] .= ' (?)'; - } - $RowData['ally_name'] = ($RowData['ally_id'] > 0 ? "{$RowData['ally_name']}" : ' '); - if($RowData['rank'] > 0) - { - $RowData['position'] = "{$RowData['rank']}"; - } - else - { - $RowData['position'] = $NotCounted; - } - $RowData['skinpath'] = $_SkinPath; - $RowData['coordinated'] = "{$RowData['galaxy']}:{$RowData['system']}:{$RowData['planet']}"; - $RowData['buddy_request'] = $_Lang['buddy_request']; - $RowData['write_a_messege'] = $_Lang['write_a_messege']; - if($_User['ally_id'] > 0 AND $RowData['ally_id'] <= 0) - { - $RowData['Ally_Invite_Title'] = $_Lang['Ally_Invite_Title']; - } - else - { - $RowData['Insert_HideAllyInvite'] = 'display: none;'; - } - - $Results[] = parsetemplate($row, $RowData); - } - else - { - $RowData['ally_points'] = prettyNumber($RowData['ally_points']); - - $RowData['ally_tag'] = "{$RowData['ally_tag']}"; - $Results[] = parsetemplate($row, $RowData); - } - } - - $_Lang['result_list'] = implode('', $Results); - $Results = parsetemplate($table, $_Lang); - } - else - { - // Nothing found - $Indicators_NothingFound = true; - } - } - else - { - // Bad signs - $Indicators_BadSigns = true; - } - } - - //Rest of things... - if(isset($_GET['type'])) - { - $_Lang['type_playername'] = ($_GET['type'] == 'playername') ? ' SELECTED' : ''; - $_Lang['type_allytag'] = ($_GET['type'] == 'allytag') ? ' SELECTED' : ''; - $_Lang['type_allyname'] = ($_GET['type'] == 'allyname') ? ' SELECTED' : ''; - } - $_Lang['searchtext'] = $SearchTextUnsecure; - $_Lang['search_results'] = $Results; - $rc['found_results'] = $_Lang['found_results']; - $rc['results_count'] = (isset($Get_Count['count']) ? $Get_Count['count'] : 0); - $TPL_Count = gettemplate('search_results_count'); - - if(!empty($Results)) - { - $_Lang['search_results_count'] = parsetemplate(gettemplate('search_results_count'), $rc); - if($Get_Count['count'] > 30) - { - include_once($_EnginePath.'includes/functions/Pagination.php'); - - $Pagin = CreatePaginationArray($Get_Count['count'], $PerPage, $ThisPage, 7); - $PaginationTPL = "{\$ShowValue}"; - $PaginationViewOpt = array('CurrentPage_Classes' => 'orange', 'Breaker_View' => '...'); - $CreatePagination = implode(' ', ParsePaginationArray($Pagin, $ThisPage, $PaginationTPL, $PaginationViewOpt)); - $pag['pagination'] = $CreatePagination; - $pag['pagination_title'] = $_Lang['pagination_title']; - $_Lang['pagination'] = parsetemplate(gettemplate('search_pagination'), $pag); - } - } - - if(isset($Indicators_NothingFound)) - { - $_Lang['search_results_count'] = parsetemplate($TPL_Count, array('found_results' => $_Lang['nothing_found'])); - } - if(isset($Indicators_BadSigns)) - { - $_Lang['search_results_count'] = parsetemplate($TPL_Count, array('found_results' => $_Lang['badsigns_given'])); - } - - $Display = parsetemplate(gettemplate('search_body'), $_Lang); - display($Display, $_Lang['Search'], false); - -?> \ No newline at end of file +0'; + +// Generate Queries +switch($Type) +{ + case 'playername': + { + $table = gettemplate('search_user_table'); + $row = gettemplate('search_user_row'); + $NeedenFields = "`ally`.`ally_name`, `planet`.`name`, `stat`.`total_rank` AS `rank`"; + $Query_Get = "SELECT {{table}}.*, {$NeedenFields} FROM {{table}} "; + $Query_Get .= "LEFT JOIN {{prefix}}alliance AS `ally` ON {{table}}.ally_id = `ally`.`id` "; + $Query_Get .= "LEFT JOIN {{prefix}}planets AS `planet` ON {{table}}.id_planet = `planet`.`id` "; + $Query_Get .= "LEFT JOIN {{prefix}}statpoints AS `stat` ON {{table}}.id = `stat`.`id_owner` AND `stat_type` = '1' "; + $Query_Get .= "WHERE `username` LIKE '%{\$SearchVar}%' LIMIT {\$QueryStart}, {$PerPage};"; + $Query_Count = "SELECT COUNT(`id`) as `count` FROM {{table}} WHERE `username` LIKE '%{\$SearchVar}%';"; + $Query_Table = 'users'; + $Search_CheckRegExp = REGEXP_USERNAME; + break; + } + case 'allytag': + { + $table = gettemplate('search_ally_table'); + $row = gettemplate('search_ally_row'); + $NeedenFields = "`stat`.`total_points` AS `ally_points`"; + $Query_Get = "SELECT {{table}}.*, {$NeedenFields} FROM {{table}} "; + $Query_Get .= "LEFT JOIN {{prefix}}statpoints AS `stat` ON `stat`.`id_owner` = `{{table}}`.`id` AND `stat_type` = '2' "; + $Query_Get .= "WHERE `ally_tag` LIKE '%{\$SearchVar}%' LIMIT {\$QueryStart}, {$PerPage};"; + $Query_Count = "SELECT COUNT(`id`) as `count` FROM {{table}} WHERE `ally_tag` LIKE '%{\$SearchVar}%';"; + $Query_Table = 'alliance'; + $Search_CheckRegExp = REGEXP_ALLYNAMEANDTAG; + break; + } + case 'allyname': + { + $table = gettemplate('search_ally_table'); + $row = gettemplate('search_ally_row'); + $NeedenFields = "`stat`.`total_points` AS `ally_points`"; + $Query_Get = "SELECT {{table}}.*, {$NeedenFields} FROM {{table}} "; + $Query_Get .= "LEFT JOIN {{prefix}}statpoints AS `stat` ON `stat`.`id_owner` = `{{table}}`.`id` AND `stat_type` = '2' "; + $Query_Get .= "WHERE `ally_name` LIKE '%{\$SearchVar}%' LIMIT {\$QueryStart}, {$PerPage};"; + $Query_Count = "SELECT COUNT(`id`) as `count` FROM {{table}} WHERE `ally_name` LIKE '%{\$SearchVar}%';"; + $Query_Table = 'alliance'; + $Search_CheckRegExp = REGEXP_ALLYNAMEANDTAG; + break; + } +} + +$Results = null; +if(!empty($Search_Value)) +{ + if(empty($Search_CheckRegExp) OR preg_match($Search_CheckRegExp, $Search_Value)) + { + $Search_Value = preg_replace(REGEXP_SANITIZELIKE_SEARCH, REGEXP_SANITIZELIKE_REPLACE, $Search_Value); + + $Query_Count = str_replace('{$SearchVar}', $Search_Value, $Query_Count); + $Get_Count = doquery($Query_Count, $Query_Table, true); + if($Get_Count['count'] > 0) + { + if($QueryStart >= $Get_Count['count']) + { + $QueryStart = 0; + $ThisPage = 1; + } + $Query_Get = str_replace(array('{$SearchVar}', '{$QueryStart}'), array($Search_Value, $QueryStart), $Query_Get); + $Get_Rows = doquery($Query_Get, $Query_Table); + + while($RowData = mysql_fetch_assoc($Get_Rows)) + { + if($Type == 'playername') + { + $RowData['planet_name'] = $RowData['name']; + if($RowData['old_username_expire'] > $Now){ + $RowData['username'] .= ' (?)'; + } + $RowData['ally_name'] = ($RowData['ally_id'] > 0 ? "{$RowData['ally_name']}" : ' '); + if($RowData['rank'] > 0) + { + $RowData['position'] = "{$RowData['rank']}"; + } + else + { + $RowData['position'] = $NotCounted; + } + $RowData['skinpath'] = $_SkinPath; + $RowData['coordinated'] = "{$RowData['galaxy']}:{$RowData['system']}:{$RowData['planet']}"; + $RowData['buddy_request'] = $_Lang['buddy_request']; + $RowData['write_a_messege'] = $_Lang['write_a_messege']; + if($_User['ally_id'] > 0 AND $RowData['ally_id'] <= 0) + { + $RowData['Ally_Invite_Title'] = $_Lang['Ally_Invite_Title']; + } + else + { + $RowData['Insert_HideAllyInvite'] = 'display: none;'; + } + + $Results[] = parsetemplate($row, $RowData); + } + else + { + $RowData['ally_points'] = prettyNumber($RowData['ally_points']); + + $RowData['ally_tag'] = "{$RowData['ally_tag']}"; + $Results[] = parsetemplate($row, $RowData); + } + } + + $_Lang['result_list'] = implode('', $Results); + $Results = parsetemplate($table, $_Lang); + } + else + { + // Nothing found + $Indicators_NothingFound = true; + } + } + else + { + // Bad signs + $Indicators_BadSigns = true; + } +} + +//Rest of things... +if(isset($_GET['type'])) +{ + $_Lang['type_playername'] = ($_GET['type'] == 'playername') ? ' SELECTED' : ''; + $_Lang['type_allytag'] = ($_GET['type'] == 'allytag') ? ' SELECTED' : ''; + $_Lang['type_allyname'] = ($_GET['type'] == 'allyname') ? ' SELECTED' : ''; +} +$_Lang['searchtext'] = $SearchTextUnsecure; +$_Lang['search_results'] = $Results; +$rc['found_results'] = $_Lang['found_results']; +$rc['results_count'] = (isset($Get_Count['count']) ? $Get_Count['count'] : 0); +$TPL_Count = gettemplate('search_results_count'); + +if(!empty($Results)) +{ + $_Lang['search_results_count'] = parsetemplate(gettemplate('search_results_count'), $rc); + if($Get_Count['count'] > 30) + { + include_once($_EnginePath.'includes/functions/Pagination.php'); + + $Pagin = CreatePaginationArray($Get_Count['count'], $PerPage, $ThisPage, 7); + $PaginationTPL = "{\$ShowValue}"; + $PaginationViewOpt = array('CurrentPage_Classes' => 'orange', 'Breaker_View' => '...'); + $CreatePagination = implode(' ', ParsePaginationArray($Pagin, $ThisPage, $PaginationTPL, $PaginationViewOpt)); + $pag['pagination'] = $CreatePagination; + $pag['pagination_title'] = $_Lang['pagination_title']; + $_Lang['pagination'] = parsetemplate(gettemplate('search_pagination'), $pag); + } +} + +if(isset($Indicators_NothingFound)) +{ + $_Lang['search_results_count'] = parsetemplate($TPL_Count, array('found_results' => $_Lang['nothing_found'])); +} +if(isset($Indicators_BadSigns)) +{ + $_Lang['search_results_count'] = parsetemplate($TPL_Count, array('found_results' => $_Lang['badsigns_given'])); +} + +$Display = parsetemplate(gettemplate('search_body'), $_Lang); +display($Display, $_Lang['Search'], false); + +?> diff --git a/settings.php b/settings.php index 4ac412492..f2a11163a 100644 --- a/settings.php +++ b/settings.php @@ -1,1364 +1,1364 @@ - 'XNova', 'epicblue' => 'EpicBlue Fresh', 'epicblue_old' => 'EpicBlue Standard'); - - $SkinDir = scandir('./skins/'); - $SkinCounter = 1; - if(!empty($SkinDir)) - { - foreach($SkinDir as $Element) - { - if(strstr($Element, '.') === FALSE) - { - if(is_dir('./skins/'.$Element)) - { - if(empty($SkinNames[$Element])) - { - $SkinNames[$Element] = $Element; - } - $_Lang['ServerSkins'] .= ''; - $AvailableSkins[$SkinCounter] = "skins/{$Element}"; - $SkinCounter += 1; - } - } - } - } - - $SelectAllPlanets = doquery("SELECT `id`, `name`, `galaxy`, `system`, `planet` FROM {{table}} WHERE `id_owner` = {$_User['id']} AND `planet_type` = 1;", 'planets'); - while($Planets = mysql_fetch_assoc($SelectAllPlanets)) - { - $_Lang['QuickRes_PlanetList'] .= ""; - } - - $Mode = (isset($_GET['mode']) ? $_GET['mode'] : null); - - if(!isOnVacation()) - { - if(empty($Mode) OR $Mode == 'general') - { - // General View - $CheckMailChange = doquery("SELECT `ID`, `Date` FROM {{table}} WHERE `UserID` = {$_User['id']} AND `ConfirmType` = 0 LIMIT 1;", 'mailchange', true); - - $Query_IgnoreSystem = ''; - $Query_IgnoreSystem .= "SELECT `ignore`.`IgnoredID`, `user`.`username` FROM {{table}} AS `ignore` "; - $Query_IgnoreSystem .= "JOIN `{{prefix}}users` AS `user` ON `ignore`.`IgnoredID` = `user`.`id` "; - $Query_IgnoreSystem .= "WHERE `ignore`.`OwnerID` = {$_User['id']};"; - $Result_IgnoreSystem = doquery($Query_IgnoreSystem, 'ignoresystem'); - if(mysql_num_rows($Result_IgnoreSystem) > 0) - { - while($FetchData = mysql_fetch_assoc($Result_IgnoreSystem)) - { - $_User['IgnoredUsers'][$FetchData['IgnoredID']] = $FetchData['username']; - } - } - - if((isset($_POST['save']) && $_POST['save'] == 'yes') || !empty($_GET['ignoreadd'])) - { - if($_POST['saveType'] == $_Lang['SaveAll']) - { - $_Lang['SetActiveMarker'] = (isset($_POST['markActive']) ? $_POST['markActive'] : null); - - // Settings for Tab01 - if(isset($_POST['change_pass']) && $_POST['change_pass'] == 'on') - { - $_POST['give_newpass'] = trim($_POST['give_newpass']); - if(md5($_POST['give_oldpass']) == $_User['password']) - { - if(strlen($_POST['give_newpass']) >= 4) - { - if(md5($_POST['give_newpass']) != $_User['password']) - { - if($_POST['give_newpass'] == $_POST['give_confirmpass']) - { - $ChangeSet['password'] = md5($_POST['give_newpass']); - $ChangeSetTypes['password'] = 's'; - $InfoMsgs[] = $_Lang['Pass_Changed_plzlogout']; - setcookie($_GameConfig['COOKIE_NAME'], '', $Now - 3600, '/', ''); - } - else - { - $WarningMsgs[] = $_Lang['Pass_Confirm_isbad']; - } - } - else - { - $WarningMsgs[] = $_Lang['Pass_same_as_old']; - } - } - else - { - $WarningMsgs[] = $_Lang['Pass_is_tooshort']; - } - } - else - { - $WarningMsgs[] = $_Lang['Pass_old_isbad']; - } - } - - if(isset($_POST['change_mail']) && $_POST['change_mail'] == 'on') - { - if($CheckMailChange['ID'] <= 0) - { - $_POST['give_newemail'] = mysql_real_escape_string(strip_tags(trim($_POST['give_newemail']))); - $CheckMail = $_POST['give_newemail']; - $banned_domain_list = $_GameConfig['BannedMailDomains']; - $banned_domain_list = str_replace('.', '\.', $banned_domain_list); - - if(is_email($CheckMail)) - { - if($CheckMail !== $_User['email']) - { - if($CheckMail === $_POST['give_confirmemail']) - { - if(empty($banned_domain_list) || !preg_match('#('.$banned_domain_list.')+#si', $CheckMail)) - { - $CheckMailinDB = doquery("SELECT `id` FROM {{table}} WHERE `email` = '{$CheckMail}' LIMIT 1;", 'users', true); - if($CheckMailinDB['id'] <= 0) - { - $RandomHash = md5($_User['id'].$_User['username'].mt_rand(0, 999999999)); - $RandomHashNew = md5($_User['id'].$_User['username'].mt_rand(0, 999999999)); - $ThisTime = $Now; - - $EmailParse = array - ( - 'EP_User' => $_User['username'], - 'EP_GameLink' => GAMEURL_STRICT, - 'EP_Link' => GAMEURL."email_change.php?hash=old&key={$RandomHash}", - 'EP_Text' => $_Lang['Email_MailOld'], - 'EP_OldMail' => $_User['email'], - 'EP_NewMail' => $CheckMail, - 'EP_Date' => date('d.m.Y - H:i:s', $ThisTime), - 'EP_IP' => $_User['user_lastip'], - 'EP_ContactLink' => GAMEURL_STRICT.'/contact.php', - 'EP_Text2' => $_Lang['Email_WarnOld'] - ); - $EmailParseNew = array - ( - 'EP_User' => $_User['username'], - 'EP_GameLink' => GAMEURL_STRICT, - 'EP_Link' => GAMEURL."email_change.php?hash=new&key={$RandomHashNew}", - 'EP_Text' => $_Lang['Email_MailNew'], - 'EP_OldMail' => $_User['email'], - 'EP_NewMail' => $CheckMail, - 'EP_Date' => date('d.m.Y - H:i:s', $ThisTime), - 'EP_IP' => $_User['user_lastip'], - 'EP_ContactLink' => GAMEURL_STRICT.'/contact.php', - 'EP_Text2' => $_Lang['Email_WarnNew'] - ); - - include($_EnginePath.'includes/functions/SendMail.php'); - $EmailBody = parsetemplate($_Lang['Email_Body'], $EmailParse); - $EmailBodyNew = parsetemplate($_Lang['Email_Body'], $EmailParseNew); - $SendResult = SendMail($_User['email'], $_Lang['Email_Title'], $EmailBody, '', true); - $SendResult2 = SendMail($CheckMail, $_Lang['Email_Title'], $EmailBodyNew); - CloseMailConnection(); - - if($SendResult === TRUE AND $SendResult2 === TRUE) - { - $ChangeSet['email_2'] = $CheckMail; - $ChangeSetTypes['email_2'] = 's'; - - doquery("INSERT INTO {{table}} VALUES (NULL, {$ThisTime}, {$_User['id']}, '{$_User['email']}', '{$CheckMail}', 0, 0, '{$RandomHash}', '{$RandomHashNew}');", 'mailchange'); - $CheckMailChange = array('ID' => 1, 'Date' => $ThisTime); - $InfoMsgs[] = sprintf($_Lang['Mail_MailChange'], $_User['email']); - } - else - { - $WarningMsgs[] = sprintf($_Lang['Mail_SendMailError'], urlencode(str_pad(mt_rand(0,999), 3, 'a', STR_PAD_RIGHT).base64_encode($SendResult).'||'.base64_encode($SendResult2))); - } - } - else - { - $WarningMsgs[] = $_Lang['Mail_some1_hasemail']; - } - } - else - { - $WarningMsgs[] = $_Lang['Mail_banned_domain']; - } - } - else - { - $WarningMsgs[] = $_Lang['Mail_Confirm_isbad']; - } - } - else - { - $WarningMsgs[] = $_Lang['Mail_same_as_old']; - } - } - else - { - $WarningMsgs[] = $_Lang['Mail_badEmail']; - } - } - else - { - $WarningMsgs[] = $_Lang['Mail_alreadyInChange']; - } - } - - if(isset($_POST['stop_email_change']) && $_POST['stop_email_change'] == 'on') - { - if($CheckMailChange['ID'] > 0) - { - doquery("UPDATE {{table}} SET `ConfirmType` = 3 WHERE `ID` = {$CheckMailChange['ID']} LIMIT 1;", 'mailchange'); - unset($CheckMailChange); - $InfoMsgs[] = $_Lang['Mail_PrcStopped']; - } - else - { - $WarningMsgs[] = $_Lang['Mail_PrcNoExists']; - } - } - - if(isset($_POST['ipcheck_deactivate']) && $_POST['ipcheck_deactivate'] == 'on') - { - $IPCheckDeactivate = '1'; - } - else - { - $IPCheckDeactivate = '0'; - } - if($_User['noipcheck'] != $IPCheckDeactivate) - { - $ChangeSet['noipcheck'] = $IPCheckDeactivate; - } - else - { - $ChangeNotDone += 1; - } - - // Settings for Tab02 - $PlanetSortMode = intval($_POST['planet_sort_mode']); - if($PlanetSortMode <= 0 OR $PlanetSortMode > 2) - { - $PlanetSortMode = '0'; - } - if($PlanetSortMode != $_User['planet_sort']) - { - $ChangeSet['planet_sort'] = $PlanetSortMode; - } - else - { - $ChangeNotDone += 1; - } - - $PlanetSortType = intval($_POST['planet_sort_type']); - if($PlanetSortType != 1) - { - $PlanetSortType = '0'; - } - if($PlanetSortType != $_User['planet_sort_order']) - { - $ChangeSet['planet_sort_order'] = $PlanetSortType; - } - else - { - $ChangeNotDone += 1; - } - - if(isset($_POST['planet_sort_moons']) && $_POST['planet_sort_moons'] == 'on') - { - $PlanetSortMoons = '1'; - } - else - { - $PlanetSortMoons = '0'; - } - - if($PlanetSortMoons != $_User['planet_sort_moons']) - { - $ChangeSet['planet_sort_moons'] = $PlanetSortMoons; - } - else - { - $ChangeNotDone += 1; - } - - $SkinPath = mysql_real_escape_string(strip_tags(trim($_POST['skin_path']))); - if(strstr($SkinPath, 'http://') === FALSE AND strstr($SkinPath, 'www.') === FALSE) - { - if($SkinPath != '') - { - $SkinPath = ltrim($SkinPath, '/'); - if(substr($SkinPath, strlen($SkinPath) - 1) != '/') - { - $SkinPath .= '/'; - } - if(!file_exists('./'.$SkinPath.'formate.css')) - { - $WarningMsgs[] = $_Lang['Skin_NoLocalSkin']; - $SkinPath = $_User['skinpath']; - } - } - else - { - $_POST['use_skin'] = ''; - } - } - else - { - if(strstr($SkinPath, 'http://') === FALSE AND strstr($SkinPath, 'www.') !== FALSE) - { - $SkinPath = str_replace('www.', 'http://', $SkinPath); - } - } - if($SkinPath != $_User['skinpath']) - { - $_SkinPath = $SkinPath; - $ChangeSet['skinpath'] = $SkinPath; - $_Lang['skinpath'] = $SkinPath; - $ChangeSetTypes['skinpath'] = 's'; - } - else - { - $ChangeNotDone += 1; - } - - if(isset($_POST['use_skin']) && $_POST['use_skin'] == 'on') - { - $UseSkin = '1'; - } - else - { - $UseSkin = '0'; - } - if($UseSkin != $_User['design']) - { - $ChangeSet['design'] = $UseSkin; - } - else - { - $ChangeNotDone += 1; - } - - $AvatarPath = mysql_real_escape_string(strip_tags(trim($_POST['avatar_path']))); - if(strstr($AvatarPath, 'http://') === FALSE AND strstr($AvatarPath, 'www.') !== FALSE) - { - $AvatarPath = str_replace('www.', 'http://', $AvatarPath); - } - if($AvatarPath != $_User['avatar']) - { - $ChangeSet['avatar'] = $AvatarPath; - $ChangeSetTypes['avatar'] = 's'; - } - else - { - $ChangeNotDone += 1; - } - - if(isset($_POST['development_old']) && $_POST['development_old'] == 'on') - { - $DevelopmentOld = '1'; - } - else - { - $DevelopmentOld = '0'; - } - if($DevelopmentOld != $_User['settings_DevelopmentOld']) - { - $ChangeSet['settings_DevelopmentOld'] = $DevelopmentOld; - } - else - { - $ChangeNotDone += 1; - } - - if(isset($_POST['build_expandedview_use']) && $_POST['build_expandedview_use'] == 'on') - { - $BuildExpandedView = '1'; - } - else - { - $BuildExpandedView = '0'; - } - if($BuildExpandedView != $_User['settings_ExpandedBuildView']) - { - $ChangeSet['settings_ExpandedBuildView'] = $BuildExpandedView; - } - else - { - $ChangeNotDone += 1; - } - - if(isset($_POST['pretty_fleet_use']) && $_POST['pretty_fleet_use'] == 'on') - { - $UsePrettyFleet = '1'; - } - else - { - $UsePrettyFleet = '0'; - } - if($UsePrettyFleet != $_User['settings_useprettyinputbox']) - { - $ChangeSet['settings_useprettyinputbox'] = $UsePrettyFleet; - } - else - { - $ChangeNotDone += 1; - } - - $ChangeNotDone += 1; - if(isset($_POST['resSort_changed']) && $_POST['resSort_changed'] == '1') - { - $_POST['resSort_array'] = (isset($_POST['resSort_array']) ? trim($_POST['resSort_array']) : null); - if(preg_match('/^[a-z]{3}\,[a-z]{3}\,[a-z]{3}$/D', $_POST['resSort_array'])) - { - $CheckData = explode(',', $_POST['resSort_array']); - foreach($CheckData as $Data2Check) - { - if($Data2Check != 'met' AND $Data2Check != 'cry' AND $Data2Check != 'deu') - { - $DisAllowResSort_Change = true; - break; - } - } - if(!isset($DisAllowResSort_Change)) - { - $ChangeSet['settings_resSortArray'] = $_POST['resSort_array']; - $ChangeSetTypes['settings_resSortArray'] = 's'; - $ChangeNotDone -= 1; - } - } - } - - $ChangeNotDone += 1; - if($_User['settings_mainPlanetID'] != $_POST['quickres_select']) - { - $PlanetID = round(floatval($_POST['quickres_select'])); - if($PlanetID > 0) - { - $CheckPlanetExist = doquery("SELECT `id_owner` FROM {{table}} WHERE `id` = {$PlanetID} LIMIT 1;", 'planets', true); - if($CheckPlanetExist['id_owner'] == $_User['id']) - { - $ChangeSet['settings_mainPlanetID'] = $PlanetID; - $ChangeNotDone -= 1; - } - else - { - $WarningMsgs[] = $_Lang['Msgs_PlanetNotYour']; - } - } - } - - $MsgsPerPage = intval($_POST['msg_perpage']); - if($MsgsPerPage != $_User['settings_msgperpage']) - { - if(in_array($MsgsPerPage, array(5, 10, 15, 20, 25, 50, 75, 100, 150, 200))) - { - $ChangeSet['settings_msgperpage'] = $MsgsPerPage; - } - else - { - $WarningMsgs[] = $_Lang['Msgs_BadPerPageInt']; - $ChangeNotDone += 1; - } - } - else - { - $ChangeNotDone += 1; - } - - if(isset($_POST['msg_spyexpand']) && $_POST['msg_spyexpand'] == 'on') - { - $MsgExpandSpyReports = '1'; - } - else - { - $MsgExpandSpyReports = '0'; - } - if($MsgExpandSpyReports != $_User['settings_spyexpand']) - { - $ChangeSet['settings_spyexpand'] = $MsgExpandSpyReports; - } - else - { - $ChangeNotDone += 1; - } - - if(isset($_POST['msg_usethreads']) && $_POST['msg_usethreads'] == 'on') - { - $MsgUseMsgThreads = '1'; - } - else - { - $MsgUseMsgThreads = '0'; - } - if($MsgUseMsgThreads != $_User['settings_UseMsgThreads']) - { - $ChangeSet['settings_UseMsgThreads'] = $MsgUseMsgThreads; - } - else - { - $ChangeNotDone += 1; - } - - // Settings for Tab03 - $SpyCount = intval($_POST['spy_count']); - if($SpyCount < 1) - { - $SpyCount = 1; - } - else if($SpyCount > $MaxEspionageProbesCount) - { - $SpyCount = $MaxEspionageProbesCount; - } - if($SpyCount != $_User['settings_spyprobescount']) - { - $ChangeSet['settings_spyprobescount'] = $SpyCount; - } - else - { - $ChangeNotDone += 1; - } - - if(isset($_POST['use_ajaxgalaxy']) && $_POST['use_ajaxgalaxy'] == 'on') - { - $UseAJAXGalaxy = '1'; - } - else - { - $UseAJAXGalaxy = '0'; - } - if($UseAJAXGalaxy != $_User['settings_UseAJAXGalaxy']) - { - $ChangeSet['settings_UseAJAXGalaxy'] = $UseAJAXGalaxy; - } - else - { - $ChangeNotDone += 1; - } - if(isset($_POST['show_useravatars']) && $_POST['show_useravatars'] == 'on') - { - $ShowUserAvatars = '1'; - } - else - { - $ShowUserAvatars = '0'; - } - if($ShowUserAvatars != $_User['settings_Galaxy_ShowUserAvatars']) - { - $ChangeSet['settings_Galaxy_ShowUserAvatars'] = $ShowUserAvatars; - } - else - { - $ChangeNotDone += 1; - } - - if(isset($_POST['short_spy']) && $_POST['short_spy'] == 'on') - { - $ShortcutSpy = '1'; - } - else - { - $ShortcutSpy = '0'; - } - if($ShortcutSpy != $_User['settings_esp']) - { - $ChangeSet['settings_esp'] = $ShortcutSpy; - } - else - { - $ChangeNotDone += 1; - } - - if(isset($_POST['short_write']) && $_POST['short_write'] == 'on') - { - $ShortcutWrite = '1'; - } - else - { - $ShortcutWrite = '0'; - } - if($ShortcutWrite != $_User['settings_wri']) - { - $ChangeSet['settings_wri'] = $ShortcutWrite; - } - else - { - $ChangeNotDone += 1; - } - - if(isset($_POST['short_buddy']) && $_POST['short_buddy'] == 'on') - { - $ShortcutBuddy = '1'; - } - else - { - $ShortcutBuddy = '0'; - } - if($ShortcutBuddy != $_User['settings_bud']) - { - $ChangeSet['settings_bud'] = $ShortcutBuddy; - } - else - { - $ChangeNotDone += 1; - } - - if(isset($_POST['short_rocket']) && $_POST['short_rocket'] == 'on') - { - $ShortcutRocket = '1'; - } - else - { - $ShortcutRocket = '0'; - } - if($ShortcutRocket != $_User['settings_mis']) - { - $ChangeSet['settings_mis'] = $ShortcutRocket; - } - else - { - $ChangeNotDone += 1; - } - - // Settings for Tab04 - $_Lang['SetActiveMarker'] = '04'; - if((isset($_POST['vacation_activate']) && $_POST['vacation_activate'] == 'on') || (isset($_POST['delete_activate']) && $_POST['delete_activate'] == 'on')) - { - if(isset($_POST['vacation_activate']) && $_POST['vacation_activate'] == 'on') - { - $allowVacation = true; - if(($_User['vacation_leavetime'] + TIME_DAY) >= $Now) - { - $allowVacation = false; - $WarningMsgs[] = $_Lang['Vacation_24hNotPassed']; - } - - $checkFleets = doquery("SELECT COUNT(*) AS `Count` FROM {{table}} WHERE `fleet_owner` = {$_User['id']} OR `fleet_target_owner` = {$_User['id']};", 'fleets', true); - if($checkFleets['Count'] > 0) - { - $allowVacation = false; - $WarningMsgs[] = $_Lang['Vacation_FlyingFleets']; - } - - if($allowVacation === true) - { - // Update All Planets/Moons before VacationMode (don't do that if previous conditions are not fulfilled) - $AllPlanets = doquery("SELECT * FROM {{table}} WHERE `id_owner` = {$_User['id']};", 'planets'); - - $Results['planets'] = array(); - while($PlanetsData = mysql_fetch_assoc($AllPlanets)) - { - // Update Planet - Building Queue - $GeneratePlanetName[$PlanetsData['id']] = "{$PlanetsData['name']} [{$PlanetsData['galaxy']}:{$PlanetsData['system']}:{$PlanetsData['planet']}]"; - - if(HandlePlanetUpdate($PlanetsData, $_User, $Now, true) === true) - { - $Results['planets'][] = $PlanetsData; - } - if($PlanetsData['buildQueue_firstEndTime'] > 0 OR $PlanetsData['shipyardQueue'] != 0) - { - $FoundBlockingPlanets[$PlanetsData['id']] = $GeneratePlanetName[$PlanetsData['id']]; - } - } - HandlePlanetUpdate_MultiUpdate($Results, $_User); - if($_User['techQueue_EndTime'] > 0) - { - $FoundBlockingPlanets[$PlanetsData['id']] = $GeneratePlanetName[$_User['techQueue_Planet']]; - } - - if(!empty($FoundBlockingPlanets)) - { - $allowVacation = false; - $WarningMsgs[] = sprintf($_Lang['Vacation_CannotBuildOrRes'], implode(', ', $FoundBlockingPlanets)); - } - } - - if($allowVacation === true) - { - $ChangeSet['is_onvacation'] = '1'; - $ChangeSet['vacation_starttime'] = 'UNIX_TIMESTAMP()'; - $ChangeSet['vacation_endtime'] = 'UNIX_TIMESTAMP() + '.(MAXVACATIONS_REG * TIME_DAY); - $ChangeSet['vacation_type'] = '0'; - - $ChangeSetCount += 1; - $ForceGoingOnVacationMsg = true; - - $UserDev_Log[] = array('PlanetID' => '0', 'Date' => $Now, 'Place' => 26, 'Code' => '1', 'ElementID' => '0'); - } - } - if(isset($_POST['delete_activate']) && $_POST['delete_activate'] == 'on') - { - if($_User['is_ondeletion'] == 0) - { - if(md5($_POST['delete_confirm']) == $_User['password']) - { - $ChangeSet['is_ondeletion'] = '1'; - $ChangeSet['deletion_endtime'] = 'UNIX_TIMESTAMP() + '.(ACCOUNT_DELETION_TIME * TIME_DAY); - $ChangeSetCount += 1; - - if($ForceGoingOnVacationMsg === true) - { - $ShowDeletionInfo = true; - } - } - else - { - $WarningMsgs[] = $_Lang['Delete_Confirm_isbad']; - } - } - } - } - else - { - if($_User['is_ondeletion'] == 1) - { - $ChangeSet['is_ondeletion'] = '0'; - $ChangeSet['deletion_endtime'] = '0'; - $ChangeSetCount += 1; - } - } - - if(empty($_User['settings_FleetColors'])) - { - foreach($_Vars_FleetMissions['all'] as $MissionID) - { - $_User['settings_FleetColors']['ownfly'][$MissionID] = ''; - $_User['settings_FleetColors']['owncb'][$MissionID] = ''; - $_User['settings_FleetColors']['nonown'][$MissionID] = ''; - } - $FleetColors_UserVar = $_User['settings_FleetColors']; - $_User['settings_FleetColors'] = null; - } - else - { - $FleetColors_UserVar = json_decode($_User['settings_FleetColors'], true); - } - $FleetColors_NeedChange = false; - foreach($FleetColors_UserVar as $TypeKey => $Missions) - { - foreach($Missions as $MissionID => $MissionColor) - { - if(!empty($_POST['fleetColors'][$TypeKey][$MissionID]) AND preg_match(REGEXP_HEXCOLOR, $_POST['fleetColors'][$TypeKey][$MissionID])) - { - $ThisColor = $_POST['fleetColors'][$TypeKey][$MissionID]; - } - else - { - $ThisColor = ''; - } - if($ThisColor != $FleetColors_UserVar[$TypeKey][$MissionID]) - { - $FleetColors_NeedChange = true; - $FleetColors_UserVar[$TypeKey][$MissionID] = $ThisColor; - } - } - } - if($FleetColors_NeedChange === true) - { - $ChangeSet['settings_FleetColors'] = mysql_real_escape_string(json_encode($FleetColors_UserVar)); - $ChangeSetTypes['settings_FleetColors'] = 's'; - } - - if(!empty($_POST['fleetColors'])) - { - foreach($_POST['fleetColors'] as $Key => $Values) - { - if(!empty($Values)) - { - foreach($Values as $MissionID => $MissionColor) - { - if(!empty($MissionColor) AND preg_match(REGEXP_HEXCOLOR, $MissionColor)) - { - - } - } - } - } - } - } - else if(!empty($_GET['ignoreadd']) || $_POST['saveType'] == 'ignore' || $_POST['saveType'] == 'delignore') - { - // Settings for Tab05 (IgnoreList Management) - $DontShow_NoChanges = true; - if(!empty($_GET['ignoreadd'])) - { - $_Lang['SetActiveMarker'] = '05'; - } - - if($_POST['saveType'] == 'delignore') - { - if(!empty($_POST['del_ignore']) && (array)$_POST['del_ignore'] === $_POST['del_ignore']) - { - foreach($_POST['del_ignore'] as $Values) - { - $Values = intval($Values); - if($Values > 0) - { - $ToDelete[] = $Values; - } - } - } - if(!empty($ToDelete)) - { - foreach($ToDelete as $ThisID) - { - if(!empty($_User['IgnoredUsers'][$ThisID])) - { - $IgnoreSystem_Deleted[] = $ThisID; - unset($_User['IgnoredUsers'][$ThisID]); - } - } - - if(!empty($IgnoreSystem_Deleted)) - { - $IgnoreSystem_Deleted_Count = count($IgnoreSystem_Deleted); - $IgnoreSystem_Deleted = implode(',', $IgnoreSystem_Deleted); - - $Query_DeleteIgnores = ''; - $Query_DeleteIgnores .= "DELETE FROM {{table}} WHERE "; - $Query_DeleteIgnores .= "`OwnerID` = {$_User['id']} AND `IgnoredID` IN ({$IgnoreSystem_Deleted}) LIMIT {$IgnoreSystem_Deleted_Count};"; - doquery($Query_DeleteIgnores, 'ignoresystem'); - - $InfoMsgs[] = sprintf($_Lang['Ignore_DeletedXUsers'], $IgnoreSystem_Deleted_Count); - } - else - { - $WarningMsgs[] = $_Lang['Ignore_NothingDeleted']; - } - } - else - { - $WarningMsgs[] = $_Lang['Ignore_NothingSelected']; - } - } - else if(!empty($_POST['ignore_username']) OR !empty($_GET['ignoreadd'])) - { - if(!empty($_GET['ignoreadd']) AND empty($_POST['ignore_username'])) - { - $IgnoreUser = intval($_GET['ignoreadd']); - $InputType = 'id'; - } - else - { - $IgnoreUser = (isset($_POST['ignore_username']) ? trim($_POST['ignore_username']) : null); - $InputType = 'un'; - } - if((strtolower($IgnoreUser) != strtolower($_User['username']) AND $InputType == 'un') OR ($IgnoreUser != $_User['id'] AND $InputType == 'id')) - { - if((preg_match(REGEXP_USERNAME_ABSOLUTE, $IgnoreUser) AND $InputType == 'un') OR ($IgnoreUser > 0 AND $InputType == 'id')) - { - $Query_CheckUser = ''; - $Query_CheckUser .= "SELECT `id`, `username`, `authlevel` FROM {{table}} "; - $Query_CheckUser .= "WHERE "; - if($InputType == 'un') - { - $Query_CheckUser .= "`username` = '{$IgnoreUser}'"; - } - else - { - $Query_CheckUser .= "`id` = {$IgnoreUser}"; - } - $Query_CheckUser .= " LIMIT 1; -- settings.php|IgnoreSystem|CheckUser"; - $Result_CheckUser = doquery($Query_CheckUser, 'users', true); - if($Result_CheckUser['id'] > 0) - { - if(!CheckAuth('user', AUTHCHECK_HIGHER, $Result_CheckUser)) - { - if(empty($_User['IgnoredUsers'][$Result_CheckUser['id']])) - { - $_User['IgnoredUsers'][$Result_CheckUser['id']] = $Result_CheckUser['username']; - doquery("INSERT INTO {{table}} (`OwnerID`, `IgnoredID`) VALUES ({$_User['id']}, {$Result_CheckUser['id']}); -- settings.php|IgnoreSystem|Insert", 'ignoresystem'); - $InfoMsgs[] = $_Lang['Ignore_UserAdded']; - } - else - { - $NoticeMsgs[] = $_Lang['Ignore_ThisUserAlreadyIgnored']; - } - } - else - { - $WarningMsgs[] = $_Lang['Ignore_CannotIgnoreGameTeam']; - } - } - else - { - $WarningMsgs[] = $_Lang['Ignore_UserNoExists']; - } - } - else - { - $WarningMsgs[] = $_Lang['Ignore_BadSignsOrShort']; - } - } - else - { - $WarningMsgs[] = $_Lang['Ignore_CannotIgnoreYourself']; - } - } - } - - if(!empty($ChangeSet)) - { - foreach($ChangeSet as $Key => $Value) - { - $_User[$Key] = $Value; - if($Key == 'deletion_endtime' AND $Value != '0') - { - eval('$_User[$Key] = '.(str_replace('UNIX_TIMESTAMP()', $Now, $Value)).';'); - } - if(isset($ChangeSetTypes[$Key]) && $ChangeSetTypes[$Key] == 's') - { - $Value = "'{$Value}'"; - } - $UpdateQuery[] = "`{$Key}` = {$Value}"; - } - - doquery("UPDATE {{table}} SET ".implode(', ', $UpdateQuery)." WHERE `id` = {$_User['id']};", 'users'); - if($ForceGoingOnVacationMsg === TRUE) - { - message((isset($ShowDeletionInfo) ? $_Lang['Vacation_GoingOnVacationsWithDeletion'] : $_Lang['Vacation_GoingOnVacations']), $_Lang['Vacations_Title'], 'settings.php', 3); - } - - $ChangeSetCounted = count($ChangeSet) - $ChangeSetCount; - if($ChangeSetCounted > 0) - { - $InfoMsgs[] = sprintf($_Lang['Info_SaveWellDone'], $ChangeSetCounted); - } - else - { - $NoticeMsgs[] = $_Lang['Info_NoChanges']; - } - } - else - { - if(!isset($DontShow_NoChanges) || $DontShow_NoChanges !== true) - { - $NoticeMsgs[] = $_Lang['Info_NoChanges']; - } - } - } - - if(!empty($WarningMsgs)) - { - foreach($WarningMsgs as $Message) - { - $_Lang['InfoBoxMsgs'][] = "
  • {$Message}
  • "; - } - } - if(!empty($NoticeMsgs)) - { - foreach($NoticeMsgs as $Message) - { - $_Lang['InfoBoxMsgs'][] = "
  • {$Message}
  • "; - } - } - if(!empty($InfoMsgs)) - { - foreach($InfoMsgs as $Message) - { - $_Lang['InfoBoxMsgs'][] = "
  • {$Message}
  • "; - } - } - - if(empty($_Lang['InfoBoxMsgs'])) - { - $_Lang['InfoBoxShow'] = 'display: none;'; - $_Lang['InfoBoxMsgs'] = "
  • "; - } - else - { - $_Lang['InfoBoxMsgs'] = implode('', $_Lang['InfoBoxMsgs']); - } - - if($_User['noipcheck'] == 1) - { - $_Lang['ipcheck_deactivate_check'] = 'checked'; - } - if($_User['planet_sort'] == 0) - { - $_Lang['planet_sort_mode_0'] = 'selected'; - } - if($_User['planet_sort'] == 1) - { - $_Lang['planet_sort_mode_1'] = 'selected'; - } - if($_User['planet_sort'] == 2) - { - $_Lang['planet_sort_mode_2'] = 'selected'; - } - if($_User['planet_sort_order'] == 0) - { - $_Lang['planet_sort_type_asc'] = 'selected'; - } - if($_User['planet_sort_order'] == 1) - { - $_Lang['planet_sort_type_desc'] = 'selected'; - } - if($_User['planet_sort_moons'] == 1) - { - $_Lang['planet_sort_moons_check'] = 'checked'; - } - $_Lang['skin_path'] = $_User['skinpath']; - if($_User['design'] == 1) - { - $_Lang['use_skin_check'] = 'checked'; - } - $_Lang['avatar_path'] = $_User['avatar']; - if($_User['settings_DevelopmentOld'] == 1) - { - $_Lang['development_old_check'] = 'checked'; - } - if($_User['settings_ExpandedBuildView'] == 1) - { - $_Lang['build_expandedview_use_check'] = 'checked'; - } - - if($_User['settings_useprettyinputbox'] == 1) - { - $_Lang['pretty_fleet_use_check'] = 'checked'; - } - - $_Lang['OldResSort_ArrayString'] = $_User['settings_resSortArray']; - $ExplodeOldResSort = explode(',', $_User['settings_resSortArray']); - foreach($ExplodeOldResSort as $ResKey => $ResData) - { - $ResKey += 1; - $_Lang['CreateResSortList'] .= "
  • {$ResKey}. {$_Lang['ResSort_Resources'][$ResData]}
  • "; - } - - $_Lang['msg_perpage_sel_'.$_User['settings_msgperpage']] = 'selected'; - if($_User['settings_spyexpand'] == 1) - { - $_Lang['msg_spyexpand_check'] = 'checked'; - } - if($_User['settings_UseMsgThreads'] == 1) - { - $_Lang['msg_usethreads_check'] = 'checked'; - } - $_Lang['spy_count'] = $_User['settings_spyprobescount']; - if($_User['settings_UseAJAXGalaxy'] == 1) - { - $_Lang['use_ajaxgalaxy_check'] = 'checked'; - } - if($_User['settings_Galaxy_ShowUserAvatars'] == 1) - { - $_Lang['show_useravatars_check'] = 'checked'; - } - if($_User['settings_esp'] == 1) - { - $_Lang['short_spy_check'] = 'checked'; - } - if($_User['settings_wri'] == 1) - { - $_Lang['short_write_check'] = 'checked'; - } - if($_User['settings_bud'] == 1) - { - $_Lang['short_buddy_check'] = 'checked'; - } - if($_User['settings_mis'] == 1) - { - $_Lang['short_rocket_check'] = 'checked'; - } - if($_User['is_ondeletion'] == 1) - { - $_Lang['delete_active_color'] = 'red'; - $_Lang['delete_activate_check'] = 'checked'; - $_Lang['DeleteMsg'] = sprintf($_Lang['DeleteMsg'], date('d.m.Y H:i:s', intval($_User['deletion_endtime']))); - $_Lang['DeleteAccount'] = $_Lang['DeleteAccountOff']; - $_Lang['DeleteConfirmShow'] = 'style="display: none;"'; - } - else - { - $_Lang['DontShowDeleteWarning'] = 'display: none;'; - $_Lang['DeleteClickToRemoveShow'] = 'style="display: none;"'; - $_Lang['DeleteMsg'] = ''; - } - if(strstr($_User['skinpath'], 'http://') === FALSE) - { - foreach($AvailableSkins as $Key => $Skin) - { - if(strstr($_User['skinpath'], $Skin)) - { - $_Lang['ServerSkins'] = str_replace('{select_no'.$Key.'}', 'selected', $_Lang['ServerSkins']); - } - else - { - $_Lang['ServerSkins'] = str_replace('{select_no'.$Key.'}', '', $_Lang['ServerSkins']); - } - } - } - $_Lang['QuickRes_PlanetList'] = str_replace('{sel_planet_'.$_User['settings_mainPlanetID'].'}', 'selected', $_Lang['QuickRes_PlanetList']); - $_Lang['QuickRes_PlanetList'] = preg_replace('#\{sel\_planet\_[0-9]{1,}\}#si', '', $_Lang['QuickRes_PlanetList']); - - if(!empty($_User['IgnoredUsers'])) - { - foreach($_User['IgnoredUsers'] as $IgnoredID => $IgnoredName) - { - $_Lang['ParseIgnoreList'][] = " "; - } - $_Lang['ParseIgnoreList'] = implode('
    ', $_Lang['ParseIgnoreList']); - if(count($_User['IgnoredUsers']) < 15) - { - $_Lang['IgnoreList_Hide2Del'] = 'style="display: none;"'; - } - } - else - { - $_Lang['ParseIgnoreList'] = "
    {$_Lang['IgnoreList_NoIgnored']}
    "; - $_Lang['IgnoreList_Hide1Del'] = 'style="display: none;"'; - $_Lang['IgnoreList_Hide2Del'] = 'style="display: none;"'; - } - - if($CheckMailChange['ID'] > 0) - { - $_Lang['EMChange1'] = 'style="display: none;"'; - $_Lang['EmailPrc_Active_Since'] = sprintf($_Lang['EmailPrc_Active_Since'], date('d.m.Y H:i:s', $CheckMailChange['Date'])); - $_Lang['OldEmail']= $_Lang['RealOldEmail']; - $_Lang['EmailPrc_NewEmail'] = $_User['email_2']; - } - else - { - $_Lang['EMChange2'] = 'style="display: none;"'; - } - - if(empty($_Lang['SetActiveMarker'])) - { - if(!empty($_GET['tab'])) - { - if(in_array($_GET['tab'], array(1,2,3,4,5,6))) - { - $_Lang['SetActiveMarker'] = str_pad($_GET['tab'], 2, '0', STR_PAD_LEFT); - } - } - } - - // Logons List - $Query_GetLogons = ''; - $Query_GetLogons .= "SELECT `Log`.*, `IPTable`.`Value` FROM {{table}} AS `Log` "; - $Query_GetLogons .= "LEFT JOIN `{{prefix}}used_ip_and_ua` AS `IPTable` ON `Log`.`IP_ID` = `IPTable`.`ID` "; - $Query_GetLogons .= "WHERE `Log`.`User_ID` = {$_User['id']} "; - $Query_GetLogons .= "ORDER BY `Log`.`LastTime` DESC LIMIT {$LogonLIMIT};"; - $GetLogons = doquery($Query_GetLogons, 'user_enterlog'); - if(mysql_num_rows($GetLogons) > 0) - { - while($LogonData = mysql_fetch_assoc($GetLogons)) - { - $LogonData['Times'] = array_reverse(explode(',', $LogonData['Times'])); - $LimitCounter = $LogonLIMIT; - foreach($LogonData['Times'] as $Temp) - { - if($LimitCounter <= 0) - { - break; - } - $Temp = explode('|', $Temp); - $ThisTime = SERVER_MAINOPEN_TSTAMP + $Temp[0]; - $LogonList[] = array('Time' => $ThisTime, 'IP' => $LogonData['Value'], 'State' => (isset($Temp[1]) && $Temp[1] == 'F' ? false : true)); - $LogonTimes[] = $ThisTime; - $LimitCounter -= 1; - } - } - - array_multisort($LogonList, SORT_DESC, $LogonTimes); - $LimitCounter = $LogonLIMIT; - foreach($LogonList as $LogonData) - { - if($LimitCounter <= 0) - { - break; - } - if($LogonData['IP'] == $_User['user_lastip']) - { - $LogonData['IPColor'] = 'lime'; - } - if($LogonData['State'] === false) - { - if($LogonData['IP'] != $_User['user_lastip']) - { - $LogonData['DateColor'] = 'red'; - $LogonData['IPColor'] = 'red'; - $LogonData['StateColor'] = 'red'; - } - else - { - $LogonData['StateColor'] = 'orange'; - } - } - - - $ThisRow = ''; - $ThisRow .= ''.prettyDate('d m Y, H:i:s', $LogonData['Time'], 1).''; - $ThisRow .= ''.pretty_time($Now - $LogonData['Time'], true, 'D').' '.$_Lang['Logons_ago'].''; - $ThisRow .= ''.$LogonData['IP'].''; - $ThisRow .= ''.($LogonData['State'] === true ? $_Lang['Logons_Success'] : $_Lang['Logons_Failed']).''; - $ThisRow .= ''; - $_Lang['ParseLogonsList'][] = $ThisRow; - $LimitCounter -= 1; - } - $_Lang['ParseLogonsList'] = implode('', $_Lang['ParseLogonsList']); - } - else - { - $_Lang['ParseLogonsList'] = ''.$_Lang['Logons_ListEmpty'].''; - } - - // FleetColors - Pickers - $TPL_FleetColors_Row = gettemplate('settings_fleetcolors_row'); - if(!empty($_User['settings_FleetColors'])) - { - if(isset($FleetColors_NeedChange) && $FleetColors_NeedChange === true) - { - $_User['settings_FleetColors'] = stripslashes($_User['settings_FleetColors']); - } - $FleetColors = json_decode($_User['settings_FleetColors'], true); - } - foreach($_Vars_FleetMissions['all'] as $MissionID) - { - $_Lang['Insert_FleetColors_Pickers'][] = parsetemplate($TPL_FleetColors_Row, array - ( - 'MissionName' => $_Lang['type_mission'][$MissionID], - 'MissionID' => $MissionID, - 'Value_OwnFly' => (isset($FleetColors['ownfly'][$MissionID]) ? $FleetColors['ownfly'][$MissionID] : null), - 'Value_OwnComeback' => (isset($FleetColors['owncb'][$MissionID]) ? $FleetColors['owncb'][$MissionID] : null), - 'Value_NonOwn' => (isset($FleetColors['nonown'][$MissionID]) ? $FleetColors['nonown'][$MissionID] : null) - )); - } - $_Lang['Insert_FleetColors_Pickers'] = implode('', $_Lang['Insert_FleetColors_Pickers']); - - $BodyTPL = gettemplate('settings_body'); - $Page = parsetemplate($BodyTPL, $_Lang); - display($Page, $_Lang['Page_Title'], false); - } - else if($Mode == 'nickchange') - { - // User is trying to change his nickname - if(!empty($_POST['newnick'])) - { - // Nickname Change in progress - if($_User['darkEnergy'] < 10) - { - message($_Lang['NewNick_donthave_DE'], $_Lang['NickChange_Title'], 'settings.php?mode=nickchange'); - } - $NewNick = trim($_POST['newnick']); - if($NewNick == $_User['username']) - { - message($_Lang['NewNick_is_like_old'], $_Lang['NickChange_Title'], 'settings.php?mode=nickchange'); - } - if(strlen($NewNick) < 4) - { - message($_Lang['NewNick_is_tooshort'], $_Lang['NickChange_Title'], 'settings.php?mode=nickchange'); - } - if(strstr($NewNick, 'http') OR strstr($NewNick, 'www.')) - { - message($_Lang['NewNick_nolinks'], $_Lang['NickChange_Title'], 'settings.php?mode=nickchange'); - } - if(!preg_match(REGEXP_USERNAME_ABSOLUTE, $NewNick)) - { - message($_Lang['NewNick_badSigns'], $_Lang['NickChange_Title'], 'settings.php?mode=nickchange'); - } - $SelectNewNick = doquery("SELECT `id` FROM {{table}} WHERE `username` = '{$NewNick}' LIMIT 1;", 'users', true); - if($SelectNewNick['id'] > 0) - { - message($_Lang['NewNick_already_taken'], $_Lang['NickChange_Title'], 'settings.php?mode=nickchange'); - } - - doquery("UPDATE {{table}} SET `darkEnergy` = `darkEnergy` - 10, `username` = '{$NewNick}', `old_username` = '{$_User['username']}', `old_username_expire` = UNIX_TIMESTAMP() + (7*24*60*60) WHERE `id` = {$_User['id']} LIMIT 1;", 'users'); - doquery("INSERT INTO {{table}} VALUES(NULL, {$_User['id']}, UNIX_TIMESTAMP(), '{$NewNick}', '{$_User['username']}');", 'nick_changelog'); - setcookie($_GameConfig['COOKIE_NAME'], '', $Now - 3600, '/', ''); - message($_Lang['NewNick_saved'], $_Lang['NickChange_Title'], 'login.php'); - } - else - { - $_Lang['skinpath'] = $_SkinPath; - $_Lang['DarkEnergy_Counter'] = $_User['darkEnergy']; - if($_User['darkEnergy'] >= 15) - { - $_Lang['DarkEnergy_Color'] = 'lime'; - } - else if($_User['darkEnergy'] > 0) - { - $_Lang['DarkEnergy_Color'] = 'orange'; - } - else - { - $_Lang['DarkEnergy_Color'] = 'red'; - } - - // Informations box - display(parsetemplate(gettemplate('settings_changenick'), $_Lang), $_Lang['NickChange_Title'], false); - } - } - } - else - { - // User is on Vacation - if($Mode == 'exit') - { - // User is trying to remove Vacation mode - if(isset($_POST['exit_modus']) && $_POST['exit_modus'] == 'on' && canTakeVacationOff($Now)) - { - doquery("UPDATE {{table}} SET `is_onvacation` = '0', `vacation_starttime` = '0', `vacation_endtime` = '0', `vacation_leavetime` = IF(`vacation_type` = 2, 0, UNIX_TIMESTAMP()) WHERE `id` = {$_User['id']} LIMIT 1;", 'users'); - doquery("UPDATE {{table}} SET `last_update` = UNIX_TIMESTAMP() WHERE `id_owner` = {$_User['id']}", 'planets'); - $_Planet['last_update'] = $Now; - - $UserDev_Log[] = array('PlanetID' => '0', 'Date' => $Now, 'Place' => 26, 'Code' => '2', 'ElementID' => '0'); - - message($_Lang['Vacation_GoOut'], $_Lang['Vacations_Title'], 'overview.php', 3); - } - else - { - message($_Lang['Vacation_CantGoOut'], $_Lang['Vacations_Title'], 'settings.php', 3); - } - } - - $MinimalVacationTime = ($_User['pro_time'] > $_User['vacation_starttime'] ? MINURLOP_PRO : MINURLOP_FREE) + $_User['vacation_starttime']; - if($_User['vacation_type'] != 0) - { - $_Lang['Parse_Vacation_EndTime'] = $_Lang['Vacation_EndTimeNoBlock']; - } - else - { - if($MinimalVacationTime <= $Now) - { - $MinimalVacationTimeColor = 'lime'; - } - else - { - $MinimalVacationTimeColor = 'orange'; - } - $_Lang['Parse_Vacation_EndTime'] = sprintf($_Lang['Vacation_EndTime'], $MinimalVacationTimeColor, prettyDate('d m Y, H:i:s', $MinimalVacationTime, 1)); - } - - display(parsetemplate(gettemplate('settings_vacations'), $_Lang), $_Lang['Vacations_Title'], false); - } - -?> \ No newline at end of file + 'XNova', 'epicblue' => 'EpicBlue Fresh', 'epicblue_old' => 'EpicBlue Standard'); + +$SkinDir = scandir('./skins/'); +$SkinCounter = 1; +if(!empty($SkinDir)) +{ + foreach($SkinDir as $Element) + { + if(strstr($Element, '.') === FALSE) + { + if(is_dir('./skins/'.$Element)) + { + if(empty($SkinNames[$Element])) + { + $SkinNames[$Element] = $Element; + } + $_Lang['ServerSkins'] .= ''; + $AvailableSkins[$SkinCounter] = "skins/{$Element}"; + $SkinCounter += 1; + } + } + } +} + +$SelectAllPlanets = doquery("SELECT `id`, `name`, `galaxy`, `system`, `planet` FROM {{table}} WHERE `id_owner` = {$_User['id']} AND `planet_type` = 1;", 'planets'); +while($Planets = mysql_fetch_assoc($SelectAllPlanets)) +{ + $_Lang['QuickRes_PlanetList'] .= ""; +} + +$Mode = (isset($_GET['mode']) ? $_GET['mode'] : null); + +if(!isOnVacation()) +{ + if(empty($Mode) OR $Mode == 'general') + { + // General View + $CheckMailChange = doquery("SELECT `ID`, `Date` FROM {{table}} WHERE `UserID` = {$_User['id']} AND `ConfirmType` = 0 LIMIT 1;", 'mailchange', true); + + $Query_IgnoreSystem = ''; + $Query_IgnoreSystem .= "SELECT `ignore`.`IgnoredID`, `user`.`username` FROM {{table}} AS `ignore` "; + $Query_IgnoreSystem .= "JOIN `{{prefix}}users` AS `user` ON `ignore`.`IgnoredID` = `user`.`id` "; + $Query_IgnoreSystem .= "WHERE `ignore`.`OwnerID` = {$_User['id']};"; + $Result_IgnoreSystem = doquery($Query_IgnoreSystem, 'ignoresystem'); + if(mysql_num_rows($Result_IgnoreSystem) > 0) + { + while($FetchData = mysql_fetch_assoc($Result_IgnoreSystem)) + { + $_User['IgnoredUsers'][$FetchData['IgnoredID']] = $FetchData['username']; + } + } + + if((isset($_POST['save']) && $_POST['save'] == 'yes') || !empty($_GET['ignoreadd'])) + { + if($_POST['saveType'] == $_Lang['SaveAll']) + { + $_Lang['SetActiveMarker'] = (isset($_POST['markActive']) ? $_POST['markActive'] : null); + + // Settings for Tab01 + if(isset($_POST['change_pass']) && $_POST['change_pass'] == 'on') + { + $_POST['give_newpass'] = trim($_POST['give_newpass']); + if(md5($_POST['give_oldpass']) == $_User['password']) + { + if(strlen($_POST['give_newpass']) >= 4) + { + if(md5($_POST['give_newpass']) != $_User['password']) + { + if($_POST['give_newpass'] == $_POST['give_confirmpass']) + { + $ChangeSet['password'] = md5($_POST['give_newpass']); + $ChangeSetTypes['password'] = 's'; + $InfoMsgs[] = $_Lang['Pass_Changed_plzlogout']; + setcookie($_GameConfig['COOKIE_NAME'], '', $Now - 3600, '/', ''); + } + else + { + $WarningMsgs[] = $_Lang['Pass_Confirm_isbad']; + } + } + else + { + $WarningMsgs[] = $_Lang['Pass_same_as_old']; + } + } + else + { + $WarningMsgs[] = $_Lang['Pass_is_tooshort']; + } + } + else + { + $WarningMsgs[] = $_Lang['Pass_old_isbad']; + } + } + + if(isset($_POST['change_mail']) && $_POST['change_mail'] == 'on') + { + if($CheckMailChange['ID'] <= 0) + { + $_POST['give_newemail'] = mysql_real_escape_string(strip_tags(trim($_POST['give_newemail']))); + $CheckMail = $_POST['give_newemail']; + $banned_domain_list = $_GameConfig['BannedMailDomains']; + $banned_domain_list = str_replace('.', '\.', $banned_domain_list); + + if(is_email($CheckMail)) + { + if($CheckMail !== $_User['email']) + { + if($CheckMail === $_POST['give_confirmemail']) + { + if(empty($banned_domain_list) || !preg_match('#('.$banned_domain_list.')+#si', $CheckMail)) + { + $CheckMailinDB = doquery("SELECT `id` FROM {{table}} WHERE `email` = '{$CheckMail}' LIMIT 1;", 'users', true); + if($CheckMailinDB['id'] <= 0) + { + $RandomHash = md5($_User['id'].$_User['username'].mt_rand(0, 999999999)); + $RandomHashNew = md5($_User['id'].$_User['username'].mt_rand(0, 999999999)); + $ThisTime = $Now; + + $EmailParse = array + ( + 'EP_User' => $_User['username'], + 'EP_GameLink' => GAMEURL_STRICT, + 'EP_Link' => GAMEURL."email_change.php?hash=old&key={$RandomHash}", + 'EP_Text' => $_Lang['Email_MailOld'], + 'EP_OldMail' => $_User['email'], + 'EP_NewMail' => $CheckMail, + 'EP_Date' => date('d.m.Y - H:i:s', $ThisTime), + 'EP_IP' => $_User['user_lastip'], + 'EP_ContactLink' => GAMEURL_STRICT.'/contact.php', + 'EP_Text2' => $_Lang['Email_WarnOld'] + ); + $EmailParseNew = array + ( + 'EP_User' => $_User['username'], + 'EP_GameLink' => GAMEURL_STRICT, + 'EP_Link' => GAMEURL."email_change.php?hash=new&key={$RandomHashNew}", + 'EP_Text' => $_Lang['Email_MailNew'], + 'EP_OldMail' => $_User['email'], + 'EP_NewMail' => $CheckMail, + 'EP_Date' => date('d.m.Y - H:i:s', $ThisTime), + 'EP_IP' => $_User['user_lastip'], + 'EP_ContactLink' => GAMEURL_STRICT.'/contact.php', + 'EP_Text2' => $_Lang['Email_WarnNew'] + ); + + include($_EnginePath.'includes/functions/SendMail.php'); + $EmailBody = parsetemplate($_Lang['Email_Body'], $EmailParse); + $EmailBodyNew = parsetemplate($_Lang['Email_Body'], $EmailParseNew); + $SendResult = SendMail($_User['email'], $_Lang['Email_Title'], $EmailBody, '', true); + $SendResult2 = SendMail($CheckMail, $_Lang['Email_Title'], $EmailBodyNew); + CloseMailConnection(); + + if($SendResult === TRUE AND $SendResult2 === TRUE) + { + $ChangeSet['email_2'] = $CheckMail; + $ChangeSetTypes['email_2'] = 's'; + + doquery("INSERT INTO {{table}} VALUES (NULL, {$ThisTime}, {$_User['id']}, '{$_User['email']}', '{$CheckMail}', 0, 0, '{$RandomHash}', '{$RandomHashNew}');", 'mailchange'); + $CheckMailChange = array('ID' => 1, 'Date' => $ThisTime); + $InfoMsgs[] = sprintf($_Lang['Mail_MailChange'], $_User['email']); + } + else + { + $WarningMsgs[] = sprintf($_Lang['Mail_SendMailError'], urlencode(str_pad(mt_rand(0,999), 3, 'a', STR_PAD_RIGHT).base64_encode($SendResult).'||'.base64_encode($SendResult2))); + } + } + else + { + $WarningMsgs[] = $_Lang['Mail_some1_hasemail']; + } + } + else + { + $WarningMsgs[] = $_Lang['Mail_banned_domain']; + } + } + else + { + $WarningMsgs[] = $_Lang['Mail_Confirm_isbad']; + } + } + else + { + $WarningMsgs[] = $_Lang['Mail_same_as_old']; + } + } + else + { + $WarningMsgs[] = $_Lang['Mail_badEmail']; + } + } + else + { + $WarningMsgs[] = $_Lang['Mail_alreadyInChange']; + } + } + + if(isset($_POST['stop_email_change']) && $_POST['stop_email_change'] == 'on') + { + if($CheckMailChange['ID'] > 0) + { + doquery("UPDATE {{table}} SET `ConfirmType` = 3 WHERE `ID` = {$CheckMailChange['ID']} LIMIT 1;", 'mailchange'); + unset($CheckMailChange); + $InfoMsgs[] = $_Lang['Mail_PrcStopped']; + } + else + { + $WarningMsgs[] = $_Lang['Mail_PrcNoExists']; + } + } + + if(isset($_POST['ipcheck_deactivate']) && $_POST['ipcheck_deactivate'] == 'on') + { + $IPCheckDeactivate = '1'; + } + else + { + $IPCheckDeactivate = '0'; + } + if($_User['noipcheck'] != $IPCheckDeactivate) + { + $ChangeSet['noipcheck'] = $IPCheckDeactivate; + } + else + { + $ChangeNotDone += 1; + } + + // Settings for Tab02 + $PlanetSortMode = intval($_POST['planet_sort_mode']); + if($PlanetSortMode <= 0 OR $PlanetSortMode > 2) + { + $PlanetSortMode = '0'; + } + if($PlanetSortMode != $_User['planet_sort']) + { + $ChangeSet['planet_sort'] = $PlanetSortMode; + } + else + { + $ChangeNotDone += 1; + } + + $PlanetSortType = intval($_POST['planet_sort_type']); + if($PlanetSortType != 1) + { + $PlanetSortType = '0'; + } + if($PlanetSortType != $_User['planet_sort_order']) + { + $ChangeSet['planet_sort_order'] = $PlanetSortType; + } + else + { + $ChangeNotDone += 1; + } + + if(isset($_POST['planet_sort_moons']) && $_POST['planet_sort_moons'] == 'on') + { + $PlanetSortMoons = '1'; + } + else + { + $PlanetSortMoons = '0'; + } + + if($PlanetSortMoons != $_User['planet_sort_moons']) + { + $ChangeSet['planet_sort_moons'] = $PlanetSortMoons; + } + else + { + $ChangeNotDone += 1; + } + + $SkinPath = mysql_real_escape_string(strip_tags(trim($_POST['skin_path']))); + if(strstr($SkinPath, 'http://') === FALSE AND strstr($SkinPath, 'www.') === FALSE) + { + if($SkinPath != '') + { + $SkinPath = ltrim($SkinPath, '/'); + if(substr($SkinPath, strlen($SkinPath) - 1) != '/') + { + $SkinPath .= '/'; + } + if(!file_exists('./'.$SkinPath.'formate.css')) + { + $WarningMsgs[] = $_Lang['Skin_NoLocalSkin']; + $SkinPath = $_User['skinpath']; + } + } + else + { + $_POST['use_skin'] = ''; + } + } + else + { + if(strstr($SkinPath, 'http://') === FALSE AND strstr($SkinPath, 'www.') !== FALSE) + { + $SkinPath = str_replace('www.', 'http://', $SkinPath); + } + } + if($SkinPath != $_User['skinpath']) + { + $_SkinPath = $SkinPath; + $ChangeSet['skinpath'] = $SkinPath; + $_Lang['skinpath'] = $SkinPath; + $ChangeSetTypes['skinpath'] = 's'; + } + else + { + $ChangeNotDone += 1; + } + + if(isset($_POST['use_skin']) && $_POST['use_skin'] == 'on') + { + $UseSkin = '1'; + } + else + { + $UseSkin = '0'; + } + if($UseSkin != $_User['design']) + { + $ChangeSet['design'] = $UseSkin; + } + else + { + $ChangeNotDone += 1; + } + + $AvatarPath = mysql_real_escape_string(strip_tags(trim($_POST['avatar_path']))); + if(strstr($AvatarPath, 'http://') === FALSE AND strstr($AvatarPath, 'www.') !== FALSE) + { + $AvatarPath = str_replace('www.', 'http://', $AvatarPath); + } + if($AvatarPath != $_User['avatar']) + { + $ChangeSet['avatar'] = $AvatarPath; + $ChangeSetTypes['avatar'] = 's'; + } + else + { + $ChangeNotDone += 1; + } + + if(isset($_POST['development_old']) && $_POST['development_old'] == 'on') + { + $DevelopmentOld = '1'; + } + else + { + $DevelopmentOld = '0'; + } + if($DevelopmentOld != $_User['settings_DevelopmentOld']) + { + $ChangeSet['settings_DevelopmentOld'] = $DevelopmentOld; + } + else + { + $ChangeNotDone += 1; + } + + if(isset($_POST['build_expandedview_use']) && $_POST['build_expandedview_use'] == 'on') + { + $BuildExpandedView = '1'; + } + else + { + $BuildExpandedView = '0'; + } + if($BuildExpandedView != $_User['settings_ExpandedBuildView']) + { + $ChangeSet['settings_ExpandedBuildView'] = $BuildExpandedView; + } + else + { + $ChangeNotDone += 1; + } + + if(isset($_POST['pretty_fleet_use']) && $_POST['pretty_fleet_use'] == 'on') + { + $UsePrettyFleet = '1'; + } + else + { + $UsePrettyFleet = '0'; + } + if($UsePrettyFleet != $_User['settings_useprettyinputbox']) + { + $ChangeSet['settings_useprettyinputbox'] = $UsePrettyFleet; + } + else + { + $ChangeNotDone += 1; + } + + $ChangeNotDone += 1; + if(isset($_POST['resSort_changed']) && $_POST['resSort_changed'] == '1') + { + $_POST['resSort_array'] = (isset($_POST['resSort_array']) ? trim($_POST['resSort_array']) : null); + if(preg_match('/^[a-z]{3}\,[a-z]{3}\,[a-z]{3}$/D', $_POST['resSort_array'])) + { + $CheckData = explode(',', $_POST['resSort_array']); + foreach($CheckData as $Data2Check) + { + if($Data2Check != 'met' AND $Data2Check != 'cry' AND $Data2Check != 'deu') + { + $DisAllowResSort_Change = true; + break; + } + } + if(!isset($DisAllowResSort_Change)) + { + $ChangeSet['settings_resSortArray'] = $_POST['resSort_array']; + $ChangeSetTypes['settings_resSortArray'] = 's'; + $ChangeNotDone -= 1; + } + } + } + + $ChangeNotDone += 1; + if($_User['settings_mainPlanetID'] != $_POST['quickres_select']) + { + $PlanetID = round(floatval($_POST['quickres_select'])); + if($PlanetID > 0) + { + $CheckPlanetExist = doquery("SELECT `id_owner` FROM {{table}} WHERE `id` = {$PlanetID} LIMIT 1;", 'planets', true); + if($CheckPlanetExist['id_owner'] == $_User['id']) + { + $ChangeSet['settings_mainPlanetID'] = $PlanetID; + $ChangeNotDone -= 1; + } + else + { + $WarningMsgs[] = $_Lang['Msgs_PlanetNotYour']; + } + } + } + + $MsgsPerPage = intval($_POST['msg_perpage']); + if($MsgsPerPage != $_User['settings_msgperpage']) + { + if(in_array($MsgsPerPage, array(5, 10, 15, 20, 25, 50, 75, 100, 150, 200))) + { + $ChangeSet['settings_msgperpage'] = $MsgsPerPage; + } + else + { + $WarningMsgs[] = $_Lang['Msgs_BadPerPageInt']; + $ChangeNotDone += 1; + } + } + else + { + $ChangeNotDone += 1; + } + + if(isset($_POST['msg_spyexpand']) && $_POST['msg_spyexpand'] == 'on') + { + $MsgExpandSpyReports = '1'; + } + else + { + $MsgExpandSpyReports = '0'; + } + if($MsgExpandSpyReports != $_User['settings_spyexpand']) + { + $ChangeSet['settings_spyexpand'] = $MsgExpandSpyReports; + } + else + { + $ChangeNotDone += 1; + } + + if(isset($_POST['msg_usethreads']) && $_POST['msg_usethreads'] == 'on') + { + $MsgUseMsgThreads = '1'; + } + else + { + $MsgUseMsgThreads = '0'; + } + if($MsgUseMsgThreads != $_User['settings_UseMsgThreads']) + { + $ChangeSet['settings_UseMsgThreads'] = $MsgUseMsgThreads; + } + else + { + $ChangeNotDone += 1; + } + + // Settings for Tab03 + $SpyCount = intval($_POST['spy_count']); + if($SpyCount < 1) + { + $SpyCount = 1; + } + else if($SpyCount > $MaxEspionageProbesCount) + { + $SpyCount = $MaxEspionageProbesCount; + } + if($SpyCount != $_User['settings_spyprobescount']) + { + $ChangeSet['settings_spyprobescount'] = $SpyCount; + } + else + { + $ChangeNotDone += 1; + } + + if(isset($_POST['use_ajaxgalaxy']) && $_POST['use_ajaxgalaxy'] == 'on') + { + $UseAJAXGalaxy = '1'; + } + else + { + $UseAJAXGalaxy = '0'; + } + if($UseAJAXGalaxy != $_User['settings_UseAJAXGalaxy']) + { + $ChangeSet['settings_UseAJAXGalaxy'] = $UseAJAXGalaxy; + } + else + { + $ChangeNotDone += 1; + } + if(isset($_POST['show_useravatars']) && $_POST['show_useravatars'] == 'on') + { + $ShowUserAvatars = '1'; + } + else + { + $ShowUserAvatars = '0'; + } + if($ShowUserAvatars != $_User['settings_Galaxy_ShowUserAvatars']) + { + $ChangeSet['settings_Galaxy_ShowUserAvatars'] = $ShowUserAvatars; + } + else + { + $ChangeNotDone += 1; + } + + if(isset($_POST['short_spy']) && $_POST['short_spy'] == 'on') + { + $ShortcutSpy = '1'; + } + else + { + $ShortcutSpy = '0'; + } + if($ShortcutSpy != $_User['settings_esp']) + { + $ChangeSet['settings_esp'] = $ShortcutSpy; + } + else + { + $ChangeNotDone += 1; + } + + if(isset($_POST['short_write']) && $_POST['short_write'] == 'on') + { + $ShortcutWrite = '1'; + } + else + { + $ShortcutWrite = '0'; + } + if($ShortcutWrite != $_User['settings_wri']) + { + $ChangeSet['settings_wri'] = $ShortcutWrite; + } + else + { + $ChangeNotDone += 1; + } + + if(isset($_POST['short_buddy']) && $_POST['short_buddy'] == 'on') + { + $ShortcutBuddy = '1'; + } + else + { + $ShortcutBuddy = '0'; + } + if($ShortcutBuddy != $_User['settings_bud']) + { + $ChangeSet['settings_bud'] = $ShortcutBuddy; + } + else + { + $ChangeNotDone += 1; + } + + if(isset($_POST['short_rocket']) && $_POST['short_rocket'] == 'on') + { + $ShortcutRocket = '1'; + } + else + { + $ShortcutRocket = '0'; + } + if($ShortcutRocket != $_User['settings_mis']) + { + $ChangeSet['settings_mis'] = $ShortcutRocket; + } + else + { + $ChangeNotDone += 1; + } + + // Settings for Tab04 + $_Lang['SetActiveMarker'] = '04'; + if((isset($_POST['vacation_activate']) && $_POST['vacation_activate'] == 'on') || (isset($_POST['delete_activate']) && $_POST['delete_activate'] == 'on')) + { + if(isset($_POST['vacation_activate']) && $_POST['vacation_activate'] == 'on') + { + $allowVacation = true; + if(($_User['vacation_leavetime'] + TIME_DAY) >= $Now) + { + $allowVacation = false; + $WarningMsgs[] = $_Lang['Vacation_24hNotPassed']; + } + + $checkFleets = doquery("SELECT COUNT(*) AS `Count` FROM {{table}} WHERE `fleet_owner` = {$_User['id']} OR `fleet_target_owner` = {$_User['id']};", 'fleets', true); + if($checkFleets['Count'] > 0) + { + $allowVacation = false; + $WarningMsgs[] = $_Lang['Vacation_FlyingFleets']; + } + + if($allowVacation === true) + { + // Update All Planets/Moons before VacationMode (don't do that if previous conditions are not fulfilled) + $AllPlanets = doquery("SELECT * FROM {{table}} WHERE `id_owner` = {$_User['id']};", 'planets'); + + $Results['planets'] = array(); + while($PlanetsData = mysql_fetch_assoc($AllPlanets)) + { + // Update Planet - Building Queue + $GeneratePlanetName[$PlanetsData['id']] = "{$PlanetsData['name']} [{$PlanetsData['galaxy']}:{$PlanetsData['system']}:{$PlanetsData['planet']}]"; + + if(HandlePlanetUpdate($PlanetsData, $_User, $Now, true) === true) + { + $Results['planets'][] = $PlanetsData; + } + if($PlanetsData['buildQueue_firstEndTime'] > 0 OR $PlanetsData['shipyardQueue'] != 0) + { + $FoundBlockingPlanets[$PlanetsData['id']] = $GeneratePlanetName[$PlanetsData['id']]; + } + } + HandlePlanetUpdate_MultiUpdate($Results, $_User); + if($_User['techQueue_EndTime'] > 0) + { + $FoundBlockingPlanets[$PlanetsData['id']] = $GeneratePlanetName[$_User['techQueue_Planet']]; + } + + if(!empty($FoundBlockingPlanets)) + { + $allowVacation = false; + $WarningMsgs[] = sprintf($_Lang['Vacation_CannotBuildOrRes'], implode(', ', $FoundBlockingPlanets)); + } + } + + if($allowVacation === true) + { + $ChangeSet['is_onvacation'] = '1'; + $ChangeSet['vacation_starttime'] = 'UNIX_TIMESTAMP()'; + $ChangeSet['vacation_endtime'] = 'UNIX_TIMESTAMP() + '.(MAXVACATIONS_REG * TIME_DAY); + $ChangeSet['vacation_type'] = '0'; + + $ChangeSetCount += 1; + $ForceGoingOnVacationMsg = true; + + $UserDev_Log[] = array('PlanetID' => '0', 'Date' => $Now, 'Place' => 26, 'Code' => '1', 'ElementID' => '0'); + } + } + if(isset($_POST['delete_activate']) && $_POST['delete_activate'] == 'on') + { + if($_User['is_ondeletion'] == 0) + { + if(md5($_POST['delete_confirm']) == $_User['password']) + { + $ChangeSet['is_ondeletion'] = '1'; + $ChangeSet['deletion_endtime'] = 'UNIX_TIMESTAMP() + '.(ACCOUNT_DELETION_TIME * TIME_DAY); + $ChangeSetCount += 1; + + if($ForceGoingOnVacationMsg === true) + { + $ShowDeletionInfo = true; + } + } + else + { + $WarningMsgs[] = $_Lang['Delete_Confirm_isbad']; + } + } + } + } + else + { + if($_User['is_ondeletion'] == 1) + { + $ChangeSet['is_ondeletion'] = '0'; + $ChangeSet['deletion_endtime'] = '0'; + $ChangeSetCount += 1; + } + } + + if(empty($_User['settings_FleetColors'])) + { + foreach($_Vars_FleetMissions['all'] as $MissionID) + { + $_User['settings_FleetColors']['ownfly'][$MissionID] = ''; + $_User['settings_FleetColors']['owncb'][$MissionID] = ''; + $_User['settings_FleetColors']['nonown'][$MissionID] = ''; + } + $FleetColors_UserVar = $_User['settings_FleetColors']; + $_User['settings_FleetColors'] = null; + } + else + { + $FleetColors_UserVar = json_decode($_User['settings_FleetColors'], true); + } + $FleetColors_NeedChange = false; + foreach($FleetColors_UserVar as $TypeKey => $Missions) + { + foreach($Missions as $MissionID => $MissionColor) + { + if(!empty($_POST['fleetColors'][$TypeKey][$MissionID]) AND preg_match(REGEXP_HEXCOLOR, $_POST['fleetColors'][$TypeKey][$MissionID])) + { + $ThisColor = $_POST['fleetColors'][$TypeKey][$MissionID]; + } + else + { + $ThisColor = ''; + } + if($ThisColor != $FleetColors_UserVar[$TypeKey][$MissionID]) + { + $FleetColors_NeedChange = true; + $FleetColors_UserVar[$TypeKey][$MissionID] = $ThisColor; + } + } + } + if($FleetColors_NeedChange === true) + { + $ChangeSet['settings_FleetColors'] = mysql_real_escape_string(json_encode($FleetColors_UserVar)); + $ChangeSetTypes['settings_FleetColors'] = 's'; + } + + if(!empty($_POST['fleetColors'])) + { + foreach($_POST['fleetColors'] as $Key => $Values) + { + if(!empty($Values)) + { + foreach($Values as $MissionID => $MissionColor) + { + if(!empty($MissionColor) AND preg_match(REGEXP_HEXCOLOR, $MissionColor)) + { + + } + } + } + } + } + } + else if(!empty($_GET['ignoreadd']) || $_POST['saveType'] == 'ignore' || $_POST['saveType'] == 'delignore') + { + // Settings for Tab05 (IgnoreList Management) + $DontShow_NoChanges = true; + if(!empty($_GET['ignoreadd'])) + { + $_Lang['SetActiveMarker'] = '05'; + } + + if($_POST['saveType'] == 'delignore') + { + if(!empty($_POST['del_ignore']) && (array)$_POST['del_ignore'] === $_POST['del_ignore']) + { + foreach($_POST['del_ignore'] as $Values) + { + $Values = intval($Values); + if($Values > 0) + { + $ToDelete[] = $Values; + } + } + } + if(!empty($ToDelete)) + { + foreach($ToDelete as $ThisID) + { + if(!empty($_User['IgnoredUsers'][$ThisID])) + { + $IgnoreSystem_Deleted[] = $ThisID; + unset($_User['IgnoredUsers'][$ThisID]); + } + } + + if(!empty($IgnoreSystem_Deleted)) + { + $IgnoreSystem_Deleted_Count = count($IgnoreSystem_Deleted); + $IgnoreSystem_Deleted = implode(',', $IgnoreSystem_Deleted); + + $Query_DeleteIgnores = ''; + $Query_DeleteIgnores .= "DELETE FROM {{table}} WHERE "; + $Query_DeleteIgnores .= "`OwnerID` = {$_User['id']} AND `IgnoredID` IN ({$IgnoreSystem_Deleted}) LIMIT {$IgnoreSystem_Deleted_Count};"; + doquery($Query_DeleteIgnores, 'ignoresystem'); + + $InfoMsgs[] = sprintf($_Lang['Ignore_DeletedXUsers'], $IgnoreSystem_Deleted_Count); + } + else + { + $WarningMsgs[] = $_Lang['Ignore_NothingDeleted']; + } + } + else + { + $WarningMsgs[] = $_Lang['Ignore_NothingSelected']; + } + } + else if(!empty($_POST['ignore_username']) OR !empty($_GET['ignoreadd'])) + { + if(!empty($_GET['ignoreadd']) AND empty($_POST['ignore_username'])) + { + $IgnoreUser = intval($_GET['ignoreadd']); + $InputType = 'id'; + } + else + { + $IgnoreUser = (isset($_POST['ignore_username']) ? trim($_POST['ignore_username']) : null); + $InputType = 'un'; + } + if((strtolower($IgnoreUser) != strtolower($_User['username']) AND $InputType == 'un') OR ($IgnoreUser != $_User['id'] AND $InputType == 'id')) + { + if((preg_match(REGEXP_USERNAME_ABSOLUTE, $IgnoreUser) AND $InputType == 'un') OR ($IgnoreUser > 0 AND $InputType == 'id')) + { + $Query_CheckUser = ''; + $Query_CheckUser .= "SELECT `id`, `username`, `authlevel` FROM {{table}} "; + $Query_CheckUser .= "WHERE "; + if($InputType == 'un') + { + $Query_CheckUser .= "`username` = '{$IgnoreUser}'"; + } + else + { + $Query_CheckUser .= "`id` = {$IgnoreUser}"; + } + $Query_CheckUser .= " LIMIT 1; -- settings.php|IgnoreSystem|CheckUser"; + $Result_CheckUser = doquery($Query_CheckUser, 'users', true); + if($Result_CheckUser['id'] > 0) + { + if(!CheckAuth('user', AUTHCHECK_HIGHER, $Result_CheckUser)) + { + if(empty($_User['IgnoredUsers'][$Result_CheckUser['id']])) + { + $_User['IgnoredUsers'][$Result_CheckUser['id']] = $Result_CheckUser['username']; + doquery("INSERT INTO {{table}} (`OwnerID`, `IgnoredID`) VALUES ({$_User['id']}, {$Result_CheckUser['id']}); -- settings.php|IgnoreSystem|Insert", 'ignoresystem'); + $InfoMsgs[] = $_Lang['Ignore_UserAdded']; + } + else + { + $NoticeMsgs[] = $_Lang['Ignore_ThisUserAlreadyIgnored']; + } + } + else + { + $WarningMsgs[] = $_Lang['Ignore_CannotIgnoreGameTeam']; + } + } + else + { + $WarningMsgs[] = $_Lang['Ignore_UserNoExists']; + } + } + else + { + $WarningMsgs[] = $_Lang['Ignore_BadSignsOrShort']; + } + } + else + { + $WarningMsgs[] = $_Lang['Ignore_CannotIgnoreYourself']; + } + } + } + + if(!empty($ChangeSet)) + { + foreach($ChangeSet as $Key => $Value) + { + $_User[$Key] = $Value; + if($Key == 'deletion_endtime' AND $Value != '0') + { + eval('$_User[$Key] = '.(str_replace('UNIX_TIMESTAMP()', $Now, $Value)).';'); + } + if(isset($ChangeSetTypes[$Key]) && $ChangeSetTypes[$Key] == 's') + { + $Value = "'{$Value}'"; + } + $UpdateQuery[] = "`{$Key}` = {$Value}"; + } + + doquery("UPDATE {{table}} SET ".implode(', ', $UpdateQuery)." WHERE `id` = {$_User['id']};", 'users'); + if($ForceGoingOnVacationMsg === TRUE) + { + message((isset($ShowDeletionInfo) ? $_Lang['Vacation_GoingOnVacationsWithDeletion'] : $_Lang['Vacation_GoingOnVacations']), $_Lang['Vacations_Title'], 'settings.php', 3); + } + + $ChangeSetCounted = count($ChangeSet) - $ChangeSetCount; + if($ChangeSetCounted > 0) + { + $InfoMsgs[] = sprintf($_Lang['Info_SaveWellDone'], $ChangeSetCounted); + } + else + { + $NoticeMsgs[] = $_Lang['Info_NoChanges']; + } + } + else + { + if(!isset($DontShow_NoChanges) || $DontShow_NoChanges !== true) + { + $NoticeMsgs[] = $_Lang['Info_NoChanges']; + } + } + } + + if(!empty($WarningMsgs)) + { + foreach($WarningMsgs as $Message) + { + $_Lang['InfoBoxMsgs'][] = "
  • {$Message}
  • "; + } + } + if(!empty($NoticeMsgs)) + { + foreach($NoticeMsgs as $Message) + { + $_Lang['InfoBoxMsgs'][] = "
  • {$Message}
  • "; + } + } + if(!empty($InfoMsgs)) + { + foreach($InfoMsgs as $Message) + { + $_Lang['InfoBoxMsgs'][] = "
  • {$Message}
  • "; + } + } + + if(empty($_Lang['InfoBoxMsgs'])) + { + $_Lang['InfoBoxShow'] = 'display: none;'; + $_Lang['InfoBoxMsgs'] = "
  • "; + } + else + { + $_Lang['InfoBoxMsgs'] = implode('', $_Lang['InfoBoxMsgs']); + } + + if($_User['noipcheck'] == 1) + { + $_Lang['ipcheck_deactivate_check'] = 'checked'; + } + if($_User['planet_sort'] == 0) + { + $_Lang['planet_sort_mode_0'] = 'selected'; + } + if($_User['planet_sort'] == 1) + { + $_Lang['planet_sort_mode_1'] = 'selected'; + } + if($_User['planet_sort'] == 2) + { + $_Lang['planet_sort_mode_2'] = 'selected'; + } + if($_User['planet_sort_order'] == 0) + { + $_Lang['planet_sort_type_asc'] = 'selected'; + } + if($_User['planet_sort_order'] == 1) + { + $_Lang['planet_sort_type_desc'] = 'selected'; + } + if($_User['planet_sort_moons'] == 1) + { + $_Lang['planet_sort_moons_check'] = 'checked'; + } + $_Lang['skin_path'] = $_User['skinpath']; + if($_User['design'] == 1) + { + $_Lang['use_skin_check'] = 'checked'; + } + $_Lang['avatar_path'] = $_User['avatar']; + if($_User['settings_DevelopmentOld'] == 1) + { + $_Lang['development_old_check'] = 'checked'; + } + if($_User['settings_ExpandedBuildView'] == 1) + { + $_Lang['build_expandedview_use_check'] = 'checked'; + } + + if($_User['settings_useprettyinputbox'] == 1) + { + $_Lang['pretty_fleet_use_check'] = 'checked'; + } + + $_Lang['OldResSort_ArrayString'] = $_User['settings_resSortArray']; + $ExplodeOldResSort = explode(',', $_User['settings_resSortArray']); + foreach($ExplodeOldResSort as $ResKey => $ResData) + { + $ResKey += 1; + $_Lang['CreateResSortList'] .= "
  • {$ResKey}. {$_Lang['ResSort_Resources'][$ResData]}
  • "; + } + + $_Lang['msg_perpage_sel_'.$_User['settings_msgperpage']] = 'selected'; + if($_User['settings_spyexpand'] == 1) + { + $_Lang['msg_spyexpand_check'] = 'checked'; + } + if($_User['settings_UseMsgThreads'] == 1) + { + $_Lang['msg_usethreads_check'] = 'checked'; + } + $_Lang['spy_count'] = $_User['settings_spyprobescount']; + if($_User['settings_UseAJAXGalaxy'] == 1) + { + $_Lang['use_ajaxgalaxy_check'] = 'checked'; + } + if($_User['settings_Galaxy_ShowUserAvatars'] == 1) + { + $_Lang['show_useravatars_check'] = 'checked'; + } + if($_User['settings_esp'] == 1) + { + $_Lang['short_spy_check'] = 'checked'; + } + if($_User['settings_wri'] == 1) + { + $_Lang['short_write_check'] = 'checked'; + } + if($_User['settings_bud'] == 1) + { + $_Lang['short_buddy_check'] = 'checked'; + } + if($_User['settings_mis'] == 1) + { + $_Lang['short_rocket_check'] = 'checked'; + } + if($_User['is_ondeletion'] == 1) + { + $_Lang['delete_active_color'] = 'red'; + $_Lang['delete_activate_check'] = 'checked'; + $_Lang['DeleteMsg'] = sprintf($_Lang['DeleteMsg'], date('d.m.Y H:i:s', intval($_User['deletion_endtime']))); + $_Lang['DeleteAccount'] = $_Lang['DeleteAccountOff']; + $_Lang['DeleteConfirmShow'] = 'style="display: none;"'; + } + else + { + $_Lang['DontShowDeleteWarning'] = 'display: none;'; + $_Lang['DeleteClickToRemoveShow'] = 'style="display: none;"'; + $_Lang['DeleteMsg'] = ''; + } + if(strstr($_User['skinpath'], 'http://') === FALSE) + { + foreach($AvailableSkins as $Key => $Skin) + { + if(strstr($_User['skinpath'], $Skin)) + { + $_Lang['ServerSkins'] = str_replace('{select_no'.$Key.'}', 'selected', $_Lang['ServerSkins']); + } + else + { + $_Lang['ServerSkins'] = str_replace('{select_no'.$Key.'}', '', $_Lang['ServerSkins']); + } + } + } + $_Lang['QuickRes_PlanetList'] = str_replace('{sel_planet_'.$_User['settings_mainPlanetID'].'}', 'selected', $_Lang['QuickRes_PlanetList']); + $_Lang['QuickRes_PlanetList'] = preg_replace('#\{sel\_planet\_[0-9]{1,}\}#si', '', $_Lang['QuickRes_PlanetList']); + + if(!empty($_User['IgnoredUsers'])) + { + foreach($_User['IgnoredUsers'] as $IgnoredID => $IgnoredName) + { + $_Lang['ParseIgnoreList'][] = " "; + } + $_Lang['ParseIgnoreList'] = implode('
    ', $_Lang['ParseIgnoreList']); + if(count($_User['IgnoredUsers']) < 15) + { + $_Lang['IgnoreList_Hide2Del'] = 'style="display: none;"'; + } + } + else + { + $_Lang['ParseIgnoreList'] = "
    {$_Lang['IgnoreList_NoIgnored']}
    "; + $_Lang['IgnoreList_Hide1Del'] = 'style="display: none;"'; + $_Lang['IgnoreList_Hide2Del'] = 'style="display: none;"'; + } + + if($CheckMailChange['ID'] > 0) + { + $_Lang['EMChange1'] = 'style="display: none;"'; + $_Lang['EmailPrc_Active_Since'] = sprintf($_Lang['EmailPrc_Active_Since'], date('d.m.Y H:i:s', $CheckMailChange['Date'])); + $_Lang['OldEmail']= $_Lang['RealOldEmail']; + $_Lang['EmailPrc_NewEmail'] = $_User['email_2']; + } + else + { + $_Lang['EMChange2'] = 'style="display: none;"'; + } + + if(empty($_Lang['SetActiveMarker'])) + { + if(!empty($_GET['tab'])) + { + if(in_array($_GET['tab'], array(1,2,3,4,5,6))) + { + $_Lang['SetActiveMarker'] = str_pad($_GET['tab'], 2, '0', STR_PAD_LEFT); + } + } + } + + // Logons List + $Query_GetLogons = ''; + $Query_GetLogons .= "SELECT `Log`.*, `IPTable`.`Value` FROM {{table}} AS `Log` "; + $Query_GetLogons .= "LEFT JOIN `{{prefix}}used_ip_and_ua` AS `IPTable` ON `Log`.`IP_ID` = `IPTable`.`ID` "; + $Query_GetLogons .= "WHERE `Log`.`User_ID` = {$_User['id']} "; + $Query_GetLogons .= "ORDER BY `Log`.`LastTime` DESC LIMIT {$LogonLIMIT};"; + $GetLogons = doquery($Query_GetLogons, 'user_enterlog'); + if(mysql_num_rows($GetLogons) > 0) + { + while($LogonData = mysql_fetch_assoc($GetLogons)) + { + $LogonData['Times'] = array_reverse(explode(',', $LogonData['Times'])); + $LimitCounter = $LogonLIMIT; + foreach($LogonData['Times'] as $Temp) + { + if($LimitCounter <= 0) + { + break; + } + $Temp = explode('|', $Temp); + $ThisTime = SERVER_MAINOPEN_TSTAMP + $Temp[0]; + $LogonList[] = array('Time' => $ThisTime, 'IP' => $LogonData['Value'], 'State' => (isset($Temp[1]) && $Temp[1] == 'F' ? false : true)); + $LogonTimes[] = $ThisTime; + $LimitCounter -= 1; + } + } + + array_multisort($LogonList, SORT_DESC, $LogonTimes); + $LimitCounter = $LogonLIMIT; + foreach($LogonList as $LogonData) + { + if($LimitCounter <= 0) + { + break; + } + if($LogonData['IP'] == $_User['user_lastip']) + { + $LogonData['IPColor'] = 'lime'; + } + if($LogonData['State'] === false) + { + if($LogonData['IP'] != $_User['user_lastip']) + { + $LogonData['DateColor'] = 'red'; + $LogonData['IPColor'] = 'red'; + $LogonData['StateColor'] = 'red'; + } + else + { + $LogonData['StateColor'] = 'orange'; + } + } + + + $ThisRow = ''; + $ThisRow .= ''.prettyDate('d m Y, H:i:s', $LogonData['Time'], 1).''; + $ThisRow .= ''.pretty_time($Now - $LogonData['Time'], true, 'D').' '.$_Lang['Logons_ago'].''; + $ThisRow .= ''.$LogonData['IP'].''; + $ThisRow .= ''.($LogonData['State'] === true ? $_Lang['Logons_Success'] : $_Lang['Logons_Failed']).''; + $ThisRow .= ''; + $_Lang['ParseLogonsList'][] = $ThisRow; + $LimitCounter -= 1; + } + $_Lang['ParseLogonsList'] = implode('', $_Lang['ParseLogonsList']); + } + else + { + $_Lang['ParseLogonsList'] = ''.$_Lang['Logons_ListEmpty'].''; + } + + // FleetColors - Pickers + $TPL_FleetColors_Row = gettemplate('settings_fleetcolors_row'); + if(!empty($_User['settings_FleetColors'])) + { + if(isset($FleetColors_NeedChange) && $FleetColors_NeedChange === true) + { + $_User['settings_FleetColors'] = stripslashes($_User['settings_FleetColors']); + } + $FleetColors = json_decode($_User['settings_FleetColors'], true); + } + foreach($_Vars_FleetMissions['all'] as $MissionID) + { + $_Lang['Insert_FleetColors_Pickers'][] = parsetemplate($TPL_FleetColors_Row, array + ( + 'MissionName' => $_Lang['type_mission'][$MissionID], + 'MissionID' => $MissionID, + 'Value_OwnFly' => (isset($FleetColors['ownfly'][$MissionID]) ? $FleetColors['ownfly'][$MissionID] : null), + 'Value_OwnComeback' => (isset($FleetColors['owncb'][$MissionID]) ? $FleetColors['owncb'][$MissionID] : null), + 'Value_NonOwn' => (isset($FleetColors['nonown'][$MissionID]) ? $FleetColors['nonown'][$MissionID] : null) + )); + } + $_Lang['Insert_FleetColors_Pickers'] = implode('', $_Lang['Insert_FleetColors_Pickers']); + + $BodyTPL = gettemplate('settings_body'); + $Page = parsetemplate($BodyTPL, $_Lang); + display($Page, $_Lang['Page_Title'], false); + } + else if($Mode == 'nickchange') + { + // User is trying to change his nickname + if(!empty($_POST['newnick'])) + { + // Nickname Change in progress + if($_User['darkEnergy'] < 10) + { + message($_Lang['NewNick_donthave_DE'], $_Lang['NickChange_Title'], 'settings.php?mode=nickchange'); + } + $NewNick = trim($_POST['newnick']); + if($NewNick == $_User['username']) + { + message($_Lang['NewNick_is_like_old'], $_Lang['NickChange_Title'], 'settings.php?mode=nickchange'); + } + if(strlen($NewNick) < 4) + { + message($_Lang['NewNick_is_tooshort'], $_Lang['NickChange_Title'], 'settings.php?mode=nickchange'); + } + if(strstr($NewNick, 'http') OR strstr($NewNick, 'www.')) + { + message($_Lang['NewNick_nolinks'], $_Lang['NickChange_Title'], 'settings.php?mode=nickchange'); + } + if(!preg_match(REGEXP_USERNAME_ABSOLUTE, $NewNick)) + { + message($_Lang['NewNick_badSigns'], $_Lang['NickChange_Title'], 'settings.php?mode=nickchange'); + } + $SelectNewNick = doquery("SELECT `id` FROM {{table}} WHERE `username` = '{$NewNick}' LIMIT 1;", 'users', true); + if($SelectNewNick['id'] > 0) + { + message($_Lang['NewNick_already_taken'], $_Lang['NickChange_Title'], 'settings.php?mode=nickchange'); + } + + doquery("UPDATE {{table}} SET `darkEnergy` = `darkEnergy` - 10, `username` = '{$NewNick}', `old_username` = '{$_User['username']}', `old_username_expire` = UNIX_TIMESTAMP() + (7*24*60*60) WHERE `id` = {$_User['id']} LIMIT 1;", 'users'); + doquery("INSERT INTO {{table}} VALUES(NULL, {$_User['id']}, UNIX_TIMESTAMP(), '{$NewNick}', '{$_User['username']}');", 'nick_changelog'); + setcookie($_GameConfig['COOKIE_NAME'], '', $Now - 3600, '/', ''); + message($_Lang['NewNick_saved'], $_Lang['NickChange_Title'], 'login.php'); + } + else + { + $_Lang['skinpath'] = $_SkinPath; + $_Lang['DarkEnergy_Counter'] = $_User['darkEnergy']; + if($_User['darkEnergy'] >= 15) + { + $_Lang['DarkEnergy_Color'] = 'lime'; + } + else if($_User['darkEnergy'] > 0) + { + $_Lang['DarkEnergy_Color'] = 'orange'; + } + else + { + $_Lang['DarkEnergy_Color'] = 'red'; + } + + // Informations box + display(parsetemplate(gettemplate('settings_changenick'), $_Lang), $_Lang['NickChange_Title'], false); + } + } +} +else +{ + // User is on Vacation + if($Mode == 'exit') + { + // User is trying to remove Vacation mode + if(isset($_POST['exit_modus']) && $_POST['exit_modus'] == 'on' && canTakeVacationOff($Now)) + { + doquery("UPDATE {{table}} SET `is_onvacation` = '0', `vacation_starttime` = '0', `vacation_endtime` = '0', `vacation_leavetime` = IF(`vacation_type` = 2, 0, UNIX_TIMESTAMP()) WHERE `id` = {$_User['id']} LIMIT 1;", 'users'); + doquery("UPDATE {{table}} SET `last_update` = UNIX_TIMESTAMP() WHERE `id_owner` = {$_User['id']}", 'planets'); + $_Planet['last_update'] = $Now; + + $UserDev_Log[] = array('PlanetID' => '0', 'Date' => $Now, 'Place' => 26, 'Code' => '2', 'ElementID' => '0'); + + message($_Lang['Vacation_GoOut'], $_Lang['Vacations_Title'], 'overview.php', 3); + } + else + { + message($_Lang['Vacation_CantGoOut'], $_Lang['Vacations_Title'], 'settings.php', 3); + } + } + + $MinimalVacationTime = ($_User['pro_time'] > $_User['vacation_starttime'] ? MINURLOP_PRO : MINURLOP_FREE) + $_User['vacation_starttime']; + if($_User['vacation_type'] != 0) + { + $_Lang['Parse_Vacation_EndTime'] = $_Lang['Vacation_EndTimeNoBlock']; + } + else + { + if($MinimalVacationTime <= $Now) + { + $MinimalVacationTimeColor = 'lime'; + } + else + { + $MinimalVacationTimeColor = 'orange'; + } + $_Lang['Parse_Vacation_EndTime'] = sprintf($_Lang['Vacation_EndTime'], $MinimalVacationTimeColor, prettyDate('d m Y, H:i:s', $MinimalVacationTime, 1)); + } + + display(parsetemplate(gettemplate('settings_vacations'), $_Lang), $_Lang['Vacations_Title'], false); +} + +?> diff --git a/simulator.php b/simulator.php index f6600d49e..90e826784 100644 --- a/simulator.php +++ b/simulator.php @@ -1,788 +1,788 @@ - 109, - 2 => 110, - 3 => 111, - 4 => 120, - 5 => 121, - 6 => 122, - 7 => 125, - 8 => 126, - 9 => 199, - ); - $TechCount = count($TechEquivalents); - $MaxACSSlots = ACS_MAX_JOINED_FLEETS + 1; - $MaxStringLength = 30; - - if(!empty($_POST['spyreport'])) - { - $_POST['spyreport'] = json_decode(stripslashes($_POST['spyreport']), true); - $_POST['def_techs'][1] = (isset($_POST['spyreport']['tech']) ? $_POST['spyreport']['tech'] : null); - $_POST['def_ships'][1] = (isset($_POST['spyreport']['ships']) ? $_POST['spyreport']['ships'] : null); - $_POST['spyreport'] = null; - } - - if(isset($_POST['simulate']) && $_POST['simulate'] == 'yes') - { - $Calculate = true; - - if(!empty($_POST['atk_techs'])) - { - foreach($_POST['atk_techs'] as $User => $Vals) - { - $UserTemp = $User - 1; - foreach($TechEquivalents as $TechID => $TechKey) - { - if(!isset($Vals[$TechID]) || $Vals[$TechID] <= 0) - { - $Value = 0; - } - else - { - $Value = intval($Vals[$TechID]); - } - $AttackingTechs[$UserTemp][$TechKey] = $Value; - } - $AttackersData[$UserTemp] = array - ( - 'username' => $_Lang['Attacker_Txt'].$User, - 'techs' => Array2String($AttackingTechs[$UserTemp]), - 'pos' => '0:0:0' - ); - } - } - if(!empty($_POST['def_techs'])) - { - foreach($_POST['def_techs'] as $User => $Vals) - { - $UserTemp = $User - 1; - foreach($TechEquivalents as $TechID => $TechKey) - { - if(!isset($Vals[$TechID]) || $Vals[$TechID] <= 0) - { - $Value = 0; - } - else - { - $Value = intval($Vals[$TechID]); - } - $DefendingTechs[$UserTemp][$TechKey] = $Value; - } - $DefendersData[$UserTemp] = array - ( - 'username' => $_Lang['Defender_Txt'].$User, - 'techs' => Array2String($DefendingTechs[$UserTemp]), - 'pos' => '0:0:0' - ); - } - } - if(!empty($_POST['atk_ships'])) - { - foreach($_POST['atk_ships'] as $User => $Vals) - { - $UserTemp = $User - 1; - foreach($Vals as $ID => $Count) - { - $Count = str_replace(array('.', ','), '', $Count); - if($Count > 0) - { - if(strlen($Count) > $MaxStringLength) - { - $Count = substr($Count, 0, $MaxStringLength); - } - $AttackingFleets[$UserTemp][$ID] = floor($Count); - } - } - if(empty($AttackingFleets[$UserTemp])) - { - unset($AttackingFleets[$UserTemp]); - unset($AttackingTechs[$UserTemp]); - unset($AttackersData[$UserTemp]); - } - else - { - if(empty($AttackersData[$UserTemp])) - { - foreach($TechEquivalents as $TechID => $TechKey) - { - if(!isset($Vals[$TechID]) || $Vals[$TechID] <= 0) - { - $Value = 0; - } - else - { - $Value = intval($Vals[$TechID]); - } - $AttackingTechs[$UserTemp][$TechKey] = $Value; - } - $AttackersData[$UserTemp] = array - ( - 'username' => $_Lang['Attacker_Txt'].$User, - 'techs' => Array2String($AttackingTechs[$UserTemp]), - 'pos' => '0:0:0' - ); - } - } - } - } - else - { - $Calculate = false; - $BreakMSG = $_Lang['Break_noATKShips']; - } - if(!empty($_POST['def_ships'])) - { - foreach($_POST['def_ships'] as $User => $Vals) - { - $UserTemp = $User - 1; - foreach($Vals as $ID => $Count) - { - $Count = str_replace(array('.', ','), '', $Count); - if($Count > 0) - { - if(strlen($Count) > $MaxStringLength) - { - $Count = substr($Count, 0, $MaxStringLength); - } - $DefendingFleets[$UserTemp][$ID] = floor($Count); - } - } - if(empty($DefendingFleets[$UserTemp])) - { - unset($DefendingFleets[$UserTemp]); - unset($DefendingTechs[$UserTemp]); - unset($DefendersData[$UserTemp]); - } - else - { - if(empty($DefendersData[$UserTemp])) - { - foreach($TechEquivalents as $TechID => $TechKey) - { - if(!isset($Vals[$TechID]) || $Vals[$TechID] <= 0) - { - $Value = 0; - } - else - { - $Value = intval($Vals[$TechID]); - } - $DefendingTechs[$UserTemp][$TechKey] = $Value; - } - $DefendersData[$UserTemp] = array - ( - 'username' => $_Lang['Defender_Txt'].$User, - 'techs' => Array2String($DefendingTechs[$UserTemp]), - 'pos' => '0:0:0' - ); - } - } - } - } - else - { - $Calculate = false; - $BreakMSG = $_Lang['Break_noDEFShips']; - } - - if(isset($AttackersData)) - { - foreach($AttackersData as $UserTemp => $Data) - { - if(empty($AttackingFleets[$UserTemp])) - { - unset($AttackingFleets[$UserTemp]); - unset($AttackingTechs[$UserTemp]); - unset($AttackersData[$UserTemp]); - } - } - } - if(isset($DefendersData)) - { - foreach($DefendersData as $UserTemp => $Data) - { - if(empty($DefendingFleets[$UserTemp])) - { - unset($DefendingFleets[$UserTemp]); - unset($DefendingTechs[$UserTemp]); - unset($DefendersData[$UserTemp]); - } - } - } - - if(empty($AttackingFleets) OR (empty($DefendingFleets))) - { - if(empty($AttackingFleets)) - { - $BreakMSG = $_Lang['Break_noATKShips']; - } - else if(empty($DefendingFleets)) - { - $BreakMSG = $_Lang['Break_noDEFShips']; - } - $Calculate = false; - } - - if(MORALE_ENABLED) - { - if(!empty($AttackingFleets)) - { - foreach($AttackingFleets as $ThisUser => $ThisData) - { - $ThisMoraleLevel = intval($_POST['atk_morale'][($ThisUser + 1)]); - if($ThisMoraleLevel > 100) - { - $ThisMoraleLevel = 100; - } - else if($ThisMoraleLevel < -100) - { - $ThisMoraleLevel = -100; - } - $AttackersData[$ThisUser]['morale'] = $ThisMoraleLevel; - - // Bonuses - if($ThisMoraleLevel >= MORALE_BONUS_FLEETPOWERUP1) - { - $AttackingTechs[$ThisUser]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; - } - if($ThisMoraleLevel >= MORALE_BONUS_FLEETSHIELDUP1) - { - $AttackingTechs[$ThisUser]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; - } - if($ThisMoraleLevel >= MORALE_BONUS_FLEETSDADDITION) - { - $AttackingTechs[$ThisUser]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; - } - // Penalties - if($ThisMoraleLevel <= MORALE_PENALTY_FLEETPOWERDOWN1) - { - $AttackingTechs[$ThisUser]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; - } - if($ThisMoraleLevel <= MORALE_PENALTY_FLEETPOWERDOWN2) - { - $AttackingTechs[$ThisUser]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; - } - if($ThisMoraleLevel <= MORALE_PENALTY_FLEETSHIELDDOWN1) - { - $AttackingTechs[$ThisUser]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; - } - if($ThisMoraleLevel <= MORALE_PENALTY_FLEETSHIELDDOWN2) - { - $AttackingTechs[$ThisUser]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; - } - if($ThisMoraleLevel <= MORALE_PENALTY_FLEETSDDOWN) - { - $AttackingTechs[$ThisUser]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; - } - } - } - if(!empty($DefendingFleets)) - { - foreach($DefendingFleets as $ThisUser => $ThisData) - { - $ThisMoraleLevel = intval($_POST['def_morale'][($ThisUser + 1)]); - if($ThisMoraleLevel > 100) - { - $ThisMoraleLevel = 100; - } - else if($ThisMoraleLevel < -100) - { - $ThisMoraleLevel = -100; - } - $DefendersData[$ThisUser]['morale'] = $ThisMoraleLevel; - - // Bonuses - if($ThisMoraleLevel >= MORALE_BONUS_FLEETPOWERUP1) - { - $DefendingTechs[$ThisUser]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; - } - if($ThisMoraleLevel >= MORALE_BONUS_FLEETSHIELDUP1) - { - $DefendingTechs[$ThisUser]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; - } - if($ThisMoraleLevel >= MORALE_BONUS_FLEETSDADDITION) - { - $DefendingTechs[$ThisUser]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; - } - // Penalties - if($ThisMoraleLevel <= MORALE_PENALTY_FLEETPOWERDOWN1) - { - $DefendingTechs[$ThisUser]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; - } - if($ThisMoraleLevel <= MORALE_PENALTY_FLEETPOWERDOWN2) - { - $DefendingTechs[$ThisUser]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; - } - if($ThisMoraleLevel <= MORALE_PENALTY_FLEETSHIELDDOWN1) - { - $DefendingTechs[$ThisUser]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; - } - if($ThisMoraleLevel <= MORALE_PENALTY_FLEETSHIELDDOWN2) - { - $DefendingTechs[$ThisUser]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; - } - if($ThisMoraleLevel <= MORALE_PENALTY_FLEETSDDOWN) - { - $DefendingTechs[$ThisUser]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; - } - } - } - } - - if($Calculate === true) - { - $MoonCreationCount = false; - $MoonDestructionCount = false; - $Loop = 1; - - if(!isset($IncludeCombatEngine)) - { - include($_EnginePath.'includes/CombatEngineAres.php'); - include($_EnginePath.'includes/functions/CreateBattleReport.php'); - $IncludeCombatEngine = true; - } - - $SimData['atk_win'] = 0; - $SimData['def_win'] = 0; - $SimData['draw'] = 0; - $SimData['rounds'] = 0; - $SimData['max_rounds'] = 0; - $SimData['min_rounds'] = 99; - - $SimData['total_lost_atk'] = array('met' => 0, 'cry' => 0, 'deu' => 0); - $SimData['total_lost_def'] = array('met' => 0, 'cry' => 0, 'deu' => 0); - $SimData['ship_lost_atk'] = 0; - $SimData['ship_lost_def'] = 0; - $SimData['ship_lost_atk_min'] = 99999999999999999999.0; - $SimData['ship_lost_atk_max'] = 0; - $SimData['ship_lost_def_min'] = 99999999999999999999.0; - $SimData['ship_lost_def_max'] = 0; - - $TotalTime = 0; - for($i = 1; $i <= $Loop; $i += 1) - { - $MoonHasBeenCreated = false; - $MoonHasBeenDestroyed = false; - $chance = 0; - $RIPDestroyedByMoon = false; - $chance2 = 0; - $Temp['ship_lost_atk'] = 0; - $Temp['ship_lost_def'] = 0; - - $StartTime = microtime(true); - - // Now start Combat calculations - $Combat = Combat($AttackingFleets, $DefendingFleets, $AttackingTechs, $DefendingTechs, true); - - $EndTime = microtime(true); - $TimeNow = $EndTime - $StartTime; - $TotalTime += $TimeNow; - $totaltime = sprintf('%0.6f', $TimeNow); - - $RoundsData = $Combat['rounds']; - - $RoundCount = count($RoundsData) - 1; - if($RoundCount > $SimData['max_rounds']) - { - $SimData['max_rounds'] = $RoundCount; - } - if($RoundCount < $SimData['min_rounds']) - { - $SimData['min_rounds'] = $RoundCount; - } - $SimData['rounds'] += $RoundCount; - - $Result = $Combat['result']; - - $DebrisMetalAtk = 0; - $DebrisCrystalAtk = 0; - $RealDebrisMetalAtk = 0; - $RealDebrisCrystalAtk = 0; - $RealDebrisDeuteriumAtk = 0; - $DebrisMetalDef = 0; - $DebrisCrystalDef = 0; - $RealDebrisMetalDef = 0; - $RealDebrisCrystalDef = 0; - $RealDebrisDeuteriumDef = 0; - - $TotalLostMetal = 0; - $TotalLostCrystal = 0; - - $AtkShips = $Combat['AttackerShips']; - $DefShips = $Combat['DefenderShips']; - $AtkLost = $Combat['AtkLose']; - $DefLost = $Combat['DefLose']; - $DefSysLost = $Combat['DefSysLost']; - - if(!empty($AtkLost)) - { - foreach($AtkLost as $ID => $Count) - { - if($ID > 200 AND $ID < 300 AND $_GameConfig['Fleet_Cdr'] > 0) - { - $DebrisMetalAtk += floor($_Vars_Prices[$ID]['metal'] * $Count * ($_GameConfig['Fleet_Cdr'] / 100)); - $DebrisCrystalAtk += floor($_Vars_Prices[$ID]['crystal'] * $Count * ($_GameConfig['Fleet_Cdr'] / 100)); - $RealDebrisMetalAtk += floor($_Vars_Prices[$ID]['metal'] * $Count); - $RealDebrisCrystalAtk += floor($_Vars_Prices[$ID]['crystal'] * $Count); - $RealDebrisDeuteriumAtk += floor($_Vars_Prices[$ID]['deuterium'] * $Count); - $SimData['ship_lost_atk'] += $Count; - $Temp['ship_lost_atk'] += $Count; - } - } - $TotalLostMetal = $DebrisMetalAtk; - $TotalLostCrystal = $DebrisCrystalAtk; - } - - $SimData['total_lost_atk']['met'] += $RealDebrisMetalAtk; - $SimData['total_lost_atk']['cry'] += $RealDebrisCrystalAtk; - $SimData['total_lost_atk']['deu'] += $RealDebrisDeuteriumAtk; - - // Calculate looses - defender - if(!empty($DefLost)) - { - foreach($DefLost as $ID => $Count) - { - if($ID > 200 AND $ID < 300 AND $_GameConfig['Fleet_Cdr'] > 0) - { - $DebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count * ($_GameConfig['Fleet_Cdr'] / 100)); - $DebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count * ($_GameConfig['Fleet_Cdr'] / 100)); - } - else if($ID > 400 AND $_GameConfig['Defs_Cdr'] > 0) - { - $DebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count * ($_GameConfig['Defs_Cdr'] / 100)); - $DebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count * ($_GameConfig['Defs_Cdr'] / 100)); - } - $RealDebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count); - $RealDebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count); - $RealDebrisDeuteriumDef += floor($_Vars_Prices[$ID]['deuterium'] * $Count); - $SimData['ship_lost_def'] += $Count; - $Temp['ship_lost_def'] += $Count; - } - $TotalLostMetal += $DebrisMetalDef; - $TotalLostCrystal += $DebrisCrystalDef; - } - - $SimData['total_lost_def']['met'] += $RealDebrisMetalDef; - $SimData['total_lost_def']['cry'] += $RealDebrisCrystalDef; - $SimData['total_lost_def']['deu'] += $RealDebrisDeuteriumDef; - - switch($Result) - { - case COMBAT_ATK: - $SimData['atk_win'] += 1; - break; - case COMBAT_DEF: - $SimData['def_win'] += 1; - break; - case COMBAT_DRAW: - $SimData['draw'] +=1 ; - break; - } - - switch($Result) - { - case COMBAT_ATK: - $_Lang['Winner_Color'] = 'red'; - $_Lang['Winner_Name'] = $_Lang['WonBy_Attacker']; - break; - case COMBAT_DEF: - $_Lang['Winner_Color'] = 'lime'; - $_Lang['Winner_Name'] = $_Lang['WonBy_Defender']; - break; - case COMBAT_DRAW: - $_Lang['Winner_Color'] = 'orange'; - $_Lang['Winner_Name'] = $_Lang['WonBy_Draw']; - break; - } - - $FleetDebris = $TotalLostCrystal + $TotalLostMetal; - $MoonChance = floor($FleetDebris / COMBAT_MOONPERCENT_RESOURCES); - $TotalMoonChance = $MoonChance; - if($MoonChance > 20) - { - $MoonChance = 20; - } - - $ReportData = array(); - - $ReportData['init']['usr']['atk'] = $AttackersData; - $ReportData['init']['usr']['def'] = $DefendersData; - - $ReportData['init']['time'] = $totaltime; - $ReportData['init']['date'] = time(); - - $ReportData['init']['result'] = $Result; - $ReportData['init']['met'] = 0; - $ReportData['init']['cry'] = 0; - $ReportData['init']['deu'] = 0; - $ReportData['init']['deb_met'] = $TotalLostMetal; - $ReportData['init']['deb_cry'] = $TotalLostCrystal; - $ReportData['init']['moon_chance'] = $MoonChance; - $ReportData['init']['total_moon_chance'] = $TotalMoonChance; - $ReportData['init']['moon_created'] = $MoonHasBeenCreated; - $ReportData['init']['moon_destroyed'] = $MoonHasBeenDestroyed; - $ReportData['init']['moon_des_chance'] = ($chance >= 0 ? (($chance == 0) ? '0' : $chance) : false); - $ReportData['init']['fleet_destroyed'] = $RIPDestroyedByMoon; - $ReportData['init']['fleet_des_chance'] = ($chance2 >= 0 ? (($chance2 == 0) ? '0' : $chance2) : false); - $ReportData['init']['planet_name'] = 'Planeta'; - $ReportData['init']['onMoon'] = false; - $ReportData['init']['atk_lost'] = $RealDebrisMetalAtk + $RealDebrisCrystalAtk + $RealDebrisDeuteriumAtk; - $ReportData['init']['def_lost'] = $RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef; - - foreach($RoundsData as $RoundKey => $RoundData) - { - foreach($RoundData as $MainKey => $RoundData2) - { - if(!empty($RoundData2['ships'])) - { - foreach($RoundData2['ships'] as $UserKey => $UserData) - { - $RoundsData[$RoundKey][$MainKey]['ships'][$UserKey] = Array2String($UserData); - } - } - } - } - $ReportData['rounds'] = $RoundsData; - - $ReportID = CreateBattleReport($ReportData, array('atk' => $_User['id'], 'def' => 0), 0, true); - - $parse = $_Lang; - $parse['id'] = $ReportID; - - $AllReports[] = $ReportID; - if($i == $Loop) - { - $parse['time'] = sprintf('%0.6f', $TotalTime); - } - else - { - $parse['time'] = $totaltime; - } - - if($Temp['ship_lost_atk'] < $SimData['ship_lost_atk_min']) - { - $SimData['ship_lost_atk_min'] = $Temp['ship_lost_atk']; - } - if($Temp['ship_lost_atk'] > $SimData['ship_lost_atk_max']) - { - $SimData['ship_lost_atk_max'] = $Temp['ship_lost_atk']; - } - - if($Temp['ship_lost_def'] < $SimData['ship_lost_def_min']) - { - $SimData['ship_lost_def_min'] = $Temp['ship_lost_def']; - } - if($Temp['ship_lost_def'] > $SimData['ship_lost_def_max']) - { - $SimData['ship_lost_def_max'] = $Temp['ship_lost_def']; - } - } - - $SimData['ship_lost_def_max'] = prettyNumber($SimData['ship_lost_def_max']); - $SimData['ship_lost_def_min'] = prettyNumber($SimData['ship_lost_def_min']); - $SimData['ship_lost_atk_max'] = prettyNumber($SimData['ship_lost_atk_max']); - $SimData['ship_lost_atk_min'] = prettyNumber($SimData['ship_lost_atk_min']); - $SimData['total_lost_atk_met'] = prettyNumber(round($SimData['total_lost_atk']['met'] / $Loop)); - $SimData['total_lost_atk_cry'] = prettyNumber(round($SimData['total_lost_atk']['cry'] / $Loop)); - $SimData['total_lost_atk_deu'] = prettyNumber(round($SimData['total_lost_atk']['deu'] / $Loop)); - $SimData['total_lost_def_met'] = prettyNumber(round($SimData['total_lost_def']['met'] / $Loop)); - $SimData['total_lost_def_cry'] = prettyNumber(round($SimData['total_lost_def']['cry'] / $Loop)); - $SimData['total_lost_def_deu'] = prettyNumber(round($SimData['total_lost_def']['deu'] / $Loop)); - $SimData['ship_lost_atk'] = prettyNumber(round($SimData['ship_lost_atk'] / $Loop)); - $SimData['ship_lost_def'] = prettyNumber(round($SimData['ship_lost_def'] / $Loop)); - $SimData['rounds'] = round($SimData['rounds']/$Loop); - if($MoonCreationCount !== FALSE) - { - $SimData['ShowMoonCreationCount'] = '
    '.$_Lang['Moon_created_x_times'].': '.prettyNumber($MoonCreationCount); - } - if($MoonDestructionCount !== FALSE) - { - $SimData['ShowMoonDestructionCount'] = '
    '.$_Lang['Moon_destroyed_x_times'].': '.prettyNumber($MoonDestructionCount); - } - - $SimData['sim_loop'] = $Loop; - $SimData['AddInfo'] = ((!empty($SimData['AddInfo'])) ? implode('
    ', $SimData['AddInfo']).'

    ' : ''); - $parse = array_merge($parse, $SimData); - - $_Lang['SimResult'] .= parsetemplate(gettemplate('simulator_result'), $parse); - - // Trigger Tasks Check - Tasks_TriggerTask($_User, 'USE_SIMULATOR'); - } - else - { - $parse = $_Lang; - $parse['msg'] = $BreakMSG; - $_Lang['SimResult'] .= parsetemplate(gettemplate('simulator_result_warn'), $parse); - } - - } - - $TPL_Slot = gettemplate('simulator_slot'); - $TPL_SingleRow = gettemplate('simulator_single_row'); - $TPL_NoBoth = gettemplate('simulator_row_noboth'); - $TPL_Row = gettemplate('simulator_row'); - $TPL_NoLeft = gettemplate('simulator_row_noleft'); - - $Offsets; - - for($i = 1; $i <= $MaxACSSlots; $i += 1) - { - $ThisSlot = array(); - $ThisSlot['SlotID'] = $i; - $ThisSlot['txt'] = ''; - - $InsertTabIndex1 = 1; - $InsertTabIndex2 = 1; - $parse = $_Lang; - $parse['i'] = $i; - if($i > 1) - { - $ThisSlot['SlotHidden'] = 'hide'; - } - - if(MORALE_ENABLED) - { - $parse['RowText'] = $_Lang['Morale']; - $ThisSlot['txt'] .= parsetemplate($TPL_SingleRow, $parse); - $parse['RowText'] = $_Lang['Morale_Level']; - $parse['RowInput'] = "%"; - $parse['RowText2'] = $_Lang['Morale_Level']; - $parse['RowInput2'] = "%"; - - $ThisSlot['txt'] .= parsetemplate($TPL_Row, $parse); - $InsertTabIndex1 += 1; - $InsertTabIndex2 += 1; - } - - $parse['RowText'] = $_Lang['Technology']; - $ThisSlot['txt'] .= parsetemplate($TPL_SingleRow, $parse); - $parse['RowText'] = ''.$_Lang['FillMyTechs'].' / '.$_Lang['Fill_Clean'].''; - $parse['RowText2'] = ''.$_Lang['FillMyTechs'].' / '.$_Lang['Fill_Clean'].''; - $ThisSlot['txt'] .= parsetemplate($TPL_NoBoth, $parse); - - for($techs = 1; $techs <= $TechCount; $techs += 1) - { - $ThisRow_InsertValue_Atk = isset($_POST['atk_techs'][$i][$techs]) ? $_POST['atk_techs'][$i][$techs] : null; - $ThisRow_InsertValue_Def = isset($_POST['def_techs'][$i][$techs]) ? $_POST['def_techs'][$i][$techs] : null; - - $parse['RowText'] = $_Lang['Techs'][$techs]; - $parse['RowInput'] = ""; - $parse['RowText2'] = $_Lang['Techs'][$techs]; - $parse['RowInput2'] = ""; - - $ThisSlot['txt'] .= parsetemplate($TPL_Row, $parse); - $InsertTabIndex1 += 1; - $InsertTabIndex2 += 1; - } - - $parse['RowText'] = $_Lang['Fleets']; - $ThisSlot['txt'] .= parsetemplate($TPL_SingleRow, $parse); - $parse['RowText'] = ''.$_Lang['FillMyFleets'].' / '.$_Lang['Fill_Clean'].''; - $parse['RowText2'] = ''.$_Lang['FillMyFleets'].' / '.$_Lang['Fill_Clean'].''; - $ThisSlot['txt'] .= parsetemplate($TPL_NoBoth, $parse); - - foreach($_Vars_ElementCategories['fleet'] as $Ships) - { - $ThisRow_InsertValue_Def = isset($_POST['def_ships'][$i][$Ships]) ? $_POST['def_ships'][$i][$Ships] : null; - - if(!empty($_Vars_Prices[$Ships]['engine'])) - { - $ThisRow_InsertValue_Atk = isset($_POST['atk_ships'][$i][$Ships]) ? $_POST['atk_ships'][$i][$Ships] : null; - - $parse['RowText'] = $_Lang['tech'][$Ships]; - $parse['RowInput'] = " ({$_Lang['Button_Min']} / {$_Lang['Button_Max']})"; - $parse['RowText2'] = $_Lang['tech'][$Ships]; - $parse['RowInput2'] = " ({$_Lang['Button_Min']} / {$_Lang['Button_Max']})"; - - $ThisSlot['txt'] .= parsetemplate($TPL_Row, $parse); - $InsertTabIndex1 += 1; - $InsertTabIndex2 += 1; - } - else - { - $parse['RowText'] = '-'; - $parse['RowText2'] = $_Lang['tech'][$Ships]; - $parse['RowInput2'] = " ({$_Lang['Button_Min']} / {$_Lang['Button_Max']})"; - - $ThisSlot['txt'] .= parsetemplate($TPL_NoLeft, $parse); - $InsertTabIndex2 += 1; - } - } - - if($i == 1) - { - $parse['RowText'] = $_Lang['Defense']; - $ThisSlot['txt'] .= parsetemplate($TPL_SingleRow, $parse); - - foreach($_Vars_ElementCategories['defense'] as $Ships) - { - if(in_array($Ships, $_Vars_ElementCategories['rockets'])) - { - continue; - } - - $ThisRow_InsertValue_Def = isset($_POST['def_ships'][$i][$Ships]) ? $_POST['def_ships'][$i][$Ships] : null; - - $parse['RowText'] = '-'; - $parse['RowText2'] = $_Lang['tech'][$Ships]; - $parse['RowInput2'] = " ({$_Lang['Button_Min']} / {$_Lang['Button_Max']})"; - - $ThisSlot['txt'] .= parsetemplate($TPL_NoLeft, $parse); - $InsertTabIndex2 += 1; - } - } - $Offsets[$i] = $InsertTabIndex1 - 1; - - $_Lang['rows'] .= parsetemplate($TPL_Slot, $ThisSlot); - } - - $_Lang['rows'] = preg_replace('#\{REP1_O([0-9]{1,})_([0-9]{1,})\}#Ssie', "($1 * 1000) + $2", $_Lang['rows']); - $_Lang['rows'] = preg_replace('#\{REP2_O([0-9]{1,})_([0-9]{1,})\}#Ssie', '($1 * 1000) + $Offsets[\'$1\'] + $2', $_Lang['rows']); - - $_Lang['fill_with_mytechs'] = "var MyTechs = new Array();\nMyTechs[1] = ".(string)($_User['tech_weapons'] + 0).";\nMyTechs[3] = ".(string)($_User['tech_shielding'] + 0).";\nMyTechs[2] = ".(string)($_User['tech_armour'] + 0).";\nMyTechs[4] = ".(string)($_User['tech_laser'] + 0).";\nMyTechs[5] = ".(string)($_User['tech_ion'] + 0).";\nMyTechs[6] = ".(string)($_User['tech_plasma'] + 0).";\nMyTechs[7] = ".(string)($_User['tech_antimatter'] + 0).";\nMyTechs[8] = ".(string)($_User['tech_disintegration'] + 0).";\nMyTechs[9] = ".(string)($_User['tech_graviton'] + 0).";\n"; - $_Lang['fill_with_myfleets'] = "var MyFleets = new Array();\n"; - - $UsingPrettyInputBox = ($_User['settings_useprettyinputbox'] == 1 ? true : false); - - foreach($_Vars_ElementCategories['fleet'] as $ID) - { - if($_Planet[$_Vars_GameElements[$ID]] > 0) - { - $_Lang['fill_with_myfleets'] .= "MyFleets[{$ID}] = '".($UsingPrettyInputBox === true ? prettyNumber($_Planet[$_Vars_GameElements[$ID]]) : $_Planet[$_Vars_GameElements[$ID]])."';\n"; - } - } - foreach($_Vars_ElementCategories['defense'] as $ID) - { - if(in_array($ID, $_Vars_ElementCategories['rockets'])) - { - continue; - } - - if($_Planet[$_Vars_GameElements[$ID]] > 0) - { - $_Lang['fill_with_myfleets'] .= "MyFleets[{$ID}] = '".($UsingPrettyInputBox === true ? prettyNumber($_Planet[$_Vars_GameElements[$ID]]) : $_Planet[$_Vars_GameElements[$ID]])."';\n"; - } - } - $_Lang['fill_with_myfleets'] .= "\n"; - $_Lang['AllowPrettyInputBox'] = ($_User['settings_useprettyinputbox'] == 1 ? 'true' : 'false'); - - //Display page - $page = parsetemplate(gettemplate('simulator'), $_Lang); - - display($page,$_Lang['Title'], false); - -?> \ No newline at end of file + 109, + 2 => 110, + 3 => 111, + 4 => 120, + 5 => 121, + 6 => 122, + 7 => 125, + 8 => 126, + 9 => 199, +); +$TechCount = count($TechEquivalents); +$MaxACSSlots = ACS_MAX_JOINED_FLEETS + 1; +$MaxStringLength = 30; + +if(!empty($_POST['spyreport'])) +{ + $_POST['spyreport'] = json_decode(stripslashes($_POST['spyreport']), true); + $_POST['def_techs'][1] = (isset($_POST['spyreport']['tech']) ? $_POST['spyreport']['tech'] : null); + $_POST['def_ships'][1] = (isset($_POST['spyreport']['ships']) ? $_POST['spyreport']['ships'] : null); + $_POST['spyreport'] = null; +} + +if(isset($_POST['simulate']) && $_POST['simulate'] == 'yes') +{ + $Calculate = true; + + if(!empty($_POST['atk_techs'])) + { + foreach($_POST['atk_techs'] as $User => $Vals) + { + $UserTemp = $User - 1; + foreach($TechEquivalents as $TechID => $TechKey) + { + if(!isset($Vals[$TechID]) || $Vals[$TechID] <= 0) + { + $Value = 0; + } + else + { + $Value = intval($Vals[$TechID]); + } + $AttackingTechs[$UserTemp][$TechKey] = $Value; + } + $AttackersData[$UserTemp] = array + ( + 'username' => $_Lang['Attacker_Txt'].$User, + 'techs' => Array2String($AttackingTechs[$UserTemp]), + 'pos' => '0:0:0' + ); + } + } + if(!empty($_POST['def_techs'])) + { + foreach($_POST['def_techs'] as $User => $Vals) + { + $UserTemp = $User - 1; + foreach($TechEquivalents as $TechID => $TechKey) + { + if(!isset($Vals[$TechID]) || $Vals[$TechID] <= 0) + { + $Value = 0; + } + else + { + $Value = intval($Vals[$TechID]); + } + $DefendingTechs[$UserTemp][$TechKey] = $Value; + } + $DefendersData[$UserTemp] = array + ( + 'username' => $_Lang['Defender_Txt'].$User, + 'techs' => Array2String($DefendingTechs[$UserTemp]), + 'pos' => '0:0:0' + ); + } + } + if(!empty($_POST['atk_ships'])) + { + foreach($_POST['atk_ships'] as $User => $Vals) + { + $UserTemp = $User - 1; + foreach($Vals as $ID => $Count) + { + $Count = str_replace(array('.', ','), '', $Count); + if($Count > 0) + { + if(strlen($Count) > $MaxStringLength) + { + $Count = substr($Count, 0, $MaxStringLength); + } + $AttackingFleets[$UserTemp][$ID] = floor($Count); + } + } + if(empty($AttackingFleets[$UserTemp])) + { + unset($AttackingFleets[$UserTemp]); + unset($AttackingTechs[$UserTemp]); + unset($AttackersData[$UserTemp]); + } + else + { + if(empty($AttackersData[$UserTemp])) + { + foreach($TechEquivalents as $TechID => $TechKey) + { + if(!isset($Vals[$TechID]) || $Vals[$TechID] <= 0) + { + $Value = 0; + } + else + { + $Value = intval($Vals[$TechID]); + } + $AttackingTechs[$UserTemp][$TechKey] = $Value; + } + $AttackersData[$UserTemp] = array + ( + 'username' => $_Lang['Attacker_Txt'].$User, + 'techs' => Array2String($AttackingTechs[$UserTemp]), + 'pos' => '0:0:0' + ); + } + } + } + } + else + { + $Calculate = false; + $BreakMSG = $_Lang['Break_noATKShips']; + } + if(!empty($_POST['def_ships'])) + { + foreach($_POST['def_ships'] as $User => $Vals) + { + $UserTemp = $User - 1; + foreach($Vals as $ID => $Count) + { + $Count = str_replace(array('.', ','), '', $Count); + if($Count > 0) + { + if(strlen($Count) > $MaxStringLength) + { + $Count = substr($Count, 0, $MaxStringLength); + } + $DefendingFleets[$UserTemp][$ID] = floor($Count); + } + } + if(empty($DefendingFleets[$UserTemp])) + { + unset($DefendingFleets[$UserTemp]); + unset($DefendingTechs[$UserTemp]); + unset($DefendersData[$UserTemp]); + } + else + { + if(empty($DefendersData[$UserTemp])) + { + foreach($TechEquivalents as $TechID => $TechKey) + { + if(!isset($Vals[$TechID]) || $Vals[$TechID] <= 0) + { + $Value = 0; + } + else + { + $Value = intval($Vals[$TechID]); + } + $DefendingTechs[$UserTemp][$TechKey] = $Value; + } + $DefendersData[$UserTemp] = array + ( + 'username' => $_Lang['Defender_Txt'].$User, + 'techs' => Array2String($DefendingTechs[$UserTemp]), + 'pos' => '0:0:0' + ); + } + } + } + } + else + { + $Calculate = false; + $BreakMSG = $_Lang['Break_noDEFShips']; + } + + if(isset($AttackersData)) + { + foreach($AttackersData as $UserTemp => $Data) + { + if(empty($AttackingFleets[$UserTemp])) + { + unset($AttackingFleets[$UserTemp]); + unset($AttackingTechs[$UserTemp]); + unset($AttackersData[$UserTemp]); + } + } + } + if(isset($DefendersData)) + { + foreach($DefendersData as $UserTemp => $Data) + { + if(empty($DefendingFleets[$UserTemp])) + { + unset($DefendingFleets[$UserTemp]); + unset($DefendingTechs[$UserTemp]); + unset($DefendersData[$UserTemp]); + } + } + } + + if(empty($AttackingFleets) OR (empty($DefendingFleets))) + { + if(empty($AttackingFleets)) + { + $BreakMSG = $_Lang['Break_noATKShips']; + } + else if(empty($DefendingFleets)) + { + $BreakMSG = $_Lang['Break_noDEFShips']; + } + $Calculate = false; + } + + if(MORALE_ENABLED) + { + if(!empty($AttackingFleets)) + { + foreach($AttackingFleets as $ThisUser => $ThisData) + { + $ThisMoraleLevel = intval($_POST['atk_morale'][($ThisUser + 1)]); + if($ThisMoraleLevel > 100) + { + $ThisMoraleLevel = 100; + } + else if($ThisMoraleLevel < -100) + { + $ThisMoraleLevel = -100; + } + $AttackersData[$ThisUser]['morale'] = $ThisMoraleLevel; + + // Bonuses + if($ThisMoraleLevel >= MORALE_BONUS_FLEETPOWERUP1) + { + $AttackingTechs[$ThisUser]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; + } + if($ThisMoraleLevel >= MORALE_BONUS_FLEETSHIELDUP1) + { + $AttackingTechs[$ThisUser]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; + } + if($ThisMoraleLevel >= MORALE_BONUS_FLEETSDADDITION) + { + $AttackingTechs[$ThisUser]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; + } + // Penalties + if($ThisMoraleLevel <= MORALE_PENALTY_FLEETPOWERDOWN1) + { + $AttackingTechs[$ThisUser]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; + } + if($ThisMoraleLevel <= MORALE_PENALTY_FLEETPOWERDOWN2) + { + $AttackingTechs[$ThisUser]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; + } + if($ThisMoraleLevel <= MORALE_PENALTY_FLEETSHIELDDOWN1) + { + $AttackingTechs[$ThisUser]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; + } + if($ThisMoraleLevel <= MORALE_PENALTY_FLEETSHIELDDOWN2) + { + $AttackingTechs[$ThisUser]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; + } + if($ThisMoraleLevel <= MORALE_PENALTY_FLEETSDDOWN) + { + $AttackingTechs[$ThisUser]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; + } + } + } + if(!empty($DefendingFleets)) + { + foreach($DefendingFleets as $ThisUser => $ThisData) + { + $ThisMoraleLevel = intval($_POST['def_morale'][($ThisUser + 1)]); + if($ThisMoraleLevel > 100) + { + $ThisMoraleLevel = 100; + } + else if($ThisMoraleLevel < -100) + { + $ThisMoraleLevel = -100; + } + $DefendersData[$ThisUser]['morale'] = $ThisMoraleLevel; + + // Bonuses + if($ThisMoraleLevel >= MORALE_BONUS_FLEETPOWERUP1) + { + $DefendingTechs[$ThisUser]['TotalForceFactor'] = MORALE_BONUS_FLEETPOWERUP1_FACTOR; + } + if($ThisMoraleLevel >= MORALE_BONUS_FLEETSHIELDUP1) + { + $DefendingTechs[$ThisUser]['TotalShieldFactor'] = MORALE_BONUS_FLEETSHIELDUP1_FACTOR; + } + if($ThisMoraleLevel >= MORALE_BONUS_FLEETSDADDITION) + { + $DefendingTechs[$ThisUser]['SDAdd'] = MORALE_BONUS_FLEETSDADDITION_VALUE; + } + // Penalties + if($ThisMoraleLevel <= MORALE_PENALTY_FLEETPOWERDOWN1) + { + $DefendingTechs[$ThisUser]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN1_FACTOR; + } + if($ThisMoraleLevel <= MORALE_PENALTY_FLEETPOWERDOWN2) + { + $DefendingTechs[$ThisUser]['TotalForceFactor'] = MORALE_PENALTY_FLEETPOWERDOWN2_FACTOR; + } + if($ThisMoraleLevel <= MORALE_PENALTY_FLEETSHIELDDOWN1) + { + $DefendingTechs[$ThisUser]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN1_FACTOR; + } + if($ThisMoraleLevel <= MORALE_PENALTY_FLEETSHIELDDOWN2) + { + $DefendingTechs[$ThisUser]['TotalShieldFactor'] = MORALE_PENALTY_FLEETSHIELDDOWN2_FACTOR; + } + if($ThisMoraleLevel <= MORALE_PENALTY_FLEETSDDOWN) + { + $DefendingTechs[$ThisUser]['SDFactor'] = MORALE_PENALTY_FLEETSDDOWN_FACTOR; + } + } + } + } + + if($Calculate === true) + { + $MoonCreationCount = false; + $MoonDestructionCount = false; + $Loop = 1; + + if(!isset($IncludeCombatEngine)) + { + include($_EnginePath.'includes/CombatEngineAres.php'); + include($_EnginePath.'includes/functions/CreateBattleReport.php'); + $IncludeCombatEngine = true; + } + + $SimData['atk_win'] = 0; + $SimData['def_win'] = 0; + $SimData['draw'] = 0; + $SimData['rounds'] = 0; + $SimData['max_rounds'] = 0; + $SimData['min_rounds'] = 99; + + $SimData['total_lost_atk'] = array('met' => 0, 'cry' => 0, 'deu' => 0); + $SimData['total_lost_def'] = array('met' => 0, 'cry' => 0, 'deu' => 0); + $SimData['ship_lost_atk'] = 0; + $SimData['ship_lost_def'] = 0; + $SimData['ship_lost_atk_min'] = 99999999999999999999.0; + $SimData['ship_lost_atk_max'] = 0; + $SimData['ship_lost_def_min'] = 99999999999999999999.0; + $SimData['ship_lost_def_max'] = 0; + + $TotalTime = 0; + for($i = 1; $i <= $Loop; $i += 1) + { + $MoonHasBeenCreated = false; + $MoonHasBeenDestroyed = false; + $chance = 0; + $RIPDestroyedByMoon = false; + $chance2 = 0; + $Temp['ship_lost_atk'] = 0; + $Temp['ship_lost_def'] = 0; + + $StartTime = microtime(true); + + // Now start Combat calculations + $Combat = Combat($AttackingFleets, $DefendingFleets, $AttackingTechs, $DefendingTechs, true); + + $EndTime = microtime(true); + $TimeNow = $EndTime - $StartTime; + $TotalTime += $TimeNow; + $totaltime = sprintf('%0.6f', $TimeNow); + + $RoundsData = $Combat['rounds']; + + $RoundCount = count($RoundsData) - 1; + if($RoundCount > $SimData['max_rounds']) + { + $SimData['max_rounds'] = $RoundCount; + } + if($RoundCount < $SimData['min_rounds']) + { + $SimData['min_rounds'] = $RoundCount; + } + $SimData['rounds'] += $RoundCount; + + $Result = $Combat['result']; + + $DebrisMetalAtk = 0; + $DebrisCrystalAtk = 0; + $RealDebrisMetalAtk = 0; + $RealDebrisCrystalAtk = 0; + $RealDebrisDeuteriumAtk = 0; + $DebrisMetalDef = 0; + $DebrisCrystalDef = 0; + $RealDebrisMetalDef = 0; + $RealDebrisCrystalDef = 0; + $RealDebrisDeuteriumDef = 0; + + $TotalLostMetal = 0; + $TotalLostCrystal = 0; + + $AtkShips = $Combat['AttackerShips']; + $DefShips = $Combat['DefenderShips']; + $AtkLost = $Combat['AtkLose']; + $DefLost = $Combat['DefLose']; + $DefSysLost = $Combat['DefSysLost']; + + if(!empty($AtkLost)) + { + foreach($AtkLost as $ID => $Count) + { + if($ID > 200 AND $ID < 300 AND $_GameConfig['Fleet_Cdr'] > 0) + { + $DebrisMetalAtk += floor($_Vars_Prices[$ID]['metal'] * $Count * ($_GameConfig['Fleet_Cdr'] / 100)); + $DebrisCrystalAtk += floor($_Vars_Prices[$ID]['crystal'] * $Count * ($_GameConfig['Fleet_Cdr'] / 100)); + $RealDebrisMetalAtk += floor($_Vars_Prices[$ID]['metal'] * $Count); + $RealDebrisCrystalAtk += floor($_Vars_Prices[$ID]['crystal'] * $Count); + $RealDebrisDeuteriumAtk += floor($_Vars_Prices[$ID]['deuterium'] * $Count); + $SimData['ship_lost_atk'] += $Count; + $Temp['ship_lost_atk'] += $Count; + } + } + $TotalLostMetal = $DebrisMetalAtk; + $TotalLostCrystal = $DebrisCrystalAtk; + } + + $SimData['total_lost_atk']['met'] += $RealDebrisMetalAtk; + $SimData['total_lost_atk']['cry'] += $RealDebrisCrystalAtk; + $SimData['total_lost_atk']['deu'] += $RealDebrisDeuteriumAtk; + + // Calculate looses - defender + if(!empty($DefLost)) + { + foreach($DefLost as $ID => $Count) + { + if($ID > 200 AND $ID < 300 AND $_GameConfig['Fleet_Cdr'] > 0) + { + $DebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count * ($_GameConfig['Fleet_Cdr'] / 100)); + $DebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count * ($_GameConfig['Fleet_Cdr'] / 100)); + } + else if($ID > 400 AND $_GameConfig['Defs_Cdr'] > 0) + { + $DebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count * ($_GameConfig['Defs_Cdr'] / 100)); + $DebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count * ($_GameConfig['Defs_Cdr'] / 100)); + } + $RealDebrisMetalDef += floor($_Vars_Prices[$ID]['metal'] * $Count); + $RealDebrisCrystalDef += floor($_Vars_Prices[$ID]['crystal'] * $Count); + $RealDebrisDeuteriumDef += floor($_Vars_Prices[$ID]['deuterium'] * $Count); + $SimData['ship_lost_def'] += $Count; + $Temp['ship_lost_def'] += $Count; + } + $TotalLostMetal += $DebrisMetalDef; + $TotalLostCrystal += $DebrisCrystalDef; + } + + $SimData['total_lost_def']['met'] += $RealDebrisMetalDef; + $SimData['total_lost_def']['cry'] += $RealDebrisCrystalDef; + $SimData['total_lost_def']['deu'] += $RealDebrisDeuteriumDef; + + switch($Result) + { + case COMBAT_ATK: + $SimData['atk_win'] += 1; + break; + case COMBAT_DEF: + $SimData['def_win'] += 1; + break; + case COMBAT_DRAW: + $SimData['draw'] +=1 ; + break; + } + + switch($Result) + { + case COMBAT_ATK: + $_Lang['Winner_Color'] = 'red'; + $_Lang['Winner_Name'] = $_Lang['WonBy_Attacker']; + break; + case COMBAT_DEF: + $_Lang['Winner_Color'] = 'lime'; + $_Lang['Winner_Name'] = $_Lang['WonBy_Defender']; + break; + case COMBAT_DRAW: + $_Lang['Winner_Color'] = 'orange'; + $_Lang['Winner_Name'] = $_Lang['WonBy_Draw']; + break; + } + + $FleetDebris = $TotalLostCrystal + $TotalLostMetal; + $MoonChance = floor($FleetDebris / COMBAT_MOONPERCENT_RESOURCES); + $TotalMoonChance = $MoonChance; + if($MoonChance > 20) + { + $MoonChance = 20; + } + + $ReportData = array(); + + $ReportData['init']['usr']['atk'] = $AttackersData; + $ReportData['init']['usr']['def'] = $DefendersData; + + $ReportData['init']['time'] = $totaltime; + $ReportData['init']['date'] = time(); + + $ReportData['init']['result'] = $Result; + $ReportData['init']['met'] = 0; + $ReportData['init']['cry'] = 0; + $ReportData['init']['deu'] = 0; + $ReportData['init']['deb_met'] = $TotalLostMetal; + $ReportData['init']['deb_cry'] = $TotalLostCrystal; + $ReportData['init']['moon_chance'] = $MoonChance; + $ReportData['init']['total_moon_chance'] = $TotalMoonChance; + $ReportData['init']['moon_created'] = $MoonHasBeenCreated; + $ReportData['init']['moon_destroyed'] = $MoonHasBeenDestroyed; + $ReportData['init']['moon_des_chance'] = ($chance >= 0 ? (($chance == 0) ? '0' : $chance) : false); + $ReportData['init']['fleet_destroyed'] = $RIPDestroyedByMoon; + $ReportData['init']['fleet_des_chance'] = ($chance2 >= 0 ? (($chance2 == 0) ? '0' : $chance2) : false); + $ReportData['init']['planet_name'] = 'Planeta'; + $ReportData['init']['onMoon'] = false; + $ReportData['init']['atk_lost'] = $RealDebrisMetalAtk + $RealDebrisCrystalAtk + $RealDebrisDeuteriumAtk; + $ReportData['init']['def_lost'] = $RealDebrisMetalDef + $RealDebrisCrystalDef + $RealDebrisDeuteriumDef; + + foreach($RoundsData as $RoundKey => $RoundData) + { + foreach($RoundData as $MainKey => $RoundData2) + { + if(!empty($RoundData2['ships'])) + { + foreach($RoundData2['ships'] as $UserKey => $UserData) + { + $RoundsData[$RoundKey][$MainKey]['ships'][$UserKey] = Array2String($UserData); + } + } + } + } + $ReportData['rounds'] = $RoundsData; + + $ReportID = CreateBattleReport($ReportData, array('atk' => $_User['id'], 'def' => 0), 0, true); + + $parse = $_Lang; + $parse['id'] = $ReportID; + + $AllReports[] = $ReportID; + if($i == $Loop) + { + $parse['time'] = sprintf('%0.6f', $TotalTime); + } + else + { + $parse['time'] = $totaltime; + } + + if($Temp['ship_lost_atk'] < $SimData['ship_lost_atk_min']) + { + $SimData['ship_lost_atk_min'] = $Temp['ship_lost_atk']; + } + if($Temp['ship_lost_atk'] > $SimData['ship_lost_atk_max']) + { + $SimData['ship_lost_atk_max'] = $Temp['ship_lost_atk']; + } + + if($Temp['ship_lost_def'] < $SimData['ship_lost_def_min']) + { + $SimData['ship_lost_def_min'] = $Temp['ship_lost_def']; + } + if($Temp['ship_lost_def'] > $SimData['ship_lost_def_max']) + { + $SimData['ship_lost_def_max'] = $Temp['ship_lost_def']; + } + } + + $SimData['ship_lost_def_max'] = prettyNumber($SimData['ship_lost_def_max']); + $SimData['ship_lost_def_min'] = prettyNumber($SimData['ship_lost_def_min']); + $SimData['ship_lost_atk_max'] = prettyNumber($SimData['ship_lost_atk_max']); + $SimData['ship_lost_atk_min'] = prettyNumber($SimData['ship_lost_atk_min']); + $SimData['total_lost_atk_met'] = prettyNumber(round($SimData['total_lost_atk']['met'] / $Loop)); + $SimData['total_lost_atk_cry'] = prettyNumber(round($SimData['total_lost_atk']['cry'] / $Loop)); + $SimData['total_lost_atk_deu'] = prettyNumber(round($SimData['total_lost_atk']['deu'] / $Loop)); + $SimData['total_lost_def_met'] = prettyNumber(round($SimData['total_lost_def']['met'] / $Loop)); + $SimData['total_lost_def_cry'] = prettyNumber(round($SimData['total_lost_def']['cry'] / $Loop)); + $SimData['total_lost_def_deu'] = prettyNumber(round($SimData['total_lost_def']['deu'] / $Loop)); + $SimData['ship_lost_atk'] = prettyNumber(round($SimData['ship_lost_atk'] / $Loop)); + $SimData['ship_lost_def'] = prettyNumber(round($SimData['ship_lost_def'] / $Loop)); + $SimData['rounds'] = round($SimData['rounds']/$Loop); + if($MoonCreationCount !== FALSE) + { + $SimData['ShowMoonCreationCount'] = '
    '.$_Lang['Moon_created_x_times'].': '.prettyNumber($MoonCreationCount); + } + if($MoonDestructionCount !== FALSE) + { + $SimData['ShowMoonDestructionCount'] = '
    '.$_Lang['Moon_destroyed_x_times'].': '.prettyNumber($MoonDestructionCount); + } + + $SimData['sim_loop'] = $Loop; + $SimData['AddInfo'] = ((!empty($SimData['AddInfo'])) ? implode('
    ', $SimData['AddInfo']).'

    ' : ''); + $parse = array_merge($parse, $SimData); + + $_Lang['SimResult'] .= parsetemplate(gettemplate('simulator_result'), $parse); + + // Trigger Tasks Check + Tasks_TriggerTask($_User, 'USE_SIMULATOR'); + } + else + { + $parse = $_Lang; + $parse['msg'] = $BreakMSG; + $_Lang['SimResult'] .= parsetemplate(gettemplate('simulator_result_warn'), $parse); + } + +} + +$TPL_Slot = gettemplate('simulator_slot'); +$TPL_SingleRow = gettemplate('simulator_single_row'); +$TPL_NoBoth = gettemplate('simulator_row_noboth'); +$TPL_Row = gettemplate('simulator_row'); +$TPL_NoLeft = gettemplate('simulator_row_noleft'); + +$Offsets; + +for($i = 1; $i <= $MaxACSSlots; $i += 1) +{ + $ThisSlot = array(); + $ThisSlot['SlotID'] = $i; + $ThisSlot['txt'] = ''; + + $InsertTabIndex1 = 1; + $InsertTabIndex2 = 1; + $parse = $_Lang; + $parse['i'] = $i; + if($i > 1) + { + $ThisSlot['SlotHidden'] = 'hide'; + } + + if(MORALE_ENABLED) + { + $parse['RowText'] = $_Lang['Morale']; + $ThisSlot['txt'] .= parsetemplate($TPL_SingleRow, $parse); + $parse['RowText'] = $_Lang['Morale_Level']; + $parse['RowInput'] = "%"; + $parse['RowText2'] = $_Lang['Morale_Level']; + $parse['RowInput2'] = "%"; + + $ThisSlot['txt'] .= parsetemplate($TPL_Row, $parse); + $InsertTabIndex1 += 1; + $InsertTabIndex2 += 1; + } + + $parse['RowText'] = $_Lang['Technology']; + $ThisSlot['txt'] .= parsetemplate($TPL_SingleRow, $parse); + $parse['RowText'] = ''.$_Lang['FillMyTechs'].' / '.$_Lang['Fill_Clean'].''; + $parse['RowText2'] = ''.$_Lang['FillMyTechs'].' / '.$_Lang['Fill_Clean'].''; + $ThisSlot['txt'] .= parsetemplate($TPL_NoBoth, $parse); + + for($techs = 1; $techs <= $TechCount; $techs += 1) + { + $ThisRow_InsertValue_Atk = isset($_POST['atk_techs'][$i][$techs]) ? $_POST['atk_techs'][$i][$techs] : null; + $ThisRow_InsertValue_Def = isset($_POST['def_techs'][$i][$techs]) ? $_POST['def_techs'][$i][$techs] : null; + + $parse['RowText'] = $_Lang['Techs'][$techs]; + $parse['RowInput'] = ""; + $parse['RowText2'] = $_Lang['Techs'][$techs]; + $parse['RowInput2'] = ""; + + $ThisSlot['txt'] .= parsetemplate($TPL_Row, $parse); + $InsertTabIndex1 += 1; + $InsertTabIndex2 += 1; + } + + $parse['RowText'] = $_Lang['Fleets']; + $ThisSlot['txt'] .= parsetemplate($TPL_SingleRow, $parse); + $parse['RowText'] = ''.$_Lang['FillMyFleets'].' / '.$_Lang['Fill_Clean'].''; + $parse['RowText2'] = ''.$_Lang['FillMyFleets'].' / '.$_Lang['Fill_Clean'].''; + $ThisSlot['txt'] .= parsetemplate($TPL_NoBoth, $parse); + + foreach($_Vars_ElementCategories['fleet'] as $Ships) + { + $ThisRow_InsertValue_Def = isset($_POST['def_ships'][$i][$Ships]) ? $_POST['def_ships'][$i][$Ships] : null; + + if(!empty($_Vars_Prices[$Ships]['engine'])) + { + $ThisRow_InsertValue_Atk = isset($_POST['atk_ships'][$i][$Ships]) ? $_POST['atk_ships'][$i][$Ships] : null; + + $parse['RowText'] = $_Lang['tech'][$Ships]; + $parse['RowInput'] = " ({$_Lang['Button_Min']} / {$_Lang['Button_Max']})"; + $parse['RowText2'] = $_Lang['tech'][$Ships]; + $parse['RowInput2'] = " ({$_Lang['Button_Min']} / {$_Lang['Button_Max']})"; + + $ThisSlot['txt'] .= parsetemplate($TPL_Row, $parse); + $InsertTabIndex1 += 1; + $InsertTabIndex2 += 1; + } + else + { + $parse['RowText'] = '-'; + $parse['RowText2'] = $_Lang['tech'][$Ships]; + $parse['RowInput2'] = " ({$_Lang['Button_Min']} / {$_Lang['Button_Max']})"; + + $ThisSlot['txt'] .= parsetemplate($TPL_NoLeft, $parse); + $InsertTabIndex2 += 1; + } + } + + if($i == 1) + { + $parse['RowText'] = $_Lang['Defense']; + $ThisSlot['txt'] .= parsetemplate($TPL_SingleRow, $parse); + + foreach($_Vars_ElementCategories['defense'] as $Ships) + { + if(in_array($Ships, $_Vars_ElementCategories['rockets'])) + { + continue; + } + + $ThisRow_InsertValue_Def = isset($_POST['def_ships'][$i][$Ships]) ? $_POST['def_ships'][$i][$Ships] : null; + + $parse['RowText'] = '-'; + $parse['RowText2'] = $_Lang['tech'][$Ships]; + $parse['RowInput2'] = " ({$_Lang['Button_Min']} / {$_Lang['Button_Max']})"; + + $ThisSlot['txt'] .= parsetemplate($TPL_NoLeft, $parse); + $InsertTabIndex2 += 1; + } + } + $Offsets[$i] = $InsertTabIndex1 - 1; + + $_Lang['rows'] .= parsetemplate($TPL_Slot, $ThisSlot); +} + +$_Lang['rows'] = preg_replace('#\{REP1_O([0-9]{1,})_([0-9]{1,})\}#Ssie', "($1 * 1000) + $2", $_Lang['rows']); +$_Lang['rows'] = preg_replace('#\{REP2_O([0-9]{1,})_([0-9]{1,})\}#Ssie', '($1 * 1000) + $Offsets[\'$1\'] + $2', $_Lang['rows']); + +$_Lang['fill_with_mytechs'] = "var MyTechs = new Array();\nMyTechs[1] = ".(string)($_User['tech_weapons'] + 0).";\nMyTechs[3] = ".(string)($_User['tech_shielding'] + 0).";\nMyTechs[2] = ".(string)($_User['tech_armour'] + 0).";\nMyTechs[4] = ".(string)($_User['tech_laser'] + 0).";\nMyTechs[5] = ".(string)($_User['tech_ion'] + 0).";\nMyTechs[6] = ".(string)($_User['tech_plasma'] + 0).";\nMyTechs[7] = ".(string)($_User['tech_antimatter'] + 0).";\nMyTechs[8] = ".(string)($_User['tech_disintegration'] + 0).";\nMyTechs[9] = ".(string)($_User['tech_graviton'] + 0).";\n"; +$_Lang['fill_with_myfleets'] = "var MyFleets = new Array();\n"; + +$UsingPrettyInputBox = ($_User['settings_useprettyinputbox'] == 1 ? true : false); + +foreach($_Vars_ElementCategories['fleet'] as $ID) +{ + if($_Planet[$_Vars_GameElements[$ID]] > 0) + { + $_Lang['fill_with_myfleets'] .= "MyFleets[{$ID}] = '".($UsingPrettyInputBox === true ? prettyNumber($_Planet[$_Vars_GameElements[$ID]]) : $_Planet[$_Vars_GameElements[$ID]])."';\n"; + } +} +foreach($_Vars_ElementCategories['defense'] as $ID) +{ + if(in_array($ID, $_Vars_ElementCategories['rockets'])) + { + continue; + } + + if($_Planet[$_Vars_GameElements[$ID]] > 0) + { + $_Lang['fill_with_myfleets'] .= "MyFleets[{$ID}] = '".($UsingPrettyInputBox === true ? prettyNumber($_Planet[$_Vars_GameElements[$ID]]) : $_Planet[$_Vars_GameElements[$ID]])."';\n"; + } +} +$_Lang['fill_with_myfleets'] .= "\n"; +$_Lang['AllowPrettyInputBox'] = ($_User['settings_useprettyinputbox'] == 1 ? 'true' : 'false'); + +//Display page +$page = parsetemplate(gettemplate('simulator'), $_Lang); + +display($page,$_Lang['Title'], false); + +?> diff --git a/skins/epicblue/gebaeude/index.php b/skins/epicblue/gebaeude/index.php index ee150fd01..bc99142d1 100644 --- a/skins/epicblue/gebaeude/index.php +++ b/skins/epicblue/gebaeude/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/epicblue/gfx/index.php b/skins/epicblue/gfx/index.php index ee150fd01..bc99142d1 100644 --- a/skins/epicblue/gfx/index.php +++ b/skins/epicblue/gfx/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/epicblue/images/index.php b/skins/epicblue/images/index.php index ee150fd01..bc99142d1 100644 --- a/skins/epicblue/images/index.php +++ b/skins/epicblue/images/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/epicblue/img/index.php b/skins/epicblue/img/index.php index ee150fd01..bc99142d1 100644 --- a/skins/epicblue/img/index.php +++ b/skins/epicblue/img/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/epicblue/index.php b/skins/epicblue/index.php index 2c5d40047..bc99142d1 100644 --- a/skins/epicblue/index.php +++ b/skins/epicblue/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/skins/epicblue/officiers/index.php b/skins/epicblue/officiers/index.php index ee150fd01..bc99142d1 100644 --- a/skins/epicblue/officiers/index.php +++ b/skins/epicblue/officiers/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/epicblue/pic/index.php b/skins/epicblue/pic/index.php index ee150fd01..bc99142d1 100644 --- a/skins/epicblue/pic/index.php +++ b/skins/epicblue/pic/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/epicblue/planeten/index.php b/skins/epicblue/planeten/index.php index ee150fd01..bc99142d1 100644 --- a/skins/epicblue/planeten/index.php +++ b/skins/epicblue/planeten/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/epicblue/planeten/small/index.php b/skins/epicblue/planeten/small/index.php index ee150fd01..bc99142d1 100644 --- a/skins/epicblue/planeten/small/index.php +++ b/skins/epicblue/planeten/small/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/epicblue_old/gebaeude/index.php b/skins/epicblue_old/gebaeude/index.php index ee150fd01..bc99142d1 100644 --- a/skins/epicblue_old/gebaeude/index.php +++ b/skins/epicblue_old/gebaeude/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/epicblue_old/gfx/index.php b/skins/epicblue_old/gfx/index.php index ee150fd01..bc99142d1 100644 --- a/skins/epicblue_old/gfx/index.php +++ b/skins/epicblue_old/gfx/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/epicblue_old/images/index.php b/skins/epicblue_old/images/index.php index ee150fd01..bc99142d1 100644 --- a/skins/epicblue_old/images/index.php +++ b/skins/epicblue_old/images/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/epicblue_old/img/index.php b/skins/epicblue_old/img/index.php index ee150fd01..bc99142d1 100644 --- a/skins/epicblue_old/img/index.php +++ b/skins/epicblue_old/img/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/epicblue_old/index.php b/skins/epicblue_old/index.php index 2c5d40047..bc99142d1 100644 --- a/skins/epicblue_old/index.php +++ b/skins/epicblue_old/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/skins/epicblue_old/officiers/index.php b/skins/epicblue_old/officiers/index.php index ee150fd01..bc99142d1 100644 --- a/skins/epicblue_old/officiers/index.php +++ b/skins/epicblue_old/officiers/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/epicblue_old/pic/index.php b/skins/epicblue_old/pic/index.php index ee150fd01..bc99142d1 100644 --- a/skins/epicblue_old/pic/index.php +++ b/skins/epicblue_old/pic/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/epicblue_old/planeten/index.php b/skins/epicblue_old/planeten/index.php index ee150fd01..bc99142d1 100644 --- a/skins/epicblue_old/planeten/index.php +++ b/skins/epicblue_old/planeten/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/epicblue_old/planeten/small/index.php b/skins/epicblue_old/planeten/small/index.php index ee150fd01..bc99142d1 100644 --- a/skins/epicblue_old/planeten/small/index.php +++ b/skins/epicblue_old/planeten/small/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/index.php b/skins/index.php index ee150fd01..bc99142d1 100644 --- a/skins/index.php +++ b/skins/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/xnova/gebaeude/index.php b/skins/xnova/gebaeude/index.php index ee150fd01..bc99142d1 100644 --- a/skins/xnova/gebaeude/index.php +++ b/skins/xnova/gebaeude/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/xnova/gfx/index.php b/skins/xnova/gfx/index.php index ee150fd01..bc99142d1 100644 --- a/skins/xnova/gfx/index.php +++ b/skins/xnova/gfx/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/xnova/images/index.php b/skins/xnova/images/index.php index ee150fd01..bc99142d1 100644 --- a/skins/xnova/images/index.php +++ b/skins/xnova/images/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/xnova/img/index.php b/skins/xnova/img/index.php index ee150fd01..bc99142d1 100644 --- a/skins/xnova/img/index.php +++ b/skins/xnova/img/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/xnova/index.php b/skins/xnova/index.php index ee150fd01..bc99142d1 100644 --- a/skins/xnova/index.php +++ b/skins/xnova/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/xnova/officiers/index.php b/skins/xnova/officiers/index.php index ee150fd01..bc99142d1 100644 --- a/skins/xnova/officiers/index.php +++ b/skins/xnova/officiers/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/xnova/pic/index.php b/skins/xnova/pic/index.php index ee150fd01..bc99142d1 100644 --- a/skins/xnova/pic/index.php +++ b/skins/xnova/pic/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/xnova/planeten/index.php b/skins/xnova/planeten/index.php index ee150fd01..bc99142d1 100644 --- a/skins/xnova/planeten/index.php +++ b/skins/xnova/planeten/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/skins/xnova/planeten/small/index.php b/skins/xnova/planeten/small/index.php index ee150fd01..bc99142d1 100644 --- a/skins/xnova/planeten/small/index.php +++ b/skins/xnova/planeten/small/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/stats.php b/stats.php index 3a1594424..2f8625002 100644 --- a/stats.php +++ b/stats.php @@ -1,305 +1,305 @@ -'. $_Lang['stat_player'] .''; - $parse['who'] .= ''; - $parse['LastWhoVal'] = $who; - - $parse['type'] = ''; - $parse['type'] .= ''; - $parse['type'] .= ''; - $parse['type'] .= ''; - $parse['type'] .= ''; - - if($type == 2) - { - $Order = 'fleet_rank'; - $Points = 'fleet_points'; - $Rank = 'fleet_rank'; - $OldRank = 'fleet_old_rank'; - $YesterdayRank = 'fleet_yesterday_rank'; - } - else if($type == 3) - { - $Order = 'tech_rank'; - $Points = 'tech_points'; - $Rank = 'tech_rank'; - $OldRank = 'tech_old_rank'; - $YesterdayRank = 'tech_yesterday_rank'; - } - else if($type == 4) - { - $Order = 'build_rank'; - $Points = 'build_points'; - $Rank = 'build_rank'; - $OldRank = 'build_old_rank'; - $YesterdayRank = 'build_yesterday_rank'; - } - else if($type == 5) - { - $Order = 'defs_rank'; - $Points = 'defs_points'; - $Rank = 'defs_rank'; - $OldRank = 'defs_old_rank'; - $YesterdayRank = 'defs_yesterday_rank'; - } - else - { - $Order = 'total_rank'; - $Points = 'total_points'; - $Rank = 'total_rank'; - $OldRank = 'total_old_rank'; - $YesterdayRank = 'total_yesterday_rank'; - } - - $SelectCount = doquery("SELECT COUNT(`id_owner`) AS `count` FROM {{table}} WHERE `stat_type` = {$who};", 'statpoints', true); - $SelectCount = $SelectCount['count']; - if($SelectCount > 100) - { - $LastPage = floor($SelectCount / 100); - if($SelectCount / 100 == $LastPage) - { - $LastPage -= 1; - } - for($Page = 0; $Page <= $LastPage; $Page += 1) - { - $PageValue = ($Page * 100) + 1; - if($Page == $LastPage) - { - $PageRange = $SelectCount; - } - else - { - $PageRange = $PageValue + 99; - } - $parse['range'] .= ''; - } - $parse['HideNoRangeSelector'] = 'display: none;'; - } - else - { - $parse['HideRangeSelector'] = 'display: none;'; - $parse['MaxPlace'] = $SelectCount; - } - - $range -= 1; - $start = floor($range / 100) * 100; - if($start == 0) - { - $start = '0'; - } - - if($who == 1) - { - // UserStats - $IsUser = true; - $UseKey = 'player'; - $StatHeader = 'stat_playertable_header'; - $NeedenFields = "{{prefix}}users.id, {{prefix}}users.username, {{prefix}}users.old_username, {{prefix}}users.old_username_expire, `ally`.`ally_name`, {{prefix}}users.ally_id, {{prefix}}users.is_banned, {{prefix}}users.is_onvacation, {{prefix}}users.ban_endtime, `users_stats`.*"; - $GetQuery = "SELECT {{table}}.*, {$NeedenFields} FROM {{table}} LEFT JOIN {{prefix}}achievements_stats AS `users_stats` ON `users_stats`.`A_UserID` = {{table}}.id_owner LEFT JOIN {{prefix}}users ON {{prefix}}users.id = {{table}}.id_owner LEFT JOIN {{prefix}}alliance AS `ally` ON `ally`.`id` = {{prefix}}users.`ally_id` WHERE `stat_type` = '1' ORDER BY `{$Order}` ASC LIMIT {$start}, 100;"; - $RowTPL = gettemplate('stat_playertable'); - $ColSpan = 10; - } - else - { - // AllyStats - $IsUser = false; - $UseKey = 'ally'; - $StatHeader = 'stat_alliancetable_header'; - $GetQuery = "SELECT {{table}}.*, {{prefix}}alliance.id AS `ally_id`, {{prefix}}alliance.ally_name, {{prefix}}alliance.ally_tag, {{prefix}}alliance.ally_members FROM {{table}} LEFT JOIN {{prefix}}alliance ON {{prefix}}alliance.id = {{table}}.id_owner WHERE `stat_type` = '2' ORDER BY `{$Order}` ASC LIMIT {$start}, 100;"; - $RowTPL = gettemplate('stat_alliancetable'); - $ColSpan = 7; - } - $parse['stat_header'] = parsetemplate(gettemplate($StatHeader), $parse); - $parse['stat_date'] = ''.prettyDate('d m Y - H:i:s', $_GameConfig['last_update'], 1).''; - - $SelectRows = doquery($GetQuery, 'statpoints'); - - $start += 1; - if(mysql_num_rows($SelectRows) > 0) - { - while($StatRow = mysql_fetch_assoc($SelectRows)) - { - if($start % 2 == 1) - { - $parse['EvenOrOdd'] = 'odd'; - } - else - { - $parse['EvenOrOdd'] = 'even'; - } - - $parse['Position'] = $start; - - // Quick Rank Change - $rank_new = $StatRow[$Rank]; - $rank_old = $StatRow[$OldRank]; - $rank_yesterday = $StatRow[$YesterdayRank]; - if($rank_old == 0) - { - $ranking = 0; - } - else - { - $ranking = $rank_old - $rank_new; - } - if($ranking == 0) - { - $parse['quickchange'] = '*'; - $parse['QuickChange_Color'] = 'sky'; - } - else if($ranking < 0) - { - $parse['quickchange'] = $ranking; - $parse['QuickChange_Color'] = 'red'; - } - else - { - $parse['quickchange'] = '+'.$ranking; - $parse['QuickChange_Color'] = 'green'; - } - // Daily Rank Change - if($rank_yesterday == 0) - { - $ranking_daily = 0; - } - else - { - $ranking_daily = $rank_yesterday - $rank_new; - } - if($ranking_daily == 0) - { - $parse['daychange'] = '*'; - $parse['DayChange_Color'] = 'sky'; - } - else if($ranking_daily < 0) - { - $parse['daychange'] = $ranking_daily; - $parse['DayChange_Color'] = 'red'; - } - else - { - $parse['daychange'] = '+'.$ranking_daily; - $parse['DayChange_Color'] = 'green'; - } - $parse['Points'] = prettyNumber($StatRow[$Points]); - $parse['ally_id'] = $StatRow['ally_id']; - - if($IsUser) - { - // Parse UserRows - $parse['player_id'] = $StatRow['id']; - if($StatRow['id'] == $_User['id']) - { - $parse['Name'] = ''.$StatRow['username'].''; - } - else - { - $parse['Name'] = $StatRow['username']; - } - if($StatRow['old_username_expire'] > $Now) - { - $parse['Name'] .= ' (?)'; - } - if($StatRow['is_banned'] == 1) - { - $parse['Name'] = ''.$parse['Name'].''; - } - else if(isOnVacation ($StatRow)) - { - $parse['Name'] = ''.$parse['Name'].''; - } - - $parse['Fig_Won'] = prettyNumber($StatRow['ustat_raids_won']); - $parse['Fig_Lost'] = prettyNumber($StatRow['ustat_raids_lost']); - $parse['Fig_Draw'] = prettyNumber($StatRow['ustat_raids_draw']); - $parse['player_mes'] = ''.$_Lang['Ecrire'].''; - if($StatRow['ally_id'] == $_User['ally_id'] AND $_User['ally_id'] > 0) - { - $parse['player_alliance'] = ''.$StatRow['ally_name'].''; - } - else - { - $parse['player_alliance'] = $StatRow['ally_name']; - } - } - else - { - // Parse AllyRows - if($StatRow['ally_id'] == $_User['ally_id']) - { - $parse['Name'] = ''.$StatRow['ally_name'].''; - } - else - { - $parse['Name'] = $StatRow['ally_name']; - } - - $parse['ally_tag'] = $StatRow['ally_tag']; - $parse['ally_members'] = $StatRow['ally_members']; - if($StatRow['ally_members'] > 0) - { - $parse['ally_members_points']= prettyNumber(floor($StatRow[$Points] / $StatRow['ally_members'])); - } - else - { - $parse['ally_members_points']= '0'; - } - } - $parse['stat_values'] .= parsetemplate($RowTPL, $parse); - $start += 1; - } - } - else - { - $parse['stat_values'] = ''.$_Lang['No_Rows_Found'].''; - } - - $page = parsetemplate(gettemplate('stat_body'), $parse); - - display($page, $_Lang['stat_title']); - -?> \ No newline at end of file +'. $_Lang['stat_player'] .''; +$parse['who'] .= ''; +$parse['LastWhoVal'] = $who; + +$parse['type'] = ''; +$parse['type'] .= ''; +$parse['type'] .= ''; +$parse['type'] .= ''; +$parse['type'] .= ''; + +if($type == 2) +{ + $Order = 'fleet_rank'; + $Points = 'fleet_points'; + $Rank = 'fleet_rank'; + $OldRank = 'fleet_old_rank'; + $YesterdayRank = 'fleet_yesterday_rank'; +} +else if($type == 3) +{ + $Order = 'tech_rank'; + $Points = 'tech_points'; + $Rank = 'tech_rank'; + $OldRank = 'tech_old_rank'; + $YesterdayRank = 'tech_yesterday_rank'; +} +else if($type == 4) +{ + $Order = 'build_rank'; + $Points = 'build_points'; + $Rank = 'build_rank'; + $OldRank = 'build_old_rank'; + $YesterdayRank = 'build_yesterday_rank'; +} +else if($type == 5) +{ + $Order = 'defs_rank'; + $Points = 'defs_points'; + $Rank = 'defs_rank'; + $OldRank = 'defs_old_rank'; + $YesterdayRank = 'defs_yesterday_rank'; +} +else +{ + $Order = 'total_rank'; + $Points = 'total_points'; + $Rank = 'total_rank'; + $OldRank = 'total_old_rank'; + $YesterdayRank = 'total_yesterday_rank'; +} + +$SelectCount = doquery("SELECT COUNT(`id_owner`) AS `count` FROM {{table}} WHERE `stat_type` = {$who};", 'statpoints', true); +$SelectCount = $SelectCount['count']; +if($SelectCount > 100) +{ + $LastPage = floor($SelectCount / 100); + if($SelectCount / 100 == $LastPage) + { + $LastPage -= 1; + } + for($Page = 0; $Page <= $LastPage; $Page += 1) + { + $PageValue = ($Page * 100) + 1; + if($Page == $LastPage) + { + $PageRange = $SelectCount; + } + else + { + $PageRange = $PageValue + 99; + } + $parse['range'] .= ''; + } + $parse['HideNoRangeSelector'] = 'display: none;'; +} +else +{ + $parse['HideRangeSelector'] = 'display: none;'; + $parse['MaxPlace'] = $SelectCount; +} + +$range -= 1; +$start = floor($range / 100) * 100; +if($start == 0) +{ + $start = '0'; +} + +if($who == 1) +{ + // UserStats + $IsUser = true; + $UseKey = 'player'; + $StatHeader = 'stat_playertable_header'; + $NeedenFields = "{{prefix}}users.id, {{prefix}}users.username, {{prefix}}users.old_username, {{prefix}}users.old_username_expire, `ally`.`ally_name`, {{prefix}}users.ally_id, {{prefix}}users.is_banned, {{prefix}}users.is_onvacation, {{prefix}}users.ban_endtime, `users_stats`.*"; + $GetQuery = "SELECT {{table}}.*, {$NeedenFields} FROM {{table}} LEFT JOIN {{prefix}}achievements_stats AS `users_stats` ON `users_stats`.`A_UserID` = {{table}}.id_owner LEFT JOIN {{prefix}}users ON {{prefix}}users.id = {{table}}.id_owner LEFT JOIN {{prefix}}alliance AS `ally` ON `ally`.`id` = {{prefix}}users.`ally_id` WHERE `stat_type` = '1' ORDER BY `{$Order}` ASC LIMIT {$start}, 100;"; + $RowTPL = gettemplate('stat_playertable'); + $ColSpan = 10; +} +else +{ + // AllyStats + $IsUser = false; + $UseKey = 'ally'; + $StatHeader = 'stat_alliancetable_header'; + $GetQuery = "SELECT {{table}}.*, {{prefix}}alliance.id AS `ally_id`, {{prefix}}alliance.ally_name, {{prefix}}alliance.ally_tag, {{prefix}}alliance.ally_members FROM {{table}} LEFT JOIN {{prefix}}alliance ON {{prefix}}alliance.id = {{table}}.id_owner WHERE `stat_type` = '2' ORDER BY `{$Order}` ASC LIMIT {$start}, 100;"; + $RowTPL = gettemplate('stat_alliancetable'); + $ColSpan = 7; +} +$parse['stat_header'] = parsetemplate(gettemplate($StatHeader), $parse); +$parse['stat_date'] = ''.prettyDate('d m Y - H:i:s', $_GameConfig['last_update'], 1).''; + +$SelectRows = doquery($GetQuery, 'statpoints'); + +$start += 1; +if(mysql_num_rows($SelectRows) > 0) +{ + while($StatRow = mysql_fetch_assoc($SelectRows)) + { + if($start % 2 == 1) + { + $parse['EvenOrOdd'] = 'odd'; + } + else + { + $parse['EvenOrOdd'] = 'even'; + } + + $parse['Position'] = $start; + + // Quick Rank Change + $rank_new = $StatRow[$Rank]; + $rank_old = $StatRow[$OldRank]; + $rank_yesterday = $StatRow[$YesterdayRank]; + if($rank_old == 0) + { + $ranking = 0; + } + else + { + $ranking = $rank_old - $rank_new; + } + if($ranking == 0) + { + $parse['quickchange'] = '*'; + $parse['QuickChange_Color'] = 'sky'; + } + else if($ranking < 0) + { + $parse['quickchange'] = $ranking; + $parse['QuickChange_Color'] = 'red'; + } + else + { + $parse['quickchange'] = '+'.$ranking; + $parse['QuickChange_Color'] = 'green'; + } + // Daily Rank Change + if($rank_yesterday == 0) + { + $ranking_daily = 0; + } + else + { + $ranking_daily = $rank_yesterday - $rank_new; + } + if($ranking_daily == 0) + { + $parse['daychange'] = '*'; + $parse['DayChange_Color'] = 'sky'; + } + else if($ranking_daily < 0) + { + $parse['daychange'] = $ranking_daily; + $parse['DayChange_Color'] = 'red'; + } + else + { + $parse['daychange'] = '+'.$ranking_daily; + $parse['DayChange_Color'] = 'green'; + } + $parse['Points'] = prettyNumber($StatRow[$Points]); + $parse['ally_id'] = $StatRow['ally_id']; + + if($IsUser) + { + // Parse UserRows + $parse['player_id'] = $StatRow['id']; + if($StatRow['id'] == $_User['id']) + { + $parse['Name'] = ''.$StatRow['username'].''; + } + else + { + $parse['Name'] = $StatRow['username']; + } + if($StatRow['old_username_expire'] > $Now) + { + $parse['Name'] .= ' (?)'; + } + if($StatRow['is_banned'] == 1) + { + $parse['Name'] = ''.$parse['Name'].''; + } + else if(isOnVacation ($StatRow)) + { + $parse['Name'] = ''.$parse['Name'].''; + } + + $parse['Fig_Won'] = prettyNumber($StatRow['ustat_raids_won']); + $parse['Fig_Lost'] = prettyNumber($StatRow['ustat_raids_lost']); + $parse['Fig_Draw'] = prettyNumber($StatRow['ustat_raids_draw']); + $parse['player_mes'] = ''.$_Lang['Ecrire'].''; + if($StatRow['ally_id'] == $_User['ally_id'] AND $_User['ally_id'] > 0) + { + $parse['player_alliance'] = ''.$StatRow['ally_name'].''; + } + else + { + $parse['player_alliance'] = $StatRow['ally_name']; + } + } + else + { + // Parse AllyRows + if($StatRow['ally_id'] == $_User['ally_id']) + { + $parse['Name'] = ''.$StatRow['ally_name'].''; + } + else + { + $parse['Name'] = $StatRow['ally_name']; + } + + $parse['ally_tag'] = $StatRow['ally_tag']; + $parse['ally_members'] = $StatRow['ally_members']; + if($StatRow['ally_members'] > 0) + { + $parse['ally_members_points']= prettyNumber(floor($StatRow[$Points] / $StatRow['ally_members'])); + } + else + { + $parse['ally_members_points']= '0'; + } + } + $parse['stat_values'] .= parsetemplate($RowTPL, $parse); + $start += 1; + } +} +else +{ + $parse['stat_values'] = ''.$_Lang['No_Rows_Found'].''; +} + +$page = parsetemplate(gettemplate('stat_body'), $parse); + +display($page, $_Lang['stat_title']); + +?> diff --git a/tasks.php b/tasks.php index 6ab43567b..3b93d8b10 100644 --- a/tasks.php +++ b/tasks.php @@ -1,511 +1,511 @@ - 0) - { - $SkipCatID = intval($_GET['skipcat']); - if(!empty($_Vars_TasksData[$SkipCatID])) - { - if($_Vars_TasksData[$SkipCatID]['skip']['possible'] === true) - { - if(!Tasks_IsCatDone($SkipCatID, $_User)) - { - foreach($_Vars_TasksData[$SkipCatID]['tasks'] as $TaskID => $TaskData) - { - if(!empty($_User['tasks_done_parsed']['done'][$SkipCatID])) - { - if(in_array($TaskID, $_User['tasks_done_parsed']['done'][$SkipCatID])) - { - continue; - } - } - $CreateSkipArray[] = $TaskID; - } - $_User['tasks_done_parsed']['locked'][$SkipCatID.'s'] = $CreateSkipArray; - $_User['tasks_done'] = json_encode($_User['tasks_done_parsed']); - - doquery("UPDATE {{table}} SET `tasks_done` = '{$_User['tasks_done']}' WHERE `id` = {$_User['id']};", 'users'); - $_User['tasks_done_parsed'] = null; - Tasks_CheckUservar($_User); - - $ShowMsgBox = true; - $_Lang['MsgBox_Text'] = sprintf($_Lang['Msg_Skiped'], $_Lang['TasksCats'][$SkipCatID]); - $_Lang['MsgBox_Colo'] = 'lime'; - } - else - { - $ShowMsgBox = true; - $_Lang['MsgBox_Text'] = $_Lang['Msg_CantSkipDone']; - $_Lang['MsgBox_Colo'] = 'orange'; - } - } - else - { - $ShowMsgBox = true; - $_Lang['MsgBox_Text'] = $_Lang['Msg_CantSkipUnSkippable']; - $_Lang['MsgBox_Colo'] = 'red'; - } - } - else - { - $ShowMsgBox = true; - $_Lang['MsgBox_Text'] = $_Lang['Msg_CatNoExist']; - $_Lang['MsgBox_Colo'] = 'red'; - } - } - - if(1 == 2/*$Mode == 'achievements'*/) - { - $_Lang['SetActiveTab'] = 'achievements'; - } - else - { - if($Mode == 'log') - { - $_Lang['SetActiveTab'] = 'log'; - $_Lang['SetActiveMode'] = 'log'; - $_Lang['Input_SetMode'] = 'mode=log'; - $_Lang['Tab01_CatList_TabTitle'] = $_Lang['Tab01_CatListDone_TabTitle']; - $ShowLog = true; - } - else - { - $ShowLog = false; - } - - // User shows Active Tasks - $SelectCat = 0; - if(isset($_GET['cat']) && $_GET['cat'] > 0) - { - $SelectCat = intval($_GET['cat']); - if(empty($_Vars_TasksData[$SelectCat])) - { - $ShowMsgBox = true; - $SelectCat = 0; - $_Lang['MsgBox_Text'] = $_Lang['Msg_CatNoExist']; - } - } - if($SelectCat > 0) - { - if($ShowLog === false) - { - if(Tasks_IsCatDone($SelectCat, $_User)) - { - $ShowMsgBox = true; - $SelectCat = 0; - $_Lang['MsgBox_Text'] = $_Lang['Msg_CatDone']; - $_Lang['MsgBox_Colo'] = 'orange'; - } - elseif(!Tasks_CheckCatAvailable($SelectCat, $_User)) - { - $ShowMsgBox = true; - $SelectCat = 0; - $_Lang['MsgBox_Text'] = $_Lang['Msg_CatNotAvailable']; - $_Lang['MsgBox_Colo'] = 'red'; - } - } - else - { - if(!Tasks_IsCatDone($SelectCat, $_User)) - { - $ShowMsgBox = true; - $SelectCat = 0; - $_Lang['MsgBox_Text'] = $_Lang['Msg_CatNotDone']; - $_Lang['MsgBox_Colo'] = 'red'; - } - } - } - - if($SelectCat > 0) - { - // User shows TasksList/CatDescription - $PageTPL = gettemplate('tasks_list_showcats_ov'); - $TaskTabTPL = gettemplate('tasks_list_showcats_ov_tasktab'); - $TaskBoxTPL_Desc = gettemplate('tasks_list_showcats_ov_taskbox_desc'); - $TaskBoxTPL_NoDesc = gettemplate('tasks_list_showcats_ov_taskbox_nodesc'); - - $_Lang['Input_CatID'] = $SelectCat; - $_Lang['Input_TasksCat'] = $_Lang['TasksCats'][$SelectCat]; - $_Lang['Input_TabFullLen'] = count($_Vars_TasksData[$SelectCat]['tasks']) + 4; - if($_Lang['Input_TabFullLen'] > $TabsPerRow + 4) - { - $_Lang['Input_TabFullLen'] = $TabsPerRow + 4; - } - $_Lang['Input_TaskTabWidth'] = floor(($TableWidth - (($TaskTabWidthReal + 10) * $_Lang['Input_TabFullLen'])) / 2); - - if($_Vars_TasksData[$SelectCat]['skip']['possible'] === true AND $ShowLog === false) - { - if($_Vars_TasksData[$SelectCat]['skip']['tasksrew'] === true AND $_Vars_TasksData[$SelectCat]['skip']['catrew'] === true) - { - $_Lang['Tab01_CatSel_SkipInfo'] = sprintf($_Lang['Tab01_CatSel_SkipInfo'], 'lime', $_Lang['Tab01_CatSel_SkipBoth']); - } - elseif($_Vars_TasksData[$SelectCat]['skip']['tasksrew'] === true AND $_Vars_TasksData[$SelectCat]['skip']['catrew'] === false) - { - $_Lang['Tab01_CatSel_SkipInfo'] = sprintf($_Lang['Tab01_CatSel_SkipInfo'], 'orange', $_Lang['Tab01_CatSel_SkipTaskOnly']); - } - elseif($_Vars_TasksData[$SelectCat]['skip']['tasksrew'] === false AND $_Vars_TasksData[$SelectCat]['skip']['catrew'] === true) - { - $_Lang['Tab01_CatSel_SkipInfo'] = sprintf($_Lang['Tab01_CatSel_SkipInfo'], 'orange', $_Lang['Tab01_CatSel_SkipCatOnly']); - } - else - { - $_Lang['Tab01_CatSel_SkipInfo'] = sprintf($_Lang['Tab01_CatSel_SkipInfo'], 'red', $_Lang['Tab01_CatSel_SkipNone']); - } - } - else - { - $_Lang['Input_HideCatSkip'] = ' class="hide"'; - } - - if(!empty($_Lang['TasksCatRewards'][$SelectCat])) - { - $_Lang['Input_CatRewards'] = ''; - foreach($_Lang['TasksCatRewards'][$SelectCat] as $CatReward) - { - $_Lang['Input_CatRewards'] .= "• {$CatReward}
    "; - } - } - else - { - $_Lang['Input_HideCatRewards'] = ' class="hide"'; - } - - if(!empty($_Lang['Input_HideCatSkip']) AND !empty($_Lang['Input_HideCatRewards'])) - { - $_Lang['Input_HideCatRewardsOrSkip'] = ' class="hide"'; - } - else - { - if(empty($_Lang['Input_HideCatSkip'])) - { - if(empty($_Lang['Input_HideCatRewards'])) - { - $_Lang['Input_CatSkipTDClass'] = 'noBorL w50p'; - $_Lang['Input_CatRewardsTDClass'] = 'w50p'; - } - else - { - $_Lang['Input_CatSkipTDClass'] = 'noBor w100p'; - $_Lang['Input_CatRewardsTDClass'] = 'w0p'; - } - } - } - - $_Lang['SetActiveTask'] = '1'; - - $_Lang['Input_CreateTaskRows'] = ''; - - $TaskLoop = 1; - $TabRow = 1; - foreach($_Vars_TasksData[$SelectCat]['tasks'] as $TaskID => $TaskData) - { - $TaskNOs[$TaskID] = $TaskLoop; - - $ThisTask = array(); - $ThisTask['Input_JobsToDo'] = ''; - $ThisTask['Input_FirstToDo'] = ''; - $ThisTask['AddTaskNo'] = ''; - $ThisTask['AddCatLink'] = ''; - - if($ShowLog === true) - { - $ThisTask['TaskDone'] = true; - } - else - { - $ThisTask['TaskDone'] = Tasks_IsDone($TaskID, $_User); - } - - $ThisTask['ID'] = $TaskID; - $ThisTask['Colspan'] = $_Lang['Input_TabFullLen']; - $ThisTask['Name'] = $_Lang['Tasks'][$TaskID]['name']; - $ThisTask['Description'] = $_Lang['Tasks'][$TaskID]['desc']; - $ThisTask['No'] = $TaskLoop; - $ThisTask['Lang_Task'] = $_Lang['Tab01_CatSel_Task']; - $ThisTask['Lang_JobsToDo'] = $_Lang['Tab01_CatSel_JobsToDo']; - if(!empty($_Lang['Tasks'][$TaskID]['rewards'])) - { - $ThisTask['Lang_Reward'] = $_Lang['Tab01_CatSel_Reward']; - $ThisTask['Input_Rewards'] = $_Lang['Tasks'][$TaskID]['rewards']; - } - else - { - $ThisTask['HideRewards'] = 'hide'; - } - $ThisTask['Image'] = $_SkinPath.$_Lang['Tasks'][$TaskID]['img']; - if(!empty($_Lang['TasksJobs'][$TaskID])) - { - foreach($_Lang['TasksJobs'][$TaskID] as $JobID => $Job) - { - $StatusIndicator = ''; - if(!empty($Job)) - { - $ThisJob_LinkClass = ''; - if($ThisTask['TaskDone'] === true OR (!empty($_User['tasks_done_parsed']['jobs'][$SelectCat][$TaskID]) AND in_array($JobID, $_User['tasks_done_parsed']['jobs'][$SelectCat][$TaskID]))) - { - $ThisJob_LinkClass = 'lime'; - if(strstr($Job, '{AddClass}') !== false) - { - $Job = str_replace('{AddClass}', 'class="lime"', $Job); - } - $Job = "{$Job}"; - } - else - { - if(strstr($Job, '{AddClass}') !== false) - { - $Job = str_replace('{AddClass}', '', $Job); - } - - if(isset($_User['tasks_done_parsed']['status'][$SelectCat][$TaskID][$JobID]) && $_User['tasks_done_parsed']['status'][$SelectCat][$TaskID][$JobID] > 0) - { - $CurrentStatus = prettyNumber($_User['tasks_done_parsed']['status'][$SelectCat][$TaskID][$JobID]); - $TotalCount = prettyNumber($_Vars_TasksData[$SelectCat]['tasks'][$TaskID]['jobs'][$JobID][$_Vars_TasksData[$SelectCat]['tasks'][$TaskID]['jobs'][$JobID]['statusField']]); - $StatusIndicator = " [{$CurrentStatus}/{$TotalCount}]"; - } - } - - if(stristr($Job, '[tech') !== false) - { - $Job = preg_replace('#\[tech=([0-9]+)\](.*?)\[/tech\]#si', '$2', $Job); - } - - $ThisTask['Input_JobsToDo'] .= "• {$Job}{$StatusIndicator}
    "; - } - } - } - - if($ThisTask['TaskDone']) - { - $ThisTabColor = 'lime'; - $TitleStatus = $_Lang['Tab01_CatSel_TaskDone']; - $ThisTask['HideFirstToDo'] = 'hide'; - } - else - { - if(Tasks_CheckAvailable($TaskID, $_User, $SelectCat)) - { - if(empty($SetActiveTask)) - { - $SetActiveTask = $TaskID; - } - $ThisTabColor = 'orange'; - $TitleStatus = $_Lang['Tab01_CatSel_TaskNotDone']; - $ThisTask['HideFirstToDo'] = 'hide'; - } - else - { - $ThisTask['Lang_FirstToDo'] = $_Lang['Tab01_CatSel_FirstToDo']; - $ThisTabColor = 'red'; - $TitleStatus = $_Lang['Tab01_CatSel_TaskLocked']; - foreach($_Vars_TasksData[$SelectCat]['tasks'][$TaskID]['requirements'] as $ReqData) - { - if($ReqData['type'] == 'CATEGORY') - { - if(!Tasks_IsCatDone($ReqData['e'], $_User)) - { - if(Tasks_CheckCatAvailable($ReqData['elementID'], $_User)) - { - $ThisTask['CreateTaskCatName'] = "\"{$_Lang['TasksCats'][$ReqData['elementID']]}\""; - } - else - { - $ThisTask['CreateTaskCatName'] = "\"{$_Lang['TasksCats'][$ReqData['elementID']]}\""; - } - $ThisTask['Input_FirstToDo'] .= "• {$_Lang['Tab01_CatSel_DoCategory']} {$ThisTask['CreateTaskCatName']}
    "; - } - } - else if($ReqData['type'] == 'TASK') - { - if(!Tasks_IsDone($ReqData['elementID'], $_User)) - { - if(!empty($_Vars_TasksData[$SelectCat]['tasks'][$ReqData['elementID']])) - { - $ThisTask['AddTaskNo'] = " {$TaskNOs[$ReqData['elementID']]}"; - $ThisTask['CreateTaskName'] = "\"{$_Lang['Tasks'][$ReqData['elementID']]['name']}\""; - } - else - { - $ReqData['categoryID'] = Tasks_GetTaskCatID($ReqData['elementID']); - $ThisTask['AddCatLink'] = " ({$_Lang['TasksCats'][$ReqData['categoryID']]})"; - $ThisTask['CreateTaskName'] = "\"{$_Lang['Tasks'][$ReqData['elementID']]['name']}\""; - } - $ThisTask['Input_FirstToDo'] .= "• {$_Lang['Tab01_CatSel_DoTask']}{$ThisTask['AddTaskNo']} {$ThisTask['CreateTaskName']}{$ThisTask['AddCatLink']}
    "; - } - } - } - } - } - $ThisTask['Color'] = $ThisTabColor; - $ThisTask['TitleStatus'] = $TitleStatus; - - $_Lang['Insert_TasksList'][$TabRow][] = parsetemplate($TaskTabTPL, array - ( - 'ID' => $TaskID, - 'Color' => $ThisTabColor, - 'No' => $TaskLoop, - 'Title' => $_Lang['Tasks'][$TaskID]['name'], - 'TitleStatus' => $TitleStatus, - 'Lang_Task' => $_Lang['Tab01_CatSel_Task'] - )); - - if(($TaskLoop % $TabsPerRow) == 0) - { - $TabRow += 1; - } - - if(empty($ThisTask['Description'])) - { - $ThisTask['Template'] = $TaskBoxTPL_NoDesc; - } - else - { - $ThisTask['Template'] = $TaskBoxTPL_Desc; - } - $_Lang['Input_CreateTaskRows'] .= parsetemplate($ThisTask['Template'], $ThisTask); - $TaskLoop += 1; - } - - $_Lang['Input_CreateTasksList_FurtherRows'] = ''; - foreach($_Lang['Insert_TasksList'] as $RowIndex => $RowTabs) - { - if($RowIndex == 1) - { - $_Lang['Input_CreateTasksList_FirstRow'] = implode('', $RowTabs); - } - else - { - $CountRowTabs = count($RowTabs); - if($CountRowTabs == $TabsPerRow) - { - $_Lang['Input_CreateTasksList_FurtherRows'] .= ''.implode('', $RowTabs).''; - } - else - { - $_Lang['Input_CreateTasksList_FurtherRows'] .= ''.implode('', $RowTabs).' '; - } - } - } - $_Lang['Insert_TaskListRowspan'] = count($_Lang['Insert_TasksList']); - - if(isset($SetActiveTask) && $SetActiveTask > $_Lang['SetActiveTask']) - { - $_Lang['SetActiveTask'] = $SetActiveTask; - } - if(isset($_GET['showtask']) && $_GET['showtask'] > 0) - { - $_GET['showtask'] = intval($_GET['showtask']); - if(!empty($_Vars_TasksData[$SelectCat]['tasks'][$_GET['showtask']])) - { - $_Lang['SetActiveTask'] = $_GET['showtask']; - } - } - } - else - { - // User shows CatList - if($ShowLog === false) - { - $PageTPL = gettemplate('tasks_list_showcats_list_active'); - } - else - { - $PageTPL = gettemplate('tasks_list_showcats_list_done'); - } - $TaskCatTPL = gettemplate('tasks_list_showcats_list_cattab'); - - $_Lang['Input_CreateTaskCatsList'] = ''; - foreach($_Vars_TasksData as $TaskCat => $TaskCatData) - { - $TaskCatData['DoneCount'] = '0'; - if($ShowLog === false) - { - if(Tasks_IsCatDone($TaskCat, $_User)) - { - continue; - } - if(!Tasks_CheckCatAvailable($TaskCat, $_User)) - { - $TaskCatData['CatNotAvailable'] = 'red'; - } - foreach($TaskCatData['tasks'] as $TaskID => $TaskData) - { - if(Tasks_IsDone($TaskID, $_User)) - { - $TaskCatData['DoneCount'] += 1; - } - } - } - else - { - if(!Tasks_IsCatDone($TaskCat, $_User)) - { - continue; - } - $TaskCatData['DoneCount'] = count($TaskCatData['tasks']); - } - - $TaskCatData['CatID'] = $TaskCat; - $TaskCatData['Name'] = $_Lang['TasksCats'][$TaskCat]; - $TaskCatData['Lang_Done'] = $_Lang['Tab01_CatList_Done']; - $TaskCatData['TotalCount'] = count($TaskCatData['tasks']); - - $_Lang['Input_CreateTaskCatsList'] .= parsetemplate($TaskCatTPL, $TaskCatData); - } - if(empty($_Lang['Input_CreateTaskCatsList'])) - { - if(empty($_Vars_TasksData)) - { - $_Lang['Input_CreateTaskCatsList'] = "{$_Lang['Tab01_CatList_NoCats']}"; - } - else - { - if($ShowLog === false) - { - $_Lang['Input_CreateTaskCatsList'] = "{$_Lang['Tab01_CatList_AllCatsMade']}"; - } - else - { - $_Lang['Input_CreateTaskCatsList'] = "{$_Lang['Tab01_CatList_NoCatsMade']}"; - } - } - } - } - } - - if($ShowMsgBox === true) - { - $_Lang['MsgBox_Hide'] = ''; - if(empty($_Lang['MsgBox_Colo'])) - { - $_Lang['MsgBox_Colo'] = 'red'; - } - } - - if(!empty($PageTPL)) - { - $BodyTPL = str_replace('{PageBody}', $PageTPL, $BodyTPL); - } - $Page = parsetemplate($BodyTPL, $_Lang); - display($Page, $_Lang['PageTitle']); - -?> \ No newline at end of file + 0) +{ + $SkipCatID = intval($_GET['skipcat']); + if(!empty($_Vars_TasksData[$SkipCatID])) + { + if($_Vars_TasksData[$SkipCatID]['skip']['possible'] === true) + { + if(!Tasks_IsCatDone($SkipCatID, $_User)) + { + foreach($_Vars_TasksData[$SkipCatID]['tasks'] as $TaskID => $TaskData) + { + if(!empty($_User['tasks_done_parsed']['done'][$SkipCatID])) + { + if(in_array($TaskID, $_User['tasks_done_parsed']['done'][$SkipCatID])) + { + continue; + } + } + $CreateSkipArray[] = $TaskID; + } + $_User['tasks_done_parsed']['locked'][$SkipCatID.'s'] = $CreateSkipArray; + $_User['tasks_done'] = json_encode($_User['tasks_done_parsed']); + + doquery("UPDATE {{table}} SET `tasks_done` = '{$_User['tasks_done']}' WHERE `id` = {$_User['id']};", 'users'); + $_User['tasks_done_parsed'] = null; + Tasks_CheckUservar($_User); + + $ShowMsgBox = true; + $_Lang['MsgBox_Text'] = sprintf($_Lang['Msg_Skiped'], $_Lang['TasksCats'][$SkipCatID]); + $_Lang['MsgBox_Colo'] = 'lime'; + } + else + { + $ShowMsgBox = true; + $_Lang['MsgBox_Text'] = $_Lang['Msg_CantSkipDone']; + $_Lang['MsgBox_Colo'] = 'orange'; + } + } + else + { + $ShowMsgBox = true; + $_Lang['MsgBox_Text'] = $_Lang['Msg_CantSkipUnSkippable']; + $_Lang['MsgBox_Colo'] = 'red'; + } + } + else + { + $ShowMsgBox = true; + $_Lang['MsgBox_Text'] = $_Lang['Msg_CatNoExist']; + $_Lang['MsgBox_Colo'] = 'red'; + } +} + +if(1 == 2/*$Mode == 'achievements'*/) +{ + $_Lang['SetActiveTab'] = 'achievements'; +} +else +{ + if($Mode == 'log') + { + $_Lang['SetActiveTab'] = 'log'; + $_Lang['SetActiveMode'] = 'log'; + $_Lang['Input_SetMode'] = 'mode=log'; + $_Lang['Tab01_CatList_TabTitle'] = $_Lang['Tab01_CatListDone_TabTitle']; + $ShowLog = true; + } + else + { + $ShowLog = false; + } + + // User shows Active Tasks + $SelectCat = 0; + if(isset($_GET['cat']) && $_GET['cat'] > 0) + { + $SelectCat = intval($_GET['cat']); + if(empty($_Vars_TasksData[$SelectCat])) + { + $ShowMsgBox = true; + $SelectCat = 0; + $_Lang['MsgBox_Text'] = $_Lang['Msg_CatNoExist']; + } + } + if($SelectCat > 0) + { + if($ShowLog === false) + { + if(Tasks_IsCatDone($SelectCat, $_User)) + { + $ShowMsgBox = true; + $SelectCat = 0; + $_Lang['MsgBox_Text'] = $_Lang['Msg_CatDone']; + $_Lang['MsgBox_Colo'] = 'orange'; + } + elseif(!Tasks_CheckCatAvailable($SelectCat, $_User)) + { + $ShowMsgBox = true; + $SelectCat = 0; + $_Lang['MsgBox_Text'] = $_Lang['Msg_CatNotAvailable']; + $_Lang['MsgBox_Colo'] = 'red'; + } + } + else + { + if(!Tasks_IsCatDone($SelectCat, $_User)) + { + $ShowMsgBox = true; + $SelectCat = 0; + $_Lang['MsgBox_Text'] = $_Lang['Msg_CatNotDone']; + $_Lang['MsgBox_Colo'] = 'red'; + } + } + } + + if($SelectCat > 0) + { + // User shows TasksList/CatDescription + $PageTPL = gettemplate('tasks_list_showcats_ov'); + $TaskTabTPL = gettemplate('tasks_list_showcats_ov_tasktab'); + $TaskBoxTPL_Desc = gettemplate('tasks_list_showcats_ov_taskbox_desc'); + $TaskBoxTPL_NoDesc = gettemplate('tasks_list_showcats_ov_taskbox_nodesc'); + + $_Lang['Input_CatID'] = $SelectCat; + $_Lang['Input_TasksCat'] = $_Lang['TasksCats'][$SelectCat]; + $_Lang['Input_TabFullLen'] = count($_Vars_TasksData[$SelectCat]['tasks']) + 4; + if($_Lang['Input_TabFullLen'] > $TabsPerRow + 4) + { + $_Lang['Input_TabFullLen'] = $TabsPerRow + 4; + } + $_Lang['Input_TaskTabWidth'] = floor(($TableWidth - (($TaskTabWidthReal + 10) * $_Lang['Input_TabFullLen'])) / 2); + + if($_Vars_TasksData[$SelectCat]['skip']['possible'] === true AND $ShowLog === false) + { + if($_Vars_TasksData[$SelectCat]['skip']['tasksrew'] === true AND $_Vars_TasksData[$SelectCat]['skip']['catrew'] === true) + { + $_Lang['Tab01_CatSel_SkipInfo'] = sprintf($_Lang['Tab01_CatSel_SkipInfo'], 'lime', $_Lang['Tab01_CatSel_SkipBoth']); + } + elseif($_Vars_TasksData[$SelectCat]['skip']['tasksrew'] === true AND $_Vars_TasksData[$SelectCat]['skip']['catrew'] === false) + { + $_Lang['Tab01_CatSel_SkipInfo'] = sprintf($_Lang['Tab01_CatSel_SkipInfo'], 'orange', $_Lang['Tab01_CatSel_SkipTaskOnly']); + } + elseif($_Vars_TasksData[$SelectCat]['skip']['tasksrew'] === false AND $_Vars_TasksData[$SelectCat]['skip']['catrew'] === true) + { + $_Lang['Tab01_CatSel_SkipInfo'] = sprintf($_Lang['Tab01_CatSel_SkipInfo'], 'orange', $_Lang['Tab01_CatSel_SkipCatOnly']); + } + else + { + $_Lang['Tab01_CatSel_SkipInfo'] = sprintf($_Lang['Tab01_CatSel_SkipInfo'], 'red', $_Lang['Tab01_CatSel_SkipNone']); + } + } + else + { + $_Lang['Input_HideCatSkip'] = ' class="hide"'; + } + + if(!empty($_Lang['TasksCatRewards'][$SelectCat])) + { + $_Lang['Input_CatRewards'] = ''; + foreach($_Lang['TasksCatRewards'][$SelectCat] as $CatReward) + { + $_Lang['Input_CatRewards'] .= "• {$CatReward}
    "; + } + } + else + { + $_Lang['Input_HideCatRewards'] = ' class="hide"'; + } + + if(!empty($_Lang['Input_HideCatSkip']) AND !empty($_Lang['Input_HideCatRewards'])) + { + $_Lang['Input_HideCatRewardsOrSkip'] = ' class="hide"'; + } + else + { + if(empty($_Lang['Input_HideCatSkip'])) + { + if(empty($_Lang['Input_HideCatRewards'])) + { + $_Lang['Input_CatSkipTDClass'] = 'noBorL w50p'; + $_Lang['Input_CatRewardsTDClass'] = 'w50p'; + } + else + { + $_Lang['Input_CatSkipTDClass'] = 'noBor w100p'; + $_Lang['Input_CatRewardsTDClass'] = 'w0p'; + } + } + } + + $_Lang['SetActiveTask'] = '1'; + + $_Lang['Input_CreateTaskRows'] = ''; + + $TaskLoop = 1; + $TabRow = 1; + foreach($_Vars_TasksData[$SelectCat]['tasks'] as $TaskID => $TaskData) + { + $TaskNOs[$TaskID] = $TaskLoop; + + $ThisTask = array(); + $ThisTask['Input_JobsToDo'] = ''; + $ThisTask['Input_FirstToDo'] = ''; + $ThisTask['AddTaskNo'] = ''; + $ThisTask['AddCatLink'] = ''; + + if($ShowLog === true) + { + $ThisTask['TaskDone'] = true; + } + else + { + $ThisTask['TaskDone'] = Tasks_IsDone($TaskID, $_User); + } + + $ThisTask['ID'] = $TaskID; + $ThisTask['Colspan'] = $_Lang['Input_TabFullLen']; + $ThisTask['Name'] = $_Lang['Tasks'][$TaskID]['name']; + $ThisTask['Description'] = $_Lang['Tasks'][$TaskID]['desc']; + $ThisTask['No'] = $TaskLoop; + $ThisTask['Lang_Task'] = $_Lang['Tab01_CatSel_Task']; + $ThisTask['Lang_JobsToDo'] = $_Lang['Tab01_CatSel_JobsToDo']; + if(!empty($_Lang['Tasks'][$TaskID]['rewards'])) + { + $ThisTask['Lang_Reward'] = $_Lang['Tab01_CatSel_Reward']; + $ThisTask['Input_Rewards'] = $_Lang['Tasks'][$TaskID]['rewards']; + } + else + { + $ThisTask['HideRewards'] = 'hide'; + } + $ThisTask['Image'] = $_SkinPath.$_Lang['Tasks'][$TaskID]['img']; + if(!empty($_Lang['TasksJobs'][$TaskID])) + { + foreach($_Lang['TasksJobs'][$TaskID] as $JobID => $Job) + { + $StatusIndicator = ''; + if(!empty($Job)) + { + $ThisJob_LinkClass = ''; + if($ThisTask['TaskDone'] === true OR (!empty($_User['tasks_done_parsed']['jobs'][$SelectCat][$TaskID]) AND in_array($JobID, $_User['tasks_done_parsed']['jobs'][$SelectCat][$TaskID]))) + { + $ThisJob_LinkClass = 'lime'; + if(strstr($Job, '{AddClass}') !== false) + { + $Job = str_replace('{AddClass}', 'class="lime"', $Job); + } + $Job = "{$Job}"; + } + else + { + if(strstr($Job, '{AddClass}') !== false) + { + $Job = str_replace('{AddClass}', '', $Job); + } + + if(isset($_User['tasks_done_parsed']['status'][$SelectCat][$TaskID][$JobID]) && $_User['tasks_done_parsed']['status'][$SelectCat][$TaskID][$JobID] > 0) + { + $CurrentStatus = prettyNumber($_User['tasks_done_parsed']['status'][$SelectCat][$TaskID][$JobID]); + $TotalCount = prettyNumber($_Vars_TasksData[$SelectCat]['tasks'][$TaskID]['jobs'][$JobID][$_Vars_TasksData[$SelectCat]['tasks'][$TaskID]['jobs'][$JobID]['statusField']]); + $StatusIndicator = " [{$CurrentStatus}/{$TotalCount}]"; + } + } + + if(stristr($Job, '[tech') !== false) + { + $Job = preg_replace('#\[tech=([0-9]+)\](.*?)\[/tech\]#si', '$2', $Job); + } + + $ThisTask['Input_JobsToDo'] .= "• {$Job}{$StatusIndicator}
    "; + } + } + } + + if($ThisTask['TaskDone']) + { + $ThisTabColor = 'lime'; + $TitleStatus = $_Lang['Tab01_CatSel_TaskDone']; + $ThisTask['HideFirstToDo'] = 'hide'; + } + else + { + if(Tasks_CheckAvailable($TaskID, $_User, $SelectCat)) + { + if(empty($SetActiveTask)) + { + $SetActiveTask = $TaskID; + } + $ThisTabColor = 'orange'; + $TitleStatus = $_Lang['Tab01_CatSel_TaskNotDone']; + $ThisTask['HideFirstToDo'] = 'hide'; + } + else + { + $ThisTask['Lang_FirstToDo'] = $_Lang['Tab01_CatSel_FirstToDo']; + $ThisTabColor = 'red'; + $TitleStatus = $_Lang['Tab01_CatSel_TaskLocked']; + foreach($_Vars_TasksData[$SelectCat]['tasks'][$TaskID]['requirements'] as $ReqData) + { + if($ReqData['type'] == 'CATEGORY') + { + if(!Tasks_IsCatDone($ReqData['e'], $_User)) + { + if(Tasks_CheckCatAvailable($ReqData['elementID'], $_User)) + { + $ThisTask['CreateTaskCatName'] = "\"{$_Lang['TasksCats'][$ReqData['elementID']]}\""; + } + else + { + $ThisTask['CreateTaskCatName'] = "\"{$_Lang['TasksCats'][$ReqData['elementID']]}\""; + } + $ThisTask['Input_FirstToDo'] .= "• {$_Lang['Tab01_CatSel_DoCategory']} {$ThisTask['CreateTaskCatName']}
    "; + } + } + else if($ReqData['type'] == 'TASK') + { + if(!Tasks_IsDone($ReqData['elementID'], $_User)) + { + if(!empty($_Vars_TasksData[$SelectCat]['tasks'][$ReqData['elementID']])) + { + $ThisTask['AddTaskNo'] = " {$TaskNOs[$ReqData['elementID']]}"; + $ThisTask['CreateTaskName'] = "\"{$_Lang['Tasks'][$ReqData['elementID']]['name']}\""; + } + else + { + $ReqData['categoryID'] = Tasks_GetTaskCatID($ReqData['elementID']); + $ThisTask['AddCatLink'] = " ({$_Lang['TasksCats'][$ReqData['categoryID']]})"; + $ThisTask['CreateTaskName'] = "\"{$_Lang['Tasks'][$ReqData['elementID']]['name']}\""; + } + $ThisTask['Input_FirstToDo'] .= "• {$_Lang['Tab01_CatSel_DoTask']}{$ThisTask['AddTaskNo']} {$ThisTask['CreateTaskName']}{$ThisTask['AddCatLink']}
    "; + } + } + } + } + } + $ThisTask['Color'] = $ThisTabColor; + $ThisTask['TitleStatus'] = $TitleStatus; + + $_Lang['Insert_TasksList'][$TabRow][] = parsetemplate($TaskTabTPL, array + ( + 'ID' => $TaskID, + 'Color' => $ThisTabColor, + 'No' => $TaskLoop, + 'Title' => $_Lang['Tasks'][$TaskID]['name'], + 'TitleStatus' => $TitleStatus, + 'Lang_Task' => $_Lang['Tab01_CatSel_Task'] + )); + + if(($TaskLoop % $TabsPerRow) == 0) + { + $TabRow += 1; + } + + if(empty($ThisTask['Description'])) + { + $ThisTask['Template'] = $TaskBoxTPL_NoDesc; + } + else + { + $ThisTask['Template'] = $TaskBoxTPL_Desc; + } + $_Lang['Input_CreateTaskRows'] .= parsetemplate($ThisTask['Template'], $ThisTask); + $TaskLoop += 1; + } + + $_Lang['Input_CreateTasksList_FurtherRows'] = ''; + foreach($_Lang['Insert_TasksList'] as $RowIndex => $RowTabs) + { + if($RowIndex == 1) + { + $_Lang['Input_CreateTasksList_FirstRow'] = implode('', $RowTabs); + } + else + { + $CountRowTabs = count($RowTabs); + if($CountRowTabs == $TabsPerRow) + { + $_Lang['Input_CreateTasksList_FurtherRows'] .= ''.implode('', $RowTabs).''; + } + else + { + $_Lang['Input_CreateTasksList_FurtherRows'] .= ''.implode('', $RowTabs).' '; + } + } + } + $_Lang['Insert_TaskListRowspan'] = count($_Lang['Insert_TasksList']); + + if(isset($SetActiveTask) && $SetActiveTask > $_Lang['SetActiveTask']) + { + $_Lang['SetActiveTask'] = $SetActiveTask; + } + if(isset($_GET['showtask']) && $_GET['showtask'] > 0) + { + $_GET['showtask'] = intval($_GET['showtask']); + if(!empty($_Vars_TasksData[$SelectCat]['tasks'][$_GET['showtask']])) + { + $_Lang['SetActiveTask'] = $_GET['showtask']; + } + } + } + else + { + // User shows CatList + if($ShowLog === false) + { + $PageTPL = gettemplate('tasks_list_showcats_list_active'); + } + else + { + $PageTPL = gettemplate('tasks_list_showcats_list_done'); + } + $TaskCatTPL = gettemplate('tasks_list_showcats_list_cattab'); + + $_Lang['Input_CreateTaskCatsList'] = ''; + foreach($_Vars_TasksData as $TaskCat => $TaskCatData) + { + $TaskCatData['DoneCount'] = '0'; + if($ShowLog === false) + { + if(Tasks_IsCatDone($TaskCat, $_User)) + { + continue; + } + if(!Tasks_CheckCatAvailable($TaskCat, $_User)) + { + $TaskCatData['CatNotAvailable'] = 'red'; + } + foreach($TaskCatData['tasks'] as $TaskID => $TaskData) + { + if(Tasks_IsDone($TaskID, $_User)) + { + $TaskCatData['DoneCount'] += 1; + } + } + } + else + { + if(!Tasks_IsCatDone($TaskCat, $_User)) + { + continue; + } + $TaskCatData['DoneCount'] = count($TaskCatData['tasks']); + } + + $TaskCatData['CatID'] = $TaskCat; + $TaskCatData['Name'] = $_Lang['TasksCats'][$TaskCat]; + $TaskCatData['Lang_Done'] = $_Lang['Tab01_CatList_Done']; + $TaskCatData['TotalCount'] = count($TaskCatData['tasks']); + + $_Lang['Input_CreateTaskCatsList'] .= parsetemplate($TaskCatTPL, $TaskCatData); + } + if(empty($_Lang['Input_CreateTaskCatsList'])) + { + if(empty($_Vars_TasksData)) + { + $_Lang['Input_CreateTaskCatsList'] = "{$_Lang['Tab01_CatList_NoCats']}"; + } + else + { + if($ShowLog === false) + { + $_Lang['Input_CreateTaskCatsList'] = "{$_Lang['Tab01_CatList_AllCatsMade']}"; + } + else + { + $_Lang['Input_CreateTaskCatsList'] = "{$_Lang['Tab01_CatList_NoCatsMade']}"; + } + } + } + } +} + +if($ShowMsgBox === true) +{ + $_Lang['MsgBox_Hide'] = ''; + if(empty($_Lang['MsgBox_Colo'])) + { + $_Lang['MsgBox_Colo'] = 'red'; + } +} + +if(!empty($PageTPL)) +{ + $BodyTPL = str_replace('{PageBody}', $PageTPL, $BodyTPL); +} +$Page = parsetemplate($BodyTPL, $_Lang); +display($Page, $_Lang['PageTitle']); + +?> diff --git a/techtree.php b/techtree.php index ef8ad5aa1..7a4972139 100644 --- a/techtree.php +++ b/techtree.php @@ -1,80 +1,80 @@ - $ElementName) - { - $parse = array(); - $parse['id'] = $Element; - $parse['skinpath'] = $_SkinPath; - $parse['tt_name'] = $ElementName; - if(!isset($_Vars_GameElements[$Element])) - { - $parse['Requirements'] = $_Lang['Requirements']; - $page .= parsetemplate($HeadTpl, $parse); - } - else - { - if(isset($_Vars_Requirements[$Element])) - { - $parse['required_list'] = ''; - foreach($_Vars_Requirements[$Element] as $ResClass => $Level) - { - $SetCurrentLevel = ''; - if(in_array($ResClass, $_Vars_ElementCategories['tech'])) - { - if($_User[$_Vars_GameElements[$ResClass]] >= $Level) - { - $SetColor = 'lime'; - } - else - { - $SetColor = 'red'; - $SetCurrentLevel = ($_User[$_Vars_GameElements[$ResClass]] > 0 ? $_User[$_Vars_GameElements[$ResClass]] : '0').'/'; - } - } - else - { - if($_Planet[$_Vars_GameElements[$ResClass]] >= $Level) - { - $SetColor = 'lime'; - } - else - { - $SetColor = 'red'; - $SetCurrentLevel = ($_Planet[$_Vars_GameElements[$ResClass]] > 0 ? $_Planet[$_Vars_GameElements[$ResClass]] : '0').'/'; - } - } - $parse['required_list'] .= "{$_Lang['tech'][$ResClass]} ({$_Lang['level']} {$SetCurrentLevel}{$Level})
    "; - } - } - else - { - $parse['required_list'] = ' '; - $parse['tt_detail'] = ''; - } - $parse['tt_info'] = $Element; - $page .= parsetemplate($RowTpl, $parse); - } - } - - $parse['techtree_list'] = $page; - $parse['Tech0'] = $_Lang['tech'][0]; - $parse['Tech100'] = $_Lang['tech'][100]; - $parse['Tech200'] = $_Lang['tech'][200]; - $parse['Tech400'] = $_Lang['tech'][400]; - $page = parsetemplate(gettemplate('techtree_body'), $parse); - - display($page, $_Lang['Tech'], false); - -?> \ No newline at end of file + $ElementName) +{ + $parse = array(); + $parse['id'] = $Element; + $parse['skinpath'] = $_SkinPath; + $parse['tt_name'] = $ElementName; + if(!isset($_Vars_GameElements[$Element])) + { + $parse['Requirements'] = $_Lang['Requirements']; + $page .= parsetemplate($HeadTpl, $parse); + } + else + { + if(isset($_Vars_Requirements[$Element])) + { + $parse['required_list'] = ''; + foreach($_Vars_Requirements[$Element] as $ResClass => $Level) + { + $SetCurrentLevel = ''; + if(in_array($ResClass, $_Vars_ElementCategories['tech'])) + { + if($_User[$_Vars_GameElements[$ResClass]] >= $Level) + { + $SetColor = 'lime'; + } + else + { + $SetColor = 'red'; + $SetCurrentLevel = ($_User[$_Vars_GameElements[$ResClass]] > 0 ? $_User[$_Vars_GameElements[$ResClass]] : '0').'/'; + } + } + else + { + if($_Planet[$_Vars_GameElements[$ResClass]] >= $Level) + { + $SetColor = 'lime'; + } + else + { + $SetColor = 'red'; + $SetCurrentLevel = ($_Planet[$_Vars_GameElements[$ResClass]] > 0 ? $_Planet[$_Vars_GameElements[$ResClass]] : '0').'/'; + } + } + $parse['required_list'] .= "{$_Lang['tech'][$ResClass]} ({$_Lang['level']} {$SetCurrentLevel}{$Level})
    "; + } + } + else + { + $parse['required_list'] = ' '; + $parse['tt_detail'] = ''; + } + $parse['tt_info'] = $Element; + $page .= parsetemplate($RowTpl, $parse); + } +} + +$parse['techtree_list'] = $page; +$parse['Tech0'] = $_Lang['tech'][0]; +$parse['Tech100'] = $_Lang['tech'][100]; +$parse['Tech200'] = $_Lang['tech'][200]; +$parse['Tech400'] = $_Lang['tech'][400]; +$page = parsetemplate(gettemplate('techtree_body'), $parse); + +display($page, $_Lang['Tech'], false); + +?> diff --git a/templates/default_template/admin/index.php b/templates/default_template/admin/index.php index 2c5d40047..bc99142d1 100644 --- a/templates/default_template/admin/index.php +++ b/templates/default_template/admin/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/templates/default_template/index.php b/templates/default_template/index.php index 2c5d40047..bc99142d1 100644 --- a/templates/default_template/index.php +++ b/templates/default_template/index.php @@ -1,5 +1,5 @@ - \ No newline at end of file + diff --git a/templates/index.php b/templates/index.php index ee150fd01..bc99142d1 100644 --- a/templates/index.php +++ b/templates/index.php @@ -2,4 +2,4 @@ header("Location: ../index.php"); -?> \ No newline at end of file +?> diff --git a/texts.php b/texts.php index 418d12499..8ae122c6c 100644 --- a/texts.php +++ b/texts.php @@ -1,40 +1,40 @@ -{Style}
    {Text}
    '; - - $TextID = (isset($_GET['id']) ? intval($_GET['id']) : 0); - if($TextID > 0) - { - if(!empty($_Lang['Texts'][$TextID])) - { - $_Lang['Title'] = $_Lang['Texts'][$TextID]['title']; - $_Lang['Text'] = $_Lang['Texts'][$TextID]['text']; - $_Lang['Style'] = $_Lang['Texts'][$TextID]['style']; - } - else - { - message($_Lang['Error_TextNoExist'], $_Lang['PageTitleError']); - } - } - else - { - message($_Lang['Error_BadID'], $_Lang['PageTitleError']); - } - - $page = parsetemplate($TPL, $_Lang); - display($page, $_Lang['PageTitle'].$_Lang['Title'], false); - -?> \ No newline at end of file +{Style}
    {Text}
    '; + +$TextID = (isset($_GET['id']) ? intval($_GET['id']) : 0); +if($TextID > 0) +{ + if(!empty($_Lang['Texts'][$TextID])) + { + $_Lang['Title'] = $_Lang['Texts'][$TextID]['title']; + $_Lang['Text'] = $_Lang['Texts'][$TextID]['text']; + $_Lang['Style'] = $_Lang['Texts'][$TextID]['style']; + } + else + { + message($_Lang['Error_TextNoExist'], $_Lang['PageTitleError']); + } +} +else +{ + message($_Lang['Error_BadID'], $_Lang['PageTitleError']); +} + +$page = parsetemplate($TPL, $_Lang); +display($page, $_Lang['PageTitle'].$_Lang['Title'], false); + +?>