From 0acd7c04ce6e6b45c7b3a0488b72732754e16c3e Mon Sep 17 00:00:00 2001 From: Yaro2709 Date: Sun, 12 Jan 2020 18:46:32 +0300 Subject: [PATCH] 1.7.0 --- .htaccess | 74 +- CombatReport.php | 64 +- admin.php | 50 +- ajax.php | 246 - chat/css/2Moons.css | 17 +- chat/css/Cobalt.css | 147 - chat/css/Core.css | 147 - chat/css/Lithium.css | 147 - chat/css/Mercury.css | 147 - chat/css/MyBB.css | 147 - chat/css/Oxygen.css | 147 - chat/css/Radium.css | 147 - chat/css/Sulfur.css | 147 - chat/css/beige.css | 144 - chat/css/black.css | 144 - chat/css/grey.css | 144 - chat/css/prosilver.css | 147 - chat/css/subSilver.css | 147 - chat/css/subblack2.css | 147 - chat/css/subsilver2.css | 147 - chat/css/vBulletin.css | 147 - chat/js/config.js | 2 +- chat/js/custom.js | 3 +- chat/lib/class/AJAXChat.php | 4 +- chat/lib/class/AJAXChatEncoding.php | 24 +- chat/lib/class/AJAXChatFileSystem.php | 2 +- chat/lib/class/AJAXChatMySQLQuery.php | 2 +- chat/lib/class/AJAXChatString.php | 4 +- chat/lib/class/CustomAJAXChat.php | 134 +- chat/lib/config.php | 2 +- chat/lib/custom.php | 22 +- chat/lib/template/loggedIn.html | 3 - cronjob.php | 61 + cronjobs.php | 126 - game.php | 335 +- .../extra/rules.txt => includes/FIRST_INSTALL | 0 includes/FleetHandler.php | 54 +- includes/GeneralFunctions.php | 908 +- includes/PlanetData.php | 26 + includes/bcmath.php | 112 - includes/classes/ArrayUtil.class.php | 84 + includes/classes/Config.class.php | 155 + includes/classes/Cronjob.class.php | 99 + includes/classes/HTTP.class.php | 97 + includes/classes/HTTPRequest.class.php | 69 + includes/classes/Language.class.php | 186 + includes/classes/Mail.class.php | 100 + includes/classes/PlayerUtil.class.php | 436 + includes/classes/SQLDumper.class.php | 233 + .../cache/builder/BannedBuildCache.class.php | 42 + .../builder/LanguageBuildCache.class.php | 50 + .../builder/TeamspeakBuildCache.class.php | 95 + .../cache/builder/VarsBuildCache.class.php | 176 + .../cache/ressource/CacheFile.class.php | 47 + includes/classes/class.BBCode.php | 2 - includes/classes/class.BuildFunctions.php | 282 + includes/classes/class.Cache.php | 92 + .../{class.MySQLi.php => class.Database.php} | 82 +- includes/classes/class.FleetFunctions.php | 586 +- includes/classes/class.FlyingFleetHandler.php | 107 +- includes/classes/class.FlyingFleetsTable.php | 402 +- includes/classes/class.GalaxyRows.php | 371 +- includes/classes/class.Lang.php | 179 - includes/classes/class.Log.php | 19 +- includes/classes/class.MissionFunctions.php | 81 +- includes/classes/class.PlanetRessUpdate.php | 449 +- includes/classes/class.Records.php | 86 - includes/classes/class.Session.php | 147 +- includes/classes/class.StatBanner.php | 110 +- includes/classes/class.StringParser.php | 2 - includes/classes/class.SupportTickets.php | 70 + includes/classes/class.phpmailer.php | 2320 --- includes/classes/class.smtp.php | 814 - includes/classes/class.statbuilder.php | 348 +- includes/classes/class.template.php | 276 +- includes/classes/class.theme.php | 32 +- .../classes/cronjob/CleanerCronjob.class.php | 81 + .../classes/cronjob/DailyCronjob.class.php | 68 + .../classes/cronjob/DumpCronjob.class.php | 60 + .../cronjob/InactiveMailCronjob.class.php | 63 + .../classes/cronjob/ReferralCronjob.class.php | 65 + .../cronjob/StatisticCronjob.class.php} | 39 +- .../cronjob/TeamSpeakCronjob.class.php} | 35 +- .../classes/cronjob/TrackingCronjob.class.php | 71 + includes/classes/missions/GenerateReport.php | 122 +- includes/classes/missions/MissionCaseACS.php | 22 +- .../classes/missions/MissionCaseAttack.php | 641 +- .../missions/MissionCaseColonisation.php | 45 +- .../missions/MissionCaseDestruction.php | 643 +- .../missions/MissionCaseExpedition.php | 415 +- .../classes/missions/MissionCaseFoundDM.php | 27 +- includes/classes/missions/MissionCaseMIP.php | 125 +- .../classes/missions/MissionCaseRecycling.php | 138 +- includes/classes/missions/MissionCaseSpy.php | 350 +- includes/classes/missions/MissionCaseStay.php | 43 +- .../classes/missions/MissionCaseStayAlly.php | 45 +- .../classes/missions/MissionCaseTransport.php | 44 +- includes/classes/missions/calculateAttack.php | 108 +- .../classes/missions/calculateMIPAttack.php | 76 +- includes/classes/missions/calculateSteal.php | 101 +- includes/common.php | 253 +- includes/config.sample.php | 15 +- includes/constants.php | 265 +- includes/dbtables.php | 79 + includes/extauth/facebook.class.php | 103 + includes/extauth/openid.class.php | 114 + includes/functions/BBCode.php | 16 +- includes/functions/CreateOneMoonRecord.php | 120 +- includes/functions/CreateOnePlanetRecord.php | 78 +- includes/functions/DeleteSelectedUser.php | 119 +- includes/functions/GetBuildingPrice.php | 50 - includes/functions/GetBuildingTime.php | 71 - includes/functions/GetElementPrice.php | 54 - includes/functions/IsElementBuyable.php | 62 - .../functions/IsTechnologieAccessible.php | 46 - includes/functions/mvc/mvc_2Moons.php | 13 - includes/libs/FirePHP/FirePHP.class.php | 1784 -- includes/libs/FirePHP/fb.php | 276 - includes/libs/OpenID/openid.php | 831 + includes/libs/Smarty/Smarty.class.php | 1110 +- includes/libs/Smarty/debug.tpl | 133 - includes/libs/Smarty/plugins/block.lang.php | 45 - .../libs/Smarty/plugins/block.textformat.php | 4 +- .../libs/Smarty/plugins/function.fetch.php | 320 +- .../plugins/function.html_checkboxes.php | 15 +- .../Smarty/plugins/function.html_image.php | 43 +- .../Smarty/plugins/function.html_options.php | 2 + .../Smarty/plugins/function.html_radios.php | 15 +- .../plugins/function.html_select_date.php | 7 +- .../plugins/function.html_select_time.php | 7 +- .../libs/Smarty/plugins/function.mailto.php | 2 +- .../Smarty/plugins/modifier.capitalize.php | 18 +- .../Smarty/plugins/modifier.date_format.php | 7 +- .../plugins/modifier.debug_print_var.php | 12 +- .../libs/Smarty/plugins/modifier.escape.php | 69 +- .../libs/Smarty/plugins/modifier.replace.php | 2 +- .../libs/Smarty/plugins/modifier.spacify.php | 2 +- .../libs/Smarty/plugins/modifier.truncate.php | 12 +- .../modifiercompiler.count_characters.php | 6 +- .../modifiercompiler.count_sentences.php | 2 +- .../plugins/modifiercompiler.count_words.php | 6 +- .../plugins/modifiercompiler.escape.php | 67 +- .../plugins/modifiercompiler.from_charset.php | 4 +- .../Smarty/plugins/modifiercompiler.json.php | 25 + .../Smarty/plugins/modifiercompiler.lower.php | 4 +- .../plugins/modifiercompiler.number.php | 25 + .../Smarty/plugins/modifiercompiler.strip.php | 2 +- .../Smarty/plugins/modifiercompiler.time.php | 25 + .../plugins/modifiercompiler.to_charset.php | 4 +- .../plugins/modifiercompiler.unescape.php | 11 +- .../Smarty/plugins/modifiercompiler.upper.php | 4 +- .../plugins/modifiercompiler.wordwrap.php | 2 +- .../plugins/outputfilter.trimwhitespace.php | 2 + .../plugins/shared.escape_special_chars.php | 2 +- .../plugins/shared.literal_compiler_param.php | 10 +- .../Smarty/plugins/shared.mb_wordwrap.php | 14 +- .../variablefilter.htmlspecialchars.php | 2 +- .../sysplugins/smarty_cacheresource.php | 1 + .../smarty_cacheresource_custom.php | 11 +- .../smarty_internal_cacheresource_file.php | 8 +- .../smarty_internal_compile_assign.php | 15 +- .../smarty_internal_compile_block.php | 89 +- .../smarty_internal_compile_capture.php | 8 +- .../smarty_internal_compile_extends.php | 26 +- .../smarty_internal_compile_include.php | 4 +- ...arty_internal_compile_private_modifier.php | 129 +- ...ernal_compile_private_print_expression.php | 2 +- ...ernal_compile_private_special_variable.php | 9 +- .../sysplugins/smarty_internal_config.php | 5 +- .../smarty_internal_configfilelexer.php | 94 +- .../smarty_internal_configfileparser.php | 197 +- .../smarty_internal_function_call_handler.php | 4 +- .../smarty_internal_get_include_path.php | 9 +- .../smarty_internal_nocache_insert.php | 4 +- .../smarty_internal_resource_extends.php | 30 +- .../sysplugins/smarty_internal_template.php | 30 +- .../smarty_internal_templatebase.php | 122 +- .../smarty_internal_templatecompilerbase.php | 144 +- .../smarty_internal_templatelexer.php | 257 +- .../smarty_internal_templateparser.php | 3666 ++-- .../sysplugins/smarty_internal_utility.php | 38 +- .../sysplugins/smarty_internal_write_file.php | 30 +- .../Smarty/sysplugins/smarty_resource.php | 141 +- .../Smarty/sysplugins/smarty_security.php | 36 +- includes/libs/facebook/base_facebook.php | 1425 ++ includes/libs/facebook/facebook.php | 1055 +- includes/libs/reCAPTCHA/recaptchalib.php | 2 +- includes/libs/swift/classes/Swift.php | 81 + .../libs/swift/classes/Swift/Attachment.php | 73 + .../AbstractFilterableInputStream.php | 183 + .../Swift/ByteStream/ArrayByteStream.php | 186 + .../Swift/ByteStream/FileByteStream.php | 222 + .../swift/classes/Swift/CharacterReader.php | 69 + .../GenericFixedWidthReader.php | 99 + .../Swift/CharacterReader/UsAsciiReader.php | 85 + .../Swift/CharacterReader/Utf8Reader.php | 181 + .../classes/Swift/CharacterReaderFactory.php | 28 + .../SimpleCharacterReaderFactory.php | 126 + .../swift/classes/Swift/CharacterStream.php | 91 + .../CharacterStream/ArrayCharacterStream.php | 296 + .../CharacterStream/NgCharacterStream.php | 277 + .../swift/classes/Swift/ConfigurableSpool.php | 64 + .../classes/Swift/DependencyContainer.php | 373 + .../classes/Swift/DependencyException.php | 28 + .../libs/swift/classes/Swift/EmbeddedFile.php | 71 + includes/libs/swift/classes/Swift/Encoder.php | 29 + .../classes/Swift/Encoder/Base64Encoder.php | 60 + .../swift/classes/Swift/Encoder/QpEncoder.php | 286 + .../classes/Swift/Encoder/Rfc2231Encoder.php | 86 + .../libs/swift/classes/Swift/Encoding.php | 66 + .../classes/Swift/Events/CommandEvent.php | 67 + .../classes/Swift/Events/CommandListener.php | 26 + .../libs/swift/classes/Swift/Events/Event.php | 40 + .../classes/Swift/Events/EventDispatcher.php | 85 + .../classes/Swift/Events/EventListener.php | 20 + .../classes/Swift/Events/EventObject.php | 65 + .../classes/Swift/Events/ResponseEvent.php | 68 + .../classes/Swift/Events/ResponseListener.php | 26 + .../swift/classes/Swift/Events/SendEvent.php | 128 + .../classes/Swift/Events/SendListener.php | 33 + .../Swift/Events/SimpleEventDispatcher.php | 161 + .../Swift/Events/TransportChangeEvent.php | 29 + .../Swift/Events/TransportChangeListener.php | 47 + .../Swift/Events/TransportExceptionEvent.php | 48 + .../Events/TransportExceptionListener.php | 26 + .../swift/classes/Swift/FailoverTransport.php | 47 + .../libs/swift/classes/Swift/FileSpool.php | 201 + .../libs/swift/classes/Swift/FileStream.php | 26 + .../libs/swift/classes/Swift/Filterable.php | 33 + includes/libs/swift/classes/Swift/Image.php | 63 + .../swift/classes/Swift/InputByteStream.php | 77 + .../libs/swift/classes/Swift/IoException.php | 28 + .../libs/swift/classes/Swift/KeyCache.php | 107 + .../classes/Swift/KeyCache/ArrayKeyCache.php | 210 + .../classes/Swift/KeyCache/DiskKeyCache.php | 328 + .../classes/Swift/KeyCache/DummyKeyCache.php | 117 + .../Swift/KeyCache/KeyCacheInputStream.php | 53 + .../classes/Swift/KeyCache/NullKeyCache.php | 117 + .../KeyCache/SimpleKeyCacheInputStream.php | 129 + .../classes/Swift/LoadBalancedTransport.php | 47 + .../swift/classes/Swift/MailTransport.php | 47 + includes/libs/swift/classes/Swift/Mailer.php | 115 + .../Swift/Mailer/ArrayRecipientIterator.php | 57 + .../Swift/Mailer/RecipientIterator.php | 34 + .../libs/swift/classes/Swift/MemorySpool.php | 84 + includes/libs/swift/classes/Swift/Message.php | 85 + .../swift/classes/Swift/Mime/Attachment.php | 155 + .../classes/Swift/Mime/CharsetObserver.php | 26 + .../classes/Swift/Mime/ContentEncoder.php | 36 + .../ContentEncoder/Base64ContentEncoder.php | 69 + .../ContentEncoder/NativeQpContentEncoder.php | 75 + .../ContentEncoder/PlainContentEncoder.php | 167 + .../Mime/ContentEncoder/QpContentEncoder.php | 125 + .../swift/classes/Swift/Mime/EmbeddedFile.php | 47 + .../classes/Swift/Mime/EncodingObserver.php | 26 + .../libs/swift/classes/Swift/Mime/Grammar.php | 178 + .../libs/swift/classes/Swift/Mime/Header.php | 95 + .../classes/Swift/Mime/HeaderEncoder.php | 26 + .../HeaderEncoder/Base64HeaderEncoder.php | 57 + .../Mime/HeaderEncoder/QpHeaderEncoder.php | 67 + .../classes/Swift/Mime/HeaderFactory.php | 80 + .../swift/classes/Swift/Mime/HeaderSet.php | 165 + .../Swift/Mime/Headers/AbstractHeader.php | 502 + .../classes/Swift/Mime/Headers/DateHeader.php | 127 + .../Mime/Headers/IdentificationHeader.php | 183 + .../Swift/Mime/Headers/MailboxHeader.php | 358 + .../Mime/Headers/ParameterizedHeader.php | 265 + .../classes/Swift/Mime/Headers/PathHeader.php | 146 + .../Swift/Mime/Headers/UnstructuredHeader.php | 114 + .../libs/swift/classes/Swift/Mime/Message.php | 225 + .../swift/classes/Swift/Mime/MimeEntity.php | 117 + .../swift/classes/Swift/Mime/MimePart.php | 218 + .../Swift/Mime/ParameterizedHeader.php | 36 + .../Swift/Mime/SimpleHeaderFactory.php | 192 + .../classes/Swift/Mime/SimpleHeaderSet.php | 375 + .../classes/Swift/Mime/SimpleMessage.php | 654 + .../classes/Swift/Mime/SimpleMimeEntity.php | 841 + .../libs/swift/classes/Swift/MimePart.php | 61 + .../swift/classes/Swift/NullTransport.php | 40 + .../swift/classes/Swift/OutputByteStream.php | 48 + .../classes/Swift/Plugins/AntiFloodPlugin.php | 143 + .../Swift/Plugins/BandwidthMonitorPlugin.php | 166 + .../Swift/Plugins/Decorator/Replacements.php | 33 + .../classes/Swift/Plugins/DecoratorPlugin.php | 211 + .../Swift/Plugins/ImpersonatePlugin.php | 70 + .../swift/classes/Swift/Plugins/Logger.php | 38 + .../classes/Swift/Plugins/LoggerPlugin.php | 143 + .../Swift/Plugins/Loggers/ArrayLogger.php | 74 + .../Swift/Plugins/Loggers/EchoLogger.php | 60 + .../classes/Swift/Plugins/MessageLogger.php | 77 + .../Swift/Plugins/Pop/Pop3Connection.php | 33 + .../Swift/Plugins/Pop/Pop3Exception.php | 29 + .../Swift/Plugins/PopBeforeSmtpPlugin.php | 278 + .../Swift/Plugins/RedirectingPlugin.php | 195 + .../swift/classes/Swift/Plugins/Reporter.php | 34 + .../classes/Swift/Plugins/ReporterPlugin.php | 75 + .../Swift/Plugins/Reporters/HitReporter.php | 61 + .../Swift/Plugins/Reporters/HtmlReporter.php | 41 + .../swift/classes/Swift/Plugins/Sleeper.php | 26 + .../classes/Swift/Plugins/ThrottlerPlugin.php | 204 + .../swift/classes/Swift/Plugins/Timer.php | 26 + .../libs/swift/classes/Swift/Preferences.php | 104 + .../Swift/ReplacementFilterFactory.php | 28 + .../classes/Swift/RfcComplianceException.php | 28 + .../swift/classes/Swift/SendmailTransport.php | 47 + .../swift/classes/Swift/SmtpTransport.php | 53 + includes/libs/swift/classes/Swift/Spool.php | 54 + .../swift/classes/Swift/SpoolTransport.php | 48 + .../libs/swift/classes/Swift/StreamFilter.php | 36 + .../ByteArrayReplacementFilter.php | 171 + .../StreamFilters/StringReplacementFilter.php | 67 + .../StringReplacementFilterFactory.php | 46 + .../swift/classes/Swift/SwiftException.php | 28 + .../libs/swift/classes/Swift/Transport.php | 56 + .../Swift/Transport/AbstractSmtpTransport.php | 502 + .../Esmtp/Auth/CramMd5Authenticator.php | 83 + .../Esmtp/Auth/LoginAuthenticator.php | 53 + .../Esmtp/Auth/PlainAuthenticator.php | 52 + .../Swift/Transport/Esmtp/AuthHandler.php | 268 + .../Swift/Transport/Esmtp/Authenticator.php | 37 + .../classes/Swift/Transport/EsmtpHandler.php | 88 + .../Swift/Transport/EsmtpTransport.php | 393 + .../Swift/Transport/FailoverTransport.php | 90 + .../classes/Swift/Transport/IoBuffer.php | 69 + .../Swift/Transport/LoadBalancedTransport.php | 171 + .../classes/Swift/Transport/MailInvoker.php | 34 + .../classes/Swift/Transport/MailTransport.php | 231 + .../classes/Swift/Transport/NullTransport.php | 88 + .../Swift/Transport/SendmailTransport.php | 163 + .../Swift/Transport/SimpleMailInvoker.php | 51 + .../classes/Swift/Transport/SmtpAgent.php | 38 + .../Swift/Transport/SpoolTransport.php | 118 + .../classes/Swift/Transport/StreamBuffer.php | 315 + .../classes/Swift/TransportException.php | 29 + .../libs/swift/classes/Swift/Validate.php | 43 + .../libs/swift/dependency_maps/cache_deps.php | 23 + .../swift/dependency_maps/message_deps.php | 9 + .../libs/swift/dependency_maps/mime_deps.php | 119 + .../swift/dependency_maps/transport_deps.php | 68 + includes/libs/swift/mime_types.php | 76 + includes/libs/swift/preferences.php | 21 + includes/libs/swift/swift_init.php | 28 + includes/libs/swift/swift_required.php | 32 + includes/libs/swift/swift_required_pear.php | 32 + includes/libs/tdcron/class.tdcron.entry.php | 324 + includes/libs/tdcron/class.tdcron.php | 441 + includes/libs/teamspeak/class.teamspeak3.php | 134 +- includes/pages/ShowBannedPage.php | 72 - includes/pages/ShowBattleSimPage.php | 190 - includes/pages/ShowBuddyPage.php | 148 - includes/pages/ShowFleetTraderPage.php | 77 - includes/pages/ShowImperiumPage.php | 133 - includes/pages/ShowOverviewPage.php | 205 - includes/pages/ShowPhalanxPage.php | 137 - includes/pages/ShowPlayerCard.php | 99 - includes/pages/ShowRecordsPage.php | 90 - includes/pages/ShowResourcesPage.php | 153 - includes/pages/ShowSearchPage.php | 155 - includes/pages/ShowStatisticsPage.php | 173 - includes/pages/ShowSupportPage.php | 137 - includes/pages/ShowTechTreePage.php | 73 - includes/pages/ShowTopKB.php | 81 - includes/pages/ShowTraderPage.php | 103 - includes/pages/adm/ShowAccountDataPage.php | 85 +- includes/pages/adm/ShowAccountEditorPage.php | 427 +- includes/pages/adm/ShowActivePage.php | 136 +- includes/pages/adm/ShowAutoCompletePage.php | 67 + includes/pages/adm/ShowBanPage.php | 90 +- includes/pages/adm/ShowChatConfigPage.php | 237 +- includes/pages/adm/ShowClearCachePage.php | 17 +- includes/pages/adm/ShowConfigBasicPage.php | 126 +- includes/pages/adm/ShowConfigUniPage.php | 332 +- includes/pages/adm/ShowCreatorPage.php | 194 +- includes/pages/adm/ShowCronjobPage.php | 205 + includes/pages/adm/ShowDisclamerPage.php | 85 + includes/pages/adm/ShowDumpPage.php | 85 + includes/pages/adm/ShowFacebookPage.php | 38 +- includes/pages/adm/ShowFlyingFleetPage.php | 121 +- includes/pages/adm/ShowGiveawayPage.php | 101 + includes/pages/adm/ShowIndexPage.php | 16 +- includes/pages/adm/ShowInformationPage.php | 57 +- includes/pages/adm/ShowLogPage.php | 134 +- includes/pages/adm/ShowLoginPage.php | 40 +- includes/pages/adm/ShowLogoutPage.php | 34 + includes/pages/adm/ShowMenuPage.php | 79 +- includes/pages/adm/ShowMessageListPage.php | 196 +- includes/pages/adm/ShowModVersionPage.php | 71 - includes/pages/adm/ShowModulePage.php | 126 +- includes/pages/adm/ShowMultiIPPage.php | 45 +- includes/pages/adm/ShowNewsPage.php | 183 +- includes/pages/adm/ShowOverviewPage.php | 145 +- includes/pages/adm/ShowPassEncripterPage.php | 98 +- includes/pages/adm/ShowQuickEditorPage.php | 138 +- includes/pages/adm/ShowResetPage.php | 83 +- includes/pages/adm/ShowRightsPage.php | 53 +- includes/pages/adm/ShowSearchPage.php | 263 +- includes/pages/adm/ShowSendMessagesPage.php | 84 +- includes/pages/adm/ShowStatUpdatePage.php | 17 +- includes/pages/adm/ShowStatsPage.php | 179 +- includes/pages/adm/ShowSupportPage.php | 317 +- includes/pages/adm/ShowTeamspeakPage.php | 63 +- includes/pages/adm/ShowTopnavPage.php | 113 +- includes/pages/adm/ShowUniversePage.php | 347 +- includes/pages/adm/ShowUpdatePage.php | 51 +- includes/pages/adm/ShowVertify.php | 66 +- includes/pages/class.ShowAlliancePage.php | 1184 -- includes/pages/class.ShowBuildingsPage.php | 351 - includes/pages/class.ShowFleetPages.php | 1145 -- includes/pages/class.ShowGalaxyPage.php | 192 - includes/pages/class.ShowInfosPage.php | 311 - includes/pages/class.ShowMessagesPage.php | 233 - includes/pages/class.ShowNotesPage.php | 183 - includes/pages/class.ShowOfficierPage.php | 175 - includes/pages/class.ShowOptionsPage.php | 278 - includes/pages/class.ShowResearchPage.php | 361 - includes/pages/class.ShowShipyardPage.php | 414 - includes/pages/game/class.AbstractPage.php | 260 + .../pages/game/class.ShowAlliancePage.php | 1264 ++ includes/pages/game/class.ShowBanListPage.php | 76 + .../pages/game/class.ShowBattleHallPage.php | 112 + .../game/class.ShowBattleSimulatorPage.php | 295 + includes/pages/game/class.ShowBoardPage.php | 48 + .../pages/game/class.ShowBuddyListPage.php | 200 + .../pages/game/class.ShowBuildingsPage.php | 359 + .../pages/game/class.ShowChangelogPage.php | 52 + includes/pages/game/class.ShowChatPage.php | 48 + includes/pages/game/class.ShowErrorPage.php | 52 + .../pages/game/class.ShowFleetAjaxPage.php | 212 + .../pages/game/class.ShowFleetDealerPage.php | 95 + .../pages/game/class.ShowFleetMissilePage.php | 121 + .../pages/game/class.ShowFleetStep1Page.php | 279 + .../pages/game/class.ShowFleetStep2Page.php | 132 + .../pages/game/class.ShowFleetStep3Page.php | 352 + .../pages/game/class.ShowFleetTablePage.php | 290 + includes/pages/game/class.ShowGalaxyPage.php | 131 + .../pages/game/class.ShowImperiumPage.php | 113 + .../pages/game/class.ShowInformationPage.php | 334 + includes/pages/game/class.ShowLogoutPage.php | 47 + .../pages/game/class.ShowMessagesPage.php | 307 + includes/pages/game/class.ShowNotesPage.php | 129 + .../pages/game/class.ShowOfficierPage.php | 162 + .../pages/game/class.ShowOverviewPage.php | 344 + includes/pages/game/class.ShowPhalanxPage.php | 108 + .../pages/game/class.ShowPlayerCardPage.php | 109 + .../pages/game/class.ShowQuestionsPage.php | 65 + includes/pages/game/class.ShowRaportPage.php | 172 + includes/pages/game/class.ShowRecordsPage.php | 73 + .../pages/game/class.ShowResearchPage.php | 377 + .../pages/game/class.ShowResourcesPage.php | 221 + includes/pages/game/class.ShowSearchPage.php | 242 + .../pages/game/class.ShowSettingsPage.php | 324 + .../pages/game/class.ShowShipyardPage.php | 276 + .../pages/game/class.ShowStatisticsPage.php | 178 + .../pages/game/class.ShowTechtreePage.php | 72 + includes/pages/game/class.ShowTicketPage.php | 142 + includes/pages/game/class.ShowTraderPage.php | 127 + includes/pages/login/AbstractPage.class.php | 179 + .../pages/login/ShowBanListPage.class.php | 82 + .../pages/login/ShowBattleHallPage.class.php | 85 + includes/pages/login/ShowBoardPage.class.php | 48 + .../ShowDisclamerPage.class.php} | 47 +- includes/pages/login/ShowErrorPage.class.php | 54 + .../login/ShowExternalAuthPage.class.php | 71 + includes/pages/login/ShowIndexPage.class.php | 93 + includes/pages/login/ShowLoginPage.class.php | 72 + .../login/ShowLostPasswordPage.class.php | 165 + includes/pages/login/ShowNewsPage.class.php | 60 + .../pages/login/ShowRegisterPage.class.php | 306 + includes/pages/login/ShowRulesPage.class.php | 50 + .../pages/login/ShowScreensPage.class.php | 68 + .../pages/login/ShowVertifyPage.class.php | 120 + includes/update.php | 135 - includes/vars.php | 404 +- index.php | 584 +- install/VERSION | 1 + install/index.php | 885 +- install/install.sql | 1021 +- .../templates => install/updates}/.htaccess | 0 {updates => install/updates}/update_1006.sql | 0 {updates => install/updates}/update_1041.sql | 0 {updates => install/updates}/update_1057.sql | 0 {updates => install/updates}/update_1066.sql | 0 {updates => install/updates}/update_1097.sql | 0 {updates => install/updates}/update_1131.sql | 0 {updates => install/updates}/update_1192.sql | 0 {updates => install/updates}/update_1231.php | 5 +- {updates => install/updates}/update_1231.sql | 0 {updates => install/updates}/update_1235.sql | 0 {updates => install/updates}/update_1242.sql | 0 {updates => install/updates}/update_1290.sql | 0 {updates => install/updates}/update_1330.sql | 0 {updates => install/updates}/update_1341.sql | 0 {updates => install/updates}/update_1359.sql | 0 {updates => install/updates}/update_1366.sql | 0 {updates => install/updates}/update_1416.sql | 0 {updates => install/updates}/update_1443.sql | 0 {updates => install/updates}/update_1493.sql | 2 +- {updates => install/updates}/update_1497.sql | 0 {updates => install/updates}/update_1512.sql | 0 {updates => install/updates}/update_1520.sql | 0 {updates => install/updates}/update_1534.sql | 0 {updates => install/updates}/update_1539.sql | 2 +- {updates => install/updates}/update_1540.sql | 0 {updates => install/updates}/update_1544.sql | 0 {updates => install/updates}/update_1551.sql | 0 {updates => install/updates}/update_1554.sql | 0 {updates => install/updates}/update_1559.sql | 0 {updates => install/updates}/update_1568.sql | 0 {updates => install/updates}/update_1576.sql | 0 {updates => install/updates}/update_1600.sql | 0 {updates => install/updates}/update_1611.sql | 0 {updates => install/updates}/update_1624.sql | 0 {updates => install/updates}/update_1634.sql | 0 {updates => install/updates}/update_1657.sql | 0 {updates => install/updates}/update_1683.sql | 0 {updates => install/updates}/update_1689.sql | 0 {updates => install/updates}/update_1698.sql | 0 {updates => install/updates}/update_1721.sql | 0 {updates => install/updates}/update_1728.sql | 0 {updates => install/updates}/update_1737.sql | 0 {updates => install/updates}/update_1753.sql | 0 {updates => install/updates}/update_1782.sql | 0 {updates => install/updates}/update_1802.sql | 0 {updates => install/updates}/update_1811.php | 2 - {updates => install/updates}/update_1820.sql | 0 {updates => install/updates}/update_1843.sql | 0 {updates => install/updates}/update_1850.sql | 0 {updates => install/updates}/update_1881.sql | 0 {updates => install/updates}/update_1894.sql | 0 {updates => install/updates}/update_1902.sql | 0 {updates => install/updates}/update_1962.sql | 0 {updates => install/updates}/update_1968.sql | 0 {updates => install/updates}/update_1979.sql | 0 {updates => install/updates}/update_1982.sql | 0 {updates => install/updates}/update_1993.sql | 0 {updates => install/updates}/update_2001.sql | 0 {updates => install/updates}/update_2003.sql | 0 {updates => install/updates}/update_2017.sql | 0 {updates => install/updates}/update_2025.sql | 0 install/updates/update_2080.php | 77 + install/updates/update_2099.sql | 15 + install/updates/update_2105.sql | 31 + install/updates/update_2126.sql | 567 + install/updates/update_2246.sql | 6 + install/updates/update_2290.sql | 2 + install/updates/update_2296.sql | 6 + install/updates/update_2306.sql | 1 + install/updates/update_2327.sql | 1 + install/updates/update_2333.sql | 1 + install/updates/update_2365.sql | 1 + install/updates/update_2369.sql | 2 + install/updates/update_2374.sql | 1 + install/updates/update_2416.sql | 99 + install/updates/update_2417.sql | 3 + install/updates/update_2430.sql | 6 + install/updates/update_2463.sql | 5 + install/updates/update_2480.sql | 1 + install/updates/update_2484.sql | 1 + install/updates/update_2502.sql | 1 + install/updates/update_2505.sql | 3 + install/updates/update_2538.sql | 2 + install/updates/update_2543.sql | 2 + install/updates/update_2564.sql | 1 + install/updates/update_2568.sql | 2 + install/updates/update_2577.sql | 4 + install/updates/update_2579.sql | 3 + {updates => install/updates}/update_411.sql | 0 {updates => install/updates}/update_448.sql | 0 {updates => install/updates}/update_485.sql | 0 {updates => install/updates}/update_502.sql | 0 {updates => install/updates}/update_515.sql | 0 {updates => install/updates}/update_532.sql | 0 {updates => install/updates}/update_544.sql | 0 {updates => install/updates}/update_547.sql | 0 {updates => install/updates}/update_578.sql | 0 {updates => install/updates}/update_611.sql | 0 {updates => install/updates}/update_612.sql | 0 {updates => install/updates}/update_632.sql | 0 {updates => install/updates}/update_633.sql | 0 {updates => install/updates}/update_665.sql | 0 {updates => install/updates}/update_673.php | 3 +- {updates => install/updates}/update_673.sql | 0 {updates => install/updates}/update_698.sql | 0 {updates => install/updates}/update_739.sql | 0 {updates => install/updates}/update_744.sql | 0 {updates => install/updates}/update_759.sql | 0 {updates => install/updates}/update_762.sql | 0 {updates => install/updates}/update_784.sql | 0 {updates => install/updates}/update_887.sql | 0 {updates => install/updates}/update_932.sql | 0 {updates => install/updates}/update_938.sql | 0 {updates => install/updates}/update_970.sql | 0 {updates => install/updates}/update_982.sql | 0 {updates => install/updates}/update_989.sql | 0 language/de/ADMIN.php | 546 +- language/de/BANNER.php | 26 +- language/de/CHANGELOG.php | 319 +- language/de/CUSTOM.php | 31 + language/de/FAQ.php | 188 +- language/de/FLEET.php | 129 +- language/de/INGAME.php | 363 +- language/de/INSTALL.php | 156 +- language/de/L18N.php | 30 + language/de/LANG.cfg | 31 +- language/de/PUBLIC.php | 278 +- language/de/TECH.php | 803 +- language/de/templates/createUniverseInfo.txt | 12 + .../{email => templates}/email_inactive.txt | 6 +- .../templates/email_lost_password_changed.txt | 8 + .../email_lost_password_validation.txt | 11 + language/de/templates/email_reg_done.txt | 9 + language/de/templates/email_vaild_reg.txt | 26 + .../{extra => templates}/locked_install.txt | 0 language/de/{extra => templates}/rules.txt | 0 language/en/ADMIN.php | 2147 ++- language/en/BANNER.php | 20 +- language/en/CHANGELOG.php | 1039 +- .../en/CUSTOM.php | 12 +- language/en/FAQ.php | 137 +- language/en/FLEET.php | 25 +- language/en/INGAME.php | 2082 +-- language/en/INSTALL.php | 171 +- language/en/L18N.php | 16 +- language/en/LANG.cfg | 4 +- language/en/PUBLIC.php | 258 +- language/en/TECH.php | 416 +- language/en/templates/createUniverseInfo.txt | 12 + .../{email => templates}/email_inactive.txt | 4 +- .../email_lost_password.txt | 0 .../templates/email_lost_password_changed.txt | 8 + .../email_lost_password_validation.txt | 11 + .../{email => templates}/email_reg_done.txt | 0 .../{email => templates}/email_vaild_reg.txt | 0 .../{extra => templates}/locked_install.txt | 0 language/en/{extra => templates}/rules.txt | 0 language/es/ADMIN.php | 2155 ++- language/es/BANNER.php | 28 +- language/es/CHANGELOG.php | 14 +- language/es/CUSTOM.php | 31 + language/es/FAQ.php | 170 +- language/es/FLEET.php | 368 +- language/es/INGAME.php | 2008 ++- language/es/INSTALL.php | 81 +- language/es/L18N.php | 26 +- language/es/LANG.cfg | 4 +- language/es/PUBLIC.php | 308 +- language/es/TECH.php | 595 +- .../{email => templates}/email_inactive.txt | 6 +- .../email_lost_password.txt | 0 .../{email => templates}/email_reg_done.txt | 0 .../{email => templates}/email_vaild_reg.txt | 0 language/es/templates/rules.txt | 59 + language/fr/ADMIN.php | 1181 -- language/fr/BANNER.php | 10 - language/fr/CHANGELOG.php | 628 - language/fr/FAQ.php | 29 - language/fr/FLEET.php | 198 - language/fr/INGAME.php | 1100 -- language/fr/INSTALL.php | 94 - language/fr/L18N.php | 58 - language/fr/LANG.cfg | 9 - language/fr/PUBLIC.php | 285 - language/fr/TECH.php | 450 - language/fr/email/email_inactive.txt | 8 - language/fr/email/email_lost_password.txt | 12 - language/fr/email/email_reg_done.txt | 8 - language/fr/email/email_vaild_reg.txt | 19 - language/it/ADMIN.php | 1145 -- language/it/BANNER.php | 9 - language/it/CHANGELOG.php | 628 - language/it/FAQ.php | 23 - language/it/FLEET.php | 195 - language/it/INGAME.php | 1101 -- language/it/INSTALL.php | 62 - language/it/L18N.php | 14 - language/it/LANG.cfg | 22 - language/it/PUBLIC.php | 204 - language/it/TECH.php | 457 - language/it/email/email_inactive.txt | 8 - language/it/email/email_lost_password.txt | 13 - language/it/email/email_reg_done.txt | 8 - language/it/email/email_vaild_reg.txt | 21 - language/pl/ADMIN.php | 1337 ++ language/pl/BANNER.php | 38 + language/pl/CHANGELOG.php | 883 + language/pl/CUSTOM.php | 36 + language/pl/FAQ.php | 163 + language/pl/FLEET.php | 228 + language/pl/INGAME.php | 1197 ++ language/pl/INSTALL.php | 128 + language/{si => pl}/L18N.php | 10 +- language/pl/LANG.cfg | 9 + language/pl/PUBLIC.php | 170 + language/pl/TECH.php | 404 + language/pl/templates/createUniverseInfo.txt | 12 + language/pl/templates/email_inactive.txt | 13 + language/pl/templates/email_lost_password.txt | 21 + .../templates/email_lost_password_changed.txt | 8 + .../email_lost_password_validation.txt | 21 + language/pl/templates/email_reg_done.txt | 12 + language/pl/templates/email_vaild_reg.txt | 34 + language/pl/templates/locked_install.txt | 6 + language/pl/templates/rules.txt | 62 + language/pt/ADMIN.php | 1082 +- language/pt/BANNER.php | 21 +- language/pt/CHANGELOG.php | 549 +- .../pt/CUSTOM.php | 28 +- language/pt/FAQ.php | 143 +- language/pt/FLEET.php | 31 +- language/pt/INGAME.php | 925 +- language/pt/INSTALL.php | 169 +- language/pt/L18N.php | 92 +- language/pt/LANG.cfg | 2 +- language/pt/PUBLIC.php | 266 +- language/pt/TECH.php | 817 +- language/pt/email/email_inactive.txt | 10 - language/pt/email/email_lost_password.txt | 16 - language/pt/email/email_reg_done.txt | 15 - language/pt/email/email_vaild_reg.txt | 29 - language/pt/templates/createUniverseInfo.txt | 12 + language/pt/templates/email_inactive.txt | 9 + .../templates}/email_lost_password.txt | 0 .../templates/email_lost_password_changed.txt | 8 + .../email_lost_password_validation.txt | 11 + .../email => pt/templates}/email_reg_done.txt | 0 .../templates}/email_vaild_reg.txt | 0 language/pt/templates/locked_install.txt | 6 + language/pt/templates/rules.txt | 53 + language/ru/ADMIN.php | 900 +- language/ru/BANNER.php | 22 +- language/ru/CHANGELOG.php | 344 +- language/ru/CUSTOM.php | 7 + language/ru/FAQ.php | 195 +- language/ru/FLEET.php | 73 +- language/ru/INGAME.php | 553 +- language/ru/INSTALL.php | 147 +- language/ru/L18N.php | 9 +- language/ru/LANG.cfg | 2 +- language/ru/PUBLIC.php | 234 +- language/ru/TECH.php | 761 +- language/ru/email/email_reg_done.txt | 7 - language/ru/email/email_vaild_reg.txt | 16 - language/ru/templates/createUniverseInfo.txt | 11 + .../{email => templates}/email_inactive.txt | 6 +- .../email_lost_password.txt | 4 +- .../templates/email_lost_password_changed.txt | 7 + .../email_lost_password_validation.txt | 9 + language/ru/templates/email_reg_done.txt | 5 + language/ru/templates/email_vaild_reg.txt | 16 + language/ru/templates/locked_install.txt | 6 + language/ru/{extra => templates}/rules.txt | 0 language/si/ADMIN.php | 1151 -- language/si/BANNER.php | 9 - language/si/CHANGELOG.php | 628 - language/si/FAQ.php | 27 - language/si/FLEET.php | 195 - language/si/INGAME.php | 1105 -- language/si/INSTALL.php | 67 - language/si/LANG.cfg | 8 - language/si/PUBLIC.php | 264 - language/si/TECH.php | 452 - language/si/email/email_inactive.txt | 8 - language/si/email/email_lost_password.txt | 11 - language/si/email/email_reg_done.txt | 7 - language/si/email/email_vaild_reg.txt | 19 - robots.txt | 376 +- root.php | 40 +- scripts/base/jquery.autosize-min.js | 4 + scripts/base/jquery.js | 7908 ++++---- scripts/base/jquery.tablesorter.js | 1030 ++ scripts/base/jquery.ui.js | 15029 +++++++++++++++- scripts/base/jquery.validationEngine.js | 1674 ++ scripts/base/tinymce/langs/ar.js | 1 + scripts/base/tinymce/langs/cn.js | 1 + scripts/base/tinymce/langs/de.js | 1 + scripts/base/tinymce/langs/el.js | 1 + scripts/base/tinymce/langs/en.js | 1 + scripts/base/tinymce/langs/fr.js | 1 + scripts/base/tinymce/langs/hr.js | 1 + scripts/base/tinymce/langs/hu.js | 1 + scripts/base/tinymce/langs/it.js | 1 + scripts/base/tinymce/langs/pl.js | 1 + scripts/base/tinymce/langs/pt.js | 1 + scripts/base/tinymce/langs/ru.js | 1 + scripts/base/tinymce/langs/zh.js | 1 + scripts/base/tinymce/license.txt | 504 + .../tinymce/plugins/bbcode/editor_plugin.js | 1 + .../plugins/fullscreen/editor_plugin.js | 1 + .../tinymce/plugins/fullscreen/fullscreen.htm | 110 + .../base/tinymce/themes/advanced/about.htm | 52 + .../base/tinymce/themes/advanced/anchor.htm | 26 + .../base/tinymce/themes/advanced/charmap.htm | 55 + .../tinymce/themes/advanced/color_picker.htm | 70 + .../themes/advanced/editor_template.js | 1 + .../base/tinymce/themes/advanced/image.htm | 80 + .../themes/advanced/img/colorpicker.jpg | Bin 0 -> 2584 bytes .../tinymce/themes/advanced/img/flash.gif | Bin 0 -> 239 bytes .../tinymce/themes/advanced/img/icons.gif | Bin 0 -> 11982 bytes .../tinymce/themes/advanced/img/iframe.gif | Bin 0 -> 600 bytes .../tinymce/themes/advanced/img/pagebreak.gif | Bin 0 -> 325 bytes .../tinymce/themes/advanced/img/quicktime.gif | Bin 0 -> 301 bytes .../tinymce/themes/advanced/img/realmedia.gif | Bin 0 -> 439 bytes .../tinymce/themes/advanced/img/shockwave.gif | Bin 0 -> 384 bytes .../tinymce/themes/advanced/img/trans.gif | Bin 0 -> 43 bytes .../tinymce/themes/advanced/img/video.gif | Bin 0 -> 597 bytes .../themes/advanced/img/windowsmedia.gif | Bin 0 -> 415 bytes .../base/tinymce/themes/advanced/js/about.js | 73 + .../base/tinymce/themes/advanced/js/anchor.js | 56 + .../tinymce/themes/advanced/js/charmap.js | 363 + .../themes/advanced/js/color_picker.js | 345 + .../base/tinymce/themes/advanced/js/image.js | 253 + .../base/tinymce/themes/advanced/js/link.js | 159 + .../themes/advanced/js/source_editor.js | 78 + .../base/tinymce/themes/advanced/langs/ar.js | 1 + .../tinymce/themes/advanced/langs/ar_dlg.js | 1 + .../base/tinymce/themes/advanced/langs/cn.js | 1 + .../tinymce/themes/advanced/langs/cn_dlg.js | 1 + .../base/tinymce/themes/advanced/langs/de.js | 1 + .../tinymce/themes/advanced/langs/de_dlg.js | 1 + .../base/tinymce/themes/advanced/langs/el.js | 1 + .../tinymce/themes/advanced/langs/el_dlg.js | 1 + .../base/tinymce/themes/advanced/langs/en.js | 1 + .../tinymce/themes/advanced/langs/en_dlg.js | 1 + .../base/tinymce/themes/advanced/langs/fr.js | 1 + .../tinymce/themes/advanced/langs/fr_dlg.js | 1 + .../base/tinymce/themes/advanced/langs/hr.js | 1 + .../tinymce/themes/advanced/langs/hr_dlg.js | 1 + .../base/tinymce/themes/advanced/langs/hu.js | 1 + .../tinymce/themes/advanced/langs/hu_dlg.js | 1 + .../base/tinymce/themes/advanced/langs/it.js | 1 + .../tinymce/themes/advanced/langs/it_dlg.js | 1 + .../base/tinymce/themes/advanced/langs/pl.js | 1 + .../tinymce/themes/advanced/langs/pl_dlg.js | 1 + .../base/tinymce/themes/advanced/langs/pt.js | 1 + .../tinymce/themes/advanced/langs/pt_dlg.js | 1 + .../base/tinymce/themes/advanced/langs/ru.js | 1 + .../tinymce/themes/advanced/langs/ru_dlg.js | 1 + .../base/tinymce/themes/advanced/langs/zh.js | 1 + .../tinymce/themes/advanced/langs/zh_dlg.js | 1 + scripts/base/tinymce/themes/advanced/link.htm | 57 + .../tinymce/themes/advanced/shortcuts.htm | 47 + .../themes/advanced/skins/default/content.css | 50 + .../themes/advanced/skins/default/dialog.css | 118 + .../advanced/skins/default/img/buttons.png | Bin 0 -> 3133 bytes .../advanced/skins/default/img/items.gif | Bin 0 -> 64 bytes .../advanced/skins/default/img/menu_arrow.gif | Bin 0 -> 68 bytes .../advanced/skins/default/img/menu_check.gif | Bin 0 -> 70 bytes .../advanced/skins/default/img/progress.gif | Bin 0 -> 1787 bytes .../advanced/skins/default/img/tabs.gif | Bin 0 -> 1322 bytes .../themes/advanced/skins/default/ui.css | 219 + .../advanced/skins/highcontrast/content.css | 24 + .../advanced/skins/highcontrast/dialog.css | 106 + .../themes/advanced/skins/highcontrast/ui.css | 106 + .../themes/advanced/skins/o2k7/content.css | 48 + .../themes/advanced/skins/o2k7/dialog.css | 118 + .../advanced/skins/o2k7/img/button_bg.png | Bin 0 -> 2766 bytes .../skins/o2k7/img/button_bg_black.png | Bin 0 -> 651 bytes .../skins/o2k7/img/button_bg_silver.png | Bin 0 -> 2084 bytes .../tinymce/themes/advanced/skins/o2k7/ui.css | 222 + .../themes/advanced/skins/o2k7/ui_black.css | 8 + .../themes/advanced/skins/o2k7/ui_silver.css | 5 + .../tinymce/themes/advanced/source_editor.htm | 25 + scripts/base/tinymce/tiny_mce.js | 1 + scripts/base/tinymce/tiny_mce_gzip.js | 137 + scripts/base/tinymce/tiny_mce_gzip.php | 329 + scripts/base/tinymce/tiny_mce_popup.js | 5 + .../base/tinymce/utils/editable_selects.js | 70 + scripts/base/tinymce/utils/form_utils.js | 210 + scripts/base/tinymce/utils/mctabs.js | 162 + scripts/base/tinymce/utils/validate.js | 252 + scripts/base/tooltip.js | 51 +- scripts/game/alliance.js | 75 - scripts/game/base.js | 205 +- scripts/game/battlesim.js | 22 +- scripts/game/buildlist.js | 9 +- scripts/{base => game}/filterlist.js | 2 +- scripts/game/fleetTable.js | 12 + scripts/game/fleettrader.js | 30 +- scripts/game/flotten.js | 202 +- scripts/game/galaxy.js | 17 +- scripts/game/gate.js | 17 +- scripts/game/login.js | 222 - scripts/game/message.js | 17 +- scripts/game/overview.actions.js | 31 + scripts/game/overview.js | 105 +- scripts/game/phalanx.js | 13 +- scripts/game/planetmenu.js | 40 - scripts/game/research.js | 11 +- scripts/game/search.js | 83 +- scripts/game/support.js | 8 - scripts/game/topnav.js | 18 +- scripts/game/trader.js | 8 +- scripts/game/update.js | 113 - scripts/game/vertify.js | 14 +- .../jquery.validationEngine-cz.js | 150 + .../jquery.validationEngine-da.js | 129 + .../jquery.validationEngine-de.js | 134 + .../jquery.validationEngine-en.js | 173 + .../jquery.validationEngine-es.js | 131 + .../jquery.validationEngine-et.js | 105 + .../jquery.validationEngine-fa.js | 175 + .../jquery.validationEngine-fi.js | 105 + .../jquery.validationEngine-fr.js | 123 + .../jquery.validationEngine-hr.js | 171 + .../jquery.validationEngine-it.js | 105 + .../jquery.validationEngine-ja.js | 143 + .../jquery.validationEngine-nl.js | 130 + .../jquery.validationEngine-pl.js | 134 + .../jquery.validationEngine-pt.js | 129 + .../jquery.validationEngine-pt_BR.js | 121 + .../jquery.validationEngine-ro.js | 172 + .../jquery.validationEngine-ru.js | 130 + .../jquery.validationEngine-sv.js | 147 + .../jquery.validationEngine-tr.js | 150 + .../jquery.validationEngine-zh_CN.js | 171 + .../jquery.validationEngine-zh_TW.js | 171 + scripts/login/main.js | 48 + scripts/login/register.js | 5 + styles/css/admin.css | 80 - .../images/ui-bg_flat_30_cccccc_40x100.png | Bin 180 -> 0 bytes .../images/ui-bg_flat_50_5c5c5c_40x100.png | Bin 180 -> 0 bytes .../images/ui-bg_glass_20_555555_1x400.png | Bin 115 -> 0 bytes .../images/ui-bg_glass_40_0078a3_1x400.png | Bin 179 -> 0 bytes .../images/ui-bg_glass_40_ffc73d_1x400.png | Bin 131 -> 0 bytes .../ui-bg_gloss-wave_25_333333_500x100.png | Bin 1874 -> 0 bytes .../ui-bg_highlight-soft_80_eeeeee_1x100.png | Bin 95 -> 0 bytes .../ui-bg_inset-soft_25_000000_1x100.png | Bin 98 -> 0 bytes .../ui-bg_inset-soft_30_f58400_1x100.png | Bin 117 -> 0 bytes styles/css/images/ui-icons_222222_256x240.png | Bin 4369 -> 0 bytes styles/css/images/ui-icons_cccccc_256x240.png | Bin 4369 -> 0 bytes styles/css/ingame.css | 384 - styles/images/abort.gif | Bin 842 -> 0 bytes styles/images/arrow.gif | Bin 82 -> 0 bytes styles/images/banner.jpg | Bin 19985 -> 0 bytes styles/images/buttons.gif | Bin 4140 -> 0 bytes styles/images/false.png | Bin 535 -> 0 bytes styles/images/index.htm | 0 styles/images/r1.png | Bin 466 -> 0 bytes styles/images/r2.png | Bin 729 -> 0 bytes styles/images/r3.png | Bin 269 -> 0 bytes styles/images/r4.png | Bin 691 -> 0 bytes styles/images/r5.png | Bin 576 -> 0 bytes styles/images/r6.png | Bin 942 -> 0 bytes styles/images/r7.png | Bin 651 -> 0 bytes styles/images/r8.png | Bin 319 -> 0 bytes styles/images/r9.png | Bin 842 -> 0 bytes styles/images/true.png | Bin 447 -> 0 bytes styles/resource/css/admin/main.css | 162 + styles/resource/css/base/boilerplate.css | 293 + styles/resource/css/base/images/asc.gif | Bin 0 -> 54 bytes styles/resource/css/base/images/bg.gif | Bin 0 -> 64 bytes styles/resource/css/base/images/desc.gif | Bin 0 -> 54 bytes .../ui-bg_diagonals-thick_15_0b3e6f_40x40.png | Bin 0 -> 260 bytes .../ui-bg_dots-medium_30_0b58a2_4x4.png | Bin 0 -> 98 bytes .../images/ui-bg_dots-small_20_333333_2x2.png | Bin 0 -> 83 bytes .../images/ui-bg_dots-small_30_a32d00_2x2.png | Bin 0 -> 84 bytes .../images/ui-bg_dots-small_40_00498f_2x2.png | Bin 0 -> 83 bytes .../images/ui-bg_flat_0_aaaaaa_40x100.png | Bin 0 -> 180 bytes .../images/ui-bg_flat_40_292929_40x100.png | Bin 0 -> 180 bytes .../ui-bg_gloss-wave_20_111111_500x100.png | Bin 0 -> 2103 bytes .../base/images/ui-icons_00498f_256x240.png} | Bin 4369 -> 4369 bytes .../base/images/ui-icons_98d2fb_256x240.png} | Bin 4369 -> 4369 bytes .../base/images/ui-icons_9ccdfc_256x240.png | Bin 0 -> 5355 bytes .../base}/images/ui-icons_ffffff_256x240.png | Bin styles/{css => resource/css/base}/jquery.css | 399 +- .../css/base}/jquery.fancybox.css | 66 +- .../css/base/validationEngine.jquery.css | 146 + styles/resource/css/ingame/main.css | 427 + styles/resource/css/install/main.css | 104 + .../login.css => resource/css/login/main.css} | 122 +- styles/resource/css/login/register.css | 88 + styles/{ => resource}/fonts/DroidSansMono.ttf | Bin .../fonts/Google Android License.txt | 0 .../Adm => resource/images/admin}/GO.png | Bin .../Adm => resource/images/admin}/UP.png | Bin .../images/admin}/arrowleft.png | Bin .../images/admin}/arrowright.png | Bin .../Adm => resource/images/admin}/blank.gif | Bin .../Adm => resource/images/admin}/c.gif | Bin .../Adm => resource/images/admin}/i.gif | Bin .../{css => resource/images/admin}/index.htm | 0 styles/resource/images/alliance/ADMIN.png | Bin 0 -> 1646 bytes styles/resource/images/alliance/CLOSE.png | Bin 0 -> 1049 bytes .../resource/images/alliance/DIPLOMATIC.png | Bin 0 -> 1759 bytes styles/resource/images/alliance/EVENTS.png | Bin 0 -> 1256 bytes styles/resource/images/alliance/KICK.png | Bin 0 -> 1889 bytes .../resource/images/alliance/MANAGEAPPLY.png | Bin 0 -> 1120 bytes .../resource/images/alliance/MANAGEUSERS.png | Bin 0 -> 1981 bytes .../resource/images/alliance/MEMBERLIST.png | Bin 0 -> 2088 bytes .../resource/images/alliance/ONLINESTATE.png | Bin 0 -> 1756 bytes styles/resource/images/alliance/RANKS.png | Bin 0 -> 2428 bytes styles/resource/images/alliance/ROUNDMAIL.png | Bin 0 -> 1321 bytes styles/resource/images/alliance/SEEAPPLY.png | Bin 0 -> 514 bytes styles/resource/images/alliance/TRANSFER.png | Bin 0 -> 1633 bytes styles/{ => resource}/images/banned.png | Bin styles/resource/images/banner.jpg | Bin 0 -> 23759 bytes .../images/facebook/fb-connect-large.png | Bin 0 -> 1012 bytes styles/resource/images/false.png | Bin 0 -> 932 bytes .../{ => resource}/images/fancybox/blank.gif | Bin .../images/fancybox/fancy_close.png | Bin .../images/fancybox/fancy_loading.png | Bin .../images/fancybox/fancy_nav_left.png | Bin .../images/fancybox/fancy_nav_right.png | Bin .../images/fancybox/fancy_shadow_e.png | Bin .../images/fancybox/fancy_shadow_n.png | Bin .../images/fancybox/fancy_shadow_ne.png | Bin .../images/fancybox/fancy_shadow_nw.png | Bin .../images/fancybox/fancy_shadow_s.png | Bin .../images/fancybox/fancy_shadow_se.png | Bin .../images/fancybox/fancy_shadow_sw.png | Bin .../images/fancybox/fancy_shadow_w.png | Bin .../images/fancybox/fancy_title_left.png | Bin .../images/fancybox/fancy_title_main.png | Bin .../images/fancybox/fancy_title_over.png | Bin .../images/fancybox/fancy_title_right.png | Bin .../images/fancybox/fancybox-x.png | Bin .../images/fancybox/fancybox-y.png | Bin .../images/fancybox/fancybox.png | Bin styles/resource/images/icons/closed.png | Bin 0 -> 603 bytes styles/resource/images/icons/open.png | Bin 0 -> 613 bytes .../{images/Adm => resource/images}/index.htm | 0 .../images/login/background.jpg} | Bin .../{ => resource}/images/login/flags/de.png | Bin .../{ => resource}/images/login/flags/es.png | Bin .../images/login/flags/flags.rar | Bin .../{ => resource}/images/login/flags/fr.png | Bin .../{ => resource}/images/login/flags/it.png | Bin styles/resource/images/login/flags/pl.png | Bin 0 -> 374 bytes .../{ => resource}/images/login/flags/pt.png | Bin .../{ => resource}/images/login/flags/ru.png | Bin .../{ => resource}/images/login/flags/si.png | Bin .../{ => resource}/images/login/flags/us.png | Bin .../images/login/header.png} | Bin .../images/login}/screens/ally.jpg | Bin .../images/login}/screens/build.jpg | Bin .../images/login}/screens/fleet.jpg | Bin .../images/login}/screens/galaxy.jpg | Bin .../images/login}/screens/imperium.jpg | Bin .../images/login}/screens/overview.jpg | Bin .../images/login/screens/thumbnails/ally.jpg} | Bin .../login/screens/thumbnails/build.jpg} | Bin .../login/screens/thumbnails/fleet.jpg} | Bin .../login/screens/thumbnails/galaxy.jpg} | Bin .../login/screens/thumbnails/imperium.jpg} | Bin .../login/screens/thumbnails/overview.jpg} | Bin styles/resource/images/true.png | Bin 0 -> 827 bytes styles/templates/CombatRaport.tpl | 189 - .../templates/adm/AccountDataPageDetail.tpl | 28 +- styles/templates/adm/AccountDataPageIntro.tpl | 4 +- .../adm/AccountEditorPageAlliance.tpl | 28 +- .../templates/adm/AccountEditorPageBuilds.tpl | 24 +- .../adm/AccountEditorPageDefenses.tpl | 24 +- .../templates/adm/AccountEditorPageMenu.tpl | 24 +- .../adm/AccountEditorPageOfficiers.tpl | 24 +- .../adm/AccountEditorPagePersonal.tpl | 30 +- .../adm/AccountEditorPagePlanets.tpl | 34 +- .../adm/AccountEditorPageResearch.tpl | 24 +- .../adm/AccountEditorPageResources.tpl | 28 +- .../templates/adm/AccountEditorPageShips.tpl | 24 +- styles/templates/adm/ActivePage.tpl | 36 +- styles/templates/adm/BanPage.tpl | 60 +- styles/templates/adm/ChatConfigBody.tpl | 27 +- styles/templates/adm/ConfigBasicBody.tpl | 100 +- styles/templates/adm/ConfigBodyUni.tpl | 126 +- styles/templates/adm/CreatePage.tpl | 10 +- styles/templates/adm/CreatePageMoon.tpl | 6 +- styles/templates/adm/CreatePagePlanet.tpl | 10 +- styles/templates/adm/CreatePageUser.tpl | 6 +- styles/templates/adm/CronjobDetail.tpl | 57 + styles/templates/adm/CronjobOverview.tpl | 40 + styles/templates/adm/DisclamerConfigBody.tpl | 29 + styles/templates/adm/DumpPage.tpl | 35 + styles/templates/adm/FacebookPage.tpl | 4 +- styles/templates/adm/FlyingFleetPage.tpl | 54 +- styles/templates/adm/LogDetail.tpl | 4 +- styles/templates/adm/LogList.tpl | 4 +- styles/templates/adm/LogOverview.tpl | 15 +- styles/templates/adm/LoginPage.tpl | 12 +- styles/templates/adm/MessageList.tpl | 146 +- styles/templates/adm/ModVersionPage.tpl | 4 +- .../templates/adm/ModerrationRightsPage.tpl | 4 +- .../adm/ModerrationRightsPostPage.tpl | 4 +- styles/templates/adm/ModerrationUsersPage.tpl | 4 +- styles/templates/adm/ModulePage.tpl | 4 +- styles/templates/adm/MultiIPs.tpl | 38 +- styles/templates/adm/NewsPage.tpl | 12 +- styles/templates/adm/OverviewBody.tpl | 203 +- styles/templates/adm/PassEncripterPage.tpl | 4 +- styles/templates/adm/QuickEditorPlanet.tpl | 42 +- styles/templates/adm/QuickEditorUser.tpl | 35 +- styles/templates/adm/ResetPage.tpl | 6 +- styles/templates/adm/SearchPage.tpl | 6 +- styles/templates/adm/SendMessagesPage.tpl | 20 +- styles/templates/adm/ShowInformationPage.tpl | 4 +- styles/templates/adm/ShowMenuPage.tpl | 77 +- styles/templates/adm/ShowTopnavPage.tpl | 16 +- styles/templates/adm/StatsPage.tpl | 10 +- styles/templates/adm/SupportPage.tpl | 82 - styles/templates/adm/TeamspeakPage.tpl | 8 +- styles/templates/adm/UniversePage.tpl | 48 +- styles/templates/adm/UpdatePage.tpl | 4 +- styles/templates/adm/VertifyPage.tpl | 22 +- styles/templates/adm/VertifyPageResult.tpl | 12 +- styles/templates/adm/error_message_body.tpl | 4 +- styles/templates/adm/giveaway.tpl | 98 + styles/templates/adm/overall_footer.tpl | 2 + styles/templates/adm/overall_header.tpl | 109 +- styles/templates/adm/page.ticket.create.tpl | 28 + styles/templates/adm/page.ticket.default.tpl | 50 + styles/templates/adm/page.ticket.view.tpl | 48 + styles/templates/alliance_admin.tpl | 112 - styles/templates/alliance_admin_diplo.tpl | 73 - .../templates/alliance_admin_diplo_form.tpl | 36 - styles/templates/alliance_admin_members.tpl | 51 - styles/templates/alliance_admin_ranks.tpl | 107 - styles/templates/alliance_admin_rename.tpl | 21 - styles/templates/alliance_admin_request.tpl | 57 - styles/templates/alliance_admin_transfer.tpl | 22 - styles/templates/alliance_ainfo.tpl | 87 - styles/templates/alliance_apply_waitform.tpl | 20 - styles/templates/alliance_applyform.tpl | 21 - styles/templates/alliance_circular.tpl | 46 - styles/templates/alliance_defaultmenu.tpl | 16 - styles/templates/alliance_frontpage.tpl | 110 - styles/templates/alliance_make.tpl | 25 - styles/templates/alliance_memberslist.tpl | 37 - styles/templates/alliance_searchform.tpl | 38 - styles/templates/banned_overview.tpl | 28 - styles/templates/battlesim.tpl | 71 - styles/templates/buddy_overview.tpl | 76 - styles/templates/buddy_send_form.tpl | 32 - styles/templates/buildings_overview.tpl | 126 - styles/templates/buildings_research.tpl | 134 - styles/templates/changelog_overview.tpl | 19 - styles/templates/chat_overview.tpl | 12 - styles/templates/empire_overview.tpl | 109 - styles/templates/error_message_body.tpl | 19 - styles/templates/faq_overview.tpl | 23 - styles/templates/fleet1_table.tpl | 146 - styles/templates/fleet2_table.tpl | 85 - styles/templates/fleet3_table.tpl | 53 - styles/templates/fleetACS_table.tpl | 41 - styles/templates/fleet_table.tpl | 136 - styles/templates/fleettrader_overview.tpl | 28 - styles/templates/galaxy_overview.tpl | 188 - {updates => styles/templates/game}/.htaccess | 0 styles/templates/game/error.default.tpl | 11 + styles/templates/game/layout.ajax.tpl | 1 + styles/templates/game/layout.full.tpl | 11 + styles/templates/game/layout.popup.tpl | 3 + .../main.footer.tpl} | 4 - styles/templates/game/main.header.tpl | 68 + styles/templates/game/main.navigation.tpl | 42 + styles/templates/game/main.topnav.tpl | 97 + .../game/page.alliance.admin.detailApply.tpl | 151 + .../page.alliance.admin.diplomacy.create.tpl | 59 + .../page.alliance.admin.diplomacy.default.tpl | 95 + .../game/page.alliance.admin.mangeApply.tpl | 25 + .../game/page.alliance.admin.members.tpl | 56 + .../game/page.alliance.admin.overview.tpl | 163 + .../game/page.alliance.admin.permissions.tpl | 70 + .../game/page.alliance.admin.rename.name.tpl | 17 + .../game/page.alliance.admin.rename.tag.tpl | 17 + .../game/page.alliance.admin.transfer.tpl | 18 + styles/templates/game/page.alliance.apply.tpl | 52 + .../game/page.alliance.applyWait.tpl | 16 + .../templates/game/page.alliance.circular.tpl | 50 + .../templates/game/page.alliance.create.tpl | 21 + .../game/page.alliance.createSelection.tpl | 12 + styles/templates/game/page.alliance.home.tpl | 132 + styles/templates/game/page.alliance.info.tpl | 91 + .../game/page.alliance.memberList.tpl | 49 + .../templates/game/page.alliance.search.tpl | 34 + .../templates/game/page.banList.default.tpl | 39 + .../game/page.battleSimulator.default.tpl | 112 + .../game/page.battlehall.default.tpl | 39 + .../templates/game/page.buddyList.default.tpl | 75 + .../templates/game/page.buddyList.request.tpl | 22 + .../templates/game/page.buildings.default.tpl | 149 + .../templates/game/page.changelog.default.tpl | 15 + styles/templates/game/page.chat.default.tpl | 4 + styles/templates/game/page.empire.default.tpl | 98 + .../game/page.fleetDealer.default.tpl | 37 + .../game/page.fleetStep1.default.tpl | 166 + .../game/page.fleetStep2.default.tpl | 75 + .../game/page.fleetStep3.default.tpl | 49 + .../game/page.fleetTable.default.tpl | 129 + styles/templates/game/page.galaxy.default.tpl | 197 + .../game/page.infomation.default.tpl | 52 + .../page.logout.default.tpl} | 16 +- .../templates/game/page.messages.default.tpl | 33 + styles/templates/game/page.messages.view.tpl | 76 + styles/templates/game/page.messages.write.tpl | 38 + styles/templates/game/page.notes.default.tpl | 44 + styles/templates/game/page.notes.detail.tpl | 36 + .../templates/game/page.officier.default.tpl | 104 + .../templates/game/page.overview.actions.tpl | 17 + .../templates/game/page.overview.default.tpl | 110 + .../templates/game/page.phalanx.default.tpl | 19 + .../game/page.playerCard.default.tpl | 105 + .../templates/game/page.questions.default.tpl | 38 + .../templates/game/page.questions.single.tpl | 18 + .../templates/game/page.records.default.tpl | 78 + .../templates/game/page.research.default.tpl | 114 + .../templates/game/page.resources.default.tpl | 75 + styles/templates/game/page.search.default.tpl | 15 + .../game/page.search.result.ally.tpl | 18 + .../game/page.search.result.default.tpl | 22 + .../templates/game/page.settings.default.tpl | 140 + .../templates/game/page.settings.vacation.tpl | 20 + .../templates/game/page.shipyard.default.tpl | 94 + .../game/page.statistics.default.tpl | 24 + .../templates/game/page.techtree.default.tpl | 25 + styles/templates/game/page.ticket.create.tpl | 36 + styles/templates/game/page.ticket.default.tpl | 27 + styles/templates/game/page.ticket.view.tpl | 50 + styles/templates/game/page.trader.default.tpl | 58 + styles/templates/game/page.trader.trade.tpl | 41 + .../game/shared.fleetTable.acsTable.tpl | 48 + .../game/shared.information.gate.tpl | 42 + .../game/shared.information.missiles.tpl | 14 + .../game/shared.information.production.tpl | 35 + .../game/shared.information.shipInfo.tpl | 40 + .../game/shared.information.storage.tpl | 37 + .../templates/game/shared.mission.raport.tpl | 187 + .../game/shared.mission.spyraport.tpl | 21 + .../game/shared.statistics.allianceTable.tpl | 16 + .../game/shared.statistics.playerTable.tpl | 16 + styles/templates/index/index.tpl | 142 - styles/templates/index/index_disclamer.tpl | 11 - styles/templates/index/index_error.tpl | 3 - styles/templates/index/index_main.tpl | 105 - styles/templates/index/index_news.tpl | 12 - styles/templates/index/index_pranger.tpl | 27 - styles/templates/index/index_rules.tpl | 5 - styles/templates/index/index_screens.tpl | 47 - styles/templates/index/index_top100.tpl | 32 - styles/templates/info_gatelist.tpl | 31 - styles/templates/info_overview.tpl | 74 - .../templates/install/error_message_body.tpl | 6 +- styles/templates/install/ins_acc.tpl | 47 +- styles/templates/install/ins_convert.tpl | 4 +- styles/templates/install/ins_doupdate.tpl | 13 + styles/templates/install/ins_form.tpl | 67 +- styles/templates/install/ins_header.tpl | 75 +- styles/templates/install/ins_intro.tpl | 28 +- styles/templates/install/ins_license.tpl | 40 +- styles/templates/install/ins_req.tpl | 59 +- styles/templates/install/ins_step4.tpl | 18 + styles/templates/install/ins_step5.tpl | 13 + styles/templates/install/ins_step8.tpl | 15 + styles/templates/install/ins_step8error.tpl | 12 + styles/templates/install/ins_update.tpl | 18 + styles/templates/install/ins_upgrade.tpl | 24 + styles/templates/left_menu.tpl | 41 - styles/templates/login/error.default.tpl | 8 + .../login/info.redirectPost.tpl.tpl.txt | 9 + styles/templates/login/layout.ajax.tpl | 1 + styles/templates/login/layout.light.tpl | 4 + styles/templates/login/layout.normal.tpl | 42 + styles/templates/login/layout.popup.tpl | 3 + styles/templates/login/main.footer.tpl | 22 + styles/templates/login/main.header.tpl | 32 + styles/templates/login/main.navigation.tpl | 22 + .../templates/login/page.banList.default.tpl | 44 + .../login/page.battleHall.default.tpl | 33 + .../login/page.disclamer.default.tpl | 23 + styles/templates/login/page.index.default.tpl | 80 + .../login/page.lostPassword.default.tpl | 52 + styles/templates/login/page.news.default.tpl | 11 + .../templates/login/page.register.default.tpl | 117 + styles/templates/login/page.rules.default.tpl | 4 + .../templates/login/page.screens.default.tpl | 21 + styles/templates/message_list.tpl | 45 - styles/templates/message_overview.tpl | 32 - styles/templates/message_send_form.tpl | 36 - styles/templates/notes_body.tpl | 38 - styles/templates/notes_edit_form.tpl | 37 - styles/templates/notes_send_form.tpl | 38 - styles/templates/officier_overview.tpl | 85 - styles/templates/options_overview.tpl | 116 - styles/templates/options_overview_vmode.tpl | 24 - styles/templates/overall_header.tpl | 49 - styles/templates/overall_topnav.tpl | 77 - styles/templates/overview_body.tpl | 122 - styles/templates/phalax_body.tpl | 23 - styles/templates/planet_menu.tpl | 28 - styles/templates/playercard_overview.tpl | 104 - styles/templates/records_overview.tpl | 26 - styles/templates/resources_overview.tpl | 74 - styles/templates/search_body.tpl | 26 - styles/templates/shipyard_defense.tpl | 99 - styles/templates/shipyard_fleet.tpl | 100 - styles/templates/stat_alliancetable.tpl | 16 - styles/templates/stat_overview.tpl | 24 - styles/templates/stat_playertable.tpl | 16 - styles/templates/support_overview.tpl | 77 - styles/templates/techtree_overview.tpl | 32 - styles/templates/topkb_overview.tpl | 41 - styles/templates/trader_overview.tpl | 43 - styles/templates/trader_trade.tpl | 38 - styles/theme/gow/formate.css | 157 +- styles/theme/gow/gebaeude/221.gif | Bin 15916 -> 0 bytes styles/theme/gow/gebaeude/222.gif | Bin 8757 -> 0 bytes styles/theme/gow/gebaeude/223.gif | Bin 19815 -> 0 bytes styles/theme/gow/gebaeude/224.gif | Bin 9374 -> 0 bytes styles/theme/gow/gebaeude/225.gif | Bin 11620 -> 0 bytes styles/theme/gow/gebaeude/226.gif | Bin 10574 -> 0 bytes styles/theme/gow/gebaeude/227.gif | Bin 11531 -> 0 bytes styles/theme/gow/gebaeude/228.gif | Bin 13015 -> 0 bytes styles/theme/gow/gebaeude/602.jpg | Bin 5723 -> 6495 bytes styles/theme/gow/gebaeude/700.gif | Bin 12207 -> 0 bytes styles/theme/gow/gebaeude/701.gif | Bin 14637 -> 12207 bytes styles/theme/gow/gebaeude/702.gif | Bin 14281 -> 14637 bytes styles/theme/gow/gebaeude/703.gif | Bin 12772 -> 14281 bytes styles/theme/gow/gebaeude/704.gif | Bin 17275 -> 12772 bytes styles/theme/gow/gebaeude/705.gif | Bin 11338 -> 17275 bytes styles/theme/gow/gebaeude/706.gif | Bin 12510 -> 11338 bytes styles/theme/gow/gebaeude/707.gif | Bin 0 -> 12510 bytes .../gow/images/{kristall.gif => crystal.gif} | Bin .../gow/images/{energie.gif => energy.gif} | Bin .../gow/images/{metall.gif => metal.gif} | Bin styles/theme/gow/img/bkd_bg.png | Bin 0 -> 408 bytes styles/theme/gow/img/bkd_page.jpg | Bin 187676 -> 993761 bytes styles/theme/gow/img/bkd_title.png | Bin 528 -> 210 bytes styles/theme/gow/img/m.gif | Bin 1122 -> 338 bytes styles/theme/gow/img/menu-item-bg.png | Bin 0 -> 129 bytes styles/theme/gow/img/menu_acc.png | Bin 1989 -> 1873 bytes styles/theme/gow/img/menu_com.png | Bin 2225 -> 2114 bytes styles/theme/gow/img/menu_wirt.png | Bin 2245 -> 2040 bytes styles/theme/gow/img/processbar.gif | Bin 0 -> 186 bytes styles/theme/gow/img/processbar.png | Bin 253 -> 0 bytes styles/theme/gow/settings.cfg | 9 + userpic.php | 48 +- 1334 files changed, 103537 insertions(+), 61114 deletions(-) delete mode 100644 ajax.php delete mode 100644 chat/css/Cobalt.css delete mode 100644 chat/css/Core.css delete mode 100644 chat/css/Lithium.css delete mode 100644 chat/css/Mercury.css delete mode 100644 chat/css/MyBB.css delete mode 100644 chat/css/Oxygen.css delete mode 100644 chat/css/Radium.css delete mode 100644 chat/css/Sulfur.css delete mode 100644 chat/css/beige.css delete mode 100644 chat/css/black.css delete mode 100644 chat/css/grey.css delete mode 100644 chat/css/prosilver.css delete mode 100644 chat/css/subSilver.css delete mode 100644 chat/css/subblack2.css delete mode 100644 chat/css/subsilver2.css delete mode 100644 chat/css/vBulletin.css create mode 100644 cronjob.php delete mode 100644 cronjobs.php rename language/pt/extra/rules.txt => includes/FIRST_INSTALL (100%) delete mode 100644 includes/bcmath.php create mode 100644 includes/classes/ArrayUtil.class.php create mode 100644 includes/classes/Config.class.php create mode 100644 includes/classes/Cronjob.class.php create mode 100644 includes/classes/HTTP.class.php create mode 100644 includes/classes/HTTPRequest.class.php create mode 100644 includes/classes/Language.class.php create mode 100644 includes/classes/Mail.class.php create mode 100644 includes/classes/PlayerUtil.class.php create mode 100644 includes/classes/SQLDumper.class.php create mode 100644 includes/classes/cache/builder/BannedBuildCache.class.php create mode 100644 includes/classes/cache/builder/LanguageBuildCache.class.php create mode 100644 includes/classes/cache/builder/TeamspeakBuildCache.class.php create mode 100644 includes/classes/cache/builder/VarsBuildCache.class.php create mode 100644 includes/classes/cache/ressource/CacheFile.class.php create mode 100644 includes/classes/class.BuildFunctions.php create mode 100644 includes/classes/class.Cache.php rename includes/classes/{class.MySQLi.php => class.Database.php} (79%) delete mode 100644 includes/classes/class.Lang.php delete mode 100644 includes/classes/class.Records.php create mode 100644 includes/classes/class.SupportTickets.php delete mode 100644 includes/classes/class.phpmailer.php delete mode 100644 includes/classes/class.smtp.php create mode 100644 includes/classes/cronjob/CleanerCronjob.class.php create mode 100644 includes/classes/cronjob/DailyCronjob.class.php create mode 100644 includes/classes/cronjob/DumpCronjob.class.php create mode 100644 includes/classes/cronjob/InactiveMailCronjob.class.php create mode 100644 includes/classes/cronjob/ReferralCronjob.class.php rename includes/{pages/ShowFAQ.php => classes/cronjob/StatisticCronjob.class.php} (57%) rename includes/{pages/ShowLogoutPage.php => classes/cronjob/TeamSpeakCronjob.class.php} (55%) create mode 100644 includes/classes/cronjob/TrackingCronjob.class.php create mode 100644 includes/dbtables.php create mode 100644 includes/extauth/facebook.class.php create mode 100644 includes/extauth/openid.class.php delete mode 100644 includes/functions/GetBuildingPrice.php delete mode 100644 includes/functions/GetBuildingTime.php delete mode 100644 includes/functions/GetElementPrice.php delete mode 100644 includes/functions/IsElementBuyable.php delete mode 100644 includes/functions/IsTechnologieAccessible.php delete mode 100644 includes/functions/mvc/mvc_2Moons.php delete mode 100644 includes/libs/FirePHP/FirePHP.class.php delete mode 100644 includes/libs/FirePHP/fb.php create mode 100644 includes/libs/OpenID/openid.php delete mode 100644 includes/libs/Smarty/debug.tpl delete mode 100644 includes/libs/Smarty/plugins/block.lang.php create mode 100644 includes/libs/Smarty/plugins/modifiercompiler.json.php create mode 100644 includes/libs/Smarty/plugins/modifiercompiler.number.php create mode 100644 includes/libs/Smarty/plugins/modifiercompiler.time.php create mode 100644 includes/libs/facebook/base_facebook.php create mode 100644 includes/libs/swift/classes/Swift.php create mode 100644 includes/libs/swift/classes/Swift/Attachment.php create mode 100644 includes/libs/swift/classes/Swift/ByteStream/AbstractFilterableInputStream.php create mode 100644 includes/libs/swift/classes/Swift/ByteStream/ArrayByteStream.php create mode 100644 includes/libs/swift/classes/Swift/ByteStream/FileByteStream.php create mode 100644 includes/libs/swift/classes/Swift/CharacterReader.php create mode 100644 includes/libs/swift/classes/Swift/CharacterReader/GenericFixedWidthReader.php create mode 100644 includes/libs/swift/classes/Swift/CharacterReader/UsAsciiReader.php create mode 100644 includes/libs/swift/classes/Swift/CharacterReader/Utf8Reader.php create mode 100644 includes/libs/swift/classes/Swift/CharacterReaderFactory.php create mode 100644 includes/libs/swift/classes/Swift/CharacterReaderFactory/SimpleCharacterReaderFactory.php create mode 100644 includes/libs/swift/classes/Swift/CharacterStream.php create mode 100644 includes/libs/swift/classes/Swift/CharacterStream/ArrayCharacterStream.php create mode 100644 includes/libs/swift/classes/Swift/CharacterStream/NgCharacterStream.php create mode 100644 includes/libs/swift/classes/Swift/ConfigurableSpool.php create mode 100644 includes/libs/swift/classes/Swift/DependencyContainer.php create mode 100644 includes/libs/swift/classes/Swift/DependencyException.php create mode 100644 includes/libs/swift/classes/Swift/EmbeddedFile.php create mode 100644 includes/libs/swift/classes/Swift/Encoder.php create mode 100644 includes/libs/swift/classes/Swift/Encoder/Base64Encoder.php create mode 100644 includes/libs/swift/classes/Swift/Encoder/QpEncoder.php create mode 100644 includes/libs/swift/classes/Swift/Encoder/Rfc2231Encoder.php create mode 100644 includes/libs/swift/classes/Swift/Encoding.php create mode 100644 includes/libs/swift/classes/Swift/Events/CommandEvent.php create mode 100644 includes/libs/swift/classes/Swift/Events/CommandListener.php create mode 100644 includes/libs/swift/classes/Swift/Events/Event.php create mode 100644 includes/libs/swift/classes/Swift/Events/EventDispatcher.php create mode 100644 includes/libs/swift/classes/Swift/Events/EventListener.php create mode 100644 includes/libs/swift/classes/Swift/Events/EventObject.php create mode 100644 includes/libs/swift/classes/Swift/Events/ResponseEvent.php create mode 100644 includes/libs/swift/classes/Swift/Events/ResponseListener.php create mode 100644 includes/libs/swift/classes/Swift/Events/SendEvent.php create mode 100644 includes/libs/swift/classes/Swift/Events/SendListener.php create mode 100644 includes/libs/swift/classes/Swift/Events/SimpleEventDispatcher.php create mode 100644 includes/libs/swift/classes/Swift/Events/TransportChangeEvent.php create mode 100644 includes/libs/swift/classes/Swift/Events/TransportChangeListener.php create mode 100644 includes/libs/swift/classes/Swift/Events/TransportExceptionEvent.php create mode 100644 includes/libs/swift/classes/Swift/Events/TransportExceptionListener.php create mode 100644 includes/libs/swift/classes/Swift/FailoverTransport.php create mode 100644 includes/libs/swift/classes/Swift/FileSpool.php create mode 100644 includes/libs/swift/classes/Swift/FileStream.php create mode 100644 includes/libs/swift/classes/Swift/Filterable.php create mode 100644 includes/libs/swift/classes/Swift/Image.php create mode 100644 includes/libs/swift/classes/Swift/InputByteStream.php create mode 100644 includes/libs/swift/classes/Swift/IoException.php create mode 100644 includes/libs/swift/classes/Swift/KeyCache.php create mode 100644 includes/libs/swift/classes/Swift/KeyCache/ArrayKeyCache.php create mode 100644 includes/libs/swift/classes/Swift/KeyCache/DiskKeyCache.php create mode 100644 includes/libs/swift/classes/Swift/KeyCache/DummyKeyCache.php create mode 100644 includes/libs/swift/classes/Swift/KeyCache/KeyCacheInputStream.php create mode 100644 includes/libs/swift/classes/Swift/KeyCache/NullKeyCache.php create mode 100644 includes/libs/swift/classes/Swift/KeyCache/SimpleKeyCacheInputStream.php create mode 100644 includes/libs/swift/classes/Swift/LoadBalancedTransport.php create mode 100644 includes/libs/swift/classes/Swift/MailTransport.php create mode 100644 includes/libs/swift/classes/Swift/Mailer.php create mode 100644 includes/libs/swift/classes/Swift/Mailer/ArrayRecipientIterator.php create mode 100644 includes/libs/swift/classes/Swift/Mailer/RecipientIterator.php create mode 100644 includes/libs/swift/classes/Swift/MemorySpool.php create mode 100644 includes/libs/swift/classes/Swift/Message.php create mode 100644 includes/libs/swift/classes/Swift/Mime/Attachment.php create mode 100644 includes/libs/swift/classes/Swift/Mime/CharsetObserver.php create mode 100644 includes/libs/swift/classes/Swift/Mime/ContentEncoder.php create mode 100644 includes/libs/swift/classes/Swift/Mime/ContentEncoder/Base64ContentEncoder.php create mode 100644 includes/libs/swift/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php create mode 100644 includes/libs/swift/classes/Swift/Mime/ContentEncoder/PlainContentEncoder.php create mode 100644 includes/libs/swift/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php create mode 100644 includes/libs/swift/classes/Swift/Mime/EmbeddedFile.php create mode 100644 includes/libs/swift/classes/Swift/Mime/EncodingObserver.php create mode 100644 includes/libs/swift/classes/Swift/Mime/Grammar.php create mode 100644 includes/libs/swift/classes/Swift/Mime/Header.php create mode 100644 includes/libs/swift/classes/Swift/Mime/HeaderEncoder.php create mode 100644 includes/libs/swift/classes/Swift/Mime/HeaderEncoder/Base64HeaderEncoder.php create mode 100644 includes/libs/swift/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php create mode 100644 includes/libs/swift/classes/Swift/Mime/HeaderFactory.php create mode 100644 includes/libs/swift/classes/Swift/Mime/HeaderSet.php create mode 100644 includes/libs/swift/classes/Swift/Mime/Headers/AbstractHeader.php create mode 100644 includes/libs/swift/classes/Swift/Mime/Headers/DateHeader.php create mode 100644 includes/libs/swift/classes/Swift/Mime/Headers/IdentificationHeader.php create mode 100644 includes/libs/swift/classes/Swift/Mime/Headers/MailboxHeader.php create mode 100644 includes/libs/swift/classes/Swift/Mime/Headers/ParameterizedHeader.php create mode 100644 includes/libs/swift/classes/Swift/Mime/Headers/PathHeader.php create mode 100644 includes/libs/swift/classes/Swift/Mime/Headers/UnstructuredHeader.php create mode 100644 includes/libs/swift/classes/Swift/Mime/Message.php create mode 100644 includes/libs/swift/classes/Swift/Mime/MimeEntity.php create mode 100644 includes/libs/swift/classes/Swift/Mime/MimePart.php create mode 100644 includes/libs/swift/classes/Swift/Mime/ParameterizedHeader.php create mode 100644 includes/libs/swift/classes/Swift/Mime/SimpleHeaderFactory.php create mode 100644 includes/libs/swift/classes/Swift/Mime/SimpleHeaderSet.php create mode 100644 includes/libs/swift/classes/Swift/Mime/SimpleMessage.php create mode 100644 includes/libs/swift/classes/Swift/Mime/SimpleMimeEntity.php create mode 100644 includes/libs/swift/classes/Swift/MimePart.php create mode 100644 includes/libs/swift/classes/Swift/NullTransport.php create mode 100644 includes/libs/swift/classes/Swift/OutputByteStream.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/AntiFloodPlugin.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/BandwidthMonitorPlugin.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/Decorator/Replacements.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/DecoratorPlugin.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/ImpersonatePlugin.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/Logger.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/LoggerPlugin.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/Loggers/ArrayLogger.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/Loggers/EchoLogger.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/MessageLogger.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/Pop/Pop3Connection.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/Pop/Pop3Exception.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/PopBeforeSmtpPlugin.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/RedirectingPlugin.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/Reporter.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/ReporterPlugin.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/Reporters/HitReporter.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/Reporters/HtmlReporter.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/Sleeper.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/ThrottlerPlugin.php create mode 100644 includes/libs/swift/classes/Swift/Plugins/Timer.php create mode 100644 includes/libs/swift/classes/Swift/Preferences.php create mode 100644 includes/libs/swift/classes/Swift/ReplacementFilterFactory.php create mode 100644 includes/libs/swift/classes/Swift/RfcComplianceException.php create mode 100644 includes/libs/swift/classes/Swift/SendmailTransport.php create mode 100644 includes/libs/swift/classes/Swift/SmtpTransport.php create mode 100644 includes/libs/swift/classes/Swift/Spool.php create mode 100644 includes/libs/swift/classes/Swift/SpoolTransport.php create mode 100644 includes/libs/swift/classes/Swift/StreamFilter.php create mode 100644 includes/libs/swift/classes/Swift/StreamFilters/ByteArrayReplacementFilter.php create mode 100644 includes/libs/swift/classes/Swift/StreamFilters/StringReplacementFilter.php create mode 100644 includes/libs/swift/classes/Swift/StreamFilters/StringReplacementFilterFactory.php create mode 100644 includes/libs/swift/classes/Swift/SwiftException.php create mode 100644 includes/libs/swift/classes/Swift/Transport.php create mode 100644 includes/libs/swift/classes/Swift/Transport/AbstractSmtpTransport.php create mode 100644 includes/libs/swift/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php create mode 100644 includes/libs/swift/classes/Swift/Transport/Esmtp/Auth/LoginAuthenticator.php create mode 100644 includes/libs/swift/classes/Swift/Transport/Esmtp/Auth/PlainAuthenticator.php create mode 100644 includes/libs/swift/classes/Swift/Transport/Esmtp/AuthHandler.php create mode 100644 includes/libs/swift/classes/Swift/Transport/Esmtp/Authenticator.php create mode 100644 includes/libs/swift/classes/Swift/Transport/EsmtpHandler.php create mode 100644 includes/libs/swift/classes/Swift/Transport/EsmtpTransport.php create mode 100644 includes/libs/swift/classes/Swift/Transport/FailoverTransport.php create mode 100644 includes/libs/swift/classes/Swift/Transport/IoBuffer.php create mode 100644 includes/libs/swift/classes/Swift/Transport/LoadBalancedTransport.php create mode 100644 includes/libs/swift/classes/Swift/Transport/MailInvoker.php create mode 100644 includes/libs/swift/classes/Swift/Transport/MailTransport.php create mode 100644 includes/libs/swift/classes/Swift/Transport/NullTransport.php create mode 100644 includes/libs/swift/classes/Swift/Transport/SendmailTransport.php create mode 100644 includes/libs/swift/classes/Swift/Transport/SimpleMailInvoker.php create mode 100644 includes/libs/swift/classes/Swift/Transport/SmtpAgent.php create mode 100644 includes/libs/swift/classes/Swift/Transport/SpoolTransport.php create mode 100644 includes/libs/swift/classes/Swift/Transport/StreamBuffer.php create mode 100644 includes/libs/swift/classes/Swift/TransportException.php create mode 100644 includes/libs/swift/classes/Swift/Validate.php create mode 100644 includes/libs/swift/dependency_maps/cache_deps.php create mode 100644 includes/libs/swift/dependency_maps/message_deps.php create mode 100644 includes/libs/swift/dependency_maps/mime_deps.php create mode 100644 includes/libs/swift/dependency_maps/transport_deps.php create mode 100644 includes/libs/swift/mime_types.php create mode 100644 includes/libs/swift/preferences.php create mode 100644 includes/libs/swift/swift_init.php create mode 100644 includes/libs/swift/swift_required.php create mode 100644 includes/libs/swift/swift_required_pear.php create mode 100644 includes/libs/tdcron/class.tdcron.entry.php create mode 100644 includes/libs/tdcron/class.tdcron.php delete mode 100644 includes/pages/ShowBannedPage.php delete mode 100644 includes/pages/ShowBattleSimPage.php delete mode 100644 includes/pages/ShowBuddyPage.php delete mode 100644 includes/pages/ShowFleetTraderPage.php delete mode 100644 includes/pages/ShowImperiumPage.php delete mode 100644 includes/pages/ShowOverviewPage.php delete mode 100644 includes/pages/ShowPhalanxPage.php delete mode 100644 includes/pages/ShowPlayerCard.php delete mode 100644 includes/pages/ShowRecordsPage.php delete mode 100644 includes/pages/ShowResourcesPage.php delete mode 100644 includes/pages/ShowSearchPage.php delete mode 100644 includes/pages/ShowStatisticsPage.php delete mode 100644 includes/pages/ShowSupportPage.php delete mode 100644 includes/pages/ShowTechTreePage.php delete mode 100644 includes/pages/ShowTopKB.php delete mode 100644 includes/pages/ShowTraderPage.php create mode 100644 includes/pages/adm/ShowAutoCompletePage.php create mode 100644 includes/pages/adm/ShowCronjobPage.php create mode 100644 includes/pages/adm/ShowDisclamerPage.php create mode 100644 includes/pages/adm/ShowDumpPage.php create mode 100644 includes/pages/adm/ShowGiveawayPage.php create mode 100644 includes/pages/adm/ShowLogoutPage.php delete mode 100644 includes/pages/adm/ShowModVersionPage.php delete mode 100644 includes/pages/class.ShowAlliancePage.php delete mode 100644 includes/pages/class.ShowBuildingsPage.php delete mode 100644 includes/pages/class.ShowFleetPages.php delete mode 100644 includes/pages/class.ShowGalaxyPage.php delete mode 100644 includes/pages/class.ShowInfosPage.php delete mode 100644 includes/pages/class.ShowMessagesPage.php delete mode 100644 includes/pages/class.ShowNotesPage.php delete mode 100644 includes/pages/class.ShowOfficierPage.php delete mode 100644 includes/pages/class.ShowOptionsPage.php delete mode 100644 includes/pages/class.ShowResearchPage.php delete mode 100644 includes/pages/class.ShowShipyardPage.php create mode 100644 includes/pages/game/class.AbstractPage.php create mode 100644 includes/pages/game/class.ShowAlliancePage.php create mode 100644 includes/pages/game/class.ShowBanListPage.php create mode 100644 includes/pages/game/class.ShowBattleHallPage.php create mode 100644 includes/pages/game/class.ShowBattleSimulatorPage.php create mode 100644 includes/pages/game/class.ShowBoardPage.php create mode 100644 includes/pages/game/class.ShowBuddyListPage.php create mode 100644 includes/pages/game/class.ShowBuildingsPage.php create mode 100644 includes/pages/game/class.ShowChangelogPage.php create mode 100644 includes/pages/game/class.ShowChatPage.php create mode 100644 includes/pages/game/class.ShowErrorPage.php create mode 100644 includes/pages/game/class.ShowFleetAjaxPage.php create mode 100644 includes/pages/game/class.ShowFleetDealerPage.php create mode 100644 includes/pages/game/class.ShowFleetMissilePage.php create mode 100644 includes/pages/game/class.ShowFleetStep1Page.php create mode 100644 includes/pages/game/class.ShowFleetStep2Page.php create mode 100644 includes/pages/game/class.ShowFleetStep3Page.php create mode 100644 includes/pages/game/class.ShowFleetTablePage.php create mode 100644 includes/pages/game/class.ShowGalaxyPage.php create mode 100644 includes/pages/game/class.ShowImperiumPage.php create mode 100644 includes/pages/game/class.ShowInformationPage.php create mode 100644 includes/pages/game/class.ShowLogoutPage.php create mode 100644 includes/pages/game/class.ShowMessagesPage.php create mode 100644 includes/pages/game/class.ShowNotesPage.php create mode 100644 includes/pages/game/class.ShowOfficierPage.php create mode 100644 includes/pages/game/class.ShowOverviewPage.php create mode 100644 includes/pages/game/class.ShowPhalanxPage.php create mode 100644 includes/pages/game/class.ShowPlayerCardPage.php create mode 100644 includes/pages/game/class.ShowQuestionsPage.php create mode 100644 includes/pages/game/class.ShowRaportPage.php create mode 100644 includes/pages/game/class.ShowRecordsPage.php create mode 100644 includes/pages/game/class.ShowResearchPage.php create mode 100644 includes/pages/game/class.ShowResourcesPage.php create mode 100644 includes/pages/game/class.ShowSearchPage.php create mode 100644 includes/pages/game/class.ShowSettingsPage.php create mode 100644 includes/pages/game/class.ShowShipyardPage.php create mode 100644 includes/pages/game/class.ShowStatisticsPage.php create mode 100644 includes/pages/game/class.ShowTechtreePage.php create mode 100644 includes/pages/game/class.ShowTicketPage.php create mode 100644 includes/pages/game/class.ShowTraderPage.php create mode 100644 includes/pages/login/AbstractPage.class.php create mode 100644 includes/pages/login/ShowBanListPage.class.php create mode 100644 includes/pages/login/ShowBattleHallPage.class.php create mode 100644 includes/pages/login/ShowBoardPage.class.php rename includes/pages/{ShowChangelogPage.php => login/ShowDisclamerPage.class.php} (51%) create mode 100644 includes/pages/login/ShowErrorPage.class.php create mode 100644 includes/pages/login/ShowExternalAuthPage.class.php create mode 100644 includes/pages/login/ShowIndexPage.class.php create mode 100644 includes/pages/login/ShowLoginPage.class.php create mode 100644 includes/pages/login/ShowLostPasswordPage.class.php create mode 100644 includes/pages/login/ShowNewsPage.class.php create mode 100644 includes/pages/login/ShowRegisterPage.class.php create mode 100644 includes/pages/login/ShowRulesPage.class.php create mode 100644 includes/pages/login/ShowScreensPage.class.php create mode 100644 includes/pages/login/ShowVertifyPage.class.php delete mode 100644 includes/update.php create mode 100644 install/VERSION rename {styles/templates => install/updates}/.htaccess (100%) rename {updates => install/updates}/update_1006.sql (100%) rename {updates => install/updates}/update_1041.sql (100%) rename {updates => install/updates}/update_1057.sql (100%) rename {updates => install/updates}/update_1066.sql (100%) rename {updates => install/updates}/update_1097.sql (100%) rename {updates => install/updates}/update_1131.sql (100%) rename {updates => install/updates}/update_1192.sql (100%) rename {updates => install/updates}/update_1231.php (99%) rename {updates => install/updates}/update_1231.sql (100%) rename {updates => install/updates}/update_1235.sql (100%) rename {updates => install/updates}/update_1242.sql (100%) rename {updates => install/updates}/update_1290.sql (100%) rename {updates => install/updates}/update_1330.sql (100%) rename {updates => install/updates}/update_1341.sql (100%) rename {updates => install/updates}/update_1359.sql (100%) rename {updates => install/updates}/update_1366.sql (100%) rename {updates => install/updates}/update_1416.sql (100%) rename {updates => install/updates}/update_1443.sql (100%) rename {updates => install/updates}/update_1493.sql (96%) rename {updates => install/updates}/update_1497.sql (100%) rename {updates => install/updates}/update_1512.sql (100%) rename {updates => install/updates}/update_1520.sql (100%) rename {updates => install/updates}/update_1534.sql (100%) rename {updates => install/updates}/update_1539.sql (58%) rename {updates => install/updates}/update_1540.sql (100%) rename {updates => install/updates}/update_1544.sql (100%) rename {updates => install/updates}/update_1551.sql (100%) rename {updates => install/updates}/update_1554.sql (100%) rename {updates => install/updates}/update_1559.sql (100%) rename {updates => install/updates}/update_1568.sql (100%) rename {updates => install/updates}/update_1576.sql (100%) rename {updates => install/updates}/update_1600.sql (100%) rename {updates => install/updates}/update_1611.sql (100%) rename {updates => install/updates}/update_1624.sql (100%) rename {updates => install/updates}/update_1634.sql (100%) rename {updates => install/updates}/update_1657.sql (100%) rename {updates => install/updates}/update_1683.sql (100%) rename {updates => install/updates}/update_1689.sql (100%) rename {updates => install/updates}/update_1698.sql (100%) rename {updates => install/updates}/update_1721.sql (100%) rename {updates => install/updates}/update_1728.sql (100%) rename {updates => install/updates}/update_1737.sql (100%) rename {updates => install/updates}/update_1753.sql (100%) rename {updates => install/updates}/update_1782.sql (100%) rename {updates => install/updates}/update_1802.sql (100%) rename {updates => install/updates}/update_1811.php (99%) rename {updates => install/updates}/update_1820.sql (100%) rename {updates => install/updates}/update_1843.sql (100%) rename {updates => install/updates}/update_1850.sql (100%) rename {updates => install/updates}/update_1881.sql (100%) rename {updates => install/updates}/update_1894.sql (100%) rename {updates => install/updates}/update_1902.sql (100%) rename {updates => install/updates}/update_1962.sql (100%) rename {updates => install/updates}/update_1968.sql (100%) rename {updates => install/updates}/update_1979.sql (100%) rename {updates => install/updates}/update_1982.sql (100%) rename {updates => install/updates}/update_1993.sql (100%) rename {updates => install/updates}/update_2001.sql (100%) rename {updates => install/updates}/update_2003.sql (100%) rename {updates => install/updates}/update_2017.sql (100%) rename {updates => install/updates}/update_2025.sql (100%) create mode 100644 install/updates/update_2080.php create mode 100644 install/updates/update_2099.sql create mode 100644 install/updates/update_2105.sql create mode 100644 install/updates/update_2126.sql create mode 100644 install/updates/update_2246.sql create mode 100644 install/updates/update_2290.sql create mode 100644 install/updates/update_2296.sql create mode 100644 install/updates/update_2306.sql create mode 100644 install/updates/update_2327.sql create mode 100644 install/updates/update_2333.sql create mode 100644 install/updates/update_2365.sql create mode 100644 install/updates/update_2369.sql create mode 100644 install/updates/update_2374.sql create mode 100644 install/updates/update_2416.sql create mode 100644 install/updates/update_2417.sql create mode 100644 install/updates/update_2430.sql create mode 100644 install/updates/update_2463.sql create mode 100644 install/updates/update_2480.sql create mode 100644 install/updates/update_2484.sql create mode 100644 install/updates/update_2502.sql create mode 100644 install/updates/update_2505.sql create mode 100644 install/updates/update_2538.sql create mode 100644 install/updates/update_2543.sql create mode 100644 install/updates/update_2564.sql create mode 100644 install/updates/update_2568.sql create mode 100644 install/updates/update_2577.sql create mode 100644 install/updates/update_2579.sql rename {updates => install/updates}/update_411.sql (100%) rename {updates => install/updates}/update_448.sql (100%) rename {updates => install/updates}/update_485.sql (100%) rename {updates => install/updates}/update_502.sql (100%) rename {updates => install/updates}/update_515.sql (100%) rename {updates => install/updates}/update_532.sql (100%) rename {updates => install/updates}/update_544.sql (100%) rename {updates => install/updates}/update_547.sql (100%) rename {updates => install/updates}/update_578.sql (100%) rename {updates => install/updates}/update_611.sql (100%) rename {updates => install/updates}/update_612.sql (100%) rename {updates => install/updates}/update_632.sql (100%) rename {updates => install/updates}/update_633.sql (100%) rename {updates => install/updates}/update_665.sql (100%) rename {updates => install/updates}/update_673.php (99%) rename {updates => install/updates}/update_673.sql (100%) rename {updates => install/updates}/update_698.sql (100%) rename {updates => install/updates}/update_739.sql (100%) rename {updates => install/updates}/update_744.sql (100%) rename {updates => install/updates}/update_759.sql (100%) rename {updates => install/updates}/update_762.sql (100%) rename {updates => install/updates}/update_784.sql (100%) rename {updates => install/updates}/update_887.sql (100%) rename {updates => install/updates}/update_932.sql (100%) rename {updates => install/updates}/update_938.sql (100%) rename {updates => install/updates}/update_970.sql (100%) rename {updates => install/updates}/update_982.sql (100%) rename {updates => install/updates}/update_989.sql (100%) create mode 100644 language/de/CUSTOM.php create mode 100644 language/de/templates/createUniverseInfo.txt rename language/de/{email => templates}/email_inactive.txt (78%) create mode 100644 language/de/templates/email_lost_password_changed.txt create mode 100644 language/de/templates/email_lost_password_validation.txt create mode 100644 language/de/templates/email_reg_done.txt create mode 100644 language/de/templates/email_vaild_reg.txt rename language/de/{extra => templates}/locked_install.txt (100%) rename language/de/{extra => templates}/rules.txt (100%) rename includes/functions/IsVacationMode.php => language/en/CUSTOM.php (83%) create mode 100644 language/en/templates/createUniverseInfo.txt rename language/en/{email => templates}/email_inactive.txt (80%) rename language/en/{email => templates}/email_lost_password.txt (100%) create mode 100644 language/en/templates/email_lost_password_changed.txt create mode 100644 language/en/templates/email_lost_password_validation.txt rename language/en/{email => templates}/email_reg_done.txt (100%) rename language/en/{email => templates}/email_vaild_reg.txt (100%) rename language/en/{extra => templates}/locked_install.txt (100%) rename language/en/{extra => templates}/rules.txt (100%) create mode 100644 language/es/CUSTOM.php rename language/es/{email => templates}/email_inactive.txt (77%) rename language/es/{email => templates}/email_lost_password.txt (100%) rename language/es/{email => templates}/email_reg_done.txt (100%) rename language/es/{email => templates}/email_vaild_reg.txt (100%) create mode 100644 language/es/templates/rules.txt delete mode 100644 language/fr/ADMIN.php delete mode 100644 language/fr/BANNER.php delete mode 100644 language/fr/CHANGELOG.php delete mode 100644 language/fr/FAQ.php delete mode 100644 language/fr/FLEET.php delete mode 100644 language/fr/INGAME.php delete mode 100644 language/fr/INSTALL.php delete mode 100644 language/fr/L18N.php delete mode 100644 language/fr/LANG.cfg delete mode 100644 language/fr/PUBLIC.php delete mode 100644 language/fr/TECH.php delete mode 100644 language/fr/email/email_inactive.txt delete mode 100644 language/fr/email/email_lost_password.txt delete mode 100644 language/fr/email/email_reg_done.txt delete mode 100644 language/fr/email/email_vaild_reg.txt delete mode 100644 language/it/ADMIN.php delete mode 100644 language/it/BANNER.php delete mode 100644 language/it/CHANGELOG.php delete mode 100644 language/it/FAQ.php delete mode 100644 language/it/FLEET.php delete mode 100644 language/it/INGAME.php delete mode 100644 language/it/INSTALL.php delete mode 100644 language/it/L18N.php delete mode 100644 language/it/LANG.cfg delete mode 100644 language/it/PUBLIC.php delete mode 100644 language/it/TECH.php delete mode 100644 language/it/email/email_inactive.txt delete mode 100644 language/it/email/email_lost_password.txt delete mode 100644 language/it/email/email_reg_done.txt delete mode 100644 language/it/email/email_vaild_reg.txt create mode 100644 language/pl/ADMIN.php create mode 100644 language/pl/BANNER.php create mode 100644 language/pl/CHANGELOG.php create mode 100644 language/pl/CUSTOM.php create mode 100644 language/pl/FAQ.php create mode 100644 language/pl/FLEET.php create mode 100644 language/pl/INGAME.php create mode 100644 language/pl/INSTALL.php rename language/{si => pl}/L18N.php (88%) create mode 100644 language/pl/LANG.cfg create mode 100644 language/pl/PUBLIC.php create mode 100644 language/pl/TECH.php create mode 100644 language/pl/templates/createUniverseInfo.txt create mode 100644 language/pl/templates/email_inactive.txt create mode 100644 language/pl/templates/email_lost_password.txt create mode 100644 language/pl/templates/email_lost_password_changed.txt create mode 100644 language/pl/templates/email_lost_password_validation.txt create mode 100644 language/pl/templates/email_reg_done.txt create mode 100644 language/pl/templates/email_vaild_reg.txt create mode 100644 language/pl/templates/locked_install.txt create mode 100644 language/pl/templates/rules.txt rename includes/pages/ShowChatPage.php => language/pt/CUSTOM.php (71%) delete mode 100644 language/pt/email/email_inactive.txt delete mode 100644 language/pt/email/email_lost_password.txt delete mode 100644 language/pt/email/email_reg_done.txt delete mode 100644 language/pt/email/email_vaild_reg.txt create mode 100644 language/pt/templates/createUniverseInfo.txt create mode 100644 language/pt/templates/email_inactive.txt rename language/{de/email => pt/templates}/email_lost_password.txt (100%) create mode 100644 language/pt/templates/email_lost_password_changed.txt create mode 100644 language/pt/templates/email_lost_password_validation.txt rename language/{de/email => pt/templates}/email_reg_done.txt (100%) rename language/{de/email => pt/templates}/email_vaild_reg.txt (100%) create mode 100644 language/pt/templates/locked_install.txt create mode 100644 language/pt/templates/rules.txt create mode 100644 language/ru/CUSTOM.php delete mode 100644 language/ru/email/email_reg_done.txt delete mode 100644 language/ru/email/email_vaild_reg.txt create mode 100644 language/ru/templates/createUniverseInfo.txt rename language/ru/{email => templates}/email_inactive.txt (84%) rename language/ru/{email => templates}/email_lost_password.txt (88%) create mode 100644 language/ru/templates/email_lost_password_changed.txt create mode 100644 language/ru/templates/email_lost_password_validation.txt create mode 100644 language/ru/templates/email_reg_done.txt create mode 100644 language/ru/templates/email_vaild_reg.txt create mode 100644 language/ru/templates/locked_install.txt rename language/ru/{extra => templates}/rules.txt (100%) delete mode 100644 language/si/ADMIN.php delete mode 100644 language/si/BANNER.php delete mode 100644 language/si/CHANGELOG.php delete mode 100644 language/si/FAQ.php delete mode 100644 language/si/FLEET.php delete mode 100644 language/si/INGAME.php delete mode 100644 language/si/INSTALL.php delete mode 100644 language/si/LANG.cfg delete mode 100644 language/si/PUBLIC.php delete mode 100644 language/si/TECH.php delete mode 100644 language/si/email/email_inactive.txt delete mode 100644 language/si/email/email_lost_password.txt delete mode 100644 language/si/email/email_reg_done.txt delete mode 100644 language/si/email/email_vaild_reg.txt create mode 100644 scripts/base/jquery.autosize-min.js create mode 100644 scripts/base/jquery.tablesorter.js create mode 100644 scripts/base/jquery.validationEngine.js create mode 100644 scripts/base/tinymce/langs/ar.js create mode 100644 scripts/base/tinymce/langs/cn.js create mode 100644 scripts/base/tinymce/langs/de.js create mode 100644 scripts/base/tinymce/langs/el.js create mode 100644 scripts/base/tinymce/langs/en.js create mode 100644 scripts/base/tinymce/langs/fr.js create mode 100644 scripts/base/tinymce/langs/hr.js create mode 100644 scripts/base/tinymce/langs/hu.js create mode 100644 scripts/base/tinymce/langs/it.js create mode 100644 scripts/base/tinymce/langs/pl.js create mode 100644 scripts/base/tinymce/langs/pt.js create mode 100644 scripts/base/tinymce/langs/ru.js create mode 100644 scripts/base/tinymce/langs/zh.js create mode 100644 scripts/base/tinymce/license.txt create mode 100644 scripts/base/tinymce/plugins/bbcode/editor_plugin.js create mode 100644 scripts/base/tinymce/plugins/fullscreen/editor_plugin.js create mode 100644 scripts/base/tinymce/plugins/fullscreen/fullscreen.htm create mode 100644 scripts/base/tinymce/themes/advanced/about.htm create mode 100644 scripts/base/tinymce/themes/advanced/anchor.htm create mode 100644 scripts/base/tinymce/themes/advanced/charmap.htm create mode 100644 scripts/base/tinymce/themes/advanced/color_picker.htm create mode 100644 scripts/base/tinymce/themes/advanced/editor_template.js create mode 100644 scripts/base/tinymce/themes/advanced/image.htm create mode 100644 scripts/base/tinymce/themes/advanced/img/colorpicker.jpg create mode 100644 scripts/base/tinymce/themes/advanced/img/flash.gif create mode 100644 scripts/base/tinymce/themes/advanced/img/icons.gif create mode 100644 scripts/base/tinymce/themes/advanced/img/iframe.gif create mode 100644 scripts/base/tinymce/themes/advanced/img/pagebreak.gif create mode 100644 scripts/base/tinymce/themes/advanced/img/quicktime.gif create mode 100644 scripts/base/tinymce/themes/advanced/img/realmedia.gif create mode 100644 scripts/base/tinymce/themes/advanced/img/shockwave.gif create mode 100644 scripts/base/tinymce/themes/advanced/img/trans.gif create mode 100644 scripts/base/tinymce/themes/advanced/img/video.gif create mode 100644 scripts/base/tinymce/themes/advanced/img/windowsmedia.gif create mode 100644 scripts/base/tinymce/themes/advanced/js/about.js create mode 100644 scripts/base/tinymce/themes/advanced/js/anchor.js create mode 100644 scripts/base/tinymce/themes/advanced/js/charmap.js create mode 100644 scripts/base/tinymce/themes/advanced/js/color_picker.js create mode 100644 scripts/base/tinymce/themes/advanced/js/image.js create mode 100644 scripts/base/tinymce/themes/advanced/js/link.js create mode 100644 scripts/base/tinymce/themes/advanced/js/source_editor.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/ar.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/ar_dlg.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/cn.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/cn_dlg.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/de.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/de_dlg.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/el.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/el_dlg.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/en.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/en_dlg.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/fr.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/fr_dlg.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/hr.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/hr_dlg.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/hu.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/hu_dlg.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/it.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/it_dlg.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/pl.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/pl_dlg.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/pt.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/pt_dlg.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/ru.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/ru_dlg.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/zh.js create mode 100644 scripts/base/tinymce/themes/advanced/langs/zh_dlg.js create mode 100644 scripts/base/tinymce/themes/advanced/link.htm create mode 100644 scripts/base/tinymce/themes/advanced/shortcuts.htm create mode 100644 scripts/base/tinymce/themes/advanced/skins/default/content.css create mode 100644 scripts/base/tinymce/themes/advanced/skins/default/dialog.css create mode 100644 scripts/base/tinymce/themes/advanced/skins/default/img/buttons.png create mode 100644 scripts/base/tinymce/themes/advanced/skins/default/img/items.gif create mode 100644 scripts/base/tinymce/themes/advanced/skins/default/img/menu_arrow.gif create mode 100644 scripts/base/tinymce/themes/advanced/skins/default/img/menu_check.gif create mode 100644 scripts/base/tinymce/themes/advanced/skins/default/img/progress.gif create mode 100644 scripts/base/tinymce/themes/advanced/skins/default/img/tabs.gif create mode 100644 scripts/base/tinymce/themes/advanced/skins/default/ui.css create mode 100644 scripts/base/tinymce/themes/advanced/skins/highcontrast/content.css create mode 100644 scripts/base/tinymce/themes/advanced/skins/highcontrast/dialog.css create mode 100644 scripts/base/tinymce/themes/advanced/skins/highcontrast/ui.css create mode 100644 scripts/base/tinymce/themes/advanced/skins/o2k7/content.css create mode 100644 scripts/base/tinymce/themes/advanced/skins/o2k7/dialog.css create mode 100644 scripts/base/tinymce/themes/advanced/skins/o2k7/img/button_bg.png create mode 100644 scripts/base/tinymce/themes/advanced/skins/o2k7/img/button_bg_black.png create mode 100644 scripts/base/tinymce/themes/advanced/skins/o2k7/img/button_bg_silver.png create mode 100644 scripts/base/tinymce/themes/advanced/skins/o2k7/ui.css create mode 100644 scripts/base/tinymce/themes/advanced/skins/o2k7/ui_black.css create mode 100644 scripts/base/tinymce/themes/advanced/skins/o2k7/ui_silver.css create mode 100644 scripts/base/tinymce/themes/advanced/source_editor.htm create mode 100644 scripts/base/tinymce/tiny_mce.js create mode 100644 scripts/base/tinymce/tiny_mce_gzip.js create mode 100644 scripts/base/tinymce/tiny_mce_gzip.php create mode 100644 scripts/base/tinymce/tiny_mce_popup.js create mode 100644 scripts/base/tinymce/utils/editable_selects.js create mode 100644 scripts/base/tinymce/utils/form_utils.js create mode 100644 scripts/base/tinymce/utils/mctabs.js create mode 100644 scripts/base/tinymce/utils/validate.js delete mode 100644 scripts/game/alliance.js rename scripts/{base => game}/filterlist.js (97%) create mode 100644 scripts/game/fleetTable.js delete mode 100644 scripts/game/login.js create mode 100644 scripts/game/overview.actions.js delete mode 100644 scripts/game/planetmenu.js delete mode 100644 scripts/game/support.js delete mode 100644 scripts/game/update.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-cz.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-da.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-de.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-en.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-es.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-et.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-fa.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-fi.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-fr.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-hr.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-it.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-ja.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-nl.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-pl.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-pt.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-pt_BR.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-ro.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-ru.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-sv.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-tr.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-zh_CN.js create mode 100644 scripts/l18n/validationEngine/jquery.validationEngine-zh_TW.js create mode 100644 scripts/login/main.js create mode 100644 scripts/login/register.js delete mode 100644 styles/css/admin.css delete mode 100644 styles/css/images/ui-bg_flat_30_cccccc_40x100.png delete mode 100644 styles/css/images/ui-bg_flat_50_5c5c5c_40x100.png delete mode 100644 styles/css/images/ui-bg_glass_20_555555_1x400.png delete mode 100644 styles/css/images/ui-bg_glass_40_0078a3_1x400.png delete mode 100644 styles/css/images/ui-bg_glass_40_ffc73d_1x400.png delete mode 100644 styles/css/images/ui-bg_gloss-wave_25_333333_500x100.png delete mode 100644 styles/css/images/ui-bg_highlight-soft_80_eeeeee_1x100.png delete mode 100644 styles/css/images/ui-bg_inset-soft_25_000000_1x100.png delete mode 100644 styles/css/images/ui-bg_inset-soft_30_f58400_1x100.png delete mode 100644 styles/css/images/ui-icons_222222_256x240.png delete mode 100644 styles/css/images/ui-icons_cccccc_256x240.png delete mode 100644 styles/css/ingame.css delete mode 100644 styles/images/abort.gif delete mode 100644 styles/images/arrow.gif delete mode 100644 styles/images/banner.jpg delete mode 100644 styles/images/buttons.gif delete mode 100644 styles/images/false.png delete mode 100644 styles/images/index.htm delete mode 100644 styles/images/r1.png delete mode 100644 styles/images/r2.png delete mode 100644 styles/images/r3.png delete mode 100644 styles/images/r4.png delete mode 100644 styles/images/r5.png delete mode 100644 styles/images/r6.png delete mode 100644 styles/images/r7.png delete mode 100644 styles/images/r8.png delete mode 100644 styles/images/r9.png delete mode 100644 styles/images/true.png create mode 100644 styles/resource/css/admin/main.css create mode 100644 styles/resource/css/base/boilerplate.css create mode 100644 styles/resource/css/base/images/asc.gif create mode 100644 styles/resource/css/base/images/bg.gif create mode 100644 styles/resource/css/base/images/desc.gif create mode 100644 styles/resource/css/base/images/ui-bg_diagonals-thick_15_0b3e6f_40x40.png create mode 100644 styles/resource/css/base/images/ui-bg_dots-medium_30_0b58a2_4x4.png create mode 100644 styles/resource/css/base/images/ui-bg_dots-small_20_333333_2x2.png create mode 100644 styles/resource/css/base/images/ui-bg_dots-small_30_a32d00_2x2.png create mode 100644 styles/resource/css/base/images/ui-bg_dots-small_40_00498f_2x2.png create mode 100644 styles/resource/css/base/images/ui-bg_flat_0_aaaaaa_40x100.png create mode 100644 styles/resource/css/base/images/ui-bg_flat_40_292929_40x100.png create mode 100644 styles/resource/css/base/images/ui-bg_gloss-wave_20_111111_500x100.png rename styles/{css/images/ui-icons_a83300_256x240.png => resource/css/base/images/ui-icons_00498f_256x240.png} (92%) rename styles/{css/images/ui-icons_4b8e0b_256x240.png => resource/css/base/images/ui-icons_98d2fb_256x240.png} (92%) create mode 100644 styles/resource/css/base/images/ui-icons_9ccdfc_256x240.png rename styles/{css => resource/css/base}/images/ui-icons_ffffff_256x240.png (100%) rename styles/{css => resource/css/base}/jquery.css (56%) rename styles/{css => resource/css/base}/jquery.fancybox.css (68%) create mode 100644 styles/resource/css/base/validationEngine.jquery.css create mode 100644 styles/resource/css/ingame/main.css create mode 100644 styles/resource/css/install/main.css rename styles/{css/login.css => resource/css/login/main.css} (94%) create mode 100644 styles/resource/css/login/register.css rename styles/{ => resource}/fonts/DroidSansMono.ttf (100%) rename styles/{ => resource}/fonts/Google Android License.txt (100%) rename styles/{images/Adm => resource/images/admin}/GO.png (100%) rename styles/{images/Adm => resource/images/admin}/UP.png (100%) rename styles/{images/Adm => resource/images/admin}/arrowleft.png (100%) rename styles/{images/Adm => resource/images/admin}/arrowright.png (100%) rename styles/{images/Adm => resource/images/admin}/blank.gif (100%) rename styles/{images/Adm => resource/images/admin}/c.gif (100%) rename styles/{images/Adm => resource/images/admin}/i.gif (100%) rename styles/{css => resource/images/admin}/index.htm (100%) create mode 100644 styles/resource/images/alliance/ADMIN.png create mode 100644 styles/resource/images/alliance/CLOSE.png create mode 100644 styles/resource/images/alliance/DIPLOMATIC.png create mode 100644 styles/resource/images/alliance/EVENTS.png create mode 100644 styles/resource/images/alliance/KICK.png create mode 100644 styles/resource/images/alliance/MANAGEAPPLY.png create mode 100644 styles/resource/images/alliance/MANAGEUSERS.png create mode 100644 styles/resource/images/alliance/MEMBERLIST.png create mode 100644 styles/resource/images/alliance/ONLINESTATE.png create mode 100644 styles/resource/images/alliance/RANKS.png create mode 100644 styles/resource/images/alliance/ROUNDMAIL.png create mode 100644 styles/resource/images/alliance/SEEAPPLY.png create mode 100644 styles/resource/images/alliance/TRANSFER.png rename styles/{ => resource}/images/banned.png (100%) create mode 100644 styles/resource/images/banner.jpg create mode 100644 styles/resource/images/facebook/fb-connect-large.png create mode 100644 styles/resource/images/false.png rename styles/{ => resource}/images/fancybox/blank.gif (100%) rename styles/{ => resource}/images/fancybox/fancy_close.png (100%) rename styles/{ => resource}/images/fancybox/fancy_loading.png (100%) rename styles/{ => resource}/images/fancybox/fancy_nav_left.png (100%) rename styles/{ => resource}/images/fancybox/fancy_nav_right.png (100%) rename styles/{ => resource}/images/fancybox/fancy_shadow_e.png (100%) rename styles/{ => resource}/images/fancybox/fancy_shadow_n.png (100%) rename styles/{ => resource}/images/fancybox/fancy_shadow_ne.png (100%) rename styles/{ => resource}/images/fancybox/fancy_shadow_nw.png (100%) rename styles/{ => resource}/images/fancybox/fancy_shadow_s.png (100%) rename styles/{ => resource}/images/fancybox/fancy_shadow_se.png (100%) rename styles/{ => resource}/images/fancybox/fancy_shadow_sw.png (100%) rename styles/{ => resource}/images/fancybox/fancy_shadow_w.png (100%) rename styles/{ => resource}/images/fancybox/fancy_title_left.png (100%) rename styles/{ => resource}/images/fancybox/fancy_title_main.png (100%) rename styles/{ => resource}/images/fancybox/fancy_title_over.png (100%) rename styles/{ => resource}/images/fancybox/fancy_title_right.png (100%) rename styles/{ => resource}/images/fancybox/fancybox-x.png (100%) rename styles/{ => resource}/images/fancybox/fancybox-y.png (100%) rename styles/{ => resource}/images/fancybox/fancybox.png (100%) create mode 100644 styles/resource/images/icons/closed.png create mode 100644 styles/resource/images/icons/open.png rename styles/{images/Adm => resource/images}/index.htm (100%) rename styles/{images/login/login_bg.jpg => resource/images/login/background.jpg} (100%) rename styles/{ => resource}/images/login/flags/de.png (100%) rename styles/{ => resource}/images/login/flags/es.png (100%) rename styles/{ => resource}/images/login/flags/flags.rar (100%) rename styles/{ => resource}/images/login/flags/fr.png (100%) rename styles/{ => resource}/images/login/flags/it.png (100%) create mode 100644 styles/resource/images/login/flags/pl.png rename styles/{ => resource}/images/login/flags/pt.png (100%) rename styles/{ => resource}/images/login/flags/ru.png (100%) rename styles/{ => resource}/images/login/flags/si.png (100%) rename styles/{ => resource}/images/login/flags/us.png (100%) rename styles/{images/login/bg1.png => resource/images/login/header.png} (100%) rename styles/{images => resource/images/login}/screens/ally.jpg (100%) rename styles/{images => resource/images/login}/screens/build.jpg (100%) rename styles/{images => resource/images/login}/screens/fleet.jpg (100%) rename styles/{images => resource/images/login}/screens/galaxy.jpg (100%) rename styles/{images => resource/images/login}/screens/imperium.jpg (100%) rename styles/{images => resource/images/login}/screens/overview.jpg (100%) rename styles/{images/screens/thumb_ally.jpg => resource/images/login/screens/thumbnails/ally.jpg} (100%) rename styles/{images/screens/thumb_build.jpg => resource/images/login/screens/thumbnails/build.jpg} (100%) rename styles/{images/screens/thumb_fleet.jpg => resource/images/login/screens/thumbnails/fleet.jpg} (100%) rename styles/{images/screens/thumb_galaxy.jpg => resource/images/login/screens/thumbnails/galaxy.jpg} (100%) rename styles/{images/screens/thumb_imperium.jpg => resource/images/login/screens/thumbnails/imperium.jpg} (100%) rename styles/{images/screens/thumb_overview.jpg => resource/images/login/screens/thumbnails/overview.jpg} (100%) create mode 100644 styles/resource/images/true.png delete mode 100644 styles/templates/CombatRaport.tpl create mode 100644 styles/templates/adm/CronjobDetail.tpl create mode 100644 styles/templates/adm/CronjobOverview.tpl create mode 100644 styles/templates/adm/DisclamerConfigBody.tpl create mode 100644 styles/templates/adm/DumpPage.tpl delete mode 100644 styles/templates/adm/SupportPage.tpl create mode 100644 styles/templates/adm/giveaway.tpl create mode 100644 styles/templates/adm/page.ticket.create.tpl create mode 100644 styles/templates/adm/page.ticket.default.tpl create mode 100644 styles/templates/adm/page.ticket.view.tpl delete mode 100644 styles/templates/alliance_admin.tpl delete mode 100644 styles/templates/alliance_admin_diplo.tpl delete mode 100644 styles/templates/alliance_admin_diplo_form.tpl delete mode 100644 styles/templates/alliance_admin_members.tpl delete mode 100644 styles/templates/alliance_admin_ranks.tpl delete mode 100644 styles/templates/alliance_admin_rename.tpl delete mode 100644 styles/templates/alliance_admin_request.tpl delete mode 100644 styles/templates/alliance_admin_transfer.tpl delete mode 100644 styles/templates/alliance_ainfo.tpl delete mode 100644 styles/templates/alliance_apply_waitform.tpl delete mode 100644 styles/templates/alliance_applyform.tpl delete mode 100644 styles/templates/alliance_circular.tpl delete mode 100644 styles/templates/alliance_defaultmenu.tpl delete mode 100644 styles/templates/alliance_frontpage.tpl delete mode 100644 styles/templates/alliance_make.tpl delete mode 100644 styles/templates/alliance_memberslist.tpl delete mode 100644 styles/templates/alliance_searchform.tpl delete mode 100644 styles/templates/banned_overview.tpl delete mode 100644 styles/templates/battlesim.tpl delete mode 100644 styles/templates/buddy_overview.tpl delete mode 100644 styles/templates/buddy_send_form.tpl delete mode 100644 styles/templates/buildings_overview.tpl delete mode 100644 styles/templates/buildings_research.tpl delete mode 100644 styles/templates/changelog_overview.tpl delete mode 100644 styles/templates/chat_overview.tpl delete mode 100644 styles/templates/empire_overview.tpl delete mode 100644 styles/templates/error_message_body.tpl delete mode 100644 styles/templates/faq_overview.tpl delete mode 100644 styles/templates/fleet1_table.tpl delete mode 100644 styles/templates/fleet2_table.tpl delete mode 100644 styles/templates/fleet3_table.tpl delete mode 100644 styles/templates/fleetACS_table.tpl delete mode 100644 styles/templates/fleet_table.tpl delete mode 100644 styles/templates/fleettrader_overview.tpl delete mode 100644 styles/templates/galaxy_overview.tpl rename {updates => styles/templates/game}/.htaccess (100%) create mode 100644 styles/templates/game/error.default.tpl create mode 100644 styles/templates/game/layout.ajax.tpl create mode 100644 styles/templates/game/layout.full.tpl create mode 100644 styles/templates/game/layout.popup.tpl rename styles/templates/{overall_footer.tpl => game/main.footer.tpl} (90%) create mode 100644 styles/templates/game/main.header.tpl create mode 100644 styles/templates/game/main.navigation.tpl create mode 100644 styles/templates/game/main.topnav.tpl create mode 100644 styles/templates/game/page.alliance.admin.detailApply.tpl create mode 100644 styles/templates/game/page.alliance.admin.diplomacy.create.tpl create mode 100644 styles/templates/game/page.alliance.admin.diplomacy.default.tpl create mode 100644 styles/templates/game/page.alliance.admin.mangeApply.tpl create mode 100644 styles/templates/game/page.alliance.admin.members.tpl create mode 100644 styles/templates/game/page.alliance.admin.overview.tpl create mode 100644 styles/templates/game/page.alliance.admin.permissions.tpl create mode 100644 styles/templates/game/page.alliance.admin.rename.name.tpl create mode 100644 styles/templates/game/page.alliance.admin.rename.tag.tpl create mode 100644 styles/templates/game/page.alliance.admin.transfer.tpl create mode 100644 styles/templates/game/page.alliance.apply.tpl create mode 100644 styles/templates/game/page.alliance.applyWait.tpl create mode 100644 styles/templates/game/page.alliance.circular.tpl create mode 100644 styles/templates/game/page.alliance.create.tpl create mode 100644 styles/templates/game/page.alliance.createSelection.tpl create mode 100644 styles/templates/game/page.alliance.home.tpl create mode 100644 styles/templates/game/page.alliance.info.tpl create mode 100644 styles/templates/game/page.alliance.memberList.tpl create mode 100644 styles/templates/game/page.alliance.search.tpl create mode 100644 styles/templates/game/page.banList.default.tpl create mode 100644 styles/templates/game/page.battleSimulator.default.tpl create mode 100644 styles/templates/game/page.battlehall.default.tpl create mode 100644 styles/templates/game/page.buddyList.default.tpl create mode 100644 styles/templates/game/page.buddyList.request.tpl create mode 100644 styles/templates/game/page.buildings.default.tpl create mode 100644 styles/templates/game/page.changelog.default.tpl create mode 100644 styles/templates/game/page.chat.default.tpl create mode 100644 styles/templates/game/page.empire.default.tpl create mode 100644 styles/templates/game/page.fleetDealer.default.tpl create mode 100644 styles/templates/game/page.fleetStep1.default.tpl create mode 100644 styles/templates/game/page.fleetStep2.default.tpl create mode 100644 styles/templates/game/page.fleetStep3.default.tpl create mode 100644 styles/templates/game/page.fleetTable.default.tpl create mode 100644 styles/templates/game/page.galaxy.default.tpl create mode 100644 styles/templates/game/page.infomation.default.tpl rename styles/templates/{logout_overview.tpl => game/page.logout.default.tpl} (54%) create mode 100644 styles/templates/game/page.messages.default.tpl create mode 100644 styles/templates/game/page.messages.view.tpl create mode 100644 styles/templates/game/page.messages.write.tpl create mode 100644 styles/templates/game/page.notes.default.tpl create mode 100644 styles/templates/game/page.notes.detail.tpl create mode 100644 styles/templates/game/page.officier.default.tpl create mode 100644 styles/templates/game/page.overview.actions.tpl create mode 100644 styles/templates/game/page.overview.default.tpl create mode 100644 styles/templates/game/page.phalanx.default.tpl create mode 100644 styles/templates/game/page.playerCard.default.tpl create mode 100644 styles/templates/game/page.questions.default.tpl create mode 100644 styles/templates/game/page.questions.single.tpl create mode 100644 styles/templates/game/page.records.default.tpl create mode 100644 styles/templates/game/page.research.default.tpl create mode 100644 styles/templates/game/page.resources.default.tpl create mode 100644 styles/templates/game/page.search.default.tpl create mode 100644 styles/templates/game/page.search.result.ally.tpl create mode 100644 styles/templates/game/page.search.result.default.tpl create mode 100644 styles/templates/game/page.settings.default.tpl create mode 100644 styles/templates/game/page.settings.vacation.tpl create mode 100644 styles/templates/game/page.shipyard.default.tpl create mode 100644 styles/templates/game/page.statistics.default.tpl create mode 100644 styles/templates/game/page.techtree.default.tpl create mode 100644 styles/templates/game/page.ticket.create.tpl create mode 100644 styles/templates/game/page.ticket.default.tpl create mode 100644 styles/templates/game/page.ticket.view.tpl create mode 100644 styles/templates/game/page.trader.default.tpl create mode 100644 styles/templates/game/page.trader.trade.tpl create mode 100644 styles/templates/game/shared.fleetTable.acsTable.tpl create mode 100644 styles/templates/game/shared.information.gate.tpl create mode 100644 styles/templates/game/shared.information.missiles.tpl create mode 100644 styles/templates/game/shared.information.production.tpl create mode 100644 styles/templates/game/shared.information.shipInfo.tpl create mode 100644 styles/templates/game/shared.information.storage.tpl create mode 100644 styles/templates/game/shared.mission.raport.tpl create mode 100644 styles/templates/game/shared.mission.spyraport.tpl create mode 100644 styles/templates/game/shared.statistics.allianceTable.tpl create mode 100644 styles/templates/game/shared.statistics.playerTable.tpl delete mode 100644 styles/templates/index/index.tpl delete mode 100644 styles/templates/index/index_disclamer.tpl delete mode 100644 styles/templates/index/index_error.tpl delete mode 100644 styles/templates/index/index_main.tpl delete mode 100644 styles/templates/index/index_news.tpl delete mode 100644 styles/templates/index/index_pranger.tpl delete mode 100644 styles/templates/index/index_rules.tpl delete mode 100644 styles/templates/index/index_screens.tpl delete mode 100644 styles/templates/index/index_top100.tpl delete mode 100644 styles/templates/info_gatelist.tpl delete mode 100644 styles/templates/info_overview.tpl create mode 100644 styles/templates/install/ins_doupdate.tpl create mode 100644 styles/templates/install/ins_step4.tpl create mode 100644 styles/templates/install/ins_step5.tpl create mode 100644 styles/templates/install/ins_step8.tpl create mode 100644 styles/templates/install/ins_step8error.tpl create mode 100644 styles/templates/install/ins_update.tpl create mode 100644 styles/templates/install/ins_upgrade.tpl delete mode 100644 styles/templates/left_menu.tpl create mode 100644 styles/templates/login/error.default.tpl create mode 100644 styles/templates/login/info.redirectPost.tpl.tpl.txt create mode 100644 styles/templates/login/layout.ajax.tpl create mode 100644 styles/templates/login/layout.light.tpl create mode 100644 styles/templates/login/layout.normal.tpl create mode 100644 styles/templates/login/layout.popup.tpl create mode 100644 styles/templates/login/main.footer.tpl create mode 100644 styles/templates/login/main.header.tpl create mode 100644 styles/templates/login/main.navigation.tpl create mode 100644 styles/templates/login/page.banList.default.tpl create mode 100644 styles/templates/login/page.battleHall.default.tpl create mode 100644 styles/templates/login/page.disclamer.default.tpl create mode 100644 styles/templates/login/page.index.default.tpl create mode 100644 styles/templates/login/page.lostPassword.default.tpl create mode 100644 styles/templates/login/page.news.default.tpl create mode 100644 styles/templates/login/page.register.default.tpl create mode 100644 styles/templates/login/page.rules.default.tpl create mode 100644 styles/templates/login/page.screens.default.tpl delete mode 100644 styles/templates/message_list.tpl delete mode 100644 styles/templates/message_overview.tpl delete mode 100644 styles/templates/message_send_form.tpl delete mode 100644 styles/templates/notes_body.tpl delete mode 100644 styles/templates/notes_edit_form.tpl delete mode 100644 styles/templates/notes_send_form.tpl delete mode 100644 styles/templates/officier_overview.tpl delete mode 100644 styles/templates/options_overview.tpl delete mode 100644 styles/templates/options_overview_vmode.tpl delete mode 100644 styles/templates/overall_header.tpl delete mode 100644 styles/templates/overall_topnav.tpl delete mode 100644 styles/templates/overview_body.tpl delete mode 100644 styles/templates/phalax_body.tpl delete mode 100644 styles/templates/planet_menu.tpl delete mode 100644 styles/templates/playercard_overview.tpl delete mode 100644 styles/templates/records_overview.tpl delete mode 100644 styles/templates/resources_overview.tpl delete mode 100644 styles/templates/search_body.tpl delete mode 100644 styles/templates/shipyard_defense.tpl delete mode 100644 styles/templates/shipyard_fleet.tpl delete mode 100644 styles/templates/stat_alliancetable.tpl delete mode 100644 styles/templates/stat_overview.tpl delete mode 100644 styles/templates/stat_playertable.tpl delete mode 100644 styles/templates/support_overview.tpl delete mode 100644 styles/templates/techtree_overview.tpl delete mode 100644 styles/templates/topkb_overview.tpl delete mode 100644 styles/templates/trader_overview.tpl delete mode 100644 styles/templates/trader_trade.tpl delete mode 100644 styles/theme/gow/gebaeude/221.gif delete mode 100644 styles/theme/gow/gebaeude/222.gif delete mode 100644 styles/theme/gow/gebaeude/223.gif delete mode 100644 styles/theme/gow/gebaeude/224.gif delete mode 100644 styles/theme/gow/gebaeude/225.gif delete mode 100644 styles/theme/gow/gebaeude/226.gif delete mode 100644 styles/theme/gow/gebaeude/227.gif delete mode 100644 styles/theme/gow/gebaeude/228.gif delete mode 100644 styles/theme/gow/gebaeude/700.gif create mode 100644 styles/theme/gow/gebaeude/707.gif rename styles/theme/gow/images/{kristall.gif => crystal.gif} (100%) rename styles/theme/gow/images/{energie.gif => energy.gif} (100%) rename styles/theme/gow/images/{metall.gif => metal.gif} (100%) create mode 100644 styles/theme/gow/img/bkd_bg.png create mode 100644 styles/theme/gow/img/menu-item-bg.png create mode 100644 styles/theme/gow/img/processbar.gif delete mode 100644 styles/theme/gow/img/processbar.png create mode 100644 styles/theme/gow/settings.cfg diff --git a/.htaccess b/.htaccess index aefaa22..121156b 100644 --- a/.htaccess +++ b/.htaccess @@ -1,38 +1,50 @@ +# ---------------------------------------------------------------------- +# Better website experience for IE users +# ---------------------------------------------------------------------- + +# Force the latest IE version, in various cases when it may fall back to IE7 mode +# github.com/rails/rails/commit/123eb25#commitcomment-118920 +# Use ChromeFrame if it's installed for a better experience for the poor IE folk + + Header set X-UA-Compatible "IE=Edge,chrome=1" + # mod_headers can't match by content-type, but we don't want to send this header on *everything*... + + Header unset X-UA-Compatible + + + + +# ---------------------------------------------------------------------- +# UTF-8 encoding +# ---------------------------------------------------------------------- + +# Use UTF-8 encoding for anything served text/plain or text/html AddDefaultCharset utf-8 -FileETag MTime Size - - - SetOutputFilter DEFLATE - BrowserMatch ^Mozilla/4 gzip-only-text/html - BrowserMatch ^Mozilla/4.0[678] no-gzip - BrowserMatch bMSI[E] !no-gzip !gzip-only-text/html - SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary - - Header append Vary User-Agent env=!dont-vary - + +# Force UTF-8 for a number of file formats +AddCharset utf-8 .css .js .xml .json .rss .atom + + + Options -Indexes - RewriteEngine on - RewriteCond %{REQUEST_FILENAME} !-f - RewriteCond %{REQUEST_FILENAME} !-d - RewriteCond %{REQUEST_FILENAME} !-l - RewriteRule .* index.php [L] + RewriteCond %{SCRIPT_FILENAME} -d + RewriteCond %{SCRIPT_FILENAME} -f + RewriteRule "(^|/)\." - [F] - - ExpiresActive On - ExpiresDefault A3600 - - ExpiresDefault A43200 - - - ExpiresDefault A172800 - - - ExpiresDefault A604800 - - - ExpiresActive Off - + + Order allow,deny + Deny from all + Satisfy All + + +# ---------------------------------------------------------------------- +# 2Moons: Multiuniverse support +# ---------------------------------------------------------------------- + + + RewriteEngine on + RewriteRule uni([0-9]+)/?(.*)?$ $2 [L,QSA,E=UNI:$1] \ No newline at end of file diff --git a/CombatReport.php b/CombatReport.php index 4582daf..ab790d9 100644 --- a/CombatReport.php +++ b/CombatReport.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,65 +18,17 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ -define('INSIDE' , true); -define('AJAX', true ); +define('MODE', 'INGAME'); define('ROOT_PATH', str_replace('\\', '/',dirname(__FILE__)).'/'); -require(ROOT_PATH . 'includes/common.php'); -require(ROOT_PATH . 'includes/classes/class.template.php'); -if(isset($_SESSION['USER'])) - $LANG->setUser($_SESSION['USER']['lang']); -else - $LANG->GetLangFromBrowser(); - -$LANG->includeLang(array('L18N', 'FLEET', 'TECH')); - -$RID = request_var('raport', 0); -$Fame = request_var('fame', 0); -if($Fame == 1) { - $Raport = $db->uniquequery("SELECT - `raport`, `time`, - ( - SELECT - GROUP_CONCAT(username SEPARATOR ' & ') as attacker - FROM ".USERS." - WHERE `id` IN (SELECT `uid` FROM ".TOPKB_USERS." WHERE ".TOPKB_USERS.".`rid` = ".RW.".`rid` AND `role` = 1) - ) as `attacker`, - ( - SELECT - GROUP_CONCAT(username SEPARATOR ' & ') as defender - FROM ".USERS." - WHERE `id` IN (SELECT `uid` FROM ".TOPKB_USERS." WHERE ".TOPKB_USERS.".`rid` = ".RW.".`rid` AND `role` = 2) - ) as `defender` - FROM ".RW." - WHERE `rid` = ".$RID.";"); - $Info = array($Raport["attacker"], $Raport["defender"]); -} else { - $Raport = $db->uniquequery("SELECT `raport` FROM ".RW." WHERE `rid` = ".$RID.";"); - $Info = array(); -} - -$template = new template(); -if(!isset($Raport)) { - $template->message($LNG['sys_raport_not_found'], 0, false, true); - exit; -} -$template->isPopup(true); -$template->assign_vars(array( - 'Raport' => unserialize($Raport["raport"]), - 'Info' => $Info, - 'fame' => $Fame -)); -$template->show('CombatRaport.tpl'); - -?> \ No newline at end of file +require(ROOT_PATH.'includes/common.php'); +HTTP::redirectTo('game.php?page=raport&raport='.HTTP::_GP('raport', '')); \ No newline at end of file diff --git a/admin.php b/admin.php index 501dc9d..0a89c30 100644 --- a/admin.php +++ b/admin.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,24 +18,22 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ -define('INSIDE' , true); -define('IN_ADMIN', true); +define('MODE', 'ADMIN'); define('ROOT_PATH', str_replace('\\', '/',dirname(__FILE__)).'/'); require(ROOT_PATH . 'includes/common.php'); require_once(ROOT_PATH . 'includes/classes/class.Log.php'); -if ($USER['authlevel'] == AUTH_USR) redirectTo('game.php'); +if ($USER['authlevel'] == AUTH_USR) HTTP::redirectTo('game.php'); if(!isset($_SESSION['admin_login']) || $_SESSION['admin_login'] != $USER['password']) { @@ -44,8 +42,8 @@ exit; } -$page = request_var('page', ''); -$uni = request_var('uni', 0); +$page = HTTP::_GP('page', ''); +$uni = HTTP::_GP('uni', 0); if($USER['authlevel'] == AUTH_ADM && !empty($uni)) $_SESSION['adminuni'] = $uni; @@ -54,6 +52,10 @@ switch($page) { + case 'logout': + include_once(ROOT_PATH . 'includes/pages/adm/ShowLogoutPage.php'); + ShowLogoutPage(); + break; case 'infos': include_once(ROOT_PATH . 'includes/pages/adm/ShowInformationPage.php'); ShowInformationPage(); @@ -90,9 +92,9 @@ include_once(ROOT_PATH . 'includes/pages/adm/ShowStatsPage.php'); ShowStatsPage(); break; - case 'update': - include_once(ROOT_PATH . 'includes/pages/adm/ShowUpdatePage.php'); - ShowUpdatePage(); + case 'disclamer': + include_once(ROOT_PATH . 'includes/pages/adm/ShowDisclamerPage.php'); + ShowDisclamerPage(); break; case 'create': include_once(ROOT_PATH . 'includes/pages/adm/ShowCreatorPage.php'); @@ -128,7 +130,7 @@ break; case 'support': include_once(ROOT_PATH . 'includes/pages/adm/ShowSupportPage.php'); - ShowSupportPage(); + new ShowSupportPage(); break; case 'password': include_once(ROOT_PATH . 'includes/pages/adm/ShowPassEncripterPage.php'); @@ -190,10 +192,24 @@ include_once(ROOT_PATH . 'includes/pages/adm/ShowVertify.php'); ShowVertify(); break; + case 'cronjob': + include_once(ROOT_PATH . 'includes/pages/adm/ShowCronjobPage.php'); + ShowCronjob(); + break; + case 'giveaway': + include_once(ROOT_PATH . 'includes/pages/adm/ShowGiveawayPage.php'); + ShowGiveaway(); + break; + case 'autocomplete': + include_once(ROOT_PATH . 'includes/pages/adm/ShowAutoCompletePage.php'); + ShowAutoCompletePage(); + break; + case 'dump': + include_once(ROOT_PATH . 'includes/pages/adm/ShowDumpPage.php'); + ShowDumpPage(); + break; default: include_once(ROOT_PATH . 'includes/pages/adm/ShowIndexPage.php'); ShowIndexPage(); break; } - -?> \ No newline at end of file diff --git a/ajax.php b/ajax.php deleted file mode 100644 index 20fa3bd..0000000 --- a/ajax.php +++ /dev/null @@ -1,246 +0,0 @@ -. - * - * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) - * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) - * @info $Id$ - * @link http://code.google.com/p/2moons/ - */ - -define('INSIDE', true ); -define('AJAX', true ); - -define('ROOT_PATH', str_replace('\\', '/',dirname(__FILE__)).'/'); - -require(ROOT_PATH . 'includes/common.php'); -$SESSION = new Session(); - -if(!$SESSION->IsUserLogin() || ($CONF['game_disable'] == 0 && $_SESSION['authlevel'] == AUTH_USR)) - exit(json_encode(array())); - -$LANG->setUser($_SESSION['USER']['lang']); -$LANG->includeLang(array('INGAME')); -$action = request_var('action', ''); -switch($action) -{ - case 'fleet1': - $TargetGalaxy = request_var('galaxy', 0); - $TargetSystem = request_var('system', 0); - $TargetPlanet = request_var('planet', 0); - $TargetPlanettype = request_var('planet_type', 1); - - if($TargetGalaxy == $_SESSION['PLANET']['galaxy'] && $TargetSystem == $_SESSION['PLANET']['system'] && $TargetPlanet == $_SESSION['PLANET']['planet'] && $TargetPlanettype == $_SESSION['PLANET']['planet_type']) - exit($LNG['fl_error_same_planet']); - - if ($TargetPlanet != $CONF['max_planets'] + 1) { - $Data = $db->uniquequery("SELECT u.`urlaubs_modus`, u.`authattack`, p.`destruyed`, p.`der_metal`, p.`der_crystal`, p.`destruyed` FROM ".USERS." as u, ".PLANETS." as p WHERE p.universe = '".$UNI."' AND p.`galaxy` = '".$TargetGalaxy."' AND p.`system` = '".$TargetSystem."' AND p.`planet` = '".$TargetPlanet."' AND p.`planet_type` = '".(($TargetPlanettype == 2) ? 1 : $TargetPlanettype)."' AND `u`.`id` = p.`id_owner`;"); - if ($TargetPlanettype == 3 && !isset($Data)) - exit($LNG['fl_error_no_moon']); - elseif ($_GET['kolo'] == 0 && !isset($Data)) - exit($LNG['fl_error_not_avalible']); - elseif ($TargetPlanettype != 2 && $Data['urlaubs_modus']) - exit($LNG['fl_in_vacation_player']); - elseif ($CONF['adm_attack'] == 1 && $Data['authattack'] > $_SESSION['authlevel']) - exit($LNG['fl_admins_cannot_be_attacked']); - elseif ($Data['destruyed'] != 0) - exit($LNG['fl_error_not_avalible']); - elseif($TargetPlanettype == 2 && $Data['der_metal'] == 0 && $Data['der_crystal'] == 0) - exit($LNG['fl_error_empty_derbis']); - } else { - if ($_SESSION['USER'][$resource[124]] == 0) - exit($LNG['fl_expedition_tech_required']); - - $ActualFleets = $db->countquery("SELECT COUNT(*) FROM ".FLEETS." WHERE `fleet_owner` = '".$_SESSION['id']."' AND `fleet_mission` = '15';"); - - if ($ActualFleets['state'] >= floor(sqrt($_SESSION['USER'][$resource[124]]))) - exit($LNG['fl_expedition_fleets_limit']); - } - exit('OK'); - break; - case 'renameplanet': - $newname = request_var('newname', '', UTF8_SUPPORT); - if (!empty($newname)) - { - if (!CheckName($newname)) - exit((UTF8_SUPPORT) ? $LNG['ov_newname_no_space'] : $LNG['ov_newname_alphanum']); - else - $db->query("UPDATE ".PLANETS." SET `name` = '".$db->sql_escape($newname)."' WHERE `id` = '".$_SESSION['planet']. "';"); - } - break; - case 'saveshotcut': - $Shortcut = array(); - $ShortcutData = $_REQUEST['shoutcut']; - foreach($ShortcutData as $Key => $Data) { - $Name = $db->sql_escape(request_var('', $_REQUEST['shoutcut'][$Key]['name'])); - - if(empty($Name) || !in_array($Data['type'], array(1, 2, 3))) - continue; - - $Shortcut[] = array( - $Name, - (int) $Data['galaxy'], - (int) $Data['system'], - (int) $Data['planet'], - (int) $Data['type'], - ); - } - $db->query("UPDATE ".USERS." SET `fleet_shortcut` = '".serialize($Shortcut)."' WHERE `id` = ".$_SESSION['id'].";"); - exit($LNG['fl_shortcut_saved']); - break; - case 'deleteplanet': - $password = request_var('password', '', true); - if (!empty($password)) - { - $IfFleets = $db->countquery("SELECT COUNT(*) FROM ".FLEETS." WHERE (`fleet_owner` = '".$_SESSION['id']."' AND (`fleet_start_id` = ".$_SESSION['PLANET']['id']." OR `fleet_start_id` = ".$_SESSION['PLANET']['id_luna'].")) OR (`fleet_target_owner` = '".$_SESSION['id']."' AND (`fleet_end_id` = '".$_SESSION['PLANET']['id']."' OR `fleet_end_id` = ".$_SESSION['PLANET']['id_luna']."));"); - - if ($IfFleets > 0) - exit(json_encode(array('mess' => $LNG['ov_abandon_planet_not_possible']))); - elseif ($_SESSION['USER']['id_planet'] == $_SESSION['planet']) - exit(json_encode(array('mess' => $LNG['ov_principal_planet_cant_abanone']))); - elseif (md5($password) != $_SESSION['USER']['password']) - exit(json_encode(array('mess' => $LNG['ov_wrong_pass']))); - else - { - if($_SESSION['PLANET']['planet_type'] == 1) { - $db->multi_query("UPDATE ".PLANETS." SET `destruyed` = '".(TIMESTAMP+ 86400)."' WHERE `id` = '".$_SESSION['planet']."';DELETE FROM ".PLANETS." WHERE `id` = '".$_SESSION['PLANET']['id_luna']."';"); - } else { - $db->multi_query("UPDATE ".PLANETS." SET `id_luna` = '0' WHERE `id_luna` = '".$_SESSION['planet']."';DELETE FROM ".PLANETS." WHERE `id` = '".$_SESSION['planet']."';"); - } - $_SESSION['planet'] = $_SESSION['USER']['id_planet']; - exit(json_encode(array('ok' => true, 'mess' => $LNG['ov_planet_abandoned']))); - } - } - break; - case 'getmessages': - $MessCategory = request_var('messcat', 0); - $MessageList = array(); - if($MessCategory == 999) - { - $UsrMess = $db->query("SELECT * FROM ".MESSAGES." WHERE `message_sender` = '".$_SESSION['id']."' ORDER BY `message_time` DESC;"); - - while ($CurMess = $db->fetch_array($UsrMess)) - { - $CurrUsername = $db->uniquequery("SELECT `username`, `galaxy`, `system`, `planet` FROM ".USERS." WHERE id = '".$CurMess['message_owner']."';"); - - $MessageList[$CurMess['message_id']] = array( - 'time' => tz_date($CurMess['message_time']), - 'from' => $CurrUsername['username']." [".$CurrUsername['galaxy'].":".$CurrUsername['system'].":".$CurrUsername['planet']."]", - 'subject' => $CurMess['message_subject'], - 'type' => $CurMess['message_type'], - 'text' => $CurMess['message_text'], - ); - } - $db->free_result($UsrMess); - - echo json_encode($MessageList); - - exit; - } - - $UsrMess = $db->query("SELECT * FROM ".MESSAGES." WHERE `message_owner` = '".$_SESSION['id']."' OR (`message_owner` = '0' AND `message_type` = '50') ORDER BY `message_time` DESC;"); - - while ($CurMess = $db->fetch_array($UsrMess)) - { - $MessageList[$CurMess['message_time']] = array( - 'id' => $CurMess['message_id'], - 'time' => tz_date($CurMess['message_time']), - 'from' => $CurMess['message_from'], - 'subject' => stripslashes($CurMess['message_subject']), - 'sender' => $CurMess['message_sender'], - 'type' => $CurMess['message_type'], - 'text' => stripslashes($CurMess['message_text']), - ); - } - - $db->free_result($UsrMess); - echo json_encode(array( - 'MessageList' => $MessageList, - 'LNG' => array( - 'mg_message_title' => $LNG['mg_message_title'], - 'mg_action' => $LNG['mg_action'], - 'mg_date' => $LNG['mg_date'], - 'mg_from' => $LNG['mg_from'], - 'mg_to' => $LNG['mg_to'], - 'mg_subject' => $LNG['mg_subject'], - 'mg_show_only_header_spy_reports' => $LNG['mg_show_only_header_spy_reports'], - 'mg_delete_marked' => $LNG['mg_delete_marked'], - 'mg_delete_type_all' => $LNG['mg_delete_type_all'], - 'mg_delete_unmarked' => $LNG['mg_delete_unmarked'], - 'mg_delete_all' => $LNG['mg_delete_all'], - 'mg_confirm_delete' => $LNG['mg_confirm_delete'], - 'mg_game_message' => $LNG['mg_game_message'], - 'mg_answer_to' => $LNG['mg_answer_to'], - ), - )); - exit; - break; - case 'deletemessages': - $DeleteWhat = request_var('deletemessages',''); - $MessType = request_var('mess_type', 0); - - if($DeleteWhat == 'deleteunmarked' && (empty($_REQUEST['delmes']) || !is_array($_REQUEST['delmes']))) - $DeleteWhat = 'deletetypeall'; - - if($DeleteWhat == 'deletetypeall' && $MessType == 100) - $DeleteWhat = 'deleteall'; - - - switch($DeleteWhat) - { - case 'deleteall': - $db->multi_query("DELETE FROM ".MESSAGES." WHERE `message_owner` = '".$_SESSION['id']."';UPDATE ".USERS." SET `new_message` = '0', `new_gmessage` = '0' WHERE `id` = '".$_SESSION['id']."';"); - break; - case 'deletetypeall': - $db->multi_query("DELETE FROM ".MESSAGES." WHERE `message_owner` = '".$_SESSION['id']."' AND `message_type` = '".$MessType."';UPDATE ".USERS." SET `new_message` = '0', `new_gmessage` = '0' WHERE `id` = '".$_SESSION['id']."';"); - case 'deletemarked': - $SQLWhere = array(); - if(empty($_REQUEST['delmes']) || !is_array($_REQUEST['delmes'])) - exit; - - foreach($_REQUEST['delmes'] as $MessID => $b) - { - $SQLWhere[] = "`message_id` = '".(int) $MessID."'"; - } - - $db->query("DELETE FROM ".MESSAGES." WHERE (".implode(" OR ",$SQLWhere).") AND `message_owner` = '".$_SESSION['id']."'".(($MessType != 100)? " AND `message_type` = '".$MessType."' ":"").";"); - break; - case 'deleteunmarked': - if(!empty($_REQUEST['delmes']) && is_array($_REQUEST['delmes'])) - { - $SQLWhere = array(); - foreach($_REQUEST['delmes'] as $MessID => $b) - { - $SQLWhere[] = "`message_id` != '".(int) $MessID."'"; - } - - $db->query("DELETE FROM ".MESSAGES." WHERE (".implode(" AND ",$SQLWhere).") AND `message_owner` = '".$_SESSION['id']."'".(($MessType != 100)? " AND `message_type` = '".$MessType."' ":"").";"); - } - break; - } - header('HTTP/1.1 204 No Content'); - break; - default: - header('HTTP/1.1 204 No Content'); - break; -} -?> \ No newline at end of file diff --git a/chat/css/2Moons.css b/chat/css/2Moons.css index 2d2ea40..43c726d 100644 --- a/chat/css/2Moons.css +++ b/chat/css/2Moons.css @@ -22,6 +22,9 @@ */ @media screen,projection,handheld { + :focus { + outline:0 none; + } #loginContent { background-color:#E5E5E8; @@ -56,13 +59,15 @@ } #content input, #content select, #content textarea { border:1px solid #212121; - background:#393939; + background: #0D1014; + background: rgba(13, 16, 20, 0.95); color:#CCC; font-family:Verdana; font-size:10px; } #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { - background:#393939; + background: #0D1014; + background: rgba(13, 16, 20, 0.95); border: 0px; } .statusContainerOn { @@ -107,10 +112,11 @@ background:url('../img/autoscroll-off.png') no-repeat; } #content .rowEven { - background-color:#333; + background: transparent } #content .rowOdd { - background-color:#393939; + background: #212428; + background: rgba(33, 36, 40, 0.3); } #content .guest { color:gray; @@ -148,6 +154,9 @@ padding-left:3px; text-align:left } + #onlineListContainer h3 { + padding:2px 3px; + } #content #settingsContainer #settingsList input.playback { background:url('../img/playback.png') no-repeat; } diff --git a/chat/css/Cobalt.css b/chat/css/Cobalt.css deleted file mode 100644 index 168bd82..0000000 --- a/chat/css/Cobalt.css +++ /dev/null @@ -1,147 +0,0 @@ -/* - * @package AJAX_Chat - * @author Sebastian Tschan - * @copyright (c) Sebastian Tschan - * @license GNU Affero General Public License - * @link https://blueimp.net/ajax/ - * - * Color palette inspired by PunBB style "Cobalt": - * http://punbb.org/ - */ - - -@import url('positions.css'); -@import url('borders.css'); -@import url('fonts.css'); -@import url('misc.css'); -@import url('print.css'); - - -/* - * Colors - */ - -@media screen,projection,handheld { - - #loginContent { - background-color:#2A2A2A; - color:#D4D4D4; - } - #loginContent h1 { - color:#D4D4D4; - } - #loginContent a { - color:#60A0DC; - } - #loginContent input, #loginContent select { - background-color:#424242; - color:#D4D4D4; - } - #loginContent #loginFormContainer #loginButton { - background-color:#424242; - color:#D4D4D4; - } - #loginContent #errorContainer { - color:red; - } - - #content { - background-color:#2A2A2A; - color:#D4D4D4; - } - #content h1 { - color:#D4D4D4; - } - #content a { - color:#60A0DC; - } - #content input, #content select, #content textarea { - background-color:#383838; - color:#D4D4D4; - } - #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { - border-color:#565656; - background-color:#383838; - } - .statusContainerOn { - background-image: url('../img/loading.png'); - } - .statusContainerOff { - background-image: url('../img/loading-done.png'); - } - .statusContainerAlert { - background-image: url('../img/loading-trouble.png'); - } - #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { - background-color:#383838; - color:#D4D4D4; - } - #content #colorCodesContainer a { - border-color:black; - } - #content #optionsContainer input { - background-color:transparent; - } - #content #optionsContainer #helpButton { - background:url('../img/help.png') no-repeat; - } - #content #optionsContainer #settingsButton { - background:url('../img/settings.png') no-repeat; - } - #content #optionsContainer #onlineListButton { - background:url('../img/users.png') no-repeat; - } - #content #optionsContainer #audioButton { - background:url('../img/audio.png') no-repeat; - } - #content #optionsContainer #audioButton.off { - background:url('../img/audio-off.png') no-repeat; - } - #content #optionsContainer #autoScrollButton { - background:url('../img/autoscroll.png') no-repeat; - } - #content #optionsContainer #autoScrollButton.off { - background:url('../img/autoscroll-off.png') no-repeat; - } - #content .rowEven { - background-color:#565656; - } - #content .rowOdd { - background-color:#484848; - } - #content .guest { - color:gray; - } - #content .user { - color:#D4D4D4; - } - #content .moderator { - color:#00AA00; - } - #content .admin { - color:red; - } - #content .chatBot { - color:#60A0DC; - } - #content #chatList .chatBotErrorMessage { - color:red; - } - #content #chatList a { - color:#60A0DC; - } - #content #chatList .delete { - background:url('../img/delete.png') no-repeat right; - } - #content #chatList .deleteSelected { - border-color:red; - } - #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { - background-color:#383838; - color:#D4D4D4; - } - #content #settingsContainer #settingsList input.playback { - background:url('../img/playback.png') no-repeat; - } - -} \ No newline at end of file diff --git a/chat/css/Core.css b/chat/css/Core.css deleted file mode 100644 index fe8cae4..0000000 --- a/chat/css/Core.css +++ /dev/null @@ -1,147 +0,0 @@ -/* - * @package AJAX_Chat - * @author Sebastian Tschan - * @copyright (c) Sebastian Tschan - * @license GNU Affero General Public License - * @link https://blueimp.net/ajax/ - * - * Color palette inspired by Simple Machines Forum style "SMF Default Theme - Core": - * http://www.simplemachines.org/ - */ - - -@import url('positions.css'); -@import url('borders.css'); -@import url('fonts.css'); -@import url('misc.css'); -@import url('print.css'); - - -/* - * Colors - */ - -@media screen,projection,handheld { - - #loginContent { - background-color:#E5E5E8; - color:#000; - } - #loginContent h1 { - color:#000; - } - #loginContent a { - color:#000; - } - #loginContent input, #loginContent select { - background-color:#FFF; - color:#000; - } - #loginContent #loginFormContainer #loginButton { - background-color:#F7F5F1; - color:#000; - } - #loginContent #errorContainer { - color:red; - } - - #content { - background-color:#E5E5E8; - color:#000; - } - #content h1 { - color:#000; - } - #content a { - color:#000; - } - #content input, #content select, #content textarea { - background-color:#FFF; - color:#000; - } - #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { - border-color:#ADADAD; - background-color:#FFF; - } - .statusContainerOn { - background-image: url('../img/loading.png'); - } - .statusContainerOff { - background-image: url('../img/loading-done.png'); - } - .statusContainerAlert { - background-image: url('../img/loading-trouble.png'); - } - #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { - background-color:#F7F5F1; - color:#000; - } - #content #colorCodesContainer a { - border-color:black; - } - #content #optionsContainer input { - background-color:transparent; - } - #content #optionsContainer #helpButton { - background:url('../img/help.png') no-repeat; - } - #content #optionsContainer #settingsButton { - background:url('../img/settings.png') no-repeat; - } - #content #optionsContainer #onlineListButton { - background:url('../img/users.png') no-repeat; - } - #content #optionsContainer #audioButton { - background:url('../img/audio.png') no-repeat; - } - #content #optionsContainer #audioButton.off { - background:url('../img/audio-off.png') no-repeat; - } - #content #optionsContainer #autoScrollButton { - background:url('../img/autoscroll.png') no-repeat; - } - #content #optionsContainer #autoScrollButton.off { - background:url('../img/autoscroll-off.png') no-repeat; - } - #content .rowEven { - background-color:#ECEDF3; - } - #content .rowOdd { - background-color:#F6F6F6; - } - #content .guest { - color:gray; - } - #content .user { - color:#000; - } - #content .moderator { - color:#0000FF; - } - #content .admin { - color:#FF0000; - } - #content .chatBot { - color:#476C8E; - } - #content #chatList .chatBotErrorMessage { - color:red; - } - #content #chatList a { - color:#476C8E; - } - #content #chatList .delete { - background:url('../img/delete.png') no-repeat right; - } - #content #chatList .deleteSelected { - border-color:red; - } - #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { - background-color:#88A6C0; - color:#FFF; - } - #content #settingsContainer #settingsList input.playback { - background:url('../img/playback.png') no-repeat; - } - -} \ No newline at end of file diff --git a/chat/css/Lithium.css b/chat/css/Lithium.css deleted file mode 100644 index 3dbdb55..0000000 --- a/chat/css/Lithium.css +++ /dev/null @@ -1,147 +0,0 @@ -/* - * @package AJAX_Chat - * @author Sebastian Tschan - * @copyright (c) Sebastian Tschan - * @license GNU Affero General Public License - * @link https://blueimp.net/ajax/ - * - * Color palette inspired by PunBB style "Lithium": - * http://punbb.org/ - */ - - -@import url('positions.css'); -@import url('borders.css'); -@import url('fonts.css'); -@import url('misc.css'); -@import url('print.css'); - - -/* - * Colors - */ - -@media screen,projection,handheld { - - #loginContent { - background-color:#F1F1F1; - color:#333333; - } - #loginContent h1 { - color:#333333; - } - #loginContent a { - color:#638137; - } - #loginContent input, #loginContent select { - background-color:#FFF; - color:#333333; - } - #loginContent #loginFormContainer #loginButton { - background-color:#F7F5F1; - color:#333333; - } - #loginContent #errorContainer { - color:red; - } - - #content { - background-color:#F1F1F1; - color:#333333; - } - #content h1 { - color:#333333; - } - #content a { - color:#638137; - } - #content input, #content select, #content textarea { - background-color:#FFF; - color:#333333; - } - #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { - border-color:#6C8A3F; - background-color:#FFF; - } - .statusContainerOn { - background-image: url('../img/loading.png'); - } - .statusContainerOff { - background-image: url('../img/loading-done.png'); - } - .statusContainerAlert { - background-image: url('../img/loading-trouble.png'); - } - #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { - background-color:#F7F5F1; - color:#333333; - } - #content #colorCodesContainer a { - border-color:black; - } - #content #optionsContainer input { - background-color:transparent; - } - #content #optionsContainer #helpButton { - background:url('../img/help.png') no-repeat; - } - #content #optionsContainer #settingsButton { - background:url('../img/settings.png') no-repeat; - } - #content #optionsContainer #onlineListButton { - background:url('../img/users.png') no-repeat; - } - #content #optionsContainer #audioButton { - background:url('../img/audio.png') no-repeat; - } - #content #optionsContainer #audioButton.off { - background:url('../img/audio-off.png') no-repeat; - } - #content #optionsContainer #autoScrollButton { - background:url('../img/autoscroll.png') no-repeat; - } - #content #optionsContainer #autoScrollButton.off { - background:url('../img/autoscroll-off.png') no-repeat; - } - #content .rowEven { - background-color:#F1F1F1; - } - #content .rowOdd { - background-color:#DEDFDF; - } - #content .guest { - color:gray; - } - #content .user { - color:#000; - } - #content .moderator { - color:#00AA00; - } - #content .admin { - color:red; - } - #content .chatBot { - color:#638137; - } - #content #chatList .chatBotErrorMessage { - color:red; - } - #content #chatList a { - color:#638137; - } - #content #chatList .delete { - background:url('../img/delete.png') no-repeat right; - } - #content #chatList .deleteSelected { - border-color:red; - } - #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { - background-color:#6C8A3F; - color:#FFF; - } - #content #settingsContainer #settingsList input.playback { - background:url('../img/playback.png') no-repeat; - } - -} \ No newline at end of file diff --git a/chat/css/Mercury.css b/chat/css/Mercury.css deleted file mode 100644 index b81c69a..0000000 --- a/chat/css/Mercury.css +++ /dev/null @@ -1,147 +0,0 @@ -/* - * @package AJAX_Chat - * @author Sebastian Tschan - * @copyright (c) Sebastian Tschan - * @license GNU Affero General Public License - * @link https://blueimp.net/ajax/ - * - * Color palette inspired by PunBB style "Mercury": - * http://punbb.org/ - */ - - -@import url('positions.css'); -@import url('borders.css'); -@import url('fonts.css'); -@import url('misc.css'); -@import url('print.css'); - - -/* - * Colors - */ - -@media screen,projection,handheld { - - #loginContent { - background-color:#2A2A2A; - color:#D4D4D4; - } - #loginContent h1 { - color:#D4D4D4; - } - #loginContent a { - color:#F6B620; - } - #loginContent input, #loginContent select { - background-color:#424242; - color:#D4D4D4; - } - #loginContent #loginFormContainer #loginButton { - background-color:#424242; - color:#D4D4D4; - } - #loginContent #errorContainer { - color:red; - } - - #content { - background-color:#2A2A2A; - color:#D4D4D4; - } - #content h1 { - color:#D4D4D4; - } - #content a { - color:#F6B620; - } - #content input, #content select, #content textarea { - background-color:#383838; - color:#D4D4D4; - } - #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { - border-color:#565656; - background-color:#383838; - } - .statusContainerOn { - background-image: url('../img/loading.png'); - } - .statusContainerOff { - background-image: url('../img/loading-done.png'); - } - .statusContainerAlert { - background-image: url('../img/loading-trouble.png'); - } - #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { - background-color:#383838; - color:#D4D4D4; - } - #content #colorCodesContainer a { - border-color:black; - } - #content #optionsContainer input { - background-color:transparent; - } - #content #optionsContainer #helpButton { - background:url('../img/help.png') no-repeat; - } - #content #optionsContainer #settingsButton { - background:url('../img/settings.png') no-repeat; - } - #content #optionsContainer #onlineListButton { - background:url('../img/users.png') no-repeat; - } - #content #optionsContainer #audioButton { - background:url('../img/audio.png') no-repeat; - } - #content #optionsContainer #audioButton.off { - background:url('../img/audio-off.png') no-repeat; - } - #content #optionsContainer #autoScrollButton { - background:url('../img/autoscroll.png') no-repeat; - } - #content #optionsContainer #autoScrollButton.off { - background:url('../img/autoscroll-off.png') no-repeat; - } - #content .rowEven { - background-color:#565656; - } - #content .rowOdd { - background-color:#484848; - } - #content .guest { - color:gray; - } - #content .user { - color:#D4D4D4; - } - #content .moderator { - color:#00AA00; - } - #content .admin { - color:red; - } - #content .chatBot { - color:#F6B620; - } - #content #chatList .chatBotErrorMessage { - color:red; - } - #content #chatList a { - color:#F6B620; - } - #content #chatList .delete { - background:url('../img/delete.png') no-repeat right; - } - #content #chatList .deleteSelected { - border-color:red; - } - #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { - background-color:#383838; - color:#D4D4D4; - } - #content #settingsContainer #settingsList input.playback { - background:url('../img/playback.png') no-repeat; - } - -} \ No newline at end of file diff --git a/chat/css/MyBB.css b/chat/css/MyBB.css deleted file mode 100644 index 94ebb89..0000000 --- a/chat/css/MyBB.css +++ /dev/null @@ -1,147 +0,0 @@ -/* - * @package AJAX_Chat - * @author Sebastian Tschan - * @copyright (c) Sebastian Tschan - * @license GNU Affero General Public License - * @link https://blueimp.net/ajax/ - * - * Color palette inspired by MyBB style "MyBB Default": - * http://www.mybboard.net/ - */ - - -@import url('positions.css'); -@import url('borders.css'); -@import url('fonts.css'); -@import url('misc.css'); -@import url('print.css'); - - -/* - * Colors - */ - -@media screen,projection,handheld { - - #loginContent { - background-color:#FFF; - color:#000; - } - #loginContent h1 { - color:#0F5C8E; - } - #loginContent a { - color:#026CB1; - } - #loginContent input, #loginContent select { - background-color:#EFEFEF; - color:#000; - } - #loginContent #loginFormContainer #loginButton { - background-color:#F7F5F1; - color:#000; - } - #loginContent #errorContainer { - color:red; - } - - #content { - background-color:#FFF; - color:#000; - } - #content h1 { - color:#0F5C8E; - } - #content a { - color:#026CB1; - } - #content input, #content select, #content textarea { - background-color:#EFEFEF; - color:#000; - } - #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { - border-color:#0F5C8E; - background-color:#EFEFEF; - } - .statusContainerOn { - background-image: url('../img/loading.png'); - } - .statusContainerOff { - background-image: url('../img/loading-done.png'); - } - .statusContainerAlert { - background-image: url('../img/loading-trouble.png'); - } - #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { - background-color:#F7F5F1; - color:#000; - } - #content #colorCodesContainer a { - border-color:black; - } - #content #optionsContainer input { - background-color:transparent; - } - #content #optionsContainer #helpButton { - background:url('../img/help.png') no-repeat; - } - #content #optionsContainer #settingsButton { - background:url('../img/settings.png') no-repeat; - } - #content #optionsContainer #onlineListButton { - background:url('../img/users.png') no-repeat; - } - #content #optionsContainer #audioButton { - background:url('../img/audio.png') no-repeat; - } - #content #optionsContainer #audioButton.off { - background:url('../img/audio-off.png') no-repeat; - } - #content #optionsContainer #autoScrollButton { - background:url('../img/autoscroll.png') no-repeat; - } - #content #optionsContainer #autoScrollButton.off { - background:url('../img/autoscroll-off.png') no-repeat; - } - #content .rowEven { - background-color:#EFEFEF; - } - #content .rowOdd { - background-color:#F5F5F5; - } - #content .guest { - color:gray; - } - #content .user { - color:#000; - } - #content .moderator { - color:#CC00CC; - } - #content .admin { - color:#008000; - } - #content .chatBot { - color:#026CB1; - } - #content #chatList .chatBotErrorMessage { - color:red; - } - #content #chatList a { - color:#026CB1; - } - #content #chatList .delete { - background:url('../img/delete.png') no-repeat right; - } - #content #chatList .deleteSelected { - border-color:red; - } - #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { - background-color:#ADCBE7; - color:#000; - } - #content #settingsContainer #settingsList input.playback { - background:url('../img/playback.png') no-repeat; - } - -} \ No newline at end of file diff --git a/chat/css/Oxygen.css b/chat/css/Oxygen.css deleted file mode 100644 index a489c66..0000000 --- a/chat/css/Oxygen.css +++ /dev/null @@ -1,147 +0,0 @@ -/* - * @package AJAX_Chat - * @author Sebastian Tschan - * @copyright (c) Sebastian Tschan - * @license GNU Affero General Public License - * @link https://blueimp.net/ajax/ - * - * Color palette inspired by PunBB style "Oxygen": - * http://punbb.org/ - */ - - -@import url('positions.css'); -@import url('borders.css'); -@import url('fonts.css'); -@import url('misc.css'); -@import url('print.css'); - - -/* - * Colors - */ - -@media screen,projection,handheld { - - #loginContent { - background-color:#F1F1F1; - color:#333333; - } - #loginContent h1 { - color:#333333; - } - #loginContent a { - color:#005CB1; - } - #loginContent input, #loginContent select { - background-color:#FFF; - color:#333333; - } - #loginContent #loginFormContainer #loginButton { - background-color:#F7F5F1; - color:#333333; - } - #loginContent #errorContainer { - color:red; - } - - #content { - background-color:#F1F1F1; - color:#333333; - } - #content h1 { - color:#333333; - } - #content a { - color:#005CB1; - } - #content input, #content select, #content textarea { - background-color:#FFF; - color:#333333; - } - #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { - border-color:#0066B9; - background-color:#FFF; - } - .statusContainerOn { - background-image: url('../img/loading.png'); - } - .statusContainerOff { - background-image: url('../img/loading-done.png'); - } - .statusContainerAlert { - background-image: url('../img/loading-trouble.png'); - } - #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { - background-color:#F7F5F1; - color:#333333; - } - #content #colorCodesContainer a { - border-color:black; - } - #content #optionsContainer input { - background-color:transparent; - } - #content #optionsContainer #helpButton { - background:url('../img/help.png') no-repeat; - } - #content #optionsContainer #settingsButton { - background:url('../img/settings.png') no-repeat; - } - #content #optionsContainer #onlineListButton { - background:url('../img/users.png') no-repeat; - } - #content #optionsContainer #audioButton { - background:url('../img/audio.png') no-repeat; - } - #content #optionsContainer #audioButton.off { - background:url('../img/audio-off.png') no-repeat; - } - #content #optionsContainer #autoScrollButton { - background:url('../img/autoscroll.png') no-repeat; - } - #content #optionsContainer #autoScrollButton.off { - background:url('../img/autoscroll-off.png') no-repeat; - } - #content .rowEven { - background-color:#F1F1F1; - } - #content .rowOdd { - background-color:#DEDFDF; - } - #content .guest { - color:gray; - } - #content .user { - color:#000; - } - #content .moderator { - color:#00AA00; - } - #content .admin { - color:red; - } - #content .chatBot { - color:#005CB1; - } - #content #chatList .chatBotErrorMessage { - color:red; - } - #content #chatList a { - color:#005CB1; - } - #content #chatList .delete { - background:url('../img/delete.png') no-repeat right; - } - #content #chatList .deleteSelected { - border-color:red; - } - #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { - background-color:#0066B9; - color:#FFF; - } - #content #settingsContainer #settingsList input.playback { - background:url('../img/playback.png') no-repeat; - } - -} \ No newline at end of file diff --git a/chat/css/Radium.css b/chat/css/Radium.css deleted file mode 100644 index 819e5eb..0000000 --- a/chat/css/Radium.css +++ /dev/null @@ -1,147 +0,0 @@ -/* - * @package AJAX_Chat - * @author Sebastian Tschan - * @copyright (c) Sebastian Tschan - * @license GNU Affero General Public License - * @link https://blueimp.net/ajax/ - * - * Color palette inspired by PunBB style "Radium": - * http://punbb.org/ - */ - - -@import url('positions.css'); -@import url('borders.css'); -@import url('fonts.css'); -@import url('misc.css'); -@import url('print.css'); - - -/* - * Colors - */ - -@media screen,projection,handheld { - - #loginContent { - background-color:#2A2A2A; - color:#D4D4D4; - } - #loginContent h1 { - color:#D4D4D4; - } - #loginContent a { - color:#60C860; - } - #loginContent input, #loginContent select { - background-color:#424242; - color:#D4D4D4; - } - #loginContent #loginFormContainer #loginButton { - background-color:#424242; - color:#D4D4D4; - } - #loginContent #errorContainer { - color:red; - } - - #content { - background-color:#2A2A2A; - color:#D4D4D4; - } - #content h1 { - color:#D4D4D4; - } - #content a { - color:#60C860; - } - #content input, #content select, #content textarea { - background-color:#383838; - color:#D4D4D4; - } - #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { - border-color:#565656; - background-color:#383838; - } - .statusContainerOn { - background-image: url('../img/loading.png'); - } - .statusContainerOff { - background-image: url('../img/loading-done.png'); - } - .statusContainerAlert { - background-image: url('../img/loading-trouble.png'); - } - #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { - background-color:#383838; - color:#D4D4D4; - } - #content #colorCodesContainer a { - border-color:black; - } - #content #optionsContainer input { - background-color:transparent; - } - #content #optionsContainer #helpButton { - background:url('../img/help.png') no-repeat; - } - #content #optionsContainer #settingsButton { - background:url('../img/settings.png') no-repeat; - } - #content #optionsContainer #onlineListButton { - background:url('../img/users.png') no-repeat; - } - #content #optionsContainer #audioButton { - background:url('../img/audio.png') no-repeat; - } - #content #optionsContainer #audioButton.off { - background:url('../img/audio-off.png') no-repeat; - } - #content #optionsContainer #autoScrollButton { - background:url('../img/autoscroll.png') no-repeat; - } - #content #optionsContainer #autoScrollButton.off { - background:url('../img/autoscroll-off.png') no-repeat; - } - #content .rowEven { - background-color:#565656; - } - #content .rowOdd { - background-color:#484848; - } - #content .guest { - color:gray; - } - #content .user { - color:#D4D4D4; - } - #content .moderator { - color:#00AA00; - } - #content .admin { - color:red; - } - #content .chatBot { - color:#60C860; - } - #content #chatList .chatBotErrorMessage { - color:red; - } - #content #chatList a { - color:#60C860; - } - #content #chatList .delete { - background:url('../img/delete.png') no-repeat right; - } - #content #chatList .deleteSelected { - border-color:red; - } - #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { - background-color:#383838; - color:#D4D4D4; - } - #content #settingsContainer #settingsList input.playback { - background:url('../img/playback.png') no-repeat; - } - -} \ No newline at end of file diff --git a/chat/css/Sulfur.css b/chat/css/Sulfur.css deleted file mode 100644 index a1e47f9..0000000 --- a/chat/css/Sulfur.css +++ /dev/null @@ -1,147 +0,0 @@ -/* - * @package AJAX_Chat - * @author Sebastian Tschan - * @copyright (c) Sebastian Tschan - * @license GNU Affero General Public License - * @link https://blueimp.net/ajax/ - * - * Color palette inspired by PunBB style "Sulfur": - * http://punbb.org/ - */ - - -@import url('positions.css'); -@import url('borders.css'); -@import url('fonts.css'); -@import url('misc.css'); -@import url('print.css'); - - -/* - * Colors - */ - -@media screen,projection,handheld { - - #loginContent { - background-color:#F1F1F1; - color:#333333; - } - #loginContent h1 { - color:#333333; - } - #loginContent a { - color:#822100; - } - #loginContent input, #loginContent select { - background-color:#FFF; - color:#333333; - } - #loginContent #loginFormContainer #loginButton { - background-color:#F7F5F1; - color:#333333; - } - #loginContent #errorContainer { - color:red; - } - - #content { - background-color:#F1F1F1; - color:#333333; - } - #content h1 { - color:#333333; - } - #content a { - color:#822100; - } - #content input, #content select, #content textarea { - background-color:#FFF; - color:#333333; - } - #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { - border-color:#B84623; - background-color:#FFF; - } - .statusContainerOn { - background-image: url('../img/loading.png'); - } - .statusContainerOff { - background-image: url('../img/loading-done.png'); - } - .statusContainerAlert { - background-image: url('../img/loading-trouble.png'); - } - #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { - background-color:#F7F5F1; - color:#333333; - } - #content #colorCodesContainer a { - border-color:black; - } - #content #optionsContainer input { - background-color:transparent; - } - #content #optionsContainer #helpButton { - background:url('../img/help.png') no-repeat; - } - #content #optionsContainer #settingsButton { - background:url('../img/settings.png') no-repeat; - } - #content #optionsContainer #onlineListButton { - background:url('../img/users.png') no-repeat; - } - #content #optionsContainer #audioButton { - background:url('../img/audio.png') no-repeat; - } - #content #optionsContainer #audioButton.off { - background:url('../img/audio-off.png') no-repeat; - } - #content #optionsContainer #autoScrollButton { - background:url('../img/autoscroll.png') no-repeat; - } - #content #optionsContainer #autoScrollButton.off { - background:url('../img/autoscroll-off.png') no-repeat; - } - #content .rowEven { - background-color:#F1F1F1; - } - #content .rowOdd { - background-color:#DEDFDF; - } - #content .guest { - color:gray; - } - #content .user { - color:#000; - } - #content .moderator { - color:#00AA00; - } - #content .admin { - color:red; - } - #content .chatBot { - color:#822100; - } - #content #chatList .chatBotErrorMessage { - color:red; - } - #content #chatList a { - color:#822100; - } - #content #chatList .delete { - background:url('../img/delete.png') no-repeat right; - } - #content #chatList .deleteSelected { - border-color:red; - } - #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { - background-color:#B84623; - color:#FFF; - } - #content #settingsContainer #settingsList input.playback { - background:url('../img/playback.png') no-repeat; - } - -} \ No newline at end of file diff --git a/chat/css/beige.css b/chat/css/beige.css deleted file mode 100644 index 928706f..0000000 --- a/chat/css/beige.css +++ /dev/null @@ -1,144 +0,0 @@ -/* - * @package AJAX_Chat - * @author Sebastian Tschan - * @copyright (c) Sebastian Tschan - * @license GNU Affero General Public License - * @link https://blueimp.net/ajax/ - */ - - -@import url('positions.css'); -@import url('borders.css'); -@import url('fonts.css'); -@import url('misc.css'); -@import url('print.css'); - - -/* - * Colors - */ - -@media screen,projection,handheld { - - #loginContent { - background-color:#F7F5DC; - color:#000; - } - #loginContent h1 { - color:#000; - } - #loginContent a { - color:#000; - } - #loginContent input, #loginContent select { - background-color:#FFF; - color:#000; - } - #loginContent #loginFormContainer #loginButton { - background-color:#F7F5F1; - color:#000; - } - #loginContent #errorContainer { - color:red; - } - - #content { - background-color:#F7F5DC; - color:#000; - } - #content h1 { - color:#000; - } - #content a { - color:#000; - } - #content input, #content select, #content textarea { - background-color:#FFF; - color:#000; - } - #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer{ - border-color:gray; - background-color:#FFF; - } - .statusContainerOn { - background-image: url('../img/loading.png'); - } - .statusContainerOff { - background-image: url('../img/loading-done.png'); - } - .statusContainerAlert { - background-image: url('../img/loading-trouble.png'); - } - #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { - background-color:#F7F5F1; - color:#000; - } - #content #colorCodesContainer a { - border-color:black; - } - #content #optionsContainer input { - background-color:transparent; - } - #content #optionsContainer #helpButton { - background:url('../img/help.png') no-repeat; - } - #content #optionsContainer #settingsButton { - background:url('../img/settings.png') no-repeat; - } - #content #optionsContainer #onlineListButton { - background:url('../img/users.png') no-repeat; - } - #content #optionsContainer #audioButton { - background:url('../img/audio.png') no-repeat; - } - #content #optionsContainer #audioButton.off { - background:url('../img/audio-off.png') no-repeat; - } - #content #optionsContainer #autoScrollButton { - background:url('../img/autoscroll.png') no-repeat; - } - #content #optionsContainer #autoScrollButton.off { - background:url('../img/autoscroll-off.png') no-repeat; - } - #content .rowEven { - background-color:#FFFFF0; - } - #content .rowOdd { - background-color:#F7F5DC; - } - #content .guest { - color:gray; - } - #content .user { - color:#000; - } - #content .moderator { - color:#00AA00; - } - #content .admin { - color:red; - } - #content .chatBot { - color:#FF6600; - } - #content #chatList .chatBotErrorMessage { - color:red; - } - #content #chatList a { - color:#1E90FF; - } - #content #chatList .delete { - background:url('../img/delete.png') no-repeat right; - } - #content #chatList .deleteSelected { - border-color:red; - } - #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { - background-color:#FFFFF0; - color:#000; - } - #content #settingsContainer #settingsList input.playback { - background:url('../img/playback.png') no-repeat; - } - -} \ No newline at end of file diff --git a/chat/css/black.css b/chat/css/black.css deleted file mode 100644 index 538a92c..0000000 --- a/chat/css/black.css +++ /dev/null @@ -1,144 +0,0 @@ -/* - * @package AJAX_Chat - * @author Sebastian Tschan - * @copyright (c) Sebastian Tschan - * @license GNU Affero General Public License - * @link https://blueimp.net/ajax/ - */ - - -@import url('positions.css'); -@import url('borders.css'); -@import url('fonts.css'); -@import url('misc.css'); -@import url('print.css'); - - -/* - * Colors - */ - -@media screen,projection,handheld { - - #loginContent { - background-color:#000; - color:#FFF; - } - #loginContent h1 { - color:#FFF; - } - #loginContent a { - color:#FFF; - } - #loginContent input, #loginContent select { - background-color:#212121; - color:#FFF; - } - #loginContent #loginFormContainer #loginButton { - background-color:#212121; - color:#FFF; - } - #loginContent #errorContainer { - color:red; - } - - #content { - background-color:#000; - color:#FFF; - } - #content h1 { - color:#FFF; - } - #content a { - color:#FFF; - } - #content input, #content select, #content textarea { - background-color:#212121; - color:#FFF; - } - #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { - border-color:gray; - background-color:#000; - } - .statusContainerOn { - background-image: url('../img/loading.png'); - } - .statusContainerOff { - background-image: url('../img/loading-done.png'); - } - .statusContainerAlert { - background-image: url('../img/loading-trouble.png'); - } - #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { - background-color:#212121; - color:#FFF; - } - #content #colorCodesContainer a { - border-color:black; - } - #content #optionsContainer input { - background-color:transparent; - } - #content #optionsContainer #helpButton { - background:url('../img/help.png') no-repeat; - } - #content #optionsContainer #settingsButton { - background:url('../img/settings.png') no-repeat; - } - #content #optionsContainer #onlineListButton { - background:url('../img/users.png') no-repeat; - } - #content #optionsContainer #audioButton { - background:url('../img/audio.png') no-repeat; - } - #content #optionsContainer #audioButton.off { - background:url('../img/audio-off.png') no-repeat; - } - #content #optionsContainer #autoScrollButton { - background:url('../img/autoscroll.png') no-repeat; - } - #content #optionsContainer #autoScrollButton.off { - background:url('../img/autoscroll-off.png') no-repeat; - } - #content .rowEven { - background-color:#212121; - } - #content .rowOdd { - background-color:#000; - } - #content .guest { - color:gray; - } - #content .user { - color:#FFF; - } - #content .moderator { - color:#00AA00; - } - #content .admin { - color:red; - } - #content .chatBot { - color:#FF6600; - } - #content #chatList .chatBotErrorMessage { - color:red; - } - #content #chatList a { - color:#1E90FF; - } - #content #chatList .delete { - background:url('../img/delete.png') no-repeat right; - } - #content #chatList .deleteSelected { - border-color:red; - } - #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { - background-color:#212121; - color:#FFF; - } - #content #settingsContainer #settingsList input.playback { - background:url('../img/playback.png') no-repeat; - } - -} \ No newline at end of file diff --git a/chat/css/grey.css b/chat/css/grey.css deleted file mode 100644 index f348759..0000000 --- a/chat/css/grey.css +++ /dev/null @@ -1,144 +0,0 @@ -/* - * @package AJAX_Chat - * @author Sebastian Tschan - * @copyright (c) Sebastian Tschan - * @license GNU Affero General Public License - * @link https://blueimp.net/ajax/ - */ - - -@import url('positions.css'); -@import url('borders.css'); -@import url('fonts.css'); -@import url('misc.css'); -@import url('print.css'); - - -/* - * Colors - */ - -@media screen,projection,handheld { - - #loginContent { - background-color:#F6F6F6; - color:#000; - } - #loginContent h1 { - color:#000; - } - #loginContent a { - color:#000; - } - #loginContent input, #loginContent select { - background-color:#FFF; - color:#000; - } - #loginContent #loginFormContainer #loginButton { - background-color:#F7F5F1; - color:#000; - } - #loginContent #errorContainer { - color:red; - } - - #content { - background-color:#F6F6F6; - color:#000; - } - #content h1 { - color:#000; - } - #content a { - color:#000; - } - #content input, #content select, #content textarea { - background-color:#FFF; - color:#000; - } - #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { - border-color:gray; - background-color:#FFF; - } - .statusContainerOn { - background-image: url('../img/loading.png'); - } - .statusContainerOff { - background-image: url('../img/loading-done.png'); - } - .statusContainerAlert { - background-image: url('../img/loading-trouble.png'); - } - #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { - background-color:#F7F5F1; - color:#000; - } - #content #colorCodesContainer a { - border-color:black; - } - #content #optionsContainer input { - background-color:transparent; - } - #content #optionsContainer #helpButton { - background:url('../img/help.png') no-repeat; - } - #content #optionsContainer #settingsButton { - background:url('../img/settings.png') no-repeat; - } - #content #optionsContainer #onlineListButton { - background:url('../img/users.png') no-repeat; - } - #content #optionsContainer #audioButton { - background:url('../img/audio.png') no-repeat; - } - #content #optionsContainer #audioButton.off { - background:url('../img/audio-off.png') no-repeat; - } - #content #optionsContainer #autoScrollButton { - background:url('../img/autoscroll.png') no-repeat; - } - #content #optionsContainer #autoScrollButton.off { - background:url('../img/autoscroll-off.png') no-repeat; - } - #content .rowEven { - background-color:#FFF; - } - #content .rowOdd { - background-color:#F6F6F6; - } - #content .guest { - color:gray; - } - #content .user { - color:#000; - } - #content .moderator { - color:#00AA00; - } - #content .admin { - color:red; - } - #content .chatBot { - color:#FF6600; - } - #content #chatList .chatBotErrorMessage { - color:red; - } - #content #chatList a { - color:#1E90FF; - } - #content #chatList .delete { - background:url('../img/delete.png') no-repeat right; - } - #content #chatList .deleteSelected { - border-color:red; - } - #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { - background-color:#FFF; - color:#000; - } - #content #settingsContainer #settingsList input.playback { - background:url('../img/playback.png') no-repeat; - } - -} \ No newline at end of file diff --git a/chat/css/prosilver.css b/chat/css/prosilver.css deleted file mode 100644 index 9c6ac68..0000000 --- a/chat/css/prosilver.css +++ /dev/null @@ -1,147 +0,0 @@ -/* - * @package AJAX_Chat - * @author Sebastian Tschan - * @copyright (c) Sebastian Tschan - * @license GNU Affero General Public License - * @link https://blueimp.net/ajax/ - * - * Color palette inspired by phpBB style "prosilver": - * http://www.phpbb.com/ - */ - - -@import url('positions.css'); -@import url('borders.css'); -@import url('fonts.css'); -@import url('misc.css'); -@import url('print.css'); - - -/* - * Colors - */ - -@media screen,projection,handheld { - - #loginContent { - background-color:#F9F9F9; - color:#28313F; - } - #loginContent h1 { - color:#333333; - } - #loginContent a { - color:#333333; - } - #loginContent input, #loginContent select { - background-color:#FFF; - color:#333333; - } - #loginContent #loginFormContainer #loginButton { - background-color:#F7F5F1; - color:#333333; - } - #loginContent #errorContainer { - color:red; - } - - #content { - background-color:#F9F9F9; - color:#28313F; - } - #content h1 { - color:#333333; - } - #content a { - color:#333333; - } - #content input, #content select, #content textarea { - background-color:#FFF; - color:#333333; - } - #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { - border-color:#105289; - background-color:#FFF; - } - .statusContainerOn { - background-image: url('../img/loading.png'); - } - .statusContainerOff { - background-image: url('../img/loading-done.png'); - } - .statusContainerAlert { - background-image: url('../img/loading-trouble.png'); - } - #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { - background-color:#F7F5F1; - color:#333333; - } - #content #colorCodesContainer a { - border-color:black; - } - #content #optionsContainer input { - background-color:transparent; - } - #content #optionsContainer #helpButton { - background:url('../img/help.png') no-repeat; - } - #content #optionsContainer #settingsButton { - background:url('../img/settings.png') no-repeat; - } - #content #optionsContainer #onlineListButton { - background:url('../img/users.png') no-repeat; - } - #content #optionsContainer #audioButton { - background:url('../img/audio.png') no-repeat; - } - #content #optionsContainer #audioButton.off { - background:url('../img/audio-off.png') no-repeat; - } - #content #optionsContainer #autoScrollButton { - background:url('../img/autoscroll.png') no-repeat; - } - #content #optionsContainer #autoScrollButton.off { - background:url('../img/autoscroll-off.png') no-repeat; - } - #content .rowEven { - background-color:#E1EBF2; - } - #content .rowOdd { - background-color:#ECF3F7; - } - #content .guest { - color:gray; - } - #content .user { - color:#333333; - } - #content .moderator { - color:#00AA00; - } - #content .admin { - color:#AA0000; - } - #content .chatBot { - color:#D31141; - } - #content #chatList .chatBotErrorMessage { - color:red; - } - #content #chatList a { - color:#D31141; - } - #content #chatList .delete { - background:url('../img/delete.png') no-repeat right; - } - #content #chatList .deleteSelected { - border-color:red; - } - #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { - background-color:#E1EBF2; - color:#105289; - } - #content #settingsContainer #settingsList input.playback { - background:url('../img/playback.png') no-repeat; - } - -} \ No newline at end of file diff --git a/chat/css/subSilver.css b/chat/css/subSilver.css deleted file mode 100644 index 1cca969..0000000 --- a/chat/css/subSilver.css +++ /dev/null @@ -1,147 +0,0 @@ -/* - * @package AJAX_Chat - * @author Sebastian Tschan - * @copyright (c) Sebastian Tschan - * @license GNU Affero General Public License - * @link https://blueimp.net/ajax/ - * - * Color palette inspired by phpBB style "subSilver": - * http://www.phpbb.com/ - */ - - -@import url('positions.css'); -@import url('borders.css'); -@import url('fonts.css'); -@import url('misc.css'); -@import url('print.css'); - - -/* - * Colors - */ - -@media screen,projection,handheld { - - #loginContent { - background-color:#E5E5E5; - color:#000; - } - #loginContent h1 { - color:#006699; - } - #loginContent a { - color:#000; - } - #loginContent input, #loginContent select { - background-color:#FFF; - color:#000; - } - #loginContent #loginFormContainer #loginButton { - background-color:#F7F5F1; - color:#000; - } - #loginContent #errorContainer { - color:red; - } - - #content { - background-color:#E5E5E5; - color:#000; - } - #content h1 { - color:#006699; - } - #content a { - color:#000; - } - #content input, #content select, #content textarea { - background-color:#FFF; - color:#000; - } - #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { - border-color:#006699; - background-color:#FFF; - } - .statusContainerOn { - background-image: url('../img/loading.png'); - } - .statusContainerOff { - background-image: url('../img/loading-done.png'); - } - .statusContainerAlert { - background-image: url('../img/loading-trouble.png'); - } - #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { - background-color:#F7F5F1; - color:#000; - } - #content #colorCodesContainer a { - border-color:black; - } - #content #optionsContainer input { - background-color:transparent; - } - #content #optionsContainer #helpButton { - background:url('../img/help.png') no-repeat; - } - #content #optionsContainer #settingsButton { - background:url('../img/settings.png') no-repeat; - } - #content #optionsContainer #onlineListButton { - background:url('../img/users.png') no-repeat; - } - #content #optionsContainer #audioButton { - background:url('../img/audio.png') no-repeat; - } - #content #optionsContainer #audioButton.off { - background:url('../img/audio-off.png') no-repeat; - } - #content #optionsContainer #autoScrollButton { - background:url('../img/autoscroll.png') no-repeat; - } - #content #optionsContainer #autoScrollButton.off { - background:url('../img/autoscroll-off.png') no-repeat; - } - #content .rowEven { - background-color:#DEE3E7; - } - #content .rowOdd { - background-color:#EFEFEF; - } - #content .guest { - color:gray; - } - #content .user { - color:#000; - } - #content .moderator { - color:#006600; - } - #content .admin { - color:#FFA34F; - } - #content .chatBot { - color:#DD6900; - } - #content #chatList .chatBotErrorMessage { - color:red; - } - #content #chatList a { - color:#006699; - } - #content #chatList .delete { - background:url('../img/delete.png') no-repeat right; - } - #content #chatList .deleteSelected { - border-color:red; - } - #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { - background-color:#DEE3E7; - color:#006699; - } - #content #settingsContainer #settingsList input.playback { - background:url('../img/playback.png') no-repeat; - } - -} \ No newline at end of file diff --git a/chat/css/subblack2.css b/chat/css/subblack2.css deleted file mode 100644 index e7d1daf..0000000 --- a/chat/css/subblack2.css +++ /dev/null @@ -1,147 +0,0 @@ -/* - * @package AJAX_Chat - * @author Sebastian Tschan - * @copyright (c) Sebastian Tschan - * @license GNU Affero General Public License - * @link https://blueimp.net/ajax/ - * - * Color palette inspired by phpBB style "subblack2": - * http://www.phpbb.com/ - */ - - -@import url('positions.css'); -@import url('borders.css'); -@import url('fonts.css'); -@import url('misc.css'); -@import url('print.css'); - - -/* - * Colors - */ - -@media screen,projection,handheld { - - #loginContent { - background-color:#000; - color:#FFFFCC; - } - #loginContent h1 { - color:#FFFFCC; - } - #loginContent a { - color:#FFFFCC; - } - #loginContent input, #loginContent select { - background-color:#212121; - color:#FFFFCC; - } - #loginContent #loginFormContainer #loginButton { - background-color:#212121; - color:#FFFFCC; - } - #loginContent #errorContainer { - color:red; - } - - #content { - background-color:#000; - color:#FFFFCC; - } - #content h1 { - color:#CC9900; - } - #content a { - color:#FFFFCC; - } - #content input, #content select, #content textarea { - background-color:#212121; - color:#FFFFCC; - } - #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { - border-color:gray; - background-color:#212121; - } - .statusContainerOn { - background-image: url('../img/loading.png'); - } - .statusContainerOff { - background-image: url('../img/loading-done.png'); - } - .statusContainerAlert { - background-image: url('../img/loading-trouble.png'); - } - #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { - background-color:#212121; - color:#FFFFCC; - } - #content #colorCodesContainer a { - border-color:black; - } - #content #optionsContainer input { - background-color:transparent; - } - #content #optionsContainer #helpButton { - background:url('../img/help.png') no-repeat; - } - #content #optionsContainer #settingsButton { - background:url('../img/settings.png') no-repeat; - } - #content #optionsContainer #onlineListButton { - background:url('../img/users.png') no-repeat; - } - #content #optionsContainer #audioButton { - background:url('../img/audio.png') no-repeat; - } - #content #optionsContainer #audioButton.off { - background:url('../img/audio-off.png') no-repeat; - } - #content #optionsContainer #autoScrollButton { - background:url('../img/autoscroll.png') no-repeat; - } - #content #optionsContainer #autoScrollButton.off { - background:url('../img/autoscroll-off.png') no-repeat; - } - #content .rowEven { - background-color:#212121; - } - #content .rowOdd { - background-color:#000; - } - #content .guest { - color:gray; - } - #content .user { - color:#FFFFCC; - } - #content .moderator { - color:#00AA00; - } - #content .admin { - color:red; - } - #content .chatBot { - color:#CC9900; - } - #content #chatList .chatBotErrorMessage { - color:red; - } - #content #chatList a { - color:#FFCC00; - } - #content #chatList .delete { - background:url('../img/delete.png') no-repeat right; - } - #content #chatList .deleteSelected { - border-color:red; - } - #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { - background-color:#212121; - color:#FFCC00; - } - #content #settingsContainer #settingsList input.playback { - background:url('../img/playback.png') no-repeat; - } - -} \ No newline at end of file diff --git a/chat/css/subsilver2.css b/chat/css/subsilver2.css deleted file mode 100644 index b6ae2cf..0000000 --- a/chat/css/subsilver2.css +++ /dev/null @@ -1,147 +0,0 @@ -/* - * @package AJAX_Chat - * @author Sebastian Tschan - * @copyright (c) Sebastian Tschan - * @license GNU Affero General Public License - * @link https://blueimp.net/ajax/ - * - * Color palette inspired by phpBB style "subsilver2": - * http://www.phpbb.com/ - */ - - -@import url('positions.css'); -@import url('borders.css'); -@import url('fonts.css'); -@import url('misc.css'); -@import url('print.css'); - - -/* - * Colors - */ - -@media screen,projection,handheld { - - #loginContent { - background-color:#E5E5E5; - color:#000; - } - #loginContent h1 { - color:#006699; - } - #loginContent a { - color:#000; - } - #loginContent input, #loginContent select { - background-color:#FFF; - color:#000; - } - #loginContent #loginFormContainer #loginButton { - background-color:#F7F5F1; - color:#000; - } - #loginContent #errorContainer { - color:red; - } - - #content { - background-color:#E5E5E5; - color:#000; - } - #content h1 { - color:#006699; - } - #content a { - color:#000; - } - #content input, #content select, #content textarea { - background-color:#FFF; - color:#000; - } - #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { - border-color:#006699; - background-color:#FFF; - } - .statusContainerOn { - background-image: url('../img/loading.png'); - } - .statusContainerOff { - background-image: url('../img/loading-done.png'); - } - .statusContainerAlert { - background-image: url('../img/loading-trouble.png'); - } - #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { - background-color:#F7F5F1; - color:#000; - } - #content #colorCodesContainer a { - border-color:black; - } - #content #optionsContainer input { - background-color:transparent; - } - #content #optionsContainer #helpButton { - background:url('../img/help.png') no-repeat; - } - #content #optionsContainer #settingsButton { - background:url('../img/settings.png') no-repeat; - } - #content #optionsContainer #onlineListButton { - background:url('../img/users.png') no-repeat; - } - #content #optionsContainer #audioButton { - background:url('../img/audio.png') no-repeat; - } - #content #optionsContainer #audioButton.off { - background:url('../img/audio-off.png') no-repeat; - } - #content #optionsContainer #autoScrollButton { - background:url('../img/autoscroll.png') no-repeat; - } - #content #optionsContainer #autoScrollButton.off { - background:url('../img/autoscroll-off.png') no-repeat; - } - #content .rowEven { - background-color:#DEE3E7; - } - #content .rowOdd { - background-color:#EFEFEF; - } - #content .guest { - color:gray; - } - #content .user { - color:#000; - } - #content .moderator { - color:#00AA00; - } - #content .admin { - color:#AA0000; - } - #content .chatBot { - color:#DD6900; - } - #content #chatList .chatBotErrorMessage { - color:red; - } - #content #chatList a { - color:#006699; - } - #content #chatList .delete { - background:url('../img/delete.png') no-repeat right; - } - #content #chatList .deleteSelected { - border-color:red; - } - #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { - background-color:#DEE3E7; - color:#006699; - } - #content #settingsContainer #settingsList input.playback { - background:url('../img/playback.png') no-repeat; - } - -} \ No newline at end of file diff --git a/chat/css/vBulletin.css b/chat/css/vBulletin.css deleted file mode 100644 index bd7a8fd..0000000 --- a/chat/css/vBulletin.css +++ /dev/null @@ -1,147 +0,0 @@ -/* - * @package AJAX_Chat - * @author Sebastian Tschan - * @copyright (c) Sebastian Tschan - * @license GNU Affero General Public License - * @link https://blueimp.net/ajax/ - * - * Color palette inspired by vBulletin style "Standard-Style": - * http://www.vbulletin.com/ - */ - - -@import url('positions.css'); -@import url('borders.css'); -@import url('fonts.css'); -@import url('misc.css'); -@import url('print.css'); - - -/* - * Colors - */ - -@media screen,projection,handheld { - - #loginContent { - background-color:#E1E1E2; - color:#000; - } - #loginContent h1 { - color:#3B5485; - } - #loginContent a { - color:#3B5485; - } - #loginContent input, #loginContent select { - background-color:#FFF; - color:#000; - } - #loginContent #loginFormContainer #loginButton { - background-color:#F7F5F1; - color:#000; - } - #loginContent #errorContainer { - color:red; - } - - #content { - background-color:#E1E1E2; - color:#000; - } - #content h1 { - color:#3B5485; - } - #content a { - color:#3B5485; - } - #content input, #content select, #content textarea { - background-color:#FFF; - color:#000; - } - #content #chatList, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer, #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { - border-color:#0B198C; - background-color:#FFF; - } - .statusContainerOn { - background-image: url('../img/loading.png'); - } - .statusContainerOff { - background-image: url('../img/loading-done.png'); - } - .statusContainerAlert { - background-image: url('../img/loading-trouble.png'); - } - #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { - background-color:#F7F5F1; - color:#000; - } - #content #colorCodesContainer a { - border-color:black; - } - #content #optionsContainer input { - background-color:transparent; - } - #content #optionsContainer #helpButton { - background:url('../img/help.png') no-repeat; - } - #content #optionsContainer #settingsButton { - background:url('../img/settings.png') no-repeat; - } - #content #optionsContainer #onlineListButton { - background:url('../img/users.png') no-repeat; - } - #content #optionsContainer #audioButton { - background:url('../img/audio.png') no-repeat; - } - #content #optionsContainer #audioButton.off { - background:url('../img/audio-off.png') no-repeat; - } - #content #optionsContainer #autoScrollButton { - background:url('../img/autoscroll.png') no-repeat; - } - #content #optionsContainer #autoScrollButton.off { - background:url('../img/autoscroll-off.png') no-repeat; - } - #content .rowEven { - background-color:#E1E4F2; - } - #content .rowOdd { - background-color:#F5F5FF; - } - #content .guest { - color:gray; - } - #content .user { - color:#000; - } - #content .moderator { - color:#00AA00; - } - #content .admin { - color:red; - } - #content .chatBot { - color:#3B5485; - } - #content #chatList .chatBotErrorMessage { - color:red; - } - #content #chatList a { - color:#3B5485; - } - #content #chatList .delete { - background:url('../img/delete.png') no-repeat right; - } - #content #chatList .deleteSelected { - border-color:red; - } - #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { - background-color:#738FBF; - color:#FFF; - } - #content #settingsContainer #settingsList input.playback { - background:url('../img/playback.png') no-repeat; - } - -} \ No newline at end of file diff --git a/chat/js/config.js b/chat/js/config.js index bb9bc3a..9d73c7c 100644 --- a/chat/js/config.js +++ b/chat/js/config.js @@ -15,7 +15,7 @@ var ajaxChatConfig = { loginChannelName: null, // The time in ms between update calls to retrieve new chat messages: - timerRate: 2000, + timerRate: 5000, // The URL to retrieve the XML chat messages (must at least contain one parameter): ajaxURL: './?ajax=true', diff --git a/chat/js/custom.js b/chat/js/custom.js index d19ca16..8ab35fc 100644 --- a/chat/js/custom.js +++ b/chat/js/custom.js @@ -13,5 +13,4 @@ ajaxChat.replaceCustomCommands = function(text, textParts) { return text; } - */ - \ No newline at end of file + */ \ No newline at end of file diff --git a/chat/lib/class/AJAXChat.php b/chat/lib/class/AJAXChat.php index 5ecf875..8ad7002 100644 --- a/chat/lib/class/AJAXChat.php +++ b/chat/lib/class/AJAXChat.php @@ -462,8 +462,8 @@ function getValidRequestChannelID() { // channelName might need encoding conversion: if($channelID === null) { $channelID = $this->getChannelIDFromChannelName( - $this->trimChannelName($channelName, $this->getConfig('contentEncoding')) - ); + $this->trimChannelName($channelName, $this->getConfig('contentEncoding')) + ); } } } diff --git a/chat/lib/class/AJAXChatEncoding.php b/chat/lib/class/AJAXChatEncoding.php index 095114c..c0235d7 100644 --- a/chat/lib/class/AJAXChatEncoding.php +++ b/chat/lib/class/AJAXChatEncoding.php @@ -10,8 +10,8 @@ // Class to provide static encoding methods class AJAXChatEncoding { - // Helper function to store special chars as we cannot use static class members in PHP4: - function getSpecialChars() { + // Helper static function to store special chars as we cannot use static class members in PHP4: + static function getSpecialChars() { static $specialChars; if(!$specialChars) { // As ' is not supported by IE, we use ' as replacement for "'": @@ -20,8 +20,8 @@ function getSpecialChars() { return $specialChars; } - // Helper function to store Regular expression for NO-WS-CTL as we cannot use static class members in PHP4: - function getRegExp_NO_WS_CTL() { + // Helper static function to store Regular expression for NO-WS-CTL as we cannot use static class members in PHP4: + static function getRegExp_NO_WS_CTL() { static $regExp_NO_WS_CTL; if(!$regExp_NO_WS_CTL) { // Regular expression for NO-WS-CTL, non-whitespace control characters (RFC 2822), decimal 1–8, 11–12, 14–31, and 127: @@ -30,7 +30,7 @@ function getRegExp_NO_WS_CTL() { return $regExp_NO_WS_CTL; } - function convertEncoding($str, $charsetFrom, $charsetTo) { + static function convertEncoding($str, $charsetFrom, $charsetTo) { if(function_exists('mb_convert_encoding')) { return mb_convert_encoding($str, $charsetTo, $charsetFrom); } @@ -46,7 +46,7 @@ function convertEncoding($str, $charsetFrom, $charsetTo) { return $str; } - function htmlEncode($str, $contentCharset='UTF-8') { + static function htmlEncode($str, $contentCharset='UTF-8') { switch($contentCharset) { case 'UTF-8': // Encode only special chars (&, <, >, ', ") as entities: @@ -77,22 +77,22 @@ function htmlEncode($str, $contentCharset='UTF-8') { } } - function encodeSpecialChars($str) { + static function encodeSpecialChars($str) { return strtr($str, AJAXChatEncoding::getSpecialChars()); } - function decodeSpecialChars($str) { + static function decodeSpecialChars($str) { return strtr($str, array_flip(AJAXChatEncoding::getSpecialChars())); } - function encodeEntities($str, $encoding='UTF-8', $convmap=null) { + static function encodeEntities($str, $encoding='UTF-8', $convmap=null) { if($convmap && function_exists('mb_encode_numericentity')) { return mb_encode_numericentity($str, $convmap, $encoding); } return htmlentities($str, ENT_QUOTES, $encoding); } - function decodeEntities($str, $encoding='UTF-8', $htmlEntitiesMap=null) { + static function decodeEntities($str, $encoding='UTF-8', $htmlEntitiesMap=null) { // Due to PHP bug #25670, html_entity_decode does not work with UTF-8 for PHP versions < 5: if(function_exists('html_entity_decode') && version_compare(phpversion(), 5, '>=')) { // Replace numeric and literal entities: @@ -112,7 +112,7 @@ function decodeEntities($str, $encoding='UTF-8', $htmlEntitiesMap=null) { return $str; } - function unicodeChar($c) { + static function unicodeChar($c) { if($c <= 0x7F) { return chr($c); } else if($c <= 0x7FF) { @@ -129,7 +129,7 @@ function unicodeChar($c) { } } - function removeUnsafeCharacters($str) { + static function removeUnsafeCharacters($str) { // Remove NO-WS-CTL, non-whitespace control characters (RFC 2822), decimal 1–8, 11–12, 14–31, and 127: return preg_replace(AJAXChatEncoding::getRegExp_NO_WS_CTL(), '', $str); } diff --git a/chat/lib/class/AJAXChatFileSystem.php b/chat/lib/class/AJAXChatFileSystem.php index 9196f9f..263b1c8 100644 --- a/chat/lib/class/AJAXChatFileSystem.php +++ b/chat/lib/class/AJAXChatFileSystem.php @@ -10,7 +10,7 @@ // Class to provide methods for file system access: class AJAXChatFileSystem { - function getFileContents($file) { + static function getFileContents($file) { if(function_exists('file_get_contents')) { return file_get_contents($file); } else { diff --git a/chat/lib/class/AJAXChatMySQLQuery.php b/chat/lib/class/AJAXChatMySQLQuery.php index d33b0d8..3197b95 100644 --- a/chat/lib/class/AJAXChatMySQLQuery.php +++ b/chat/lib/class/AJAXChatMySQLQuery.php @@ -67,7 +67,7 @@ function numRows() { if($this->error()) { return null; } else { - return mysql_num_rows($this->_result); + return mysql_numRows($this->_result); } } diff --git a/chat/lib/class/AJAXChatString.php b/chat/lib/class/AJAXChatString.php index d861fed..f6acd81 100644 --- a/chat/lib/class/AJAXChatString.php +++ b/chat/lib/class/AJAXChatString.php @@ -10,7 +10,7 @@ // Class to provide multibyte enabled string methods class AJAXChatString { - function subString($str, $start=0, $length=null, $encoding='UTF-8') { + static function subString($str, $start=0, $length=null, $encoding='UTF-8') { if($length === null) { $length = AJAXChatString::stringLength($str); } @@ -23,7 +23,7 @@ function subString($str, $start=0, $length=null, $encoding='UTF-8') { } } - function stringLength($str, $encoding='UTF-8') { + static function stringLength($str, $encoding='UTF-8') { if(function_exists('mb_strlen')) { return mb_strlen($str, $encoding); } else if(function_exists('iconv_strlen')) { diff --git a/chat/lib/class/CustomAJAXChat.php b/chat/lib/class/CustomAJAXChat.php index 8b1b8d4..e9f3bb6 100644 --- a/chat/lib/class/CustomAJAXChat.php +++ b/chat/lib/class/CustomAJAXChat.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kr�pke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,135 +18,105 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kr�pke + * @copyright 2012 Jan Kr�pke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class CustomAJAXChat extends AJAXChat { function initCustomConfig() { - global $db, $CONF; - $this->setConfig('dbConnection', 'link', $db); - $this->setConfig('socketServerEnabled', false, (bool)$CONF['chat_socket_active']); - $this->setConfig('socketServerHost', false, empty($CONF['chat_socket_host']) ? NULL : $CONF['chat_socket_host']); - $this->setConfig('socketServerIP', false, $CONF['chat_socket_ip']); - $this->setConfig('socketServerPort', false, $CONF['chat_socket_port']); - $this->setConfig('socketServerChatID', false, $CONF['chat_socket_chatid']); - $this->setConfig('chatBotName', false, $CONF['chat_botname']); - $this->setConfig('allowUserMessageDelete', false, (bool) $CONF['chat_allowdelmes']); - $this->setConfig('allowNickChange', false, (bool) $CONF['chat_nickchange']); - $this->setConfig('chatClosed', false, (bool) $CONF['chat_closed']); - $this->setConfig('allowPrivateChannels', false, (bool) $CONF['chat_allowchan']); - $this->setConfig('allowPrivateMessages', false, (bool) $CONF['chat_allowmes']); - $this->setConfig('defaultChannelName', false, $CONF['chat_channelname']); - $this->setConfig('showChannelMessages', false, (bool) $CONF['chat_logmessage']); + $this->setConfig('dbConnection', 'link', $GLOBALS['DATABASE']); + $this->setConfig('chatBotName', false, Config::get('chat_botname')); + $this->setConfig('allowUserMessageDelete', false, (bool) Config::get('chat_allowdelmes')); + $this->setConfig('allowNickChange', false, (bool) Config::get('chat_nickchange')); + $this->setConfig('chatClosed', false, (bool) Config::get('chat_closed')); + $this->setConfig('allowPrivateChannels', false, (bool) Config::get('chat_allowchan')); + $this->setConfig('allowPrivateMessages', false, (bool) Config::get('chat_allowmes')); + $this->setConfig('defaultChannelName', false, Config::get('chat_channelname')); + $this->setConfig('showChannelMessages', false, (bool) Config::get('chat_logmessage')); $this->setConfig('langAvailable', false, Language::getAllowedLangs()); $this->setConfig('langNames', false, Language::getAllowedLangs(false)); + $this->setConfig('forceAutoLogin', false, true); } - - function initCustomRequestVars() { - $this->setRequestVar('login', true); - $this->setRequestVar('chat_type', isset($_REQUEST['chat_type']) ? $_REQUEST['chat_type'] : ''); - - if($this->getRequestVar('chat_type') == 'ally' && $_SESSION['USER']['ally_request'] == 0) { - $this->setConfig('defaultChannelID', false, $_SESSION['USER']['ally_id']); + + function initCustomSession() { + if(!$this->getRequestVar('ajax')) + { + $this->getAllChannels(); + if(!is_null($this->getChannel())) + { + $this->switchChannel($this->getConfig('defaultChannelName')); + } } } + + function initCustomRequestVars() { + $this->setRequestVar('action', isset($_REQUEST['action']) ? $_REQUEST['action'] : ''); + } function revalidateUserID() { - global $user; - if($this->getUserID() === $_SESSION['id']) { return true; } + return false; } - + function getValidLoginUserData() { - global $auth,$user; + global $auth, $user; // Return false if given user is a bot: if(!isset($_SESSION)) { return false; } + $sqlData = $this->db->sqlQuery("SELECT authlevel, username, ally_id FROM ".USERS." WHERE id = ".$_SESSION['id']." AND id NOT IN (SELECT userid FROM ".ALLIANCE_REQUEST.");")->fetch(); + $userData = array(); $userData['userID'] = $_SESSION['id']; - $userData['userName'] = $this->trimUserName($_SESSION['username']); + $userData['userName'] = $this->trimUserName($sqlData['username']); + $userData['userAlly'] = $sqlData['ally_id']; - if($_SESSION['authlevel'] == AUTH_ADM) + if($sqlData['authlevel'] == AUTH_ADM) $userData['userRole'] = AJAX_CHAT_ADMIN; - elseif($_SESSION['authlevel'] > AUTH_USR) + elseif($sqlData['authlevel'] > AUTH_USR) $userData['userRole'] = AJAX_CHAT_MODERATOR; else $userData['userRole'] = AJAX_CHAT_USER; - + return $userData; } - // Store the channels the current user has access to - // Make sure channel names don't contain any whitespace - function getChannels() { - if($this->_channels === null) { - global $auth; - - $this->_channels = array(); - - $allChannels = $this->getAllChannels(); - - foreach($allChannels as $key=>$value) { - // Check if we have to limit the available channels: - if($this->getConfig('limitChannelList') && !in_array($value, $this->getConfig('limitChannelList'))) { - continue; - } - - // Add the valid channels to the channel list (the defaultChannelID is always valid): - if($value == $this->getConfig('defaultChannelID') || $_SESSION['USER']['ally_id'] == $value) { - $this->_channels[$key] = $value; - } - } - } - return $this->_channels; - } - // Store all existing channels // Make sure channel names don't contain any whitespace function getAllChannels() { if($this->_allChannels === null) { - global $db; - - $this->_allChannels = array(); - $result = $db->query("SELECT `id`, `ally_name` FROM ".ALLIANCE.";"); + $this->_allChannels = array( + $this->trimChannelName($this->getConfig('defaultChannelName')) => $this->getConfig('defaultChannelID') + ); + + $userAlly = $this->db->sqlQuery("SELECT ally_id as id FROM ".USERS." WHERE id = ".$_SESSION['id'].";")->fetch(); + $result = $this->db->sqlQuery("SELECT id, ally_name FROM ".ALLIANCE." WHERE id = ".$userAlly['id'].";"); $defaultChannelFound = false; - while ($row = $db->fetch_array($result)) { - $this->_allChannels[$this->trimChannelName($row['ally_name'])] = $row['id']; - if($this->getConfig('defaultChannelID') == $row['id']) - $this->setConfig('defaultChannelName', false, $this->trimChannelName($row['ally_name'])); - - if(!$defaultChannelFound && $this->getRequestVar('chat_type') == 'ally' && $row['id'] == $_SESSION['USER']['ally_id']) { + while($row = $result->fetch()) { + $row['id'] = $row['id'] + 100; + $this->_allChannels[$this->trimChannelName('+'.$row['ally_name'])] = $row['id']; + if(!$defaultChannelFound && $this->getRequestVar('action') == 'alliance' && ($userAlly['id'] + 100) == $row['id']) + { + $this->setConfig('defaultChannelName', false, $this->trimChannelName('+'.$row['ally_name'])); + $this->setConfig('defaultChannelID', false, $row['id']); $defaultChannelFound = true; } } - $db->free_result($result); - - if(!$defaultChannelFound) { - // Add the default channel as first array element to the channel list: - $this->_allChannels = array_merge( - array( - $this->trimChannelName($this->getConfig('defaultChannelName'))=>$this->getConfig('defaultChannelID') - ), - $this->_allChannels - ); - } } + return $this->_allChannels; } } diff --git a/chat/lib/config.php b/chat/lib/config.php index 84d7470..b800969 100644 --- a/chat/lib/config.php +++ b/chat/lib/config.php @@ -47,7 +47,7 @@ $config['langNames'] = array('ar'=>'عربي','bg'=>'Български','bp'=>'Português (Brasil)','ca'=>'Català','cy'=>'Cymraeg','cz'=>'Česky','de'=>'Deutsch','el'=>'Ελληνικα','en'=>'English','es'=>'Español','et'=>'Eesti','fi'=>'Suomi','fr'=>'Français','gl'=>'Galego','he'=>'עברית','hr' => 'Hrvatski','hu' => 'Magyar','in'=>'Bahasa Indonesia','it'=>'Italiano','ja'=>'日本語','ka'=>'ქართული','kr'=>'한글','nl'=>'Nederlands','no'=>'Norsk','pl'=>'Polski','ro'=>'România','ru'=>'Русский','sk'=>'Slovenčina','sl'=>'Slovensko','sr'=>'Srpski','sv'=>'Svenska','tr'=>'Türkçe','uk'=>'Українська','zh'=>'中文 (简体)', 'zh-tw'=>'中文 (繁體)'); // Available styles: -$config['styleAvailable'] = array('2Moons', 'beige','black','grey','Oxygen','Lithium','Sulfur','Cobalt','Mercury','Radium','prosilver','subsilver2','subblack2','subSilver','Core','MyBB','vBulletin'); +$config['styleAvailable'] = array('2Moons'); // Default style: $config['styleDefault'] = '2Moons'; diff --git a/chat/lib/custom.php b/chat/lib/custom.php index 3a5073a..10cd7a1 100644 --- a/chat/lib/custom.php +++ b/chat/lib/custom.php @@ -10,16 +10,20 @@ // Include custom libraries and initialization code here -define('INSIDE', true ); -define('AJAX', true ); - +define('MODE', 'CHAT'); define('ROOT_PATH', str_replace('\\', '/',dirname(AJAX_CHAT_PATH)).'/'); -require(ROOT_PATH . 'includes/common.php'); -$SESSION = new Session(); +require(ROOT_PATH.'includes/common.php'); +require(ROOT_PATH.'includes/pages/game/class.AbstractPage.php'); +require(ROOT_PATH.'includes/pages/game/class.ShowErrorPage.php'); -if(!$SESSION->IsUserLogin() || ($CONF['game_disable'] == 0 && $_SESSION['authlevel'] == AUTH_USR)) - redirectTo('index.php?code=3'); +if(!$SESSION->IsUserLogin() || (Config::get('game_disable') == 0 && $USER['authlevel'] == AUTH_USR)) +{ + HTTP::redirectTo('index.php?code=3'); +} -if(CheckModule(7)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); +if(!isModulAvalible(MODULE_CHAT)) +{ + ShowErrorPage::printError($LNG['sys_module_inactive']); +} + ?> \ No newline at end of file diff --git a/chat/lib/template/loggedIn.html b/chat/lib/template/loggedIn.html index c609b58..cb5ddb1 100644 --- a/chat/lib/template/loggedIn.html +++ b/chat/lib/template/loggedIn.html @@ -105,9 +105,6 @@
-
-

[LANG]title[/LANG]

-
diff --git a/cronjob.php b/cronjob.php new file mode 100644 index 0000000..c50bc31 --- /dev/null +++ b/cronjob.php @@ -0,0 +1,61 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + +define('MODE', 'CRON'); + +define('ROOT_PATH', str_replace('\\', '/',dirname(__FILE__)).'/'); +require(ROOT_PATH . 'includes/common.php'); + +// Output transparent gif +HTTP::sendHeader('Cache-Control', 'no-cache'); +HTTP::sendHeader('Content-Type', 'image/gif'); +HTTP::sendHeader('Expires', '0'); +$isSessionActive = $SESSION->isActiveSession(); +echo("\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00\x21\xF9\x04\x01\x00\x00\x00\x00\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3B"); + +if(!$isSessionActive) +{ + exit; +} + +$cronjobID = HTTP::_GP('cronjobID', 0); + +if(empty($cronjobID)) +{ + exit; +} + +require ROOT_PATH.'includes/classes/Cronjob.class.php'; + +$cronjobsTodo = Cronjob::getNeedTodoExecutedJobs(); +if(!in_array($cronjobID, $cronjobsTodo)) +{ + exit; +} + +Cronjob::execute($cronjobID); diff --git a/cronjobs.php b/cronjobs.php deleted file mode 100644 index 256d95a..0000000 --- a/cronjobs.php +++ /dev/null @@ -1,126 +0,0 @@ -. - * - * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) - * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) - * @info $Id$ - * @link http://code.google.com/p/2moons/ - */ - -define('INSIDE' , true); -define('IN_CRON' , true); - -define('ROOT_PATH', str_replace('\\', '/',dirname(__FILE__)).'/'); -require(ROOT_PATH . 'includes/common.php'); - -if (empty($_SESSION)) exit; - -// Output transparent gif -header('Cache-Control: no-cache'); -header('Content-type: image/gif'); -header('Content-length: 43'); -header('Expires: 0'); -echo("\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00\x21\xF9\x04\x01\x00\x00\x00\x00\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3B"); -$cron = request_var('cron',''); -switch($cron) -{ - case "stats": - if (TIMESTAMP >= ($CONF['stat_last_update'] + (60 * $CONF['stat_update_time']))) - { - update_config(array('stat_last_update' => TIMESTAMP)); - require_once(ROOT_PATH . 'includes/classes/class.statbuilder.php'); - $stat = new Statbuilder(); - $result = $stat->MakeStats(); - } - break; - case "daily": - if (TIMESTAMP >= ($CONF['stat_last_db_update'] + (60 * 60 * 24))) - { - // Optimize Database - update_config(array('stat_last_db_update' => TIMESTAMP)); - $prueba = $db->query("SHOW TABLE STATUS from ".DB_NAME.";"); - $table = ""; - while($pru = $db->fetch_array($prueba)){ - $compprefix = explode("_",$pru["Name"]); - - if($compprefix[0].'_' == DB_PREFIX && $compprefix[1] != 'session') - { - $table .= "`".$pru["Name"]."`, "; - } - } - $db->query("OPTIMIZE TABLE ".substr($table, 0, -2).";"); - - // Clear Cache - ClearCache(); - // Set Bonus for RefLink - if($CONF['ref_active'] == 1) { - $Users = $db->query("SELECT `username`, `ref_id`, `id` FROM ".USERS." WHERE `ref_bonus` = 1 AND (SELECT `total_points` FROM ".STATPOINTS." as s WHERE s.`id_owner` = `id` AND s.`stat_type` = '1') >= ".$CONF['ref_minpoints'].";"); - $LANG->setDefault($CONF['lang']); - while($User = $db->fetch_array($Users)) { - $LANG->setUser($User['lang']); - $LANG->includeLang(array('INGAME', 'TECH')); - $db->multi_query("UPDATE ".USERS." SET `darkmatter` = `darkmatter` + '".$CONF['ref_bonus']."' WHERE `id` = '".$User['ref_id']."';UPDATE ".USERS." SET `ref_bonus` = `ref_bonus` = '0' WHERE `id` = '".$User['id']."';"); - $Message = sprintf($LNG['sys_refferal_text'], $User['username'], pretty_number($CONF['ref_minpoints']), $CONF['ref_bonus'], pretty_number($LNG['Darkmatter'])); - SendSimpleMessage($User['ref_id'], '', TIMESTAMP, 4, $LNG['sys_refferal_from'], sprintf($LNG['sys_refferal_title'], $User['username']), $Message); - } - } - // Send inactive Players Mails - if($CONF['sendmail_inactive'] == 1 && $CONF['mail_active'] == 1) { - $Users = $db->query("SELECT `id`, `username`, `lang`, `email`, `onlinetime` FROM ".USERS." WHERE `inactive_mail` = '0' AND `onlinetime` < '".(TIMESTAMP - $CONF['del_user_sendmail'])."';"); - while($User = $db->fetch_array($Users)) { - $MailSubject = sprintf($LNG['reg_mail_reg_done'], $CONF['game_name']); - $MailRAW = file_get_contents("./language/".$User['lang']."/email/email_inactive.txt"); - $MailContent = sprintf($MailRAW, $User['username'], $CONF['game_name'].' - '.$CONF['uni_name'], tz_date($User['onlinetime']), PROTOCOL.$_SERVER['HTTP_HOST'].HTTP_ROOT); - MailSend($User['email'], $User['username'], $MailSubject, $MailContent); - $db->query("UPDATE ".USERS." SET `inactive_mail` = '1' WHERE `id` = '".$User['id']."';"); - } - } - } - break; - case "teamspeak": - if ($CONF['ts_modon'] == 1 && TIMESTAMP >= ($CONF['ts_cron_last'] + 60 * $CONF['ts_cron_interval'])) - { - update_config(array('ts_cron_last' => TIMESTAMP)); - if($CONF['ts_version'] == 2) - { - include_once(ROOT_PATH.'includes/libs/teamspeak/class.teamspeak2.php'); - $ts = new cyts(); - if($ts->connect($CONF['ts_server'], $CONF['ts_tcpport'], $CONF['ts_udpport'], $CONF['ts_timeout'])) { - file_put_contents(ROOT_PATH.'cache/teamspeak_cache.php', serialize(array($ts->info_serverInfo(), $ts->info_globalInfo()))); - $ts->disconnect(); - } - } elseif($CONF['ts_version'] == 3){ - require_once(ROOT_PATH . "includes/libs/teamspeak/class.teamspeak3.php"); - $tsAdmin = new ts3admin($CONF['ts_server'], $CONF['ts_udpport'], $CONF['ts_timeout']); - $Active = $tsAdmin->connect(); - if($Active['success']) { - $tsAdmin->selectServer($CONF['ts_tcpport'], 'port', true); - $tsAdmin->login($CONF['ts_login'], $CONF['ts_password']); - file_put_contents(ROOT_PATH.'cache/teamspeak_cache.php', serialize($tsAdmin->serverInfo())); - $tsAdmin->logout(); - } - } - } - break; -} -?> \ No newline at end of file diff --git a/game.php b/game.php index 581bf16..eabaabd 100644 --- a/game.php +++ b/game.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,308 +18,47 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ -define('INSIDE' , true); +define('MODE', 'INGAME'); define('ROOT_PATH', str_replace('\\', '/',dirname(__FILE__)).'/'); -require_once(ROOT_PATH.'includes/functions/GetBuildingPrice.php'); -require_once(ROOT_PATH.'includes/functions/GetBuildingTime.php'); -require_once(ROOT_PATH.'includes/functions/IsElementBuyable.php'); -require(ROOT_PATH . 'includes/common.php'); - -$page = request_var('page',''); -switch($page) -{ -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'changelog': - include_once(ROOT_PATH . 'includes/pages/ShowChangelogPage.php'); - ShowChangelogPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'galaxy': - if(CheckModule(11)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/class.ShowGalaxyPage.php'); - $ShowGalaxyPage = new ShowGalaxyPage(); - break; - case 'phalanx': - if(CheckModule(19)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/ShowPhalanxPage.php'); - ShowPhalanxPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'imperium': - if(CheckModule(15)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/ShowImperiumPage.php'); - ShowImperiumPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'fleet': - if(CheckModule(9)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/class.ShowFleetPages.php'); - ShowFleetPages::ShowFleetPage(); - break; - case 'fleet1': - if(CheckModule(9)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/class.ShowFleetPages.php'); - ShowFleetPages::ShowFleet1Page(); - break; - case 'fleet2': - if(CheckModule(9)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/class.ShowFleetPages.php'); - ShowFleetPages::ShowFleet2Page(); - break; - case 'fleet3': - if(CheckModule(9)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/class.ShowFleetPages.php'); - ShowFleetPages::ShowFleet3Page(); - break; - case 'fleetajax': - if(CheckModule(9) || CheckModule(24)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/class.ShowFleetPages.php'); - ShowFleetPages::FleetAjax(); - break; - case 'missiles': - if(CheckModule(9) || CheckModule(1)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/class.ShowFleetPages.php'); - ShowFleetPages::MissilesAjax(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'buildings': - $mode = request_var('mode', ''); - switch ($mode) - { - case 'research': - if(CheckModule(3)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/class.ShowResearchPage.php'); - new ShowResearchPage(); - break; - case 'fleet': - if(CheckModule(4)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/class.ShowShipyardPage.php'); - $FleetBuildingPage = new ShowShipyardPage(); - $FleetBuildingPage->FleetBuildingPage (); - break; - case 'defense': - if(CheckModule(5)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/class.ShowShipyardPage.php'); - $DefensesBuildingPage = new ShowShipyardPage(); - $DefensesBuildingPage->DefensesBuildingPage (); - break; - default: - if(CheckModule(2)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/class.ShowBuildingsPage.php'); - new ShowBuildingsPage(); - break; - } - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'resources': - if(CheckModule(23)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/ShowResourcesPage.php'); - ShowResourcesPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'officier': - if(CheckModule(18) && CheckModule(8)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/class.ShowOfficierPage.php'); - new ShowOfficierPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'trader': - if(CheckModule(13)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/ShowTraderPage.php'); - ShowTraderPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'techtree': - if(CheckModule(28)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/ShowTechTreePage.php'); - ShowTechTreePage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'infos': - if(CheckModule(14)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/class.ShowInfosPage.php'); - new ShowInfosPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'messages': - if(CheckModule(16)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/class.ShowMessagesPage.php'); - new ShowMessagesPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'alliance': - if(CheckModule(0)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/class.ShowAlliancePage.php'); - new ShowAlliancePage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'buddy': - if(CheckModule(6)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/ShowBuddyPage.php'); - ShowBuddyPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'notes': - if(CheckModule(17)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/class.ShowNotesPage.php'); - new ShowNotesPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'fleettrader': - if(CheckModule(38)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/ShowFleetTraderPage.php'); - ShowFleetTraderPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'statistics': - if(CheckModule(25)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/ShowStatisticsPage.php'); - ShowStatisticsPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'search': - if(CheckModule(26)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/ShowSearchPage.php'); - ShowSearchPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'options': - include_once(ROOT_PATH . 'includes/pages/class.ShowOptionsPage.php'); - new ShowOptionsPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'banned': - if(CheckModule(21)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/ShowBannedPage.php'); - ShowBannedPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'topkb': - if(CheckModule(12)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/ShowTopKB.php'); - ShowTopKB(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'records': - if(CheckModule(22)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/ShowRecordsPage.php'); - ShowRecordsPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'chat': - if(CheckModule(7)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/ShowChatPage.php'); - ShowChatPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'support': - if(CheckModule(27)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/ShowSupportPage.php'); - new ShowSupportPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'playercard': - if(CheckModule(20)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/ShowPlayerCard.php'); - ShowPlayerCard(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'faq': - include_once(ROOT_PATH . 'includes/pages/ShowFAQ.php'); - ShowFAQPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'battlesim': - if(CheckModule(39)) - message($LNG['sys_module_inactive'],"?page=overview", 3, true, true); - - include_once(ROOT_PATH . 'includes/pages/ShowBattleSimPage.php'); - ShowBattleSimPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'logout': - include_once(ROOT_PATH . 'includes/pages/ShowLogoutPage.php'); - ShowLogoutPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// - case 'overview': - default: - include_once(ROOT_PATH . 'includes/pages/ShowOverviewPage.php'); - ShowOverviewPage(); - break; -// ----------------------------------------------------------------------------------------------------------------------------------------------// +require(ROOT_PATH.'includes/pages/game/class.AbstractPage.php'); +require(ROOT_PATH.'includes/pages/game/class.ShowErrorPage.php'); +require(ROOT_PATH.'includes/common.php'); +$page = HTTP::_GP('page', 'overview'); +$mode = HTTP::_GP('mode', 'show'); +$mode = str_replace(array('_', '\\', '/', '.', "\0"), '', $mode); +$pageClass = 'Show'.ucwords($page).'Page'; + +if(!file_exists(ROOT_PATH . 'includes/pages/game/class.'.$pageClass.'.php')) { + ShowErrorPage::printError($LNG['page_doesnt_exist']); +} + +// Added Autoload in feature Versions +require(ROOT_PATH . 'includes/pages/game/class.'.$pageClass.'.php'); + +$pageObj = new $pageClass; +// PHP 5.2 FIX +// can't use $pageObj::$requireModule +$pageProps = get_class_vars(get_class($pageObj)); + +if(isset($pageProps['requireModule']) && $pageProps['requireModule'] !== 0 && !isModulAvalible($pageProps['requireModule'])) { + ShowErrorPage::printError($LNG['sys_module_inactive']); +} + +if(!is_callable(array($pageObj, $mode))) { + if(!isset($pageProps['defaultController']) || !is_callable(array($pageObj, $pageProps['defaultController']))) { + ShowErrorPage::printError($LNG['page_doesnt_exist']); + } + $mode = $pageProps['defaultController']; } -?> \ No newline at end of file + +$pageObj->{$mode}(); diff --git a/language/pt/extra/rules.txt b/includes/FIRST_INSTALL similarity index 100% rename from language/pt/extra/rules.txt rename to includes/FIRST_INSTALL diff --git a/includes/FleetHandler.php b/includes/FleetHandler.php index d4b0249..5913773 100644 --- a/includes/FleetHandler.php +++ b/includes/FleetHandler.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,48 +18,26 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ -if(php_sapi_name() === 'cli') { - error_reporting(E_ALL ^ E_NOTICE); - define('ROOT_PATH', str_replace('\\', '/', dirname(dirname(__FILE__))).'/'); - define('TIMESTAMP', time()); - ini_set('display_errors', 0); - ini_set('error_log', ROOT_PATH.'/includes/cli_error.log'); - if(!function_exists('bcadd')) - require_once(ROOT_PATH . 'includes/bcmath.php'); +#$GLOBALS['DATABASE']->query("LOCK TABLE ".AKS." WRITE, ".RW." WRITE, ".MESSAGES." WRITE, ".CONFIG." WRITE, ".FLEETS_EVENT." WRITE, ".FLEETS." WRITE, ".PLANETS." WRITE, ".PLANETS." as p WRITE, ".TOPKB." WRITE, ".USERS." WRITE, ".USERS." as u WRITE, ".STATPOINTS." WRITE;"); - require_once(ROOT_PATH . 'includes/config.php'); - require_once(ROOT_PATH . 'includes/constants.php'); - require_once(ROOT_PATH . 'includes/classes/class.MySQLi.php'); - require_once(ROOT_PATH . 'includes/classes/class.Lang.php'); - require_once(ROOT_PATH . 'includes/GeneralFunctions.php'); - require_once(ROOT_PATH . 'includes/vars.php'); - $db = new DB_MySQLi(); - unset($database); - $LANG = new Language(); -} - -$db->query("LOCK TABLE ".AKS." WRITE, ".RW." WRITE, ".MESSAGES." WRITE, ".CONFIG." WRITE, ".FLEETS." WRITE, ".PLANETS." WRITE, ".PLANETS." as p WRITE, ".TOPKB." WRITE, ".USERS." WRITE, ".USERS." as u WRITE, ".STATPOINTS." WRITE;"); +$token = getRandomString(); -$FLEET = $db->query("SELECT * FROM ".FLEETS." WHERE (`fleet_start_time` <= '". TIMESTAMP ."' AND `fleet_mess` = '0') OR (`fleet_end_time` <= '". TIMESTAMP ."' AND `fleet_mess` = '1') OR (`fleet_end_stay` <= '". TIMESTAMP ."' AND `fleet_mess` = '2') ORDER BY `fleet_start_time` ASC;"); -if($db->num_rows($FLEET) > 0) -{ - require_once(ROOT_PATH . 'includes/classes/class.FlyingFleetHandler.php'); +$fleetResult = $GLOBALS['DATABASE']->query("UPDATE ".FLEETS_EVENT." SET `lock` = '".$token."' WHERE `lock` IS NULL AND `time` <= ". TIMESTAMP .";"); - new FlyingFleetHandler($FLEET); -} -$db->free_result($FLEET); -$db->query("UNLOCK TABLES"); +if($GLOBALS['DATABASE']->affectedRows() !== 0) { + require_once(ROOT_PATH . 'includes/classes/class.FlyingFleetHandler.php'); + + $fleetObj = new FlyingFleetHandler(); + $fleetObj->setToken($token); + $fleetObj->run(); -if(php_sapi_name() === 'cli') { - echo 'OK! - '.date(TIMEFORMAT)."\r\n"; -} -?> \ No newline at end of file + $GLOBALS['DATABASE']->query("UPDATE ".FLEETS_EVENT." SET `lock` = NULL WHERE `lock` = '".$token."';"); #UNLOCK TABLES +} \ No newline at end of file diff --git a/includes/GeneralFunctions.php b/includes/GeneralFunctions.php index 854931f..c099965 100644 --- a/includes/GeneralFunctions.php +++ b/includes/GeneralFunctions.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,185 +18,268 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ function getUniverse() { - if(defined('IN_ADMIN') && isset($_SESSION['adminuni'])) { + $gameConfig = Config::getAll(NULL); + + if(MODE == 'ADMIN' && isset($_SESSION['adminuni'])) + { $UNI = (int) $_SESSION['adminuni']; - } elseif(defined('LOGIN') && isset($_REQUEST['uni'])) { - $UNI = (int) $_REQUEST['uni']; - } elseif(defined('LOGIN') && isset($_COOKIE['uni'])) { - $UNI = (int) $_COOKIE['uni']; - } elseif(isset($_SESSION['uni'])) { - $UNI = $_SESSION['uni']; - } else { + } + elseif(MODE == 'LOGIN') + { + if(isset($_COOKIE['uni'])) + { + $UNI = (int) $_COOKIE['uni']; + } + + if(isset($_REQUEST['uni'])) + { + $UNI = (int) $_REQUEST['uni']; + } + } + + if(!isset($UNI)) + { if(UNIS_WILDCAST === true) { $UNI = explode('.', $_SERVER['HTTP_HOST']); $UNI = substr($UNI[0], 3); if(!is_numeric($UNI)) + { $UNI = ROOT_UNI; + } } else { - $UNI = ROOT_UNI; + if(count($gameConfig) == 1) + { + if(HTTP_ROOT != HTTP_BASE) + { + HTTP::redirectTo(PROTOCOL.HTTP_HOST.HTTP_BASE.HTTP_FILE, true); + } + + $UNI = ROOT_UNI; + } + else + { + if(isset($_SERVER['REDIRECT_UNI'])) { + // Apache - faster then preg_match + $UNI = $_SERVER["REDIRECT_UNI"]; + } + elseif(isset($_SERVER['REDIRECT_REDIRECT_UNI'])) + { + // Patch for www.top-hoster.de - Hoster + $UNI = $_SERVER["REDIRECT_REDIRECT_UNI"]; + } + elseif(strpos($_SERVER['SERVER_SOFTWARE'], 'Apache/') === false) + { + preg_match('!/uni([0-9]+)/!', HTTP_PATH, $match); + if(isset($match[1])) + { + $UNI = $match[1]; + } + } + + if(!isset($UNI) || !isset($gameConfig[$UNI])) + { + HTTP::redirectTo(PROTOCOL.HTTP_HOST.HTTP_BASE."uni".ROOT_UNI."/".HTTP_FILE, true); + } + } } } return $UNI; } -function getFactors($USER, $Type = 'basic', $TIME = 0) { - global $CONF, $resource, $pricelist; +function t($key) +{ + global $LNG; + + if(strpos($key, '.') === false) + { + $text = $LNG[$key]; + } + else + { + $keys = explode('.', $key); + $text = $LNG[$keys[0]][$keys[1]]; + } + + $args = func_get_args(); + array_shift($args); + + switch (count($args)) { + case 0: return $text; break; + case 1: return sprintf($text, $args[0]); break; + case 2: return sprintf($text, $args[0], $args[1]); break; + case 3: return sprintf($text, $args[0], $args[1], $args[2]); break; + case 4: return sprintf($text, $args[0], $args[1], $args[2], $args[3]); break; + case 5: return sprintf($text, $args[0], $args[1], $args[2], $args[3], $args[4]); break; + case 6: return sprintf($text, $args[0], $args[1], $args[2], $args[3], $args[4], $args[5]); break; + case 7: return sprintf($text, $args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6]); break; + case 8: return sprintf($text, $args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6], $args[7]); break; + case 9: return sprintf($text, $args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6], $args[7], $args[8]); break; + case 10: return call_user_func_array('sprintf', $args); break; + } +} + +function getFactors($USER, $Type = 'basic', $TIME = NULL) { + global $CONF, $resource, $pricelist, $reslist; if(empty($TIME)) $TIME = TIMESTAMP; + + $bonusList = BuildFunctions::getBonusList(); + $factor = ArrayUtil::combineArrayWithSingleElement($bonusList, 0); + + foreach($reslist['bonus'] as $elementID) { + $bonus = $pricelist[$elementID]['bonus']; - if($Type == 'basic') { - return array( - 'shipspeed' => $USER[$resource[613]] * $pricelist[613]['info'] + DMExtra($USER[$resource[706]], $TIME, $pricelist[706]['add'], 0), - 'bulidspeed' => 1 - $USER[$resource[605]] * $pricelist[605]['info'] - DMExtra($USER[$resource[702]], $TIME, $pricelist[702]['add'], 0), - 'techspeed' => 1 - $USER[$resource[606]] * $pricelist[606]['info'] - DMExtra($USER[$resource[705]], $TIME, $pricelist[705]['add'], 0), - 'fleetspeed' => 1 - $USER[$resource[604]] * $pricelist[604]['info'], - 'defspeed' => 1 - $USER[$resource[608]] * $pricelist[608]['info'], - 'metal' => 1 + ($USER[$resource[601]] * $pricelist[601]['info']) + ($USER[$resource[131]] * 0.02) + DMExtra($USER[$resource[703]], $TIME, $pricelist[703]['add'], 0), - 'crystal' => 1 + ($USER[$resource[601]] * $pricelist[601]['info']) + ($USER[$resource[132]] * 0.02) + DMExtra($USER[$resource[703]], $TIME, $pricelist[703]['add'], 0), - 'deuterium' => 1 + ($USER[$resource[601]] * $pricelist[601]['info']) + ($USER[$resource[133]] * 0.02) + DMExtra($USER[$resource[703]], $TIME, $pricelist[703]['add'], 0), - 'energy' => 1 + ($USER[$resource[603]] * $pricelist[603]['info']) + DMExtra($USER[$resource[704]], $TIME, $pricelist[704]['add'], 0), - ); - } - - if($Type == 'attack') { - return array( - 'attack' => $USER[$resource[602]] * $pricelist[602]['info'] + DMExtra($USER[$resource[700]], $TIME, $pricelist[700]['add'], 0), - 'defensive' => $USER[$resource[602]] * $pricelist[602]['info'] + DMExtra($USER[$resource[701]], $TIME, $pricelist[701]['add'], 0), - 'shield' => $USER[$resource[602]] * $pricelist[602]['info'], - ); + if (isset($PLANET[$resource[$elementID]])) { + $elementLevel = $PLANET[$resource[$elementID]]; + } elseif (isset($USER[$resource[$elementID]])) { + $elementLevel = $USER[$resource[$elementID]]; + } else { + continue; + } + + if(in_array($elementID, $reslist['dmfunc'])) { + if(DMExtra($elementLevel, $TIME, false, true)) { + continue; + } + + foreach($bonusList as $bonusKey) + { + $factor[$bonusKey] += $bonus[$bonusKey][0]; + } + } else { + foreach($bonusList as $bonusKey) + { + $factor[$bonusKey] += $elementLevel * $bonus[$bonusKey][0]; + } + } } + + return $factor; } function getPlanets($USER) { - global $db; - if(isset($USER['PLANETS'])) + if(isset($USER['PLANETS'])) return $USER['PLANETS']; $Order = $USER['planet_sort_order'] == 1 ? "DESC" : "ASC" ; $Sort = $USER['planet_sort']; - $QryPlanets = "SELECT `id`, `name`, `galaxy`, `system`, `planet`, `planet_type`, `image`, `b_building`, `b_building_id` FROM ".PLANETS." WHERE `id_owner` = '".$USER['id']."' AND `destruyed` = '0' ORDER BY "; + $QryPlanets = "SELECT id, name, galaxy, system, planet, planet_type, image, b_building, b_building_id FROM ".PLANETS." WHERE id_owner = '".$USER['id']."' AND destruyed = '0' ORDER BY "; if($Sort == 0) - $QryPlanets .= "`id` ". $Order; + $QryPlanets .= "id ". $Order; elseif($Sort == 1) - $QryPlanets .= "`galaxy`, `system`, `planet`, `planet_type` ". $Order; + $QryPlanets .= "galaxy, system, planet, planet_type ". $Order; elseif ($Sort == 2) - $QryPlanets .= "`name` ". $Order; + $QryPlanets .= "name ". $Order; - $PlanetRAW = $db->query($QryPlanets); + $PlanetRAW = $GLOBALS['DATABASE']->query($QryPlanets); + + $Planets = array(); - while($Planet = $db->fetch_array($PlanetRAW)) + while($Planet = $GLOBALS['DATABASE']->fetch_array($PlanetRAW)) $Planets[$Planet['id']] = $Planet; - $db->free_result($PlanetRAW); + $GLOBALS['DATABASE']->free_result($PlanetRAW); return $Planets; } -function tz_dst($timezone) { - if($timezone == $GLOBALS['CONF']['timezone']) - return (int) date("I"); +function get_timezone_selector() { + global $LNG; - $OLD = date_default_timezone_get(); - $DST = (int) date("I"); - return $DST; -} + // New Timezone Selector, better support for changes in tzdata (new russian timezones, e.g.) + // http://www.php.net/manual/en/datetimezone.listidentifiers.php + + $timezones = array(); + $timezone_identifiers = DateTimeZone::listIdentifiers(); -function tz_getlist() { - return array('-12', '-11', '-10', '-9.5', '-9', '-8', '-7', '-6', '-5', '-4.5', '-4', '-3.5', '-3', '-2', '-1', '0', '1', '2', '3', '3.5', '4', '4.5', '5', '5.5', '5.75', '6', '6.5', '7', '8', '8.75', '9', '9.5', '10', '10.5', '11', '11.5', '12', '12.75', '13', '14'); + foreach( $timezone_identifiers as $value ) + { + if ( preg_match( '/^(America|Antartica|Arctic|Asia|Atlantic|Europe|Indian|Pacific)\//', $value ) ) + { + $ex=explode('/',$value); //obtain continent,city + $city = isset($ex[2])? $ex[1].' - '.$ex[2]:$ex[1]; //in case a timezone has more than one + $timezones[$ex[0]][$value] = str_replace('_', ' ', $city); + } + } + return $timezones; } -function tz_diff() { - $UTC = (int) date("Z"); +function locale_date_format($format, $time, $LNG = NULL) { + + //Workaound for locale Names. - if(isset($GLOBALS['USER'])) { - $timezone = (float) $GLOBALS['USER']['timezone']; - $DST = $GLOBALS['USER']['dst']; - } elseif(isset($_SESSION['USER'])) { - $timezone = (float) $_SESSION['USER']['timezone']; - $DST = $_SESSION['USER']['dst']; + if(!isset($LNG)) { + $LNG = $GLOBALS['LNG']; } - if($DST == 2) - $DST = tz_dst($timezone); - return (($timezone + $DST) * 3600) - $UTC; -} - -function tz_date($time, $Dateformat = '', $LNG = array(), $ToGMT = false) { - if(!$ToGMT) - $time = $time + tz_diff(); - else - $time = $time + (int) date("Z") - (int) date("I"); + $weekDay = date('w', $time); + $months = date('n', $time) - 1; - if(empty($LNG)) - $LNG = $GLOBALS['LNG']; - - if(empty($Dateformat)) - $Dateformat = $LNG['php_tdformat']; + $format = str_replace(array('D', 'M'), array('$D$', '$M$'), $format); + $format = str_replace('$D$', addcslashes($LNG['week_day'][$weekDay], 'A..z'), $format); + $format = str_replace('$M$', addcslashes($LNG['months'][$months], 'A..z'), $format); - $Dateformat = str_replace(array('D', 'M'), array("XXX", "YYY"), $Dateformat); - $Dateformat = str_replace(array("XXX", "YYY"), array(addcslashes($LNG['week_day'][(date('w', $time))], 'A..z'), addcslashes($LNG['months'][(date('n', $time) - 1)], 'A..z')), $Dateformat); - - return date($Dateformat, $time); + return $format; } -function update_config($Values, $UNI = 0) -{ - global $CONF, $db; - $SQLBASE = ""; - $SQLUNI = ""; - $UNI = (empty($UNI)) ? $GLOBALS['UNI'] : $UNI; - $BasicConf = array('VERSION', 'game_name', 'stat', 'stat_level', 'stat_last_update', 'stat_settings', 'stat_update_time', 'stat_last_db_update', 'stats_fly_lock', 'cron_lock', 'ts_modon', 'ts_server', 'ts_tcpport', 'ts_udpport', 'ts_timeout', 'ts_version', 'ts_cron_last', 'ts_cron_interval', 'ts_login', 'ts_password', 'capaktiv', 'cappublic', 'capprivate', 'mail_active', 'mail_use', 'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_ssl', 'smtp_sendmail', 'smail_path', 'fb_on', 'fb_apikey', 'fb_skey', 'ga_active', 'ga_key', 'chat_closed', 'chat_allowchan', 'chat_allowmes', 'chat_allowdelmes', 'chat_logmessage', 'chat_nickchange', 'chat_botname', 'chat_channelname', 'chat_socket_active', 'chat_socket_host', 'chat_socket_ip', 'chat_socket_port', 'chat_socket_chatid', 'ttf_file', 'sendmail_inactive', 'del_user_sendmail', 'del_user_automatic', 'del_oldstuff', 'del_user_manually', 'ref_max_referals'); - foreach($Values as $Name => $Value) { - if(!isset($CONF[$Name])) - continue; - - $GLOBALS['CONFIG'][$UNI][$Name] = $Value; - - $CONF[$Name] = $Value; - if(in_array($Name, $BasicConf)) - $SQLBASE .= "`".$Name."` = '".$db->sql_escape($Value)."', "; - else - $SQLUNI .= "`".$Name."` = '".$db->sql_escape($Value)."', "; +function _date($format, $time = null, $toTimeZone = null, $LNG = NULL) { + global $CONF; + + if(!isset($time)) { + $time = TIMESTAMP; } - if(!empty($SQLBASE)) - $db->query("UPDATE ".CONFIG." SET ".substr($SQLBASE, 0, -2).";"); - if(!empty($SQLUNI)) - $db->query("UPDATE ".CONFIG." SET ".substr($SQLUNI, 0, -2)." WHERE `uni` = '".$UNI."';"); -} - -function getConfig($UNI) { - global $db; - if(isset($GLOBALS['CONFIG'][$UNI])) - return $GLOBALS['CONFIG'][$UNI]; - $CONF = $db->uniquequery("SELECT HIGH_PRIORITY * FROM `".CONFIG."` WHERE `uni` = '".$UNI."';"); - $CONF['moduls'] = explode(";", $CONF['moduls']); - + if(isset($toTimeZone)) + { + $date = new DateTime(); + if(method_exists($date, 'setTimestamp')) + { // PHP > 5.3 + $date->setTimestamp($time); + } else { + // PHP < 5.3 + $tempDate = getdate((int) $time); + $date->setDate($tempDate['year'], $tempDate['mon'], $tempDate['mday']); + $date->setTime($tempDate['hours'], $tempDate['minutes'], $tempDate['seconds']); + } + + $time -= $date->getOffset(); + try { + $date->setTimezone(new DateTimeZone($toTimeZone)); + } catch (Exception $e) { + + } + $time += $date->getOffset(); + } - $GLOBALS['CONFIG'][$UNI] = $CONF; - return $CONF; + $format = locale_date_format($format, $time, $LNG); + return date($format, $time); } function ValidateAddress($address) { - $ValideAdress = function_exists('filter_var') ? filter_var($address, FILTER_VALIDATE_EMAIL) !== FALSE : preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address); - - return $ValideAdress; + if(function_exists('filter_var')) { + return filter_var($address, FILTER_VALIDATE_EMAIL) !== FALSE; + } else { + /* + Regex expression from swift mailer (http://swiftmailer.org) + RFC 2822 + */ + return preg_match('/^(?:(?:(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?(?:[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_\{\}\|~]+(\.[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_\{\}\|~]+)*)+(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?)|(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?"((?:(?:[ \t]*(?:\r\n))?[ \t])?(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21\x23-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])))*(?:(?:[ \t]*(?:\r\n))?[ \t])?"(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?))@(?:(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?(?:[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_\{\}\|~]+(\.[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_\{\}\|~]+)*)+(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?)|(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?\[((?:(?:[ \t]*(?:\r\n))?[ \t])?(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x5A\x5E-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])))*?(?:(?:[ \t]*(?:\r\n))?[ \t])?\](?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?)))$/D', $address); + } } function message($mes, $dest = "", $time = "3", $topnav = false, $menu = true) @@ -213,67 +296,90 @@ function CalculateMaxPlanetFields($planet) return $planet['field_max'] + ($planet[$resource[33]] * FIELDS_BY_TERRAFORMER) + ($planet[$resource[41]] * FIELDS_BY_MOONBASIS_LEVEL); } -function pretty_time ($seconds) +function pretty_time($seconds) { - $day = floor($seconds / (24 * 3600)); - $hs = floor($seconds / 3600 % 24); - $ms = floor($seconds / 60 % 60); - $sr = floor($seconds / 1 % 60); - - $hh = $hs < 10 ? "0" . $hs : $hs; - $mm = $ms < 10 ? "0" . $ms : $ms; - $ss = $sr < 10 ? "0" . $sr : $sr; - + global $LNG; + + $day = floor($seconds / 86400); + $hour = floor($seconds / 3600 % 24); + $minute = floor($seconds / 60 % 60); + $second = floor($seconds % 60); + $time = ''; - $time .= $day != 0 ? $day . 'd ' : ''; - $time .= $hs != 0 ? $hh . 'h ' : '00h '; - $time .= $ms != 0 ? $mm . 'm ' : '00m '; - $time .= $ss . 's'; + + if($day >= 10) { + $time .= $day.$LNG['short_day'].' '; + } elseif($day > 0) { + $time .= '0'.$day.$LNG['short_day'].' '; + } + + if($hour >= 10) { + $time .= $hour.$LNG['short_hour'].' '; + } else { + $time .= '0'.$hour.$LNG['short_hour'].' '; + } + + if($minute >= 10) { + $time .= $minute.$LNG['short_minute'].' '; + } else { + $time .= '0'.$minute.$LNG['short_minute'].' '; + } + + if($second >= 10) { + $time .= $second.$LNG['short_second'].' '; + } else { + $time .= '0'.$second.$LNG['short_second'].' '; + } return $time; } -function pretty_time_hour ($seconds) +function pretty_fly_time($seconds) { - $min = floor($seconds / 60 % 60); + $hour = floor($seconds / 3600); + $minute = floor($seconds / 60 % 60); + $second = floor($seconds % 60); + $time = ''; - $time .= $min != 0 ? $min . 'min ' : ''; + + if($hour >= 10) { + $time .= $hour; + } else { + $time .= '0'.$hour; + } + + $time .= ':'; + + if($minute >= 10) { + $time .= $minute; + } else { + $time .= '0'.$minute; + } + + $time .= ':'; + + if($second >= 10) { + $time .= $second; + } else { + $time .= '0'.$second; + } + return $time; } function GetStartAdressLink($FleetRow, $FleetType) { - return '['.$FleetRow['fleet_start_galaxy'].':'.$FleetRow['fleet_start_system'].':'.$FleetRow['fleet_start_planet'].']'; + return '['.$FleetRow['fleet_start_galaxy'].':'.$FleetRow['fleet_start_system'].':'.$FleetRow['fleet_start_planet'].']'; } function GetTargetAdressLink($FleetRow, $FleetType) { - return '['.$FleetRow['fleet_end_galaxy'].':'.$FleetRow['fleet_end_system'].':'.$FleetRow['fleet_end_planet'].']'; + return '['.$FleetRow['fleet_end_galaxy'].':'.$FleetRow['fleet_end_system'].':'.$FleetRow['fleet_end_planet'].']'; } function BuildPlanetAdressLink($CurrentPlanet) { - return '['.$CurrentPlanet['galaxy'].':'.$CurrentPlanet['system'].':'.$CurrentPlanet['planet'].']'; -} - -function colorNumber($n, $s = '') -{ - if ($n > 0) - return (empty($s)) ? colorGreen($n) : colorGreen($s); - elseif ($n < 0) - return (empty($s)) ? colorRed($n) : colorRed($s); - else - return (empty($s)) ? $n : $s; -} - -function colorRed($n) -{ - return '' . $n . ''; -} - -function colorGreen($n) -{ - return '' . $n . ''; + return '['.$CurrentPlanet['galaxy'].':'.$CurrentPlanet['system'].':'.$CurrentPlanet['planet'].']'; } function pretty_number($n, $dec = 0) @@ -281,90 +387,23 @@ function pretty_number($n, $dec = 0) return number_format(floattostring($n, $dec), $dec, ',', '.'); } -function request_var($var_name, $default, $multibyte = false, $specialtype = '') -{ - if(!isset($_REQUEST[$var_name])) - return $default; - - $var = $_REQUEST[$var_name]; - $type = gettype($default); - settype($var, $type); - if ($type == 'string') - { - $var = trim(htmlspecialchars(str_replace(array("\r\n", "\r", "\0"), array("\n", "\n", ''), $var), ENT_COMPAT, 'UTF-8')); - - if (!empty($var)) - { - // Make sure multibyte characters are wellformed - if ($multibyte) - { - if (!preg_match('/^./u', $var)) - { - $var = ''; - } - } - else - { - // no multibyte, allow only ASCII (0-127) - $var = preg_replace('/[\x80-\xFF]/', '?', $var); - } - } - } - return $var; -} - -function request_outofint($var_name, $Negative = false) -{ - return $Negative ? floor(request_var($var_name, 0.0)) : max(floor(request_var($var_name, 0.0)), 0) ; -} - function GetUserByID($UserID, $GetInfo = "*") { - global $db; - if(is_array($GetInfo)) { $GetOnSelect = ""; foreach($GetInfo as $id => $col) { - $GetOnSelect .= "`".$col."`,"; + $GetOnSelect .= "".$col.","; } $GetOnSelect = substr($GetOnSelect, 0, -1); } else $GetOnSelect = $GetInfo; - $User = $db->uniquequery("SELECT ".$GetOnSelect." FROM ".USERS." WHERE `id` = '". $UserID ."';"); + $User = $GLOBALS['DATABASE']->getFirstRow("SELECT ".$GetOnSelect." FROM ".USERS." WHERE id = '". $UserID ."';"); return $User; } -function MailSend($MailTarget, $MailTargetName, $MailSubject, $MailContent) -{ - global $CONF; - require_once('./includes/classes/class.phpmailer.php'); - $mail = new PHPMailer(true); - if($CONF['mail_use'] == 2) { - $mail->IsSMTP(); - $mail->SMTPAuth = true; - $mail->SMTPSecure = $CONF['smtp_ssl']; - $mail->Host = $CONF['smtp_host']; - $mail->Port = $CONF['smtp_port']; - $mail->Username = $CONF['smtp_user']; - $mail->Password = $CONF['smtp_pass']; - $mail->SMTPDebug = ($CONF['debug'] == 1) ? 2 : 0; - } elseif($CONF['mail_use'] == 1) { - $mail->IsSendmail(); - $mai->Sendmail = $CONF['smail_path']; - } else { - $mail->IsMail(); - } - $mail->CharSet = 'UTF-8'; - $mail->Subject = $MailSubject; - $mail->Body = $MailContent; - $mail->SetFrom($CONF['smtp_sendmail'], $CONF['game_name']); - $mail->AddAddress($MailTarget, $MailTargetName); - $mail->Send(); -} - function makebr($text) { // XHTML FIX for PHP 5.3.0 @@ -376,141 +415,109 @@ function makebr($text) function CheckPlanetIfExist($Galaxy, $System, $Planet, $Universe, $Planettype = 1) { - global $db; - $QrySelectGalaxy = $db->countquery("SELECT COUNT(*) FROM ".PLANETS." WHERE `universe` = '".$Universe."' AND `galaxy` = '".$Galaxy."' AND `system` = '".$System."' AND `planet` = '".$Planet."' AND `planet_type` = '".$Planettype."';"); + $QrySelectGalaxy = $GLOBALS['DATABASE']->getFirstCell("SELECT COUNT(*) FROM ".PLANETS." WHERE universe = '".$Universe."' AND galaxy = '".$Galaxy."' AND system = '".$System."' AND planet = '".$Planet."' AND planet_type = '".$Planettype."';"); return $QrySelectGalaxy ? true : false; } function CheckNoobProtec($OwnerPlayer, $TargetPlayer, $Player) { global $CONF; - if($CONF['noobprotection'] == 0 || $CONF['noobprotectionmulti'] == 0 || $OwnerPlayer['total_points'] <= $CONF['noobprotectiontime'] || $Player['banaday'] > TIMESTAMP || $Player['onlinetime'] < (TIMESTAMP - 60 * 60 * 24 * 7)) + if( + Config::get('noobprotection') == 0 + || Config::get('noobprotectiontime') == 0 + || Config::get('noobprotectionmulti') == 0 + || $Player['banaday'] > TIMESTAMP + || $Player['onlinetime'] < TIMESTAMP - INACTIVE + ) { return array('NoobPlayer' => false, 'StrongPlayer' => false); - + } + return array( - 'NoobPlayer' => $OwnerPlayer['total_points'] > $TargetPlayer['total_points'] * $CONF['noobprotectionmulti'], - 'StrongPlayer' => $OwnerPlayer['total_points'] * $CONF['noobprotectionmulti'] < $TargetPlayer['total_points'] + 'NoobPlayer' => ( + /* WAHR: + Wenn Spieler mehr als 25000 Punkte hat UND + Wenn ZielSpieler weniger als 80% der Punkte des Spieler hat. + ODER weniger als 5.000 hat. + */ + // Addional Comment: Letzteres ist eigentlich sinnfrei, bitte testen.a + ($TargetPlayer['total_points'] <= Config::get('noobprotectiontime')) && // Default: 25.000 + ($OwnerPlayer['total_points'] > $TargetPlayer['total_points'] * Config::get('noobprotectionmulti')) + ), + 'StrongPlayer' => ( + /* WAHR: + Wenn Spieler weniger als 5000 Punkte hat UND + Mehr als das funfache der eigende Punkte hat + */ + ($OwnerPlayer['total_points'] < Config::get('noobprotectiontime')) && // Default: 5.000 + ($OwnerPlayer['total_points'] * Config::get('noobprotectionmulti') < $TargetPlayer['total_points']) + ), ); } -function CheckName($String) -{ - return(ctype_alnum($String) || (UTF8_SUPPORT && !empty($String))) ? true : false; -} - -function exception_handler($exception) +function CheckName($name) { - global $CONF; - - @session_write_close(); - if($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1' && !headers_sent()) - header('HTTP/1.1 503 Service Unavailable'); - - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''.$CONF['game_name'].' - FATAL ERROR'; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo '
'; - echo 'Error:'; - echo '
Message: '.$exception->getMessage().'
'; - echo 'File: '.$exception->getFile().'
'; - echo 'Line: '.$exception->getLine().'
'; - echo 'URL: '.PROTOCOL.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].(!empty($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING']: '').'
'; - echo 'PHP-Version: '.PHP_VERSION.'
'; - echo 'PHP-API: '.php_sapi_name().'
'; - echo '2Moons Version: '.$CONF['VERSION'].'
'; - echo 'Debug Backtrace:
'.makebr(str_replace($_SERVER['DOCUMENT_ROOT'], '.', htmlspecialchars($exception->getTraceAsString()))).''; - echo '
'; - echo ''; - echo ''; - exit; + if(UTF8_SUPPORT) { + return preg_match("/^[\p{L}\p{N}_\-. ]*$/u", $name); + } else { + return preg_match("/^[A-z0-9_\-. ]*$/", $name); + } } function SendSimpleMessage($Owner, $Sender, $Time, $Type, $From, $Subject, $Message) { - global $db; - + $SQL = "INSERT INTO ".MESSAGES." SET - `message_owner` = ".(int) $Owner.", - `message_sender` = ".(int) $Sender.", - `message_time` = ".(int) $Time.", - `message_type` = ".(int) $Type.", - `message_from` = '".$db->sql_escape($From) ."', - `message_subject` = '". $db->sql_escape($Subject) ."', - `message_text` = '".$db->sql_escape($Message)."', - `message_unread` = '1', - `message_universe` = ".$GLOBALS['UNI'].";"; + message_owner = ".(int) $Owner.", + message_sender = ".(int) $Sender.", + message_time = ".(int) $Time.", + message_type = ".(int) $Type.", + message_from = '".$GLOBALS['DATABASE']->sql_escape($From) ."', + message_subject = '". $GLOBALS['DATABASE']->sql_escape($Subject) ."', + message_text = '".$GLOBALS['DATABASE']->sql_escape($Message)."', + message_unread = '1', + message_universe = ".$GLOBALS['UNI'].";"; - $db->query($SQL); + $GLOBALS['DATABASE']->query($SQL); } -function shortly_number($number) +function shortly_number($number, $decial = NULL) { - $length = strlen(floattostring(abs($number))); - if($length < 4) - return pretty_number($number); - elseif($length < 7) - return pretty_number($number/1000).' K'; - elseif($length < 13) - return pretty_number($number/1000000).' M'; - elseif($length < 19) - return pretty_number($number/1000000000000).' B'; - elseif($length < 25) - return pretty_number($number/1000000000000000000).' T'; - elseif($length < 31) - return pretty_number($number/1000000000000000000000000).' Q'; - elseif($length < 37) - return pretty_number($number/1000000000000000000000000000000).' Q+'; - elseif($length < 43) - return pretty_number($number/1000000000000000000000000000000000000).' S'; - elseif($length < 49) - return pretty_number($number/1000000000000000000000000000000000000000000).' S+'; - elseif($length < 55) - return pretty_number($number/1000000000000000000000000000000000000000000000000).' O'; - else - return pretty_number($number/1000000000000000000000000000000000000000000000000000000).' N'; + $negate = $number < 0 ? -1 : 1; + $number = abs($number); + $unit = array("", "K", "M", "B", "T", "Q", "Q+", "S", "S+", "O", "N"); + $key = 0; + + if($number >= 1000000) { + ++$key; + while($number >= 1000000) + { + ++$key; + $number = $number / 1000000; + } + } elseif($number >= 1000) { + ++$key; + $number = $number / 1000; + } + + $decial = !is_numeric($decial) ? ((int) (((int)$number != $number) && $key != 0 && $number != 0 && $number < 100)) : $decial; + return pretty_number($negate * $number, $decial).' '.$unit[$key]; } function floattostring($Numeric, $Pro = 0, $Output = false){ return ($Output) ? str_replace(",",".", sprintf("%.".$Pro."f", $Numeric)) : sprintf("%.".$Pro."f", $Numeric); } -function CheckModule($ID) +function isModulAvalible($ID) { if(!isset($GLOBALS['CONF']['moduls'][$ID])) $GLOBALS['CONF']['moduls'][$ID] = 1; - return ((!isset($_SESSION) || $_SESSION['authlevel'] !== AUTH_USR) && $GLOBALS['CONF']['moduls'][$ID] == 0) ? true : false; -} - -function redirectTo($URL) -{ - @session_write_close(); - if($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') - header('HTTP/1.1 302 Found'); - - header('Location: '.PROTOCOL.$_SERVER['HTTP_HOST'].HTTP_ROOT.$URL); - exit; + return $GLOBALS['CONF']['moduls'][$ID] == 1 || (isset($USER['authlevel']) && $USER['authlevel'] > AUTH_USR); } function ClearCache() { - $DIRS = array('cache/'); + $DIRS = array('cache/', 'cache/templates/'); foreach($DIRS as $DIR) { $FILES = array_diff(scandir($DIR), array('..', '.', '.htaccess')); foreach($FILES as $FILE) { @@ -520,54 +527,239 @@ function ClearCache() unlink(ROOT_PATH.$DIR.$FILE); } } + + require_once ROOT_PATH.'includes/classes/Cronjob.class.php'; + Cronjob::reCalculateCronjobs(); + $GLOBALS['DATABASE']->query("UPDATE ".PLANETS." SET eco_hash = '';"); + clearstatcache(); } -function MaxPlanets($Level, $Universe) +function allowedTo($side) { - return min($GLOBALS['CONFIG'][$Universe]['min_player_planets'] + ceil($Level / 2) * PLANETS_PER_TECH, $GLOBALS['CONFIG'][$Universe]['max_player_planets']); + global $USER; + return ($USER['authlevel'] == AUTH_ADM || (isset($USER['rights']) && $USER['rights'][$side] == 1)); +} + +function isactiveDMExtra($Extra, $Time) { + return $Time - $Extra <= 0; } -function GetCrons() +function DMExtra($Extra, $Time, $true, $false) { + return isactiveDMExtra($Extra, $Time) ? $true : $false; +} + +function getRandomString() { + return md5(uniqid()); +} + +function isVacationMode($USER) { - global $CONF; - $Crons = ''; - $Crons .= TIMESTAMP >= ($CONF['stat_last_update'] + (60 * $CONF['stat_update_time'])) ? '' : ''; - - $Crons .= $CONF['ts_modon'] == 1 && TIMESTAMP >= ($CONF['ts_cron_last'] + 60 * $CONF['ts_cron_interval']) ? '' : ''; - - $Crons .= TIMESTAMP >= ($CONF['stat_last_db_update'] + 86400) ? '' : ''; //Daily Cronjob - - return $Crons; + return ($USER['urlaubs_modus'] == 1) ? true : false; } -function r_implode($glue, $pieces) +function cryptPassword($password) { - $retVal = array(); - foreach($pieces as $r_pieces) + // http://www.phpgangsta.de/schoener-hashen-mit-bcrypt + global $resource, $salt; + if(!CRYPT_BLOWFISH || !isset($salt)) { - $retVal[] = is_array($r_pieces) ? r_implode($glue, $r_pieces) : $r_pieces; + return md5($password); + } else { + return crypt($password, '$2a$09$'.$salt.'$'); } - return implode($glue, $retVal); -} - -function allowedTo($side) -{ - return ($GLOBALS['USER']['authlevel'] == AUTH_ADM || $GLOBALS['USER']['rights'][$side] == 1); } -function isactiveDMExtra($Extra, $Time) { - return $Time - $Extra <= 0; +function combineArrayWithSingleElement($keys, $var) { + return array_combine($keys, array_fill(0, count($keys), $var)); } -function DMExtra($Extra, $Time, $true, $false) { - return isactiveDMExtra($Extra, $Time) ? $true : $false; +function clearGIF() { + header('Cache-Control: no-cache'); + header('Content-type: image/gif'); + header('Content-length: 43'); + header('Expires: 0'); + echo("\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00\x21\xF9\x04\x01\x00\x00\x00\x00\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3B"); + exit; } -if(!function_exists('ctype_alnum')): +function fleetAmountToArray($fleetAmount) +{ + $fleetTyps = explode(';', $fleetAmount); + + $fleetAmount = array(); + + foreach ($fleetTyps as $fleetTyp) + { + $temp = explode(',', $fleetTyp); + + if (empty($temp[0])) continue; -function ctype_alnum($test){ - return preg_match("/[^A-z0-9_\- ]/", $test) != 1; + if (!isset($fleetAmount[$temp[0]])) + { + $fleetAmount[$temp[0]] = 0; + } + + $fleetAmount[$temp[0]] += $temp[1]; + } + + return $fleetAmount; } -endif; -?> \ No newline at end of file +function exceptionHandler($exception) +{ + global $CONF; + if(!headers_sent()) { + if (!class_exists('HTTP', false)) { + require_once(ROOT_PATH . 'includes/classes/HTTP.class.php'); + } + + HTTP::sendHeader('HTTP/1.1 503 Service Unavailable'); + } + + if(method_exists($exception, 'getSeverity')) { + $errno = $exception->getSeverity(); + } else { + $errno = E_USER_ERROR; + } + + $errorType = array( + E_ERROR => 'ERROR', + E_WARNING => 'WARNING', + E_PARSE => 'PARSING ERROR', + E_NOTICE => 'NOTICE', + E_CORE_ERROR => 'CORE ERROR', + E_CORE_WARNING => 'CORE WARNING', + E_COMPILE_ERROR => 'COMPILE ERROR', + E_COMPILE_WARNING => 'COMPILE WARNING', + E_USER_ERROR => 'USER ERROR', + E_USER_WARNING => 'USER WARNING', + E_USER_NOTICE => 'USER NOTICE', + E_STRICT => 'STRICT NOTICE', + E_RECOVERABLE_ERROR => 'RECOVERABLE ERROR' + ); + + try + { + if(!class_exists('Config', false)) + { + throw new Exception("No config class"); + } + $VERSION = Config::get('VERSION'); + } catch(Exception $e) { + if(file_exists(ROOT_PATH.'install/VERSION')) + { + $VERSION = file_get_contents(ROOT_PATH.'install/VERSION').' (FILE)'; + } + else + { + $VERSION = 'UNKNOWN'; + } + } + + try + { + if(!class_exists('Config', false)) + { + throw new Exception("No config class"); + } + $gameName = Config::get('game_name'); + } catch(Exception $e) { + $gameName = '-'; + } + + $DIR = MODE == 'INSTALL' ? '..' : '.'; + ob_start(); + echo ' + + + + + + + '.$gameName.' - '.$errorType[$errno].' + + + + + + + + + + + + + + + + + + + + + + + + + +
'.$errorType[$errno].'
+ Message: '.$exception->getMessage().'
+ File: '.$exception->getFile().'
+ Line: '.$exception->getLine().'
+ URL: '.PROTOCOL.HTTP_HOST.$_SERVER['REQUEST_URI'].'
+ PHP-Version: '.PHP_VERSION.'
+ PHP-API: '.php_sapi_name().'
+ MySQL-Cleint-Version: '.mysqli_get_client_info().'
+ 2Moons Version: '.$VERSION.'
+ Debug Backtrace:
'.makebr(htmlspecialchars($exception->getTraceAsString())).' +
+ +'; + + echo str_replace(array('\\', ROOT_PATH, substr(ROOT_PATH, 0, 15)), array('/', '/', 'FILEPATH '), ob_get_clean()); + + $errorText = date("[d-M-Y H:i:s]", TIMESTAMP).' '.$errorType[$errno].': "'.strip_tags($exception->getMessage())."\"\r\n"; + $errorText .= 'File: '.$exception->getFile().' | Line: '.$exception->getLine()."\r\n"; + $errorText .= 'URL: '.PROTOCOL.HTTP_HOST.$_SERVER['REQUEST_URI'].' | Version: '.$VERSION."\r\n"; + $errorText .= "Stack trace:\r\n"; + $errorText .= str_replace(ROOT_PATH, '/', htmlspecialchars(str_replace('\\', '/',$exception->getTraceAsString())))."\r\n"; + + if(is_writable(ROOT_PATH.'includes/error.log')) + { + file_put_contents(ROOT_PATH.'includes/error.log', $errorText, FILE_APPEND); + } +} + +function errorHandler($errno, $errstr, $errfile, $errline) +{ + if (!($errno & error_reporting())) { + return; + } + + throw new ErrorException($errstr, 0, $errno, $errfile, $errline); +} \ No newline at end of file diff --git a/includes/PlanetData.php b/includes/PlanetData.php index b0bdc7b..139dfbd 100644 --- a/includes/PlanetData.php +++ b/includes/PlanetData.php @@ -1,5 +1,31 @@ . + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + $PlanetData = array( 1 => array('temp' => mt_rand(220, 260), 'fields' => mt_rand(95, 108), 'image' => array('trocken' => mt_rand(1, 10), 'wuesten' => mt_rand(1, 4))), 2 => array('temp' => mt_rand(170, 210), 'fields' => mt_rand(97, 110), 'image' => array('trocken' => mt_rand(1, 10), 'wuesten' => mt_rand(1, 4))), diff --git a/includes/bcmath.php b/includes/bcmath.php deleted file mode 100644 index a6f2fc9..0000000 --- a/includes/bcmath.php +++ /dev/null @@ -1,112 +0,0 @@ -. - * - * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) - * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) - * @info $Id$ - * @link http://code.google.com/p/2moons/ - */ - -function bcadd($Num1, $Num2, $Scale = 0) { - if(!preg_match("/^\+?(\d+)(\.\d+)?$/",$Num1,$Tmp1) || !preg_match("/^\+?(\d+)(\.\d+)?$/",$Num2,$Tmp2)) return('0'); - - $Output = array(); - - $Dec1 = isset($Tmp1[2]) ? rtrim(substr($Tmp1[2], 1), '0'):''; - $Dec2 = isset($Tmp2[2]) ? rtrim(substr($Tmp2[2], 1), '0'):''; - - $DLen = max(strlen($Dec1), strlen($Dec2)); - - if($Scale==null) $Scale = $DLen; - - $Num1 = strrev(ltrim($Tmp1[1], '0').str_pad($Dec1, $DLen, '0')); - $Num2 = strrev(ltrim($Tmp2[1], '0').str_pad($Dec2, $DLen, '0')); - - $MLen = max(strlen($Num1), strlen($Num2)); - - $Num1 = str_pad($Num1, $MLen, '0'); - $Num2 = str_pad($Num2, $MLen, '0'); - - for($i=0;$i<$MLen;$i++) { - $Sum = ((int)$Num1{$i} + (int)$Num2{$i}); - if(isset($Output[$i])) $Sum += $Output[$i]; - $Output[$i] = $Sum % 10; - - if($Sum > 9) - $Output[$i+1]=1; - } - - $Output=strrev(implode($Output)); - - $Decimal = str_pad(substr($Output, -$DLen, $Scale), $Scale, '0'); - $Output = ($MLen-$DLen<1) ? '0' : substr($Output,0,-$DLen); - $Output .= ($Scale>0) ? ".".$Decimal : ''; - return $Output; -} - -function bcsub($Num1 ,$Num2, $Scale = 0) { - return round($Num1 - $Num2, $Scale); -} - -function bcmul($Num1 ,$Num2, $Scale = 0) { - return round($Num1 * $Num2, $Scale); -} - -function bcdiv($Num1 ,$Num2, $Scale = 0) { - return round($Num1 / $Num2, $Scale); -} - -function bcpow($Num1 ,$Num2, $Scale = 0) { - return round(pow($Num1, $Num2), $Scale); -} - -function bccomp($Num1, $Num2, $Scale = 0) { - if(!preg_match("/^\+?(\d+)(\.\d+)?$/", $Num1, $Tmp1) || !preg_match("/^\+?(\d+)(\.\d+)?$/", $Num2, $Tmp2)) return('0'); - - $Num1 = ltrim($Tmp1[1],'0'); - $Num2 = ltrim($Tmp2[1],'0'); - - if(strlen($Num1) > strlen($Num2)) return(1); - if(strlen($Num1) < strlen($Num2)) return(-1); - - $Dec1 = isset($Tmp1[2]) ? rtrim(substr($Tmp1[2],1),'0') : ''; - $Dec2 = isset($Tmp2[2]) ? rtrim(substr($Tmp2[2],1),'0') : ''; - - if($Scale != null) { - $Dec1 = substr($Dec1,0,$Scale); - $Dec2 = substr($Dec2,0,$Scale); - } - - $DLen = max(strlen($Dec1), strlen($Dec2)); - - $Num1 .= str_pad($Dec1, $DLen, '0'); - $Num2 .= str_pad($Dec2, $DLen, '0'); - - for($i=0; $i (int)$Num2{$i}) return 1 ; - if((int)$Num1{$i} < (int)$Num2{$i}) return -1 ; - } - - return 0; -} -?> \ No newline at end of file diff --git a/includes/classes/ArrayUtil.class.php b/includes/classes/ArrayUtil.class.php new file mode 100644 index 0000000..087f185 --- /dev/null +++ b/includes/classes/ArrayUtil.class.php @@ -0,0 +1,84 @@ +. + * + * @package 2Moons + * @author Jan + * @copyright 2006 Perberos (UGamela) + * @copyright 2008 Chlorel (XNova) + * @copyright 2009 Lucky (XGProyecto) + * @copyright 2012 Jan (2Moons) + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 2.0 (2012-11-31) + * @info $Id$ + * @link http://code.google.com/p/2moons/ + */ + +class ArrayUtil +{ + function combineArrayWithSingleElement($keys, $var) { + if(empty($keys)) + { + return array(); + } + return array_combine($keys, array_fill(0, count($keys), $var)); + } + + function combineArrayWithKeyElements($keys, $var) { + $temp = array(); + foreach($keys as $key) + { + if(isset($var[$key])) + { + $temp[$key] = $var[$key]; + } + else + { + $temp[$key] = $key; + } + } + + return $temp; + } + + // http://www.php.net/manual/en/function.array-key-exists.php#81659 + function arrayKeyExistsRecrusive($needle, $haystack) + { + $result = array_key_exists($needle, $haystack); + + if ($result) + { + return $result; + } + + foreach ($haystack as $v) + { + if (is_array($v)) + { + $result = self::arrayKeyExistsRecrusive($needle, $v); + } + + if ($result) + { + return $result; + } + } + + return $result; + } +} \ No newline at end of file diff --git a/includes/classes/Config.class.php b/includes/classes/Config.class.php new file mode 100644 index 0000000..65abe8a --- /dev/null +++ b/includes/classes/Config.class.php @@ -0,0 +1,155 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + +class Config +{ + #static private $uniConfig; + #static private $gameConfig; + static private $config; + + static function init() + { + $configResult = $GLOBALS['DATABASE']->query("SELECT * FROM ".CONFIG.";"); + + while($configRow = $GLOBALS['DATABASE']->fetch_array($configResult)) + { + $configRow['moduls'] = explode(";", $configRow['moduls']); + self::$config[$configRow['uni']] = $configRow; + } + + $GLOBALS['DATABASE']->free_result($configResult); + } + + static function setGlobals() + { + // BC Wrapper + $GLOBALS['CONFIG'] = self::$config; + $GLOBALS['CONF'] = self::$config[$GLOBALS['UNI']]; + } + + static function get($key, $universe = NULL) + { + if(is_null($universe) || !isset(self::$config[$universe])) + { + $universe = $GLOBALS['UNI']; + } + + if(isset(self::$config[$universe][$key])) + { + return self::$config[$universe][$key]; + } + + + /* New Config + if(is_null($universe) || !isset(self::$uniConfig[$universe])) + { + $universe = $GLOBALS['UNI']; + } + + if(isset(self::$uniConfig[$universe][$key])) + { + return self::$uniConfig[$universe][$key]; + } + + if(isset(self::$gameConfig[$key])) + { + return self::$gameConfig[$key]; + } + */ + throw new Exception("Unkown Config Key ".$key."!"); + } + + static function getAll($configType, $universe = NULL) + { + switch($configType) + { + default: + if(is_null($universe) || !isset(self::$config[$universe])) { + return self::$config; + } + else { + return self::$config[$universe]; + } + break; + /* New Config + case 'universe': + return self::$uniConfig; + break; + case 'global': + return self::$gameConfig; + break; */ + } + + throw new Exception("Unkown ConfigType ".$configType."!"); + } + + static function update($newConfig, $universe = NULL) + { + if(is_null($universe) || !isset(self::$config[$universe])) { + $universe = $GLOBALS['UNI']; + } + + $gameUpdate = array(); + $uniUpdate = array(); + + foreach($newConfig as $configKey => $value) + { + if(!isset(self::$config[$universe][$configKey])) + { + throw new Exception("Unkown Config Key ".$configKey."!"); + } + + if(in_array($configKey, $GLOBALS['BASICCONFIG'])) + { + foreach(array_keys(self::$config) as $uniID) + { + self::$config[$uniID][$configKey] = $value; + } + $gameUpdate[] = $configKey." = '".$GLOBALS['DATABASE']->escape($value)."'"; + } + else + { + self::$config[$universe][$configKey] = $value; + $uniUpdate[] = $configKey." = '".$GLOBALS['DATABASE']->escape($value)."'"; + } + } + + if(!empty($uniUpdate)) + { + $GLOBALS['DATABASE']->query("UPDATE ".CONFIG." SET ".implode(', ', $uniUpdate)." WHERE uni = ".$universe.";"); + } + + if(!empty($gameUpdate)) + { + $GLOBALS['DATABASE']->query("UPDATE ".CONFIG." SET ".implode(', ', $gameUpdate).";"); + } + + $GLOBALS['CONFIG'] = self::$config; + $GLOBALS['CONF'] = self::$config[$GLOBALS['UNI']]; + } +} diff --git a/includes/classes/Cronjob.class.php b/includes/classes/Cronjob.class.php new file mode 100644 index 0000000..3cbd627 --- /dev/null +++ b/includes/classes/Cronjob.class.php @@ -0,0 +1,99 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + +class Cronjob +{ + function __construct() + { + + } + + static function execute($cronjobID) + { + $cronjobsList = array(); + $cronjobsClassName = $GLOBALS['DATABASE']->getFirstCell("SELECT class FROM ".CRONJOBS." WHERE isActive = 1 AND cronjobID = ".$cronjobID." AND `lock` IS NULL;"); + if(empty($cronjobsClassName)) + { + throw new Exception("Unkown cronjob ".$cronjobID." or is deactived"); + } + + $GLOBALS['DATABASE']->query("UPDATE ".CRONJOBS." SET `lock` = '".md5(TIMESTAMP)."' WHERE cronjobID = ".$cronjobID.";"); + + $cronjobsPath = ROOT_PATH.'includes/classes/cronjob/'.$cronjobsClassName.'.class.php'; + + // die hard, if file not exists. + require_once($cronjobsPath); + + $cronjobObj = new $cronjobsClassName; + $cronjobObj->run(); + self::reCalculateCronjobs($cronjobID); + $GLOBALS['DATABASE']->query("UPDATE ".CRONJOBS." SET `lock` = NULL WHERE cronjobID = ".$cronjobID.";"); + } + + static function getNeedTodoExecutedJobs() + { + $cronjobsList = array(); + $cronjobsRaw = $GLOBALS['DATABASE']->query("SELECT cronjobID FROM ".CRONJOBS." WHERE isActive = 1 AND nextTime < ".TIMESTAMP." AND `lock` IS NULL;"); + while($cronjobRow = $GLOBALS['DATABASE']->fetchArray($cronjobsRaw)) + { + $cronjobsList[] = $cronjobRow['cronjobID']; + } + + $GLOBALS['DATABASE']->free_result($cronjobsRaw); + + return $cronjobsList; + } + + static function reCalculateCronjobs($cronjobID = NULL) + { + + require_once ROOT_PATH.'includes/libs/tdcron/class.tdcron.php'; + require_once ROOT_PATH.'includes/libs/tdcron/class.tdcron.entry.php'; + + $cronjobsList = array(); + $SQL = ""; + $where = ""; + + if(!empty($cronjobID)) + { + $where = " WHERE cronjobID = ".$cronjobID; + } + + $cronjobsRaw = $GLOBALS['DATABASE']->query("SELECT cronjobID, min, hours, dom, month, dow FROM ".CRONJOBS.$where.";"); + + while($cronjobRow = $GLOBALS['DATABASE']->fetchArray($cronjobsRaw)) + { + $cronTabString = implode(' ', array($cronjobRow['min'], $cronjobRow['hours'], $cronjobRow['dom'], $cronjobRow['month'], $cronjobRow['dow'])); + $nextTime = tdCron::getNextOccurrence($cronTabString, TIMESTAMP); + + $SQL .= "UPDATE ".CRONJOBS." SET nextTime = ".$nextTime." WHERE cronjobID = ".$cronjobRow['cronjobID'].";"; + } + + $GLOBALS['DATABASE']->multi_query($SQL); + } +} \ No newline at end of file diff --git a/includes/classes/HTTP.class.php b/includes/classes/HTTP.class.php new file mode 100644 index 0000000..ab2026b --- /dev/null +++ b/includes/classes/HTTP.class.php @@ -0,0 +1,97 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + +class HTTP { + + static public function redirectTo($URL, $external = false) + { + if($external) + { + self::sendHeader('Location', $URL); + } + else + { + self::sendHeader('Location', HTTP_PATH.$URL); + } + exit; + } + + static public function sendHeader($name, $value = NULL) + { + header($name.(!is_null($value) ? ': '.$value : '')); + } + + static public function sendCookie($name, $value = "", $toTime = NULL) + { + setcookie($name, $value, $toTime); + } + + static public function _GP($name, $default, $multibyte = false, $highnum = false) + { + if(!isset($_REQUEST[$name])) + { + return $default; + } + + if(is_int($default)) + { + return (int) $_REQUEST[$name]; + } + + if(is_float($default)) + { + return (float) $_REQUEST[$name]; + } + + if(is_string($default)) + { + $var = trim(htmlspecialchars(str_replace(array("\r\n", "\r", "\0"), array("\n", "\n", ''), $_REQUEST[$name]), ENT_QUOTES, 'UTF-8')); + + if (empty($var)) { + return $default; + } + + if ($multibyte) { + if (!preg_match('/^./u', $var)) { + $var = ''; + } + } else { + $var = preg_replace('/[\x80-\xFF]/', '?', $var); // no multibyte, allow only ASCII (0-127) + } + + return $var; + } + + if(is_array($default)) + { + return (array) $_REQUEST[$name]; + } + + return $default; + } +} \ No newline at end of file diff --git a/includes/classes/HTTPRequest.class.php b/includes/classes/HTTPRequest.class.php new file mode 100644 index 0000000..56cf1b7 --- /dev/null +++ b/includes/classes/HTTPRequest.class.php @@ -0,0 +1,69 @@ +. + * + * @package 2Moons + * @author Jan + * @copyright 2006 Perberos (UGamela) + * @copyright 2008 Chlorel (XNova) + * @copyright 2009 Lucky (XGProyecto) + * @copyright 2012 Jan (2Moons) + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 2.0 (2012-11-31) + * @info $Id$ + * @link http://code.google.com/p/2moons/ + */ + +class HTTPRequest +{ + private $url = NULL; + private $content = NULL; + private $ch = NULL; + + function __construct($url = NULL) + { + $this->url = $url; + } + + function send() + { + if(function_exists("curl_init")) + { + $this->ch = curl_init($this->url); + curl_setopt($this->ch, CURLOPT_HTTPGET, true); + curl_setopt($this->ch, CURLOPT_AUTOREFERER, true); + curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($this->ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; 2Moons/".Config::get('VERSION')."; +http://2moons.cc)"); + curl_setopt($this->ch, CURLOPT_HTTPHEADER, array( + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3", + "Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4", + )); + + $this->content = curl_exec($this->ch); + curl_close($this->ch); + } + } + + function getResponse() + { + $this->send(); + return $this->content; + } +} \ No newline at end of file diff --git a/includes/classes/Language.class.php b/includes/classes/Language.class.php new file mode 100644 index 0000000..37a511e --- /dev/null +++ b/includes/classes/Language.class.php @@ -0,0 +1,186 @@ +. + * + * @package 2Moons + * @author Jan Kr�pke + * @copyright 2012 Jan Kr�pke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + +class Language implements ArrayAccess { + private $container = array(); + private $language = array(); + static private $allLangauges = array(); + + static function getAllowedLangs($OnlyKey = true) + { + if(count(self::$allLangauges) == 0) { + $GLOBALS['CACHE']->add('language', 'LanguageBuildCache'); + self::$allLangauges = $GLOBALS['CACHE']->get('language'); + } + + if($OnlyKey) { + return array_keys(self::$allLangauges); + } + else { + return self::$allLangauges; + } + } + + public function getUserAgentLanguage() + { + if (isset($_REQUEST['lang']) && in_array($_REQUEST['lang'], self::getAllowedLangs())) + { + HTTP::sendCookie('lang', $_REQUEST['lang'], 2147483647); + $this->setLanguage($_REQUEST['lang']); + return true; + } + + if ((MODE === 'LOGIN' || MODE === 'INSTALL') && isset($_COOKIE['lang']) && in_array($_COOKIE['lang'], self::getAllowedLangs())) + { + $this->setLanguage($_COOKIE['lang']); + return true; + } + + if (empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { + return false; + } + + $quality = 0; + + + $accepted_languages = preg_split('/,\s*/', $_SERVER['HTTP_ACCEPT_LANGUAGE']); + + $language = $this->getLanguage(); + $current_q = 0; + + foreach ($accepted_languages as $accepted_language) + { + $isValid = preg_match('/^([a-z]{1,8}(?:-[a-z]{1,8})*)'.'(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i', $accepted_language, $matches); + + if ($isValid !== 1) + { + continue; + } + + list($code) = explode('-', strtolower($matches[1])); + $quality = isset($matches[2]) ? (float)$matches[2] : 1.0; + + if($quality > $current_q && in_array($code, self::getAllowedLangs())) + { + $language = $code; + $current_q = $quality; + break; + } + } + + HTTP::sendCookie('lang', $language, 2147483647); + $this->setLanguage($language); + } + + public function __construct($language = NULL) + { + $this->setLanguage($language); + } + + public function setLanguage($language) + { + if(!is_null($language) && in_array($language, self::getAllowedLangs())) + { + $this->language = $language; + } + elseif(MODE !== 'INSTALL') + { + $this->language = Config::get('lang'); + } + else + { + $this->language = DEFAULT_LANG; + } + } + + public function addData($data) { + $this->container = array_merge_recursive($this->container, $data); + } + + public function getLanguage() + { + return $this->language; + } + + public function getTemplate($templateName) + { + if(file_exists(ROOT_PATH.'language/'.$this->getLanguage().'/templates/'.$templateName.'.txt')) + { + return file_get_contents(ROOT_PATH.'language/'.$this->getLanguage().'/templates/'.$templateName.'.txt'); + } + else + { + return '### Template "'.$templateName.'" on language "'.$this->getLanguage().'" not found! ###'; + } + } + + public function includeData($Files) + { + // Fixed BOM problems. + ob_start(); + + foreach($Files as $File) { + require(ROOT_PATH.'language/'.$this->getLanguage().'/'.$File.'.php'); + } + + if(file_exists(ROOT_PATH.'language/'.$this->getLanguage().'/CUSTOM.php')) + { + require(ROOT_PATH.'language/'.$this->getLanguage().'/CUSTOM.php'); + } + + ob_end_clean(); + $this->addData($LNG); + } + + public function insertData($Files) + { + + } + + /** ArrayAccess Functions **/ + + public function offsetSet($offset, $value) { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + public function offsetExists($offset) { + return isset($this->container[$offset]); + } + + public function offsetUnset($offset) { + unset($this->container[$offset]); + } + + public function offsetGet($offset) { + return isset($this->container[$offset]) ? $this->container[$offset] : $offset; + } +} \ No newline at end of file diff --git a/includes/classes/Mail.class.php b/includes/classes/Mail.class.php new file mode 100644 index 0000000..ed7d667 --- /dev/null +++ b/includes/classes/Mail.class.php @@ -0,0 +1,100 @@ +. + * + * @package 2Moons + * @author Jan + * @copyright 2006 Perberos (UGamela) + * @copyright 2008 Chlorel (XNova) + * @copyright 2009 Lucky (XGProyecto) + * @copyright 2012 Jan (2Moons) + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 2.0 (2012-11-31) + * @info $Id$ + * @link http://code.google.com/p/2moons/ + */ + +class Mail +{ + function send($MailTarget, $MailTargetName, $MailSubject, $MailContent) + { + $transport = self::getSwiftTransport(); + $mailer = Swift_Mailer::newInstance($transport); + + $mailFrom = Config::get('smtp_sendmail'); + $mailTo = Config::get('game_name'); + + $mail = Swift_Message::newInstance(); + $mail->setSubject($MailSubject) + ->setFrom(array($mailFrom => $mailTo)) + ->setTo(array($MailTarget => $MailTargetName)) + ->setBody($MailContent); + + $mailer->send($mail); + } + + function multiSend($MailTargets, $MailSubject, $MailContent = NULL) + { + $transport = self::getSwiftTransport(); + $mailer = Swift_Mailer::newInstance($transport); + + $mailFrom = Config::get('smtp_sendmail'); + $mailTo = Config::get('game_name'); + + $mail = Swift_Message::newInstance(); + $mail->setSubject($MailSubject) + ->setFrom(array($mailFrom => $mailTo)); + + foreach($MailTargets as $address => $data) + { + $content = isset($data['body']) ? $data['body'] : $MailContent; + $mail->setTo(array($address => $data['username'])) + ->setBody(strip_tags($content)) + ->addPart($content, 'text/html'); + + $mailer->send($mail); + } + } + + function getSwiftTransport() + { + require_once(ROOT_PATH.'includes/libs/swift/swift_required.php'); + + if(Config::get('mail_use') == 2) + { + $transport = Swift_SmtpTransport::newInstance(Config::get('smtp_host'), Config::get('smtp_port')); + + if(Config::get('smtp_ssl') == 'ssl' || Config::get('smtp_ssl') == 'tls') + { + $transport->setEncryption(Config::get('smtp_ssl')); + } + + if(Config::get('smtp_user') != '') + { + $transport->setUsername(Config::get('smtp_user')); + $transport->setPassword(Config::get('smtp_pass')); + } + } + elseif(Config::get('mailMethod') == 0) + { + $transport = Swift_MailTransport::newInstance(); + } + + return $transport; + } +} \ No newline at end of file diff --git a/includes/classes/PlayerUtil.class.php b/includes/classes/PlayerUtil.class.php new file mode 100644 index 0000000..023a2f4 --- /dev/null +++ b/includes/classes/PlayerUtil.class.php @@ -0,0 +1,436 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + +class PlayerUtil { + + const POSITION_NOT_AVALIBLE = 1; + + static function cryptPassword($password) + { + // http://www.phpgangsta.de/schoener-hashen-mit-bcrypt + require(ROOT_PATH . 'includes/config.php'); + + if(!CRYPT_BLOWFISH || !isset($salt)) { + return md5($password); + } else { + return crypt($password, '$2a$09$'.$salt.'$'); + } + } + + static function isPositionFree($Universe, $Galaxy, $System, $Position, $Type = 1) + { + return $GLOBALS['DATABASE']->getFirstCell("SELECT COUNT(*) FROM ".PLANETS." + WHERE universe = ".$Universe." AND galaxy = ".$Galaxy." + AND system = ".$System." AND planet = ".$Position." + AND planet_type = ".$Type.";") == 0; + } + + static function calculateMoonChance($FleetDebris, $universe) + { + return min(round($FleetDebris / 100000 * $uniConfig['planetMoonCreateChanceFactor'], 0), $uniConfig['planetMoonCreateMaxFactor']); + } + + static function isNameValid($name) + { + if(UTF8_SUPPORT) { + return preg_match("/^[\p{L}\p{N}_\-. ]*$/u", $name); + } else { + return preg_match("/^[A-z0-9_\-. ]*$/", $name); + } + } + + static function isMailValid($address) { + + if(function_exists('filter_var')) { + return filter_var($address, FILTER_VALIDATE_EMAIL) !== FALSE; + } else { + /* Regex expression from swift mailer (http://swiftmailer.org) - RFC 2822 */ + return preg_match('/^(?:(?:(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?(?:[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_\{\}\|~]+(\.[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_\{\}\|~]+)*)+(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?)|(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?"((?:(?:[ \t]*(?:\r\n))?[ \t])?(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21\x23-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])))*(?:(?:[ \t]*(?:\r\n))?[ \t])?"(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?))@(?:(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?(?:[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_\{\}\|~]+(\.[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_\{\}\|~]+)*)+(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?)|(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?\[((?:(?:[ \t]*(?:\r\n))?[ \t])?(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x5A\x5E-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])))*?(?:(?:[ \t]*(?:\r\n))?[ \t])?\](?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?)))$/D', $address); + } + } + + static function createPlayer($Universe, $UserName, $UserPass, $UserMail, $UserLang = NULL, $Galaxy = NULL, $System = NULL, $Position = NULL, $planetname = NULL, $authlevel = 0, $UserIP = NULL) + { + $CONF = Config::getAll(NULL, $Universe); + + if (isset($Galaxy, $System, $Position)) + { + if ($CONF['max_galaxy'] < $Galaxy || 1 > $Galaxy) { + throw new Exception("Try to create a planet at position: ".$Galaxy.":".$System.":".$Position); + } + + if ($CONF['max_system'] < $System || 1 > $System) { + throw new Exception("Try to create a planet at position: ".$Galaxy.":".$System.":".$Position); + } + + if ($CONF['max_planets'] < $Position || 1 > $Position) { + throw new Exception("Try to create a planet at position: ".$Galaxy.":".$System.":".$Position); + } + + if (!self::isPositionFree($Universe, $Galaxy, $System, $Position)) { + throw new Exception("Position is not empty: ".$Galaxy.":".$System.":".$Position); + } + } else { + $Galaxy = $CONF['LastSettedGalaxyPos']; + $System = $CONF['LastSettedSystemPos']; + $Planet = $CONF['LastSettedPlanetPos']; + + do { + $Position = mt_rand(round($CONF['max_planets'] * 0.2), round($CONF['max_planets'] * 0.8)); + if ($Planet < 3) { + $Planet += 1; + } else { + if ($System >= $CONF['max_system']) { + $System = 1; + if($Galaxy >= $CONF['max_galaxy']) { + $Galaxy = 1; + } else { + $Galaxy += 1; + } + } else { + $System += 1; + } + } + } while (self::isPositionFree($Universe, $Galaxy, $System, $Position) === false); + + Config::update(array( + 'LastSettedGalaxyPos' => $Galaxy, + 'LastSettedSystemPos' => $System, + 'LastSettedPlanetPos' => $Planet, + )); + } + + $SQL = "INSERT INTO ".USERS." SET + username = '".$GLOBALS['DATABASE']->escape($UserName)."', + email = '".$GLOBALS['DATABASE']->escape($UserMail)."', + email_2 = '".$GLOBALS['DATABASE']->escape($UserMail)."', + authlevel = ".$authlevel.", + universe = ".$Universe.", + lang = '".$UserLang."', + ip_at_reg = '".(!empty($UserIP) ? $UserIP : $_SERVER['REMOTE_ADDR'])."', + onlinetime = ".TIMESTAMP.", + register_time = ".TIMESTAMP.", + password = '".$UserPass."', + dpath = '".DEFAULT_THEME."', + timezone = '".$CONF['timezone']."', + uctime = 0"; + + foreach($GLOBALS['reslist']['resstype'][3] as $elementID) { + $SQL .= ", ".$GLOBALS['resource'][$elementID]." = ".$CONF[$GLOBALS['resource'][$elementID].'_start']; + } + + $GLOBALS['DATABASE']->query($SQL); + + $userID = $GLOBALS['DATABASE']->GetInsertID(); + $planetID = self::createPlanet($Galaxy, $System, $Position, $Universe, $userID, $planetname, true, $authlevel); + + $currentUserAmount = $CONF['users_amount'] + 1; + + Config::update(array( + 'users_amount' => $currentUserAmount + 1, + )); + + $SQL = "UPDATE ".USERS." SET + galaxy = ".$Galaxy.", + system = ".$System.", + planet = ".$Position.", + id_planet = ".$planetID." + WHERE id = ".$userID.";"; + + $GLOBALS['DATABASE']->query($SQL); + + $SQL = "INSERT INTO ".STATPOINTS." SET + id_owner = ".$userID.", + universe = ".$Universe.", + stat_type = 1, + tech_rank = ".$currentUserAmount.", + build_rank = ".$currentUserAmount.", + defs_rank = ".$currentUserAmount.", + fleet_rank = ".$currentUserAmount.", + total_rank = ".$currentUserAmount.";"; + + $GLOBALS['DATABASE']->query($SQL); + + return array($userID, $planetID); + } + + static function createPlanet($Galaxy, $System, $Position, $Universe, $PlanetOwnerID, $PlanetName = NULL, $HomeWorld = false, $authlevel = 0) + { + $CONF = Config::getAll(NULL, $Universe); + + if ($CONF['max_galaxy'] < $Galaxy || 1 > $Galaxy) { + throw new Exception("Try to create a planet at position: ".$Galaxy.":".$System.":".$Position); + } + + if ($CONF['max_system'] < $System || 1 > $System) { + throw new Exception("Try to create a planet at position: ".$Galaxy.":".$System.":".$Position); + } + + if ($CONF['max_planets'] < $Position || 1 > $Position) { + throw new Exception("Try to create a planet at position: ".$Galaxy.":".$System.":".$Position); + } + + if (!self::isPositionFree($Universe, $Galaxy, $System, $Position)) { + throw new Exception("Position is not empty: ".$Galaxy.":".$System.":".$Position); + } + + require(ROOT_PATH.'includes/PlanetData.php'); + + $Pos = ceil($Position / ($CONF['max_planets'] / count($PlanetData))); + $TMax = $PlanetData[$Pos]['temp']; + $TMin = $TMax - 40; + + if($HomeWorld) { + $Fields = $CONF['initial_fields']; + } else { + $Fields = floor($PlanetData[$Pos]['fields'] * $CONF['planet_factor']); + } + + $Types = array_keys($PlanetData[$Pos]['image']); + $Type = $Types[array_rand($Types)]; + $Class = $Type.'planet'.($PlanetData[$Pos]['image'][$Type] < 10 ? '0' : '').$PlanetData[$Pos]['image'][$Type]; + + if(empty($PlanetName)) + { + if($HomeWorld) { + $PlanetName = t('fcm_mainplanet'); + } else { + $PlanetName = t('fcp_colony'); + } + } + + $SQL = "INSERT INTO ".PLANETS." SET + name = '".$GLOBALS['DATABASE']->escape($PlanetName)."', + universe = ".$Universe.", + id_owner = ".$PlanetOwnerID.", + galaxy = ".$Galaxy.", + system = ".$System.", + planet = ".$Position.", + last_update = ".TIMESTAMP.", + planet_type = '1', + image = '".$Class."', + diameter = ".floor(1000 * sqrt($Fields)).", + field_max = ".$Fields.", + temp_min = ".$TMin.", + temp_max = ".$TMax; + + + foreach($GLOBALS['reslist']['resstype'][1] as $elementID) { + $SQL .= ", ".$GLOBALS['resource'][$elementID]." = ".$CONF[$GLOBALS['resource'][$elementID].'_start']; + } + + $GLOBALS['DATABASE']->query($SQL); + return $GLOBALS['DATABASE']->GetInsertID(); + } + + static function createMoon($Universe, $Galaxy, $System, $Position, $userID, $Chance, $Size = NULL) + { + $SQL = "SELECT id_luna, planet_type, id, name, temp_max, temp_min FROM ".PLANETS." + WHERE universe = ".$Universe." + AND galaxy = ".$Galaxy." + AND system = ".$System." + AND planet = ".$Position." + AND planet_type = '1';"; + + $MoonPlanet = $GLOBALS['DATABASE']->getFirstRow($SQL); + + if ($MoonPlanet['id_luna'] != 0) + return false; + + if($Size == 0) { + $size = floor(pow(mt_rand(10, 20) + 3 * $Chance, 0.5) * 1000); # New Calculation - 23.04.2011 + } else { + $size = $Size; + } + + $maxtemp = $MoonPlanet['temp_max'] - mt_rand(10, 45); + $mintemp = $MoonPlanet['temp_min'] - mt_rand(10, 45); + + $GLOBALS['DATABASE']->multi_query("INSERT INTO ".PLANETS." SET + name = '".$MoonName."', + id_owner = ".$Owner.", + universe = ".$Universe.", + galaxy = ".$Galaxy.", + system = ".$System.", + planet = ".$Planet.", + last_update = ".TIMESTAMP.", + planet_type = '3', + image = 'mond', + diameter = ".$size.", + field_max = '1', + temp_min = ".$mintemp.", + temp_max = ".$maxtemp.", + metal = 0, + metal_perhour = 0, + crystal = 0, + crystal_perhour = 0, + deuterium = 0, + deuterium_perhour = 0; + SET @moonID = LAST_INSERT_ID(); + UPDATE ".PLANETS." SET + id_luna = @moonID + WHERE + id = ".$MoonPlanet['id'].";"); + + return true; + } + + static function deletePlayer($userID) + { + global $db; + + if(ROOT_USER == $userID) { + return false; + } + + $userData = $GLOBALS['DATABASE']->getFirstRow("SELECT universe, ally_id FROM ".USERS." WHERE id = '".$userID."';"); + $SQL = ""; + + if (!empty($userData['ally_id'])) + { + $memberCount = $GLOBALS['DATABASE']->getFirstCell("SELECT ally_members FROM ".ALLIANCE." WHERE id = ".$userData['ally_id'].";"); + + if ($memberCount == 1) + { + $SQL .= "UPDATE ".ALLIANCE." SET ally_members = ally_members - 1 WHERE id = ".$userData['ally_id'].";"; + } + else + { + $SQL .= "DELETE FROM ".ALLIANCE." WHERE id = ".$userData['ally_id'].";"; + $SQL .= "DELETE FROM ".STATPOINTS." WHERE stat_type = '2' AND id_owner = ".$userData['ally_id'].";"; + $SQL .= "UPDATE ".STATPOINTS." WHERE id_ally = 0 AND id_ally = ".$userData['ally_id'].";"; + } + } + + $SQL .= "DELETE FROM ".ALLIANCE_REQUEST." WHERE userID = ".$userID.";"; + $SQL .= "DELETE FROM ".BUDDY." WHERE owner = ".$userID." OR sender = ".$userID.";"; + $SQL .= "DELETE FROM ".FLEETS." WHERE fleet_owner = ".$userID.";"; + $SQL .= "DELETE FROM ".MESSAGES." WHERE message_owner = ".$userID.";"; + $SQL .= "DELETE FROM ".NOTES." WHERE owner = ".$userID.";"; + $SQL .= "DELETE FROM ".PLANETS." WHERE id_owner = ".$userID.";"; + $SQL .= "DELETE FROM ".USERS." WHERE id = ".$userID.";"; + $SQL .= "DELETE FROM ".STATPOINTS." WHERE stat_type = '1' AND id_owner = ".$userID.";"; + $GLOBALS['DATABASE']->multi_query($SQL); + + $fleetData = $GLOBALS['DATABASE']->query("SELECT fleet_id FROM ".FLEETS." WHERE fleet_target_owner = ".$userID.";"); + + while($FleetID = $GLOBALS['DATABASE']->fetchArray($fleetData)) { + FleetUtil::SendFleetBack($userID, $FleetID['fleet_id']); + } + + $GLOBALS['DATABASE']->free_result($fleetData); + + $GLOBALS['DATABASE']->query("UPDATE ".UNIVERSE." SET userAmount = userAmount - 1 WHERE universe = ".$userData['universe'].";"); + + $GLOBALS['CACHE']->flush('universe'); + } + + static function deletePlanet($planetID) + { + $planetData = $GLOBALS['DATABASE']->getFirstRow("SELECT planet_type FROM ".PLANETS." WHERE id = ".$planetID." AND id NOT IN (SELECT id_planet FROM ".USERS.");"); + + if(empty($planetData)) { + return false; + } + + $fleetData = $GLOBALS['DATABASE']->query("SELECT fleet_id FROM ".FLEETS." WHERE fleet_end_id = ".$planetID.";"); + + while($FleetID = $GLOBALS['DATABASE']->fetchArray($fleetData)) { + FleetUtil::SendFleetBack($$planetID, $FleetID['fleet_id']); + } + + $GLOBALS['DATABASE']->free_result($fleetData); + + if ($planetData['planet_type'] == 3) { + $GLOBALS['DATABASE']->multi_query("DELETE FROM ".PLANETS." WHERE id = ".$planetID.";UPDATE ".PLANETS." SET id_luna = 0 WHERE id_luna = ".$planetID.";"); + } else { + $GLOBALS['DATABASE']->query("DELETE FROM ".PLANETS." WHERE id = ".$planetID." OR id_luna = ".$planetID.";"); + } + } + + static function maxPlanetCount($USER) + { + global $resource; + $CONF = Config::getAll('universe', $USER['universe']); + + if($CONF['min_player_planets'] == 0) + { + $CONF['planets_tech'] = 999; + } + + if($CONF['min_player_planets'] == 0) + { + $CONF['planets_officier'] = 999; + } + + // http://owiki.de/index.php/Astrophysik#.C3.9Cbersicht + return (int) ceil($CONF['min_player_planets'] + min($CONF['planets_tech'], $USER[$resource[124]] * $CONF['planets_per_tech']) + min($CONF['planets_officier'],$USER['factor']['Planets'])); + } + + static function allowPlanetPosition($position, $USER) + { + // http://owiki.de/index.php/Astrophysik#.C3.9Cbersicht + + global $resource; + $CONF = Config::getAll('universe', $USER['universe']); + switch($position) { + case 1: + case ($CONF['max_planets']): + return $USER[$resource[124]] >= 8; + break; + case 2: + case ($CONF['max_planets']-1): + return $USER[$resource[124]] >= 6; + break; + case 3: + case ($CONF['max_planets']-2): + return $USER[$resource[124]] >= 4; + break; + default: + return $USER[$resource[124]] >= 1; + break; + } + } + + static function sendMessage($userID, $senderID, $senderName, $messageType, $subject, $text, $time, $parentID = NULL, $hasRead = 0, $universe = NULL) + { + $SQL = "INSERT INTO ".MESSAGES." SET + parentMessageID = ".(empty($parentID) ? "messageID" : $parentID).", + senderID = ".$senderID.", + senderName = '".$GLOBALS['DATABASE']->escape($senderName)."', + userID = ".$userID.", + time = ".$time.", + messageType = ".$messageType.", + subject = '".$GLOBALS['DATABASE']->escape($subject)."', + text = '".$GLOBALS['DATABASE']->escape($text)."', + hasRead = ".$hasRead.", + universe = ".Globals::getUni().";"; + + $GLOBALS['DATABASE']->query($SQL); + } +} \ No newline at end of file diff --git a/includes/classes/SQLDumper.class.php b/includes/classes/SQLDumper.class.php new file mode 100644 index 0000000..8dba4bd --- /dev/null +++ b/includes/classes/SQLDumper.class.php @@ -0,0 +1,233 @@ +. + * + * @package 2Moons + * @author Jan Kr�pke + * @copyright 2012 Jan Kr�pke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + +class SQLDumper +{ + public function dumpTablesToFile($dbTables, $filePath) + { + if($this->canNative('mysqldump')) + { + return $this->nativeDumpToFile($dbTables, $filePath); + } + else + { + return $this->softwareDumpToFile($dbTables, $filePath); + } + } + + private function setTimelimit() + { + @set_time_limit(600); // 10 Minutes + } + + private function canNative($command) + { + return function_exists('shell_exec') && function_exists('escapeshellarg') && shell_exec($command) !== NULL; + } + + private function nativeDumpToFile($dbTables, $filePath) + { + require ROOT_PATH.'includes/config.php'; + $dbTables = array_map('escapeshellarg', $dbTables); + $sqlDump = shell_exec("mysqldump --host='".escapeshellarg($database['host'])."' --port=".((int) $database['port'])." --user='".escapeshellarg($database['user'])."' --password='".escapeshellarg($database['userpw'])."' --no-create-db --order-by-primary --add-drop-table --comments --complete-insert --hex-blob '".escapeshellarg($database['databasename'])."' ".implode(' ', $dbTables)." 2>&1 1> ".$filePath); + if(strlen($sqlDump) !== 0) #mysqldump error + { + throw new Exception($sqlDump); + } + } + + private function softwareDumpToFile($dbTables, $filePath) + { + $this->setTimelimit(); + require ROOT_PATH.'includes/config.php'; + $intergerTypes = array('tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'decimal', 'float', 'double', 'real'); + $gameVersion = Config::get('VERSION'); + $serverVersion = $GLOBALS['DATABASE']->getServerVersion(); + $fp = fopen($filePath, 'w'); + fwrite($fp, "-- MySQL dump | 2Moons dumper v{$gameVersion} +-- +-- Host: {$database['host']} Database: {$database['databasename']} +-- ------------------------------------------------------ +-- Server version {$serverVersion} + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +"); + + foreach($dbTables as $dbTable) + { + $columNames = array(); + $numColums = array(); + $firstRow = true; + + fwrite($fp, "-- +-- Table structure for table `{$dbTable}` +-- + +DROP TABLE IF EXISTS `{$dbTable}`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; + +"); + $createTable = $GLOBALS['DATABASE']->getFirstRow("SHOW CREATE TABLE ".$dbTable); + fwrite($fp, $createTable['Create Table'].';'); + fwrite($fp, " + +/*!40101 SET character_set_client = @saved_cs_client */;"); + if($GLOBALS['DATABASE']->getFirstCell("SELECT COUNT(*) FROM ".$dbTable.";") == 0) + { + fwrite($fp, " + +-- +-- No data for table `{$dbTable}` +-- + +"); + continue; + } + fwrite($fp, " + +-- +-- Dumping data for table `{$dbTable}` +-- + +LOCK TABLES `{$dbTable}` WRITE; +/*!40000 ALTER TABLE `{$dbTable}` DISABLE KEYS */; + +"); + $columsData = $GLOBALS['DATABASE']->query("SHOW COLUMNS FROM `".$dbTable."`"); + + $columNames = array(); + while($columData = $GLOBALS['DATABASE']->fetchArray($columsData)) + { + $columNames[] = $columData['Field']; + foreach($intergerTypes as $type) + { + if(strpos($columData['Type'], $type.'(') !== false) + { + $numColums[] = $columData['Field']; + break; + } + } + } + $GLOBALS['DATABASE']->free_result($columsData); + + + $insertInto = "INSERT INTO `{$dbTable}` (`".implode("`, `", $columNames)."`) VALUES\r\n"; + + fwrite($fp, $insertInto); + $i = 0; + $tableData = $GLOBALS['DATABASE']->query("SELECT * FROM ".$dbTable); + while($tableRow = $GLOBALS['DATABASE']->fetchArray($tableData)) + { + $rowData = array(); + $i++; + if(($i % 50) === 0) + { + $firstRow = true; + fwrite($fp, ";\r\n"); + fwrite($fp, $insertInto); + } + + if(!$firstRow) + { + fwrite($fp, ",\r\n"); + } + else + { + $firstRow = false; + } + + foreach($tableRow as $colum => $value) + { + if(in_array($colum, $numColums)) + { + $rowData[] = $value === NULL ? 'NULL' : $value; + } + else + { + $rowData[] = $value === NULL ? 'NULL' : "'".$GLOBALS['DATABASE']->escape($value)."'"; + } + } + fwrite($fp, "(".implode(", ",$rowData).")"); + } + $GLOBALS['DATABASE']->free_result($tableData); + fwrite($fp, "; + +/*!40000 ALTER TABLE `{$dbTable}` ENABLE KEYS */; +UNLOCK TABLES; + +"); + } + fwrite($fp, "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on ".date("Y-d-m H:i:s")); + fclose($fp); + } + + public function restoreDatabase($filePath) + { + // Ugly. + $this->setTimelimit(); + + if($this->canNative('mysql')) + { + + $sqlDump = shell_exec("mysql --host='".escapeshellarg($database['host'])."' --port=".((int) $database['port'])." --user='".escapeshellarg($database['user'])."' --password='".escapeshellarg($database['userpw'])."' '".escapeshellarg($database['databasename'])."' < ".escapeshellarg($filePath)." 2>&1 1> /dev/null"); + if(strlen($sqlDump) !== 0) #mysql error + { + throw new Exception($sqlDump); + } + } + else + { + $backupQuery = explode(";\r\n", file_get_contents($filePath)); + foreach($backupQuery as $query) + { + $GLOBALS['DATABASE']->multi_query($query); + } + } + } +} \ No newline at end of file diff --git a/includes/classes/cache/builder/BannedBuildCache.class.php b/includes/classes/cache/builder/BannedBuildCache.class.php new file mode 100644 index 0000000..3bcd3a0 --- /dev/null +++ b/includes/classes/cache/builder/BannedBuildCache.class.php @@ -0,0 +1,42 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + +class BannedBuildCache +{ + function buildCache() + { + $Data = Core::getDB()->query("SELECT userID, MAX(banTime) FROM ".BANNED." WHERE banTime > ".TIMESTAMP." GROUP BY userID;"); + $Bans = array(); + while($Row = $Data->fetchObject()) + { + $Bans[$Row->userID] = $Row; + } + + return $Bans; + } +} diff --git a/includes/classes/cache/builder/LanguageBuildCache.class.php b/includes/classes/cache/builder/LanguageBuildCache.class.php new file mode 100644 index 0000000..c4d87bb --- /dev/null +++ b/includes/classes/cache/builder/LanguageBuildCache.class.php @@ -0,0 +1,50 @@ +. + * + * @package 2Moons + * @author Jan Kr�pke + * @copyright 2012 Jan Kr�pke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + +class LanguageBuildCache +{ + function buildCache() + { + $languages = array(); + foreach (new DirectoryIterator(ROOT_PATH.'language/') as $fileInfo) { + if(!$fileInfo->isDir()) continue; + + $Lang = $fileInfo->getBasename(); + + if(!file_exists(ROOT_PATH.'language/'.$Lang.'/LANG.cfg')) continue; + + // Fixed BOM problems. + ob_start(); + require(ROOT_PATH.'language/'.$Lang.'/LANG.cfg'); + ob_end_clean(); + $languages[$Lang] = $Language['name']; + } + + return $languages; + } +} \ No newline at end of file diff --git a/includes/classes/cache/builder/TeamspeakBuildCache.class.php b/includes/classes/cache/builder/TeamspeakBuildCache.class.php new file mode 100644 index 0000000..7b62520 --- /dev/null +++ b/includes/classes/cache/builder/TeamspeakBuildCache.class.php @@ -0,0 +1,95 @@ +. + * + * @package 2Moons + * @author Jan Kr�pke + * @copyright 2012 Jan Kr�pke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + + +class TeamspeakBuildCache +{ + function buildCache() + { + global $CONF; + + $teamspeakData = array(); + + switch($CONF['ts_version']) + { + case 2: + include_once(ROOT_PATH.'includes/libs/teamspeak/class.teamspeak2.php'); + $ts = new cyts(); + + if($ts->connect($CONF['ts_server'], $CONF['ts_tcpport'], $CONF['ts_udpport'], $CONF['ts_timeout'])) { + $serverInfo = $ts->info_serverInfo(); + $teamspeakData = array( + 'password' => '', // NO Server-API avalible. + 'current' => $serverInfo["server_currentusers"], + 'maxuser' => $serverInfo["server_maxusers"], + ); + $ts->disconnect(); + } else { + throw new Exception('Teamspeak-Error: '.$ts->debug()); + } + break; + case 3: + require_once(ROOT_PATH . "includes/libs/teamspeak/class.teamspeak3.php"); + $tsAdmin = new ts3admin($CONF['ts_server'], $CONF['ts_udpport'], $CONF['ts_timeout']); + $connected = $tsAdmin->connect(); + if(!$connected['success']) + { + throw new Exception('Teamspeak-Error: '.implode("
\r\n", $connected['errors'])); + } + + $selected = $tsAdmin->selectServer($CONF['ts_tcpport'], 'port', true); + if(!$selected['success']) + { + throw new Exception('Teamspeak-Error: '.implode("
\r\n", $selected['errors'])); + } + + $loggedIn = $tsAdmin->login($CONF['ts_login'], $CONF['ts_password']); + if(!$loggedIn['success']) + { + throw new Exception('Teamspeak-Error: '.implode("
\r\n", $loggedIn['errors'])); + } + + $serverInfo = $tsAdmin->serverInfo(); + if(!$serverInfo['success']) + { + throw new Exception('Teamspeak-Error: '.implode("
\r\n", $serverInfo['errors'])); + } + + $teamspeakData = array( + 'password' => $serverInfo['data']['virtualserver_password'], + 'current' => $serverInfo['data']['virtualserver_clientsonline'] - 1, + 'maxuser' => $serverInfo['data']['virtualserver_maxclients'], + ); + + $tsAdmin->logout(); + break; + } + + return $teamspeakData; + } +} \ No newline at end of file diff --git a/includes/classes/cache/builder/VarsBuildCache.class.php b/includes/classes/cache/builder/VarsBuildCache.class.php new file mode 100644 index 0000000..a3d0570 --- /dev/null +++ b/includes/classes/cache/builder/VarsBuildCache.class.php @@ -0,0 +1,176 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + +class VarsBuildCache +{ + function buildCache() + { + $resource = array(); + $requeriments = array(); + $pricelist = array(); + $CombatCaps = array(); + $reslist = array(); + + $reslist['prod'] = array(); + $reslist['storage'] = array(); + $reslist['bonus'] = array(); + $reslist['one'] = array(); + $reslist['build'] = array(); + $reslist['allow'][1] = array(); + $reslist['allow'][3] = array(); + $reslist['tech'] = array(); + $reslist['fleet'] = array(); + $reslist['defense'] = array(); + $reslist['officier'] = array(); + $reslist['dmfunc'] = array(); + + $reqResult = $GLOBALS['DATABASE']->query("SELECT * FROM ".VARS_REQUIRE.";"); + while($reqRow = $GLOBALS['DATABASE']->fetch_array($reqResult)) { + $requeriments[$reqRow['elementID']][$reqRow['requireID']] = $reqRow['requireLevel']; + } + + $varsResult = $GLOBALS['DATABASE']->query("SELECT * FROM ".VARS.";"); + while($varsRow = $GLOBALS['DATABASE']->fetch_array($varsResult)) { + $resource[$varsRow['elementID']] = $varsRow['name']; + $CombatCaps[$varsRow['elementID']] = array( + 'attack' => $varsRow['attack'], + 'shield' => $varsRow['defend'], + ); + + $pricelist[$varsRow['elementID']] = array( + 'cost' => array( + 901 => $varsRow['cost901'], + 902 => $varsRow['cost902'], + 903 => $varsRow['cost903'], + 911 => $varsRow['cost911'], + 921 => $varsRow['cost921'], + ), + 'factor' => $varsRow['factor'], + 'max' => $varsRow['maxLevel'], + 'consumption' => $varsRow['consumption1'], + 'consumption2' => $varsRow['consumption2'], + 'speed' => $varsRow['speed1'], + 'speed2' => $varsRow['speed2'], + 'capacity' => $varsRow['capacity'], + 'tech' => $varsRow['speedTech'], + 'time' => $varsRow['timeBonus'], + 'bonus' => array( + 'Attack' => array($varsRow['bonusAttack'], $varsRow['bonusAttackUnit']), + 'Defensive' => array($varsRow['bonusDefensive'], $varsRow['bonusDefensiveUnit']), + 'Shield' => array($varsRow['bonusShield'], $varsRow['bonusShieldUnit']), + 'BuildTime' => array($varsRow['bonusBuildTime'], $varsRow['bonusBuildTimeUnit']), + 'ResearchTime' => array($varsRow['bonusResearchTime'], $varsRow['bonusResearchTimeUnit']), + 'ShipTime' => array($varsRow['bonusShipTime'], $varsRow['bonusShipTimeUnit']), + 'DefensiveTime' => array($varsRow['bonusDefensiveTime'], $varsRow['bonusDefensiveTimeUnit']), + 'Resource' => array($varsRow['bonusResource'], $varsRow['bonusResourceUnit']), + 'Energy' => array($varsRow['bonusEnergy'], $varsRow['bonusEnergyUnit']), + 'ResourceStorage' => array($varsRow['bonusResourceStorage'], $varsRow['bonusResourceStorageUnit']), + 'ShipStorage' => array($varsRow['bonusShipStorage'], $varsRow['bonusShipStorageUnit']), + 'FlyTime' => array($varsRow['bonusFlyTime'], $varsRow['bonusFlyTimeUnit']), + 'FleetSlots' => array($varsRow['bonusFleetSlots'], $varsRow['bonusFleetSlotsUnit']), + 'Planets' => array($varsRow['bonusPlanets'], $varsRow['bonusPlanetsUnit']), + 'SpyPower' => array($varsRow['bonusSpyPower'], $varsRow['bonusSpyPowerUnit']), + 'Expedition' => array($varsRow['bonusExpedition'], $varsRow['bonusExpeditionUnit']), + 'GateCoolTime' => array($varsRow['bonusGateCoolTime'], $varsRow['bonusGateCoolTimeUnit']), + 'MoreFound' => array($varsRow['bonusMoreFound'], $varsRow['bonusMoreFoundUnit']), + ), + ); + + $ProdGrid[$varsRow['elementID']]['production'] = array( + 901 => $varsRow['production901'], + 902 => $varsRow['production902'], + 903 => $varsRow['production903'], + 911 => $varsRow['production911'], + ); + + $ProdGrid[$varsRow['elementID']]['storage'] = array( + 901 => $varsRow['storage901'], + 902 => $varsRow['storage902'], + 903 => $varsRow['storage903'], + ); + + if(array_filter($ProdGrid[$varsRow['elementID']]['production'])) + $reslist['prod'][] = $varsRow['elementID']; + + if(array_filter($ProdGrid[$varsRow['elementID']]['storage'])) + $reslist['storage'][] = $varsRow['elementID']; + + if(($varsRow['bonusAttack'] + $varsRow['bonusDefensive'] + $varsRow['bonusShield'] + $varsRow['bonusBuildTime'] + + $varsRow['bonusResearchTime'] + $varsRow['bonusShipTime'] + $varsRow['bonusDefensiveTime'] + $varsRow['bonusResource'] + + $varsRow['bonusEnergy'] + $varsRow['bonusResourceStorage'] + $varsRow['bonusShipStorage'] + $varsRow['bonusFlyTime'] + + $varsRow['bonusFleetSlots'] + $varsRow['bonusPlanets'] + $varsRow['bonusSpyPower'] + $varsRow['bonusExpedition'] + + $varsRow['bonusGateCoolTime'] + $varsRow['bonusMoreFound']) != 0) + { + $reslist['bonus'][] = $varsRow['elementID']; + } + if($varsRow['onePerPlanet'] == 1) + $reslist['one'][] = $varsRow['elementID']; + + switch($varsRow['class']) { + case 0: + $reslist['build'][] = $varsRow['elementID']; + $tmp = explode(',', $varsRow['onPlanetType']); + foreach($tmp as $type) + $reslist['allow'][$type][] = $varsRow['elementID']; + break; + case 100: + $reslist['tech'][] = $varsRow['elementID']; + break; + case 200: + $reslist['fleet'][] = $varsRow['elementID']; + break; + case 400: + $reslist['defense'][] = $varsRow['elementID']; + break; + case 500: + $reslist['missile'][] = $varsRow['elementID']; + break; + case 600: + $reslist['officier'][] = $varsRow['elementID']; + break; + case 700: + $reslist['dmfunc'][] = $varsRow['elementID']; + break; + } + } + + $rapidResult = $GLOBALS['DATABASE']->query("SELECT * FROM ".VARS_RAPIDFIRE.";"); + while($rapidRow = $GLOBALS['DATABASE']->fetch_array($rapidResult)) { + $CombatCaps[$rapidRow['elementID']]['sd'][$rapidRow['rapidfireID']] = $rapidRow['shoots']; + } + + return array( + 'reslist' => $reslist, + 'ProdGrid' => $ProdGrid, + 'CombatCaps' => $CombatCaps, + 'resource' => $resource, + 'pricelist' => $pricelist, + 'requeriments' => $requeriments, + ); + } +} \ No newline at end of file diff --git a/includes/classes/cache/ressource/CacheFile.class.php b/includes/classes/cache/ressource/CacheFile.class.php new file mode 100644 index 0000000..4aab070 --- /dev/null +++ b/includes/classes/cache/ressource/CacheFile.class.php @@ -0,0 +1,47 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + +class CacheFile { + function store($Key, $Value) { + file_put_contents(CACHE_PATH.'cache.'.$Key.'.php', $Value); + } + + function open($Key) { + if(!file_exists(CACHE_PATH.'cache.'.$Key.'.php')) + return false; + + return file_get_contents(CACHE_PATH.'cache.'.$Key.'.php'); + } + + function flush($Key) { + if(!file_exists(CACHE_PATH.'cache.'.$Key.'.php')) + return false; + + unlink(CACHE_PATH.'cache.'.$Key.'.php'); + } +} \ No newline at end of file diff --git a/includes/classes/class.BBCode.php b/includes/classes/class.BBCode.php index 98c524e..ad44ef7 100644 --- a/includes/classes/class.BBCode.php +++ b/includes/classes/class.BBCode.php @@ -1975,5 +1975,3 @@ function _dumpToString () { return $str; } } - -?> \ No newline at end of file diff --git a/includes/classes/class.BuildFunctions.php b/includes/classes/class.BuildFunctions.php new file mode 100644 index 0000000..b048394 --- /dev/null +++ b/includes/classes/class.BuildFunctions.php @@ -0,0 +1,282 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + +class BuildFunctions +{ + + static $bonusList = array( + 'Attack', + 'Defensive', + 'Shield', + 'BuildTime', + 'ResearchTime', + 'ShipTime', + 'DefensiveTime', + 'Resource', + 'Energy', + 'ResourceStorage', + 'ShipStorage', + 'FlyTime', + 'FleetSlots', + 'Planets', + 'SpyPower', + 'Expedition', + 'GateCoolTime', + 'MoreFound', + ); + + public static function getBonusList() + { + return self::$bonusList; + } + + public static function getRestPrice($USER, $PLANET, $Element, $elementPrice = NULL) + { + global $resource; + + if(!isset($elementPrice)) { + $elementPrice = self::getElementPrice($USER, $PLANET, $Element); + } + + $overflow = array(); + + foreach ($elementPrice as $resType => $resPrice) { + $avalible = isset($PLANET[$resource[$resType]]) ? $PLANET[$resource[$resType]] : $USER[$resource[$resType]]; + $overflow[$resType] = max($resPrice - $avalible, 0); + } + + return $overflow; + } + + public static function getElementPrice($USER, $PLANET, $Element, $forDestroy = false, $forLevel = NULL) { + global $pricelist, $resource, $reslist; + + if (in_array($Element, $reslist['fleet']) || in_array($Element, $reslist['defense'])) { + $elementLevel = $forLevel; + } elseif (isset($forLevel)) { + $elementLevel = $forLevel; + } elseif (isset($PLANET[$resource[$Element]])) { + $elementLevel = $PLANET[$resource[$Element]]; + } elseif (isset($USER[$resource[$Element]])) { + $elementLevel = $USER[$resource[$Element]]; + } else { + return array(); + } + + $price = array(); + foreach ($reslist['ressources'] as $resType) + { + if (!isset($pricelist[$Element]['cost'][$resType])) { + continue; + } + $ressourceAmount = $pricelist[$Element]['cost'][$resType]; + + if ($ressourceAmount == 0) { + continue; + } + + $price[$resType] = $ressourceAmount; + + if(isset($pricelist[$Element]['factor']) && $pricelist[$Element]['factor'] != 0 && $pricelist[$Element]['factor'] != 1) { + $price[$resType] *= pow($pricelist[$Element]['factor'], $elementLevel); + } + + if($forLevel && (in_array($Element, $reslist['fleet']) || in_array($Element, $reslist['defense']))) { + $price[$resType] *= $elementLevel; + } + + if($forDestroy === true) { + $price[$resType] /= 2; + } + } + + return $price; + } + + public static function isTechnologieAccessible($USER, $PLANET, $Element) + { + global $requeriments, $resource; + + if(!isset($requeriments[$Element])) + return true; + + foreach($requeriments[$Element] as $ReqElement => $EleLevel) + { + if ( + (isset($USER[$resource[$ReqElement]]) && $USER[$resource[$ReqElement]] < $EleLevel) || + (isset($PLANET[$resource[$ReqElement]]) && $PLANET[$resource[$ReqElement]] < $EleLevel) + ) { + return false; + } + } + return true; + } + + public static function getBuildingTime($USER, $PLANET, $Element, $elementPrice = NULL, $forDestroy = false, $forLevel = NULL) + { + global $resource, $reslist, $requeriments; + + $CONF = Config::getAll(NULL, $USER['universe']); + + $time = 0; + + if(!isset($elementPrice)) { + $elementPrice = self::getElementPrice($USER, $PLANET, $Element, $forDestroy, $forLevel); + } + + $elementCost = 0; + + if(isset($elementPrice[901])) { + $elementCost += $elementPrice[901]; + } + + if(isset($elementPrice[902])) { + $elementCost += $elementPrice[902]; + } + + if (in_array($Element, $reslist['build'])) { + $time = $elementCost / (Config::get('game_speed') * (1 + $PLANET[$resource[14]])) * pow(0.5, $PLANET[$resource[15]]) * (1 + $USER['factor']['BuildTime']); + } elseif (in_array($Element, $reslist['fleet'])) { + $time = $elementCost / (Config::get('game_speed') * (1 + $PLANET[$resource[21]])) * pow(0.5, $PLANET[$resource[15]]) * (1 + $USER['factor']['ShipTime']); + } elseif (in_array($Element, $reslist['defense'])) { + $time = $elementCost / (Config::get('game_speed') * (1 + $PLANET[$resource[21]])) * pow(0.5, $PLANET[$resource[15]]) * (1 + $USER['factor']['DefensiveTime']); + } elseif (in_array($Element, $reslist['tech'])) { + if(is_numeric($PLANET[$resource[31].'_inter'])) + { + $Level = $PLANET[$resource[31]]; + } else { + $Level = 0; + foreach($PLANET[$resource[31].'_inter'] as $Levels) + { + if(!isset($requeriments[$Element][31]) || $Levels >= $requeriments[$Element][31]) + $Level += $Levels; + } + } + + $time = $elementCost / (1000 * (1 + $Level)) / (Config::get('game_speed') / 2500) * pow(1 - Config::get('factor_university') / 100, $PLANET[$resource[6]]) * (1 + $USER['factor']['ResearchTime']); + } + + if($forDestroy) { + $time = floor($time * 1300); + } else { + $time = floor($time * 3600); + } + + return max($time, Config::get('min_build_time')); + } + + public static function isElementBuyable($USER, $PLANET, $Element, $elementPrice = NULL, $forDestroy = false, $forLevel = NULL) + { + $rest = self::getRestPrice($USER, $PLANET, $Element, $elementPrice, $forDestroy, $forLevel); + return count(array_filter($rest)) === 0; + } + + public static function getMaxConstructibleElements($USER, $PLANET, $Element, $elementPrice = NULL) + { + global $resource, $reslist; + + if(!isset($elementPrice)) { + $elementPrice = self::getElementPrice($USER, $PLANET, $Element); + } + + $maxElement = array(); + + foreach($elementPrice as $resourceID => $price) + { + if(isset($PLANET[$resource[$resourceID]])) + { + $maxElement[] = floor($PLANET[$resource[$resourceID]] / $price); + } + elseif(isset($USER[$resource[$resourceID]])) + { + $maxElement[] = floor($USER[$resource[$resourceID]] / $price); + } + else + { + throw new Exception("Unknown Ressource ".$resourceID." at element ".$Element."."); + } + } + + if(in_array($Element, $reslist['one'])) { + $maxElement[] = 1; + } + + return min($maxElement); + } + + public static function getMaxConstructibleRockets($USER, $PLANET, $Missiles = NULL) + { + global $resource, $CONF, $reslist; + + if(!isset($Missiles)) + { + $Missiles = array(); + + foreach($reslist['missile'] as $elementID) + { + $Missiles[$elementID] = $PLANET[$resource[$elementID]]; + } + } + + $BuildArray = !empty($PLANET['b_hangar_id']) ? unserialize($PLANET['b_hangar_id']) : array(); + $MaxMissiles = $PLANET[$resource[44]] * 10 * max(Config::get('silo_factor'), 1); + + foreach($BuildArray as $ElementArray) { + if(isset($Missiles[$ElementArray[0]])) + $Missiles[$ElementArray[0]] += $ElementArray[1]; + } + + $ActuMissiles = $Missiles[502] + (2 * $Missiles[503]); + $MissilesSpace = max(0, $MaxMissiles - $ActuMissiles); + + return array( + 502 => $MissilesSpace, + 503 => floor($MissilesSpace / 2), + ); + } + + public static function getAvalibleBonus($Element) + { + global $pricelist; + + $elementBonus = array(); + + foreach(self::$bonusList as $bonus) + { + $temp = (float) $pricelist[$Element]['bonus'][$bonus][0]; + if(empty($temp)) + { + continue; + } + + $elementBonus[$bonus] = $pricelist[$Element]['bonus'][$bonus]; + } + + return $elementBonus; + } +} \ No newline at end of file diff --git a/includes/classes/class.Cache.php b/includes/classes/class.Cache.php new file mode 100644 index 0000000..676a31f --- /dev/null +++ b/includes/classes/class.Cache.php @@ -0,0 +1,92 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + +include(ROOT_PATH.'includes/classes/cache/ressource/CacheFile.class.php'); + +class Cache { + private $cacheRessource; + private $cacheBuilder = array(); + private $cacheObj = array(); + + function __construct() { + $this->cacheRessource = new CacheFile(); + } + + function add($Key, $ClassName) { + $this->cacheBuilder[$Key] = $ClassName; + } + + function get($Key, $rebuild = true) { + if(!isset($this->cacheObj[$Key]) && !$this->load($Key)) + { + if($rebuild) + { + $this->buildCache($Key); + } + else + { + return array(); + } + } + return $this->cacheObj[$Key]; + } + + function flush($Key) { + if(!isset($this->cacheObj[$Key]) && !$this->load($Key)) + $this->buildCache($Key); + + $this->cacheRessource->flush($Key); + return $this->buildCache($Key); + } + + function load($Key) { + $cacheData = $this->cacheRessource->open($Key); + + if($cacheData === false) + return false; + + $cacheData = unserialize($cacheData); + if($cacheData === false) + return false; + + $this->cacheObj[$Key] = $cacheData; + return true; + } + + function buildCache($Key) { + $className = $this->cacheBuilder[$Key]; + include_once(ROOT_PATH.'includes/classes/cache/builder/'.$className.'.class.php'); + $cacheBuilder = new $className(); + $cacheData = $cacheBuilder->buildCache(); + $cacheData = (array) $cacheData; + $this->cacheObj[$Key] = $cacheData; + $cacheData = serialize($cacheData); + $this->cacheRessource->store($Key, $cacheData); + return true; + } +} \ No newline at end of file diff --git a/includes/classes/class.MySQLi.php b/includes/classes/class.Database.php similarity index 79% rename from includes/classes/class.MySQLi.php rename to includes/classes/class.Database.php index 1e7a13b..bc5be8a 100644 --- a/includes/classes/class.MySQLi.php +++ b/includes/classes/class.Database.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,16 +18,15 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ -class DB_mysqli extends mysqli +class Database extends mysqli { protected $con; protected $exception; @@ -43,10 +42,9 @@ class DB_mysqli extends mysqli * * @return void */ - public function __construct($exception = true) + public function __construct() { $this->con = $GLOBALS['database']; - $this->exception = $exception; if (!isset($this->con['port'])) { $this->con['port'] = 3306; @@ -56,24 +54,11 @@ public function __construct($exception = true) if(mysqli_connect_error()) { - if($this->exception == true) - throw new Exception("Connection to database failed: ".mysqli_connect_error()); - elseif(defined('INSTALL')) - return false; + throw new Exception("Connection to database failed: ".mysqli_connect_error()); } parent::set_charset("utf8"); - parent::query("SET SESSION sql_mode = '';"); - } - - /** - * Close current database connection. - * - * @return void - */ - public function __destruct() - { - if(!mysqli_connect_error()) - parent::close(); + #parent::query("SET SESSION sql_mode = '';"); + parent::query("SET SESSION sql_mode = 'STRICT_ALL_TABLES';"); } /** @@ -92,21 +77,15 @@ public function query($resource) } else { - if($this->exception == true) { - throw new Exception("SQL Error: ".$this->error."

Query Code: ".$resource); - } else { - return "SQL Error: ".$this->error; - } + throw new Exception("SQL Error: ".$this->error."

Query Code: ".$resource); } return false; } - /** - * Purpose a query on selected database. - * - * @param string The SQL query - * - * @return resource Results of the query - */ + + public function getFirstRow($resource) + { + return $this->uniquequery($resource); + } public function uniquequery($resource) { @@ -124,6 +103,10 @@ public function uniquequery($resource) * @return resource Results of the query */ + public function getFirstCell($resource) + { + return $this->countquery($resource); + } public function countquery($resource) { $result = $this->query($resource); @@ -162,6 +145,11 @@ public function fetchquery($resource, $encode = array()) * * @return array The data of a row */ + public function fetchArray($result) + { + return $result->fetch_array(MYSQLI_ASSOC); + } + public function fetch_array($result) { return $result->fetch_array(MYSQLI_ASSOC); @@ -186,10 +174,15 @@ public function fetch_num($result) * * @return integer The total row number */ - public function num_rows($query) + public function numRows($query) { return $query->num_rows; } + + public function affectedRows() + { + return $this->affected_rows; + } /** * Returns the total row numbers of a query. @@ -211,6 +204,11 @@ public function GetInsertID() * @return string Returns the escaped string, or false on error. */ + public function escape($string, $flag = false) + { + return $this->sql_escape($string, $flag); + } + public function sql_escape($string, $flag = false) { return ($flag === false) ? parent::escape_string($string): addcslashes(parent::escape_string($string), '%_'); @@ -273,11 +271,7 @@ public function multi_query($resource) if ($this->errno) { - if($this->exception == true) { - throw new Exception("SQL Error: ".$this->error."

Query Code: ".$resource); - } else { - return "SQL Error: ".$this->error; - } + throw new Exception("SQL Error: ".$this->error."

Query Code: ".$resource); } } @@ -286,5 +280,3 @@ public function get_sql() return $this->queryCount; } } - -?> \ No newline at end of file diff --git a/includes/classes/class.FleetFunctions.php b/includes/classes/class.FleetFunctions.php index 259affc..c6af3db 100644 --- a/includes/classes/class.FleetFunctions.php +++ b/includes/classes/class.FleetFunctions.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,17 +18,18 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ -abstract class FleetFunctions +class FleetFunctions { + static $allowedSpeed = array(10 => 100, 9 => 90, 8 => 80, 7 => 70, 6 => 60, 5 => 50, 4 => 40, 3 => 30, 2 => 20, 1 => 10); + private static function GetShipConsumption($Ship, $Player) { global $pricelist; @@ -38,58 +39,97 @@ private static function GetShipConsumption($Ship, $Player) private static function OnlyShipByID($Ships, $ShipID) { - foreach($Ships as $Ship => $Amount){ - if($ShipID != $Ship && $Amount != 0) return false; - } - - return true; + return isset($Ships[$ShipID]) && count($Ships) === 1; } private static function GetShipSpeed($Ship, $Player) { global $pricelist; - if($pricelist[$Ship]['tech'] == 1) // Combustion - return $pricelist[$Ship]['speed'] * (1 + (0.1 * $Player['combustion_tech'])); - elseif($pricelist[$Ship]['tech'] == 2) // Impulse - return $pricelist[$Ship]['speed'] * (1 + (0.2 * $Player['impulse_motor_tech'])); - elseif($pricelist[$Ship]['tech'] == 3) // Hyperspace - return $pricelist[$Ship]['speed'] * (1 + (0.3 * $Player['hyperspace_motor_tech'])); - elseif($pricelist[$Ship]['tech'] == 4) // Special: Small Transporter - return (($Player['impulse_motor_tech'] >= 5) ? $pricelist[$Ship]['speed2'] * (1 + (0.2 * $Player['impulse_motor_tech'])) : $pricelist[$Ship]['speed'] * (1 + (0.1 * $Player['combustion_tech']))); - elseif($pricelist[$Ship]['tech'] == 5) // Special: Battleship - return (($Player['hyperspace_motor_tech'] >= 8) ? $pricelist[$Ship]['speed2'] * (1 + (0.3 * $Player['hyperspace_motor_tech'])) : $pricelist[$Ship]['speed'] * (1 + (0.2 * $Player['impulse_motor_tech']))); - else - return 0; + + $techSpeed = $pricelist[$Ship]['tech']; + + if($techSpeed == 4) { + $techSpeed = $Player['impulse_motor_tech'] >= 5 ? 2 : 1; + } + if($techSpeed == 5) { + $techSpeed = $Player['hyperspace_motor_tech'] >= 8 ? 3 : 2; + } + + + switch($techSpeed) + { + case 1: + $speed = $pricelist[$Ship]['speed'] * (1 + (0.1 * $Player['combustion_tech'])); + break; + case 2: + $speed = $pricelist[$Ship]['speed'] * (1 + (0.2 * $Player['impulse_motor_tech'])); + break; + case 3: + $speed = $pricelist[$Ship]['speed'] * (1 + (0.3 * $Player['hyperspace_motor_tech'])); + break; + default: + $speed = 0; + break; + } + + return $speed; + } + + public static function getExpeditionLimit($USER) + { + return floor(sqrt($USER[$GLOBALS['resource'][124]])); } - public static function GetAvailableSpeeds() + public static function getDMMissionLimit($USER) { - return array(10 => 100, 9 => 90, 8 => 80, 7 => 70, 6 => 60, 5 => 50, 4 => 40, 3 => 30, 2 => 20, 1 => 10); + return Config::get('max_dm_missions'); } - public static function CheckUserSpeed($GenFleetSpeed) + public static function getMissileRange($Level) { - return (array_key_exists($GenFleetSpeed, self::GetAvailableSpeeds())) ? true : false; + return max(($Level * 5) - 1, 0); + } + + public static function CheckUserSpeed($speed) + { + return isset(self::$allowedSpeed[$speed]); } - public static function GetTargetDistance ($OrigGalaxy, $DestGalaxy, $OrigSystem, $DestSystem, $OrigPlanet, $DestPlanet) + public static function GetTargetDistance($start, $target) { - if (($OrigGalaxy - $DestGalaxy) != 0) - $distance = abs($OrigGalaxy - $DestGalaxy) * 20000; - elseif (($OrigSystem - $DestSystem) != 0) - $distance = abs($OrigSystem - $DestSystem) * 95 + 2700; - elseif (($OrigPlanet - $DestPlanet) != 0) - $distance = abs($OrigPlanet - $DestPlanet) * 5 + 1000; - else - $distance = 5; + if ($start[0] != $target[0]) + return abs($start[0] - $target[0]) * 20000; + + if ($start[1] != $target[1]) + return abs($start[1] - $target[1]) * 95 + 2700; + + if ($start[2] != $target[2]) + return abs($start[2] - $target[2]) * 5 + 1000; - return $distance; + return 5; } - public static function GetMissionDuration($SpeedFactor, $MaxFleetSpeed, $Distance, $GameSpeed, $CurrentUser) + public static function GetMissionDuration($SpeedFactor, $MaxFleetSpeed, $Distance, $GameSpeed, $USER) { - global $resource; - return max(((((3500 / ($SpeedFactor * 0.1)) * pow($Distance * 10 / $MaxFleetSpeed, 0.5) + 10)) / $GameSpeed), 5); + $SpeedFactor = (3500 / ($SpeedFactor * 0.1)); + $SpeedFactor *= pow($Distance * 10 / $MaxFleetSpeed, 0.5); + $SpeedFactor += 10; + $SpeedFactor /= $GameSpeed; + + if(isset($USER['factor']['FlyTime'])) + { + $SpeedFactor *= max(0, 1 + $USER['factor']['FlyTime']); + } + + return max($SpeedFactor, MIN_FLEET_TIME); + } + + public static function GetMIPDuration($startSystem, $targetSystem) + { + $Distance = abs($startSystem - $targetSystem); + $Duration = max(round((30 + 60 * $Distance) / self::GetGameSpeedFactor()), MIN_FLEET_TIME); + + return $Duration; } public static function GetGameSpeedFactor() @@ -97,10 +137,10 @@ public static function GetGameSpeedFactor() return $GLOBALS['CONF']['fleet_speed'] / 2500; } - public static function GetMaxFleetSlots($CurrentUser) + public static function GetMaxFleetSlots($USER) { - global $resource, $pricelist; - return (1 + $CurrentUser[$resource[108]]) + ($CurrentUser['rpg_commandant'] * $pricelist[611]['info']); + global $resource; + return 1 + $USER[$resource[108]] + $USER['factor']['FleetSlots']; } public static function GetFleetRoom($Fleet) @@ -116,8 +156,6 @@ public static function GetFleetRoom($Fleet) public static function GetFleetMaxSpeed ($Fleets, $Player) { - global $reslist, $pricelist; - $FleetArray = (!is_array($Fleets)) ? array($Fleets => 1) : $Fleets; $speedalls = array(); @@ -125,160 +163,121 @@ public static function GetFleetMaxSpeed ($Fleets, $Player) $speedalls[$Ship] = self::GetShipSpeed($Ship, $Player); } - return (is_array($Fleets)) ? min($speedalls) : $speedalls[$Ship]; + return min($speedalls); } public static function GetFleetConsumption($FleetArray, $MissionDuration, $MissionDistance, $FleetMaxSpeed, $Player, $GameSpeed) { $consumption = 0; - $basicConsumption = 0; foreach ($FleetArray as $Ship => $Count) { - $ShipSpeed = self::GetShipSpeed($Ship, $Player); - $ShipConsumption = self::GetShipConsumption($Ship, $Player); - $spd = 35000 / (round($MissionDuration, 0) * $GameSpeed - 10) * sqrt($MissionDistance * 10 / $ShipSpeed); - $basicConsumption = $ShipConsumption * $Count; - $consumption += $basicConsumption * $MissionDistance / 35000 * (($spd / 10) + 1) * (($spd / 10) + 1); + $ShipSpeed = self::GetShipSpeed($Ship, $Player); + $ShipConsumption = self::GetShipConsumption($Ship, $Player); + + $spd = 35000 / (round($MissionDuration, 0) * $GameSpeed - 10) * sqrt($MissionDistance * 10 / $ShipSpeed); + $basicConsumption = $ShipConsumption * $Count; + $consumption += $basicConsumption * $MissionDistance / 35000 * (($spd / 10) + 1) * (($spd / 10) + 1); } return (round($consumption) + 1); } - public static function GetFleetArray($FleetArray) - { - $FleetArray = unserialize(base64_decode(str_rot13($FleetArray))); - if(!is_array($FleetArray)) - self::GotoFleetPage(); - - return $FleetArray; - } - - public static function SetFleetArray($FleetArray) - { - return str_rot13(base64_encode(serialize($FleetArray))); - } - - public static function CleanFleetArray(&$FleetArray) - { - foreach($FleetArray as $ShipID => $Count) { - if ($Count <= 0) unset($FleetArray[$ShipID]); - } - } - - public static function GetFleetMissions($MisInfo) + public static function GetFleetMissions($USER, $MisInfo, $Planet) { - global $LNG, $resource, $CONF; - $Missions = self::GetAvailableMissions($MisInfo); - - if (!empty($Missions[15])) { - for($i = 1;$i <= $MisInfo['CurrentUser'][$resource[124]];$i++) { - $StayBlock[$i] = $i / $CONF['halt_speed']; + global $resource, $CONF; + $Missions = self::GetAvailableMissions($USER, $MisInfo, $Planet); + $stayBlock = array();; + if (in_array(15, $Missions)) { + for($i = 1;$i <= $USER[$resource[124]];$i++) { + $stayBlock[$i] = round($i / Config::get('halt_speed'), 2); } } - elseif(!empty($Missions[5])) - $StayBlock = array(1 => 1, 2 => 2, 4 => 4, 8 => 8, 12 => 12, 16 => 16, 32 => 32); - - - return array('MissionSelector' => $Missions, 'StayBlock' => $StayBlock); - } - public static function GetUserShotcut($CurrentUser) - { - $Shoutcut = unserialize($CurrentUser['fleet_shortcut']); - if (empty($Shoutcut)) - return array(); - - $ShortCutList = array(); - - foreach ($Shoutcut as $ShortCutRow) - { - $ShortCutList[] = array( - 'name' => $ShortCutRow[0], - 'galaxy' => $ShortCutRow[1], - 'system' => $ShortCutRow[2], - 'planet' => $ShortCutRow[3], - 'planet_type' => $ShortCutRow[4], - ); + elseif(in_array(11, $Missions)) + { + $stayBlock = array(1 => 1); + } + elseif(in_array(5, $Missions)) + { + $stayBlock = array(1 => 1, 2 => 2, 4 => 4, 8 => 8, 12 => 12, 16 => 16, 32 => 32); } - return $ShortCutList; + + return array('MissionSelector' => $Missions, 'StayBlock' => $stayBlock); } - public static function GetColonyList($Colony) + public static function GetACSDuration($FleetGroup) { - global $PLANET; - foreach($Colony as $CurPlanetID => $CurPlanet) - { - if ($PLANET['id'] == $CurPlanet['id']) - continue; - - $ColonyList[] = array( - 'name' => $CurPlanet['name'], - 'galaxy' => $CurPlanet['galaxy'], - 'system' => $CurPlanet['system'], - 'planet' => $CurPlanet['planet'], - 'planet_type' => $CurPlanet['planet_type'], - ); - } + if(empty($FleetGroup)) + return 0; - return $ColonyList; + $GetAKS = $GLOBALS['DATABASE']->getFirstCell("SELECT ankunft FROM ".AKS." WHERE id = ".$FleetGroup.";"); + + return !empty($GetAKS) ? $GetAKS - TIMESTAMP : 0; } - public static function IsAKS($CurrentUserID) + public static function setACSTime($timeDifference, $FleetGroup) { - global $db, $CONF; - - $GetAKS = $db->query("SELECT a.`id`, a.`name`, p.`galaxy`, p.`system`, p.`planet`, p.`planet_type` FROM ".AKS." a INNER JOIN ".PLANETS." p ON p.id = a.target WHERE a.`eingeladen` LIKE '%,".$CurrentUserID.",%' AND '".$CONF['max_fleets_per_acs']."' > (SELECT COUNT(*) FROM ".FLEETS." WHERE `fleet_group` = a.`id`);"); - $AKSList = array(); - while($row = $db->fetch_array($GetAKS)) - $AKSList[] = $row; - - $db->free_result($GetAKS); - - return $AKSList; + if(empty($FleetGroup)) + return false; + + $GLOBALS['DATABASE']->multi_query("UPDATE ".AKS." SET ankunft = ankunft + ".$timeDifference." WHERE id = ".$FleetGroup."; + UPDATE ".FLEETS.", ".FLEETS_EVENT." SET + fleet_start_time = fleet_start_time + ".$timeDifference.", + fleet_end_stay = fleet_end_stay + ".$timeDifference.", + fleet_end_time = fleet_end_time + ".$timeDifference.", + time = time + ".$timeDifference." + WHERE fleet_group = ".$FleetGroup." AND fleet_id = fleetID;"); + + return true; } - public static function GetCurrentFleets($CurrentUserID, $Mission = 0) + public static function GetCurrentFleets($USERID, $Mission = 0) { - global $db; - - $ActualFleets = $db->uniquequery("SELECT COUNT(*) as state FROM ".FLEETS." WHERE `fleet_owner` = '".$CurrentUserID."' AND ".(($Mission != 0)?"`fleet_mission` = '".$Mission."'":"`fleet_mission` != 10").";"); + + $ActualFleets = $GLOBALS['DATABASE']->getFirstRow("SELECT COUNT(*) as state FROM ".FLEETS." WHERE fleet_owner = '".$USERID."' AND ".(($Mission != 0)?"fleet_mission = '".$Mission."'":"fleet_mission != 10").";"); return $ActualFleets['state']; } - public static function SendFleetBack($CurrentUser, $FleetID) + public static function SendFleetBack($USER, $FleetID) { - global $db; + - $FleetRow = $db->uniquequery("SELECT `start_time`, `fleet_mission`, `fleet_group`, `fleet_owner`, `fleet_mess` FROM ".FLEETS." WHERE `fleet_id` = '". $FleetID ."';"); - if ($FleetRow['fleet_owner'] != $CurrentUser['id'] || $FleetRow['fleet_mess'] == 1) + $FleetRow = $GLOBALS['DATABASE']->getFirstRow("SELECT start_time, fleet_mission, fleet_group, fleet_owner, fleet_mess FROM ".FLEETS." WHERE fleet_id = '". $FleetID ."';"); + if ($FleetRow['fleet_owner'] != $USER['id'] || $FleetRow['fleet_mess'] == 1) return; - $where = 'fleet_id'; + $sqlWhere = 'fleet_id'; - if($FleetRow['fleet_mission'] == 1 && $FleetRow['fleet_group'] > 0) + if($FleetRow['fleet_mission'] == 1 && $FleetRow['fleet_group'] != 0) { - $Aks = $db->countquery("SELECT FIND_IN_SET('".$FleetRow['fleet_owner']."', `eingeladen`) FROM ".AKS." WHERE id = '". $FleetRow['fleet_group'] ."';"); + $acsResult = $GLOBALS['DATABASE']->getFirstCell("SELECT COUNT(*) FROM ".USERS_ACS." WHERE acsID = ".$FleetRow['fleet_group'].";"); - if($Aks != 0) + if($acsResult != 0) { - $db->query("DELETE FROM ".AKS." WHERE id ='". $FleetRow['fleet_group'] ."';"); + $GLOBALS['DATABASE']->multi_query("DELETE FROM ".AKS." WHERE id = ".$FleetRow['fleet_group']."; + DELETE FROM ".USERS_ACS." WHERE acsID = ".$FleetRow['fleet_group'].";"); + $FleetID = $FleetRow['fleet_group']; - $where = 'fleet_group'; + $sqlWhere = 'fleet_group'; } } - $db->multi_query("UPDATE ".FLEETS." SET - `fleet_group` = 0, - `fleet_end_stay` = ".TIMESTAMP.", - `fleet_end_time` = ".((TIMESTAMP - $FleetRow['start_time']) + TIMESTAMP).", - `fleet_mess` = 1 - WHERE `".$where."` = '".$FleetID."'; - UPDATE ".LOG_FLEETS." SET - `fleet_end_stay` = ".TIMESTAMP.", - `fleet_end_time` = ".((TIMESTAMP - $FleetRow['start_time']) + TIMESTAMP).", - `fleet_mess` = 1, - `fleet_state` = 2 - WHERE `".$where."` = '".$FleetID."';"); + $fleetEndTime = (TIMESTAMP - $FleetRow['start_time']) + TIMESTAMP; + + $GLOBALS['DATABASE']->multi_query("UPDATE ".FLEETS.", ".FLEETS_EVENT." SET + fleet_group = 0, + fleet_end_stay = ".TIMESTAMP.", + fleet_end_time = ".$fleetEndTime.", + fleet_mess = 1, + hasCanceled = 1, + time = ".$fleetEndTime." + WHERE ".$sqlWhere." = ".$FleetID." AND fleet_id = fleetID; + UPDATE ".LOG_FLEETS." SET + fleet_end_stay = ".TIMESTAMP.", + fleet_end_time = ".$fleetEndTime.", + fleet_mess = 1, + fleet_state = 2 + WHERE ".$sqlWhere." = ".$FleetID.";"); } public static function GetFleetShipInfo($FleetArray, $Player) @@ -290,188 +289,151 @@ public static function GetFleetShipInfo($FleetArray, $Player) return $FleetInfo; } - public static function GotoFleetPage() + public static function GotoFleetPage($Code = 0) { + global $LNG; $temp = debug_backtrace(); if($GLOBALS['CONF']['debug'] == 1) - FirePHP::getInstance(true)->log(str_replace($_SERVER["DOCUMENT_ROOT"],'.',$temp[0]['file'])." on ".$temp[0]['line']); - - redirectTo("game.php?page=fleet"); - } - - public static function GetAKSPage($CurrentUser, $CurrentPlanet, $fleetid) - { - global $resource, $pricelist, $reslist, $LNG, $db, $UNI; - - $addname = request_var('addtogroup', '', UTF8_SUPPORT); - $aks_invited_mr = request_var('aks_invited_mr', 0); - $name = request_var('name', '', UTF8_SUPPORT); - - - $query = $db->query("SELECT * FROM ".FLEETS." WHERE fleet_id = '" . $fleetid . "';"); - - if ($db->num_rows($query) != 1) - self::GotoFleetPage(); - - $daten = $db->fetch_array($query); - - if ($daten['fleet_start_time'] <= TIMESTAMP || $daten['fleet_end_time'] < TIMESTAMP || $daten['fleet_mess'] == 1) - self::GotoFleetPage(); - - if (empty($daten['fleet_group'])) - { - $rand = mt_rand(100000, 999999999); - $aks_code_mr = "AG".$rand; - $aks_invited_mr = $CurrentUser['id']; - - $db->query( - "INSERT INTO ".AKS." SET - `name` = '" . $aks_code_mr . "', - `ankunft` = '" . $daten['fleet_start_time'] . "', - `target` = '" . $daten['fleet_end_id'] . "', - `eingeladen` = ',".$aks_invited_mr.",'; - "); - - $db->query("UPDATE ".FLEETS." SET - `fleet_group` = ".$db->GetInsertID()." - WHERE - `fleet_id` = '" . $fleetid . "';"); - - $aks = array( - 'name' => $aks_code_mr, - 'eingeladen' => $CurrentUser['id'], - ); - } - else - { - $AKSRAW = $db->query("SELECT `id`, `eingeladen`, `name` FROM ".AKS." WHERE `id` = '" . $daten['fleet_group'] . "';"); - - if ($db->num_rows($AKSRAW) != 1) - self::GotoFleetPage(); - - $aks = $db->fetch_array($AKSRAW); - } - - if(!empty($name)) { - if(UTF8_SUPPORT && !ctype_alnum($name)) { - exit($LNG['fl_acs_newname_alphanum']); - } - $db->query("UPDATE ".AKS." SET `name` = '".$db->sql_escape($name)."' WHERE `id` = '".$daten['fleet_group']."';"); - exit; - } - - if(!empty($addname)) - { - $member_qry_mr = $db->uniquequery("SELECT `id` FROM ".USERS." WHERE `username` = '".$db->sql_escape($addname)."' AND `universe` = ".$UNI.";"); - $added_user_id_mr = $member_qry_mr['id']; - - foreach(explode(",", $aks['eingeladen']) as $a => $b) - { - if (!empty($b) && $added_user_id_mr == $b) - redirectTo("game.php?page=fleet&action=getakspage&fleetid=".$daten['fleet_id']); - } - - if(empty($added_user_id_mr)) - $add_user_message_mr = "".$LNG['fl_player']." ".$addname." ".$LNG['fl_dont_exist']; - else - { - $aks['eingeladen'] = $aks['eingeladen'].$added_user_id_mr.','; - $db->query("UPDATE ".AKS." SET `eingeladen` = '".$aks['eingeladen']."' WHERE `id` = '".$daten['fleet_group']."';"); - $add_user_message_mr = "".$LNG['fl_player']." ".$addname." ". $LNG['fl_add_to_attack']; - $invite_message = $LNG['fl_player'] . $CurrentUser['username'] . $LNG['fl_acs_invitation_message']; - SendSimpleMessage ($added_user_id_mr, $CurrentUser['id'], TIMESTAMP, 1, $CurrentUser['username'], $LNG['fl_acs_invitation_title'], $invite_message); - } - } - $members = explode(",", $aks['eingeladen']); - foreach($members as $a => $b) { - if (empty($b)) - continue; - - $member_qry_mr = $db->query("SELECT `username` FROM ".USERS." WHERE `id` ='".$b."' ;"); - while($row = $db->fetch_array($member_qry_mr)) - { - $pageDos .= ""; - } + exit(str_replace($_SERVER["DOCUMENT_ROOT"],'.',$temp[0]['file'])." on ".$temp[0]['line']. " | Code: ".$Code." | Error: ".(isset($LNG['fl_send_error'][$Code]) ? $LNG['fl_send_error'][$Code] : '')); } - - $AKSArray = array( - 'selector' => $pageDos, - 'fleetid' => $fleetid, - 'aks_invited_mr' => $aks['eingeladen'], - 'aks_code_mr' => $aks['name'], - 'add_user_message_mr' => $add_user_message_mr, - 'fl_acs_change' => $LNG['fl_acs_change'], - 'fl_acs_change_name' => $LNG['fl_acs_change_name'], - 'fl_invite_members' => $LNG['fl_invite_members'], - 'fl_members_invited' => $LNG['fl_members_invited'], - 'fl_modify_sac_name' => $LNG['fl_modify_sac_name'], - 'fl_sac_of_fleet' => $LNG['fl_sac_of_fleet'], - 'fl_continue' => $LNG['fl_continue'], - ); - return $AKSArray; + + HTTP::redirectTo('game.php?page=fleetTable&code='.$Code); } - public static function GetAvailableMissions($MissionInfo) - { - global $LNG, $db, $UNI, $CONF; - $GetInfoPlanet = $db->uniquequery("SELECT `id_owner`, `der_metal`, `der_crystal` FROM `".PLANETS."` WHERE `universe` = '".$UNI."' AND `galaxy` = ".$MissionInfo['galaxy']." AND `system` = ".$MissionInfo['system']." AND `planet` = ".$MissionInfo['planet']." AND `planet_type` = '1';"); - $YourPlanet = (isset($GetInfoPlanet['id_owner']) && $GetInfoPlanet['id_owner'] == $MissionInfo['CurrentUser']['id']) ? true : false; - $UsedPlanet = (isset($GetInfoPlanet['id_owner'])) ? true : false; - $missiontype = array(); + public static function GetAvailableMissions($USER, $MissionInfo, $GetInfoPlanet) + { + global $CONF; + $YourPlanet = (!empty($GetInfoPlanet['id_owner']) && $GetInfoPlanet['id_owner'] == $USER['id']) ? true : false; + $UsedPlanet = (!empty($GetInfoPlanet['id_owner'])) ? true : false; + $avalibleMissions = array(); - if ($MissionInfo['planet'] == ($CONF['max_planets'] + 1) && !CheckModule(30)) - $missiontype[15] = $LNG['type_mission'][15]; + if ($MissionInfo['planet'] == (Config::get('max_planets') + 1) && isModulAvalible(MODULE_MISSION_EXPEDITION)) + $avalibleMissions[] = 15; elseif ($MissionInfo['planettype'] == 2) { - if ((isset($MissionInfo['Ship'][209]) || isset($MissionInfo['Ship'][219])) && !CheckModule(32) && !($GetInfoPlanet['der_metal'] == 0 && $GetInfoPlanet['der_crystal'] == 0)) - $missiontype[8] = $LNG['type_mission'][8]; + if ((isset($MissionInfo['Ship'][209]) || isset($MissionInfo['Ship'][219])) && isModulAvalible(MODULE_MISSION_RECYCLE) && !($GetInfoPlanet['der_metal'] == 0 && $GetInfoPlanet['der_crystal'] == 0)) + $avalibleMissions[] = 8; } else { if (!$UsedPlanet) { - if (isset($MissionInfo['Ship'][208]) && $MissionInfo['planettype'] == 1 && !CheckModule(35)) - $missiontype[7] = $LNG['type_mission'][7]; + if (isset($MissionInfo['Ship'][208]) && $MissionInfo['planettype'] == 1 && isModulAvalible(MODULE_MISSION_COLONY)) + $avalibleMissions[] = 7; } else { - if(!CheckModule(34)) - $missiontype[3] = $LNG['type_mission'][3]; + if(isModulAvalible(MODULE_MISSION_TRANSPORT)) + $avalibleMissions[] = 3; - if (!$YourPlanet && self::OnlyShipByID($MissionInfo['Ship'], 210) && !CheckModule(24)) - $missiontype[6] = $LNG['type_mission'][6]; + if (!$YourPlanet && self::OnlyShipByID($MissionInfo['Ship'], 210) && isModulAvalible(MODULE_MISSION_SPY)) + $avalibleMissions[] = 6; if (!$YourPlanet) { - if(!CheckModule(1)) - $missiontype[1] = $LNG['type_mission'][1]; - if(!CheckModule(33)) - $missiontype[5] = $LNG['type_mission'][5];} + if(isModulAvalible(MODULE_MISSION_ATTACK)) + $avalibleMissions[] = 1; + if(isModulAvalible(MODULE_MISSION_HOLD)) + $avalibleMissions[] = 5;} - elseif(!CheckModule(36)) { - $missiontype[4] = $LNG['type_mission'][4];} + elseif(isModulAvalible(MODULE_MISSION_STATION)) { + $avalibleMissions[] = 4;} - if (!empty($MissionInfo['IsAKS']) && !$YourPlanet && !CheckModule(1)) - $missiontype[2] = $LNG['type_mission'][2]; + if (!empty($MissionInfo['IsAKS']) && !$YourPlanet && isModulAvalible(MODULE_MISSION_ATTACK) && isModulAvalible(MODULE_MISSION_ACS)) + $avalibleMissions[] = 2; - if (!$YourPlanet && $MissionInfo['planettype'] == 3 && isset($MissionInfo['Ship'][214]) && !CheckModule(29)) - $missiontype[9] = $LNG['type_mission'][9]; + if (!$YourPlanet && $MissionInfo['planettype'] == 3 && isset($MissionInfo['Ship'][214]) && isModulAvalible(MODULE_MISSION_DESTROY)) + $avalibleMissions[] = 9; - if ($YourPlanet && $MissionInfo['planettype'] == 3 && self::OnlyShipByID($MissionInfo['Ship'], 220) && !CheckModule(31)) - $missiontype[11] = $LNG['type_mission'][11]; + if ($YourPlanet && $MissionInfo['planettype'] == 3 && self::OnlyShipByID($MissionInfo['Ship'], 220) && isModulAvalible(MODULE_MISSION_DARKMATTER)) + $avalibleMissions[] = 11; } } - return $missiontype; + return $avalibleMissions; } public static function CheckBash($Target) { - global $db, $USER; + global $USER; if(!BASH_ON) return false; - $Count = $db->countquery("SELECT COUNT(*) FROM `uni1_log_fleets` - WHERE `fleet_owner` = ".$USER['id']." - AND `fleet_end_id` = ".$Target." - AND `fleet_state` != 2 - AND `fleet_start_time` > ".(TIMESTAMP - BASH_TIME)." - AND `fleet_mission` IN (1,2,9);"); + $Count = $GLOBALS['DATABASE']->getFirstCell("SELECT COUNT(*) FROM ".LOG_FLEETS." + WHERE fleet_owner = ".$USER['id']." + AND fleet_end_id = ".$Target." + AND fleet_state != 2 + AND fleet_start_time > ".(TIMESTAMP - BASH_TIME)." + AND fleet_mission IN (1,2,9);"); return $Count >= BASH_COUNT; } -} -?> \ No newline at end of file + + public static function sendFleet($fleetArray, $fleetMission, $fleetStartOwner, $fleetStartPlanetID, $fleetStartPlanetGalaxy, $fleetStartPlanetSystem, $fleetStartPlanetPlanet, $fleetStartPlanetType, $fleetTargetOwner, $fleetTargetPlanetID, $fleetTargetPlanetGalaxy, $fleetTargetPlanetSystem, $fleetTargetPlanetPlanet, $fleetTargetPlanetType, $fleetRessource, $fleetStartTime, $fleetStayTime, $fleetEndTime, $fleetGroup = 0, $missleTarget = 0) + { + global $resource, $UNI; + $fleetShipCount = array_sum($fleetArray); + $fleetData = array(); + $planetQuery = ""; + foreach($fleetArray as $ShipID => $ShipCount) { + $fleetData[] = $ShipID.','.floattostring($ShipCount); + $planetQuery[] = $resource[$ShipID]." = ".$resource[$ShipID]." - ".floattostring($ShipCount); + } + + $SQL = "LOCK TABLE ".LOG_FLEETS." WRITE, ".FLEETS_EVENT." WRITE, ".FLEETS." WRITE, ".PLANETS." WRITE; + UPDATE ".PLANETS." SET ".implode(", ", $planetQuery)." WHERE id = ".$fleetStartPlanetID."; + INSERT INTO ".FLEETS." SET + fleet_owner = ".$fleetStartOwner.", + fleet_target_owner = ".$fleetTargetOwner.", + fleet_mission = ".$fleetMission.", + fleet_amount = ".$fleetShipCount.", + fleet_array = '".implode(';',$fleetData)."', + fleet_universe = ".$UNI.", + fleet_start_time = ".$fleetStartTime.", + fleet_end_stay = ".$fleetStayTime.", + fleet_end_time = ".$fleetEndTime.", + fleet_start_id = ".$fleetStartPlanetID.", + fleet_start_galaxy = ".$fleetStartPlanetGalaxy.", + fleet_start_system = ".$fleetStartPlanetSystem.", + fleet_start_planet = ".$fleetStartPlanetPlanet.", + fleet_start_type = ".$fleetStartPlanetType.", + fleet_end_id = ".$fleetTargetPlanetID.", + fleet_end_galaxy = ".$fleetTargetPlanetGalaxy.", + fleet_end_system = ".$fleetTargetPlanetSystem.", + fleet_end_planet = ".$fleetTargetPlanetPlanet.", + fleet_end_type = ".$fleetTargetPlanetType.", + fleet_resource_metal = ".$fleetRessource[901].", + fleet_resource_crystal = ".$fleetRessource[902].", + fleet_resource_deuterium = ".$fleetRessource[903].", + fleet_group = ".$fleetGroup.", + fleet_target_obj = ".$missleTarget.", + start_time = ".TIMESTAMP."; + SET @fleetID = LAST_INSERT_ID(); + INSERT INTO ".FLEETS_EVENT." SET + fleetID = @fleetID, + `time` = ".$fleetStartTime."; + INSERT INTO ".LOG_FLEETS." SET + fleet_id = @fleetID, + fleet_owner = ".$fleetStartOwner.", + fleet_target_owner = ".$fleetTargetOwner.", + fleet_mission = ".$fleetMission.", + fleet_amount = ".$fleetShipCount.", + fleet_array = '".implode(',',$fleetData)."', + fleet_universe = ".$UNI.", + fleet_start_time = ".$fleetStartTime.", + fleet_end_stay = ".$fleetStayTime.", + fleet_end_time = ".$fleetEndTime.", + fleet_start_id = ".$fleetStartPlanetID.", + fleet_start_galaxy = ".$fleetStartPlanetGalaxy.", + fleet_start_system = ".$fleetStartPlanetSystem.", + fleet_start_planet = ".$fleetStartPlanetPlanet.", + fleet_start_type = ".$fleetStartPlanetType.", + fleet_end_id = ".$fleetTargetPlanetID.", + fleet_end_galaxy = ".$fleetTargetPlanetGalaxy.", + fleet_end_system = ".$fleetTargetPlanetSystem.", + fleet_end_planet = ".$fleetTargetPlanetPlanet.", + fleet_end_type = ".$fleetTargetPlanetType.", + fleet_resource_metal = ".$fleetRessource[901].", + fleet_resource_crystal = ".$fleetRessource[902].", + fleet_resource_deuterium = ".$fleetRessource[903].", + fleet_group = ".$fleetGroup.", + fleet_target_obj = ".$missleTarget.", + start_time = ".TIMESTAMP."; + UNLOCK TABLES;"; + + $GLOBALS['DATABASE']->multi_query($SQL); + } +} \ No newline at end of file diff --git a/includes/classes/class.FlyingFleetHandler.php b/includes/classes/class.FlyingFleetHandler.php index 7ce8659..e83d7a0 100644 --- a/includes/classes/class.FlyingFleetHandler.php +++ b/includes/classes/class.FlyingFleetHandler.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,75 +18,88 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ -if (!defined('INSIDE')) die(header("location:../../")); - class FlyingFleetHandler { - function __construct($fleetquery) - { - global $db; - $MissionsPattern = array( - 1 => 'MissionCaseAttack', - 2 => 'MissionCaseACS', - 3 => 'MissionCaseTransport', - 4 => 'MissionCaseStay', - 5 => 'MissionCaseStayAlly', - 6 => 'MissionCaseSpy', - 7 => 'MissionCaseColonisation', - 8 => 'MissionCaseRecycling', - 9 => 'MissionCaseDestruction', - 10 => 'MissionCaseMIP', - 11 => 'MissionCaseFoundDM', - 15 => 'MissionCaseExpedition', - ); + protected $token; + + public static $MissionsPattern = array( + 1 => 'MissionCaseAttack', + 2 => 'MissionCaseACS', + 3 => 'MissionCaseTransport', + 4 => 'MissionCaseStay', + 5 => 'MissionCaseStayAlly', + 6 => 'MissionCaseSpy', + 7 => 'MissionCaseColonisation', + 8 => 'MissionCaseRecycling', + 9 => 'MissionCaseDestruction', + 10 => 'MissionCaseMIP', + 11 => 'MissionCaseFoundDM', + 15 => 'MissionCaseExpedition', + ); + function setToken($token) + { + $this->token = $token; + } + + + function run() + { + require_once(ROOT_PATH.'includes/classes/class.MissionFunctions.php'); - while ($CurrentFleet = $db->fetch_array($fleetquery)) + + $fleetResult = $GLOBALS['DATABASE']->query("SELECT ".FLEETS.".* + FROM ".FLEETS_EVENT." + INNER JOIN ".FLEETS." ON fleetID = fleet_id + WHERE `lock` = '".$this->token."';"); + while ($fleetRow = $GLOBALS['DATABASE']->fetch_array($fleetResult)) { - if(!isset($MissionsPattern[$CurrentFleet['fleet_mission']])) { - $db->query("DELETE FROM ".FLEETS." WHERE `fleet_id` = '".$CurrentFleet['fleet_id']."';"); + if(!isset(self::$MissionsPattern[$fleetRow['fleet_mission']])) { + $GLOBALS['DATABASE']->query("DELETE FROM ".FLEETS." WHERE `fleet_id` = '".$fleetRow['fleet_id']."';"); continue; } - if(!$this->IfFleetBusy($CurrentFleet['fleet_id'])) continue; - getConfig($CurrentFleet['fleet_universe']); + #if(!$this->IfFleetBusy($fleetRow['fleet_id'])) continue; - require_once(ROOT_PATH.'includes/classes/missions/'.$MissionsPattern[$CurrentFleet['fleet_mission']].'.php'); - $Mission = new $MissionsPattern[$CurrentFleet['fleet_mission']]($CurrentFleet); + $missionName = self::$MissionsPattern[$fleetRow['fleet_mission']]; - if($CurrentFleet['fleet_mess'] == 0 && $CurrentFleet['fleet_start_time'] <= TIMESTAMP) - $Mission->TargetEvent(); - elseif($CurrentFleet['fleet_mess'] == 2 && $CurrentFleet['fleet_end_stay'] <= TIMESTAMP) - $Mission->EndStayEvent(); - elseif($CurrentFleet['fleet_mess'] == 1 && $CurrentFleet['fleet_end_time'] <= TIMESTAMP) - $Mission->ReturnEvent(); - - $Mission = NULL; - unset($Mission); + require_once(ROOT_PATH.'includes/classes/missions/'.$missionName.'.php'); + $Mission = new $missionName($fleetRow); + + switch($fleetRow['fleet_mess']) + { + case 0: + $Mission->TargetEvent(); + break; + case 1: + $Mission->ReturnEvent(); + break; + case 2: + $Mission->EndStayEvent(); + break; + } - $db->query("UPDATE ".FLEETS." SET `fleet_busy` = '0' WHERE `fleet_id` = '".$CurrentFleet['fleet_id']."';"); + #$GLOBALS['DATABASE']->query("UPDATE ".FLEETS." SET `fleet_busy` = '0' WHERE `fleet_id` = '".$fleetRow['fleet_id']."';"); } + $GLOBALS['DATABASE']->free_result($fleetResult); } function IfFleetBusy($FleetID) { - global $db; - $FleetInfo = $db->uniquequery("SELECT fleet_busy FROM ".FLEETS." WHERE `fleet_id` = '".$FleetID."';"); + $FleetInfo = $GLOBALS['DATABASE']->getFirstRow("SELECT fleet_busy FROM ".FLEETS." WHERE `fleet_id` = '".$FleetID."';"); if($FleetInfo['fleet_busy'] == 1) { return false; } else { - $db->query("UPDATE ".FLEETS." SET `fleet_busy` = '1' WHERE `fleet_id` = '".$FleetID."';"); + $GLOBALS['DATABASE']->query("UPDATE ".FLEETS." SET `fleet_busy` = '1' WHERE `fleet_id` = '".$FleetID."';"); return true; } } -} -?> \ No newline at end of file +} \ No newline at end of file diff --git a/includes/classes/class.FlyingFleetsTable.php b/includes/classes/class.FlyingFleetsTable.php index cccd3c3..3dab471 100644 --- a/includes/classes/class.FlyingFleetsTable.php +++ b/includes/classes/class.FlyingFleetsTable.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kr?pke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,165 +18,130 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kr?pke + * @copyright 2012 Jan Kr?pke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.5 (2011-07-31) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ -if(!defined('INSIDE')){ die(header("location:../../"));} - class FlyingFleetsTable { - private function BuildHostileFleetPlayerLink($FleetRow, $Names) - { - global $LNG, $USER; - - return $Names['own_username'].' (N)'; + protected $Mode = null; + protected $UserID = null; + protected $PlanetID = null; + protected $IsPhalanx = false; + protected $missions = false; + + function __construct() { + } - - // For ShowFlyingFleets.php in admin panel. - public function BuildFlyingFleetTable() - { - global $LNG, $db; - $Table = array(); + + function setUser($UserID) { + $this->UserID = $UserID; + } + + function setPlanet($PlanetID) { + $this->PlanetID = $PlanetID; + } + + function setPhalanxMode() { + $this->IsPhalanx = true; + } + + function setMissions($missions) { + $this->missions = $missions; + } + + function getFleets($acsID = false) { + global $USER, $resource; - $FlyingFleets = $db->query("SELECT * FROM ".FLEETS." WHERE `fleeT_universe` = '".$_SESSION['adminuni']."' ORDER BY `fleet_end_time` ASC;"); - - while ($CurrentFleet = $db->fetch_array($FlyingFleets)) - { - $FleetOwner = $db->uniquequery("SELECT `username` FROM ".USERS." WHERE `id` = '". $CurrentFleet['fleet_owner'] ."';"); - $TargetOwner = $db->uniquequery("SELECT `username` FROM ".USERS." WHERE `id` = '". $CurrentFleet['fleet_target_owner'] ."';"); - - $Bloc['Id'] = $CurrentFleet['fleet_id']; - $Bloc['Mission'] = $this->CreateFleetPopupedMissionLink ( $CurrentFleet, $LNG['type_mission'][ $CurrentFleet['fleet_mission'] ], '' ); - $Bloc['Mission'] .= "
". (($CurrentFleet['fleet_mess'] == 1) ? "R" : "A" ); - $Bloc['Fleet'] = $this->CreateFleetPopupedFleetLink ( $CurrentFleet, $LNG['tech'][200], '' ); - $Bloc['St_Owner'] = "[". $CurrentFleet['fleet_owner'] ."]
". $FleetOwner['username']; - $Bloc['St_Posit'] = "[".$CurrentFleet['fleet_start_galaxy'] .":". $CurrentFleet['fleet_start_system'] .":". $CurrentFleet['fleet_start_planet'] ."]
". ( ($CurrentFleet['fleet_start_type'] == 1) ? "[P]": (($CurrentFleet['fleet_start_type'] == 2) ? "D" : "L" )) .""; - $Bloc['St_Time'] = tz_date($CurrentFleet['fleet_start_time']); - if (is_array($TargetOwner)) - $Bloc['En_Owner'] = "[". $CurrentFleet['fleet_target_owner'] ."]
". $TargetOwner['username']; - else - $Bloc['En_Owner'] = ""; - - $Bloc['En_Posit'] = "[".$CurrentFleet['fleet_end_galaxy'] .":". $CurrentFleet['fleet_end_system'] .":". $CurrentFleet['fleet_end_planet'] ."]
". ( ($CurrentFleet['fleet_end_type'] == 1) ? "[P]": (($CurrentFleet['fleet_end_type'] == 2) ? "D" : "L" )) .""; - - if ($CurrentFleet['fleet_mission'] == 5) - { - if ($CurrentFleet['fleet_mess'] == 2) - $Bloc['Wa_Time'] = tz_date($CurrentFleet['fleet_end_stay']); - elseif ($CurrentFleet['fleet_mess'] == 1) - $Bloc['Wa_Time'] = $LNG['cff_back']; - else - $Bloc['Wa_Time'] = $LNG['cff_to_destination']; - } - else - { - $Bloc['Wa_Time'] = ""; - } - - $Bloc['En_Time'] = tz_date($CurrentFleet['fleet_end_time']); - $Bloc['lock'] = $CurrentFleet['fleet_busy'] == 0 ? "".$LNG['ff_lock']."" : "".$LNG['ff_unlock'].""; - - $Table[] = $Bloc; + if($this->IsPhalanx) { + $SQLWhere = "(fleet_start_id = ".$this->PlanetID." AND fleet_mission != 4) OR (fleet_end_id = ".$this->PlanetID." AND fleet_mess IN (0, 2))"; + } elseif(!empty($acsID)) { + $SQLWhere = "fleet_group = ".$acsID; + } elseif($this->missions) { + $SQLWhere = "(fleet_owner = ". $this->UserID ." OR fleet_target_owner = ". $this->UserID .") AND fleet_mission IN (". $this->missions .")"; + } else { + $SQLWhere = "fleet_owner = ".$this->UserID." OR (fleet_target_owner = ".$this->UserID." AND fleet_mission != 8)"; } - return $Table; + return $GLOBALS['DATABASE']->query("SELECT DISTINCT fleet.*, ownuser.username as own_username, targetuser.username as target_username, ownplanet.name as own_planetname, targetplanet.name as target_planetname + FROM ".FLEETS." fleet + LEFT JOIN ".USERS." ownuser ON (ownuser.id = fleet.fleet_owner) + LEFT JOIN ".USERS." targetuser ON (targetuser.id = fleet.fleet_target_owner) + LEFT JOIN ".PLANETS." ownplanet ON (ownplanet.id = fleet.fleet_start_id) + LEFT JOIN ".PLANETS." targetplanet ON (targetplanet.id = fleet.fleet_end_id) + WHERE ".$SQLWhere.";"); } - - private function CreateFleetPopupedMissionLink($FleetRow, $Texte, $FleetType) + + function renderTable() { - global $LNG; - - $FleetTotalC = $FleetRow['fleet_resource_metal'] + $FleetRow['fleet_resource_crystal'] + $FleetRow['fleet_resource_deuterium'] + $FleetRow['fleet_resource_darkmatter']; - if ($FleetTotalC <> 0) + $fleetResult = $this->getFleets(); + $ACSDone = array(); + $FleetData = array(); + + while($fleetRow = $GLOBALS['DATABASE']->fetch_array($fleetResult)) { - $FRessource = ''; - $FRessource .= ''; - $FRessource .= ''; - $FRessource .= ''; - if($FleetRow['fleet_resource_darkmatter'] > 0) - $FRessource .= ''; - $FRessource .= '
'.$LNG['Metal'].''. pretty_number($FleetRow['fleet_resource_metal']).'
'.$LNG['Crystal'].''. pretty_number($FleetRow['fleet_resource_crystal']).'
'.$LNG['Deuterium'].''. pretty_number($FleetRow['fleet_resource_deuterium']).'
'.$LNG['Darkmatter'].''. pretty_number($FleetRow['fleet_resource_darkmatter']).'
'; - $MissionPopup = ''.$Texte.''; + if ($fleetRow['fleet_mess'] == 0 && $fleetRow['fleet_start_time'] > TIMESTAMP && ($fleetRow['fleet_group'] == 0 || !isset($ACSDone[$fleetRow['fleet_group']]))) + { + $ACSDone[$fleetRow['fleet_group']] = true; + $FleetData[$fleetRow['fleet_start_time'].$fleetRow['fleet_id']] = $this->BuildFleetEventTable($fleetRow, 0); + } + + if ($fleetRow['fleet_mission'] == 10 || ($fleetRow['fleet_mission'] == 4 && $fleetRow['fleet_mess'] == 0)) + continue; + + if ($fleetRow['fleet_end_stay'] != $fleetRow['fleet_start_time'] && $fleetRow['fleet_end_stay'] > TIMESTAMP && ($this->IsPhalanx && $fleetRow['fleet_end_id'] == $this->PlanetID)) + $FleetData[$fleetRow['fleet_end_stay'].$fleetRow['fleet_id']] = $this->BuildFleetEventTable($fleetRow, 2); + + if ($fleetRow['fleet_owner'] != $this->UserID) + continue; + + if ($fleetRow['fleet_end_time'] > TIMESTAMP) + $FleetData[$fleetRow['fleet_end_time'].$fleetRow['fleet_id']] = $this->BuildFleetEventTable($fleetRow, 1); } - else - $MissionPopup = $Texte; - - return $MissionPopup; + + ksort($FleetData); + $GLOBALS['DATABASE']->free_result($fleetResult); + return $FleetData; } - - private function CreateFleetPopupedFleetLink($FleetRow, $Texte, $FleetType) + + function BuildFleetEventTable($fleetRow, $FleetState) { - global $LNG; - - $FleetRec = explode(';', $FleetRow['fleet_array']); - $FleetPopup = ''. $Texte .''; - - return $FleetPopup; - } - - public function GetNames($FleetRow) - { - global $db; - return $db->uniquequery("SELECT ou.username as own_username, tu.username as target_username, op.name as own_planetname, tp.name as target_planetname - FROM ".USERS." as ou - LEFT JOIN ".USERS." tu ON tu.id = '".$FleetRow['fleet_target_owner']."' - LEFT JOIN ".PLANETS." op ON op.`id` = '".$FleetRow['fleet_start_id']."' - LEFT JOIN ".PLANETS." tp ON tp.`id` = '".$FleetRow['fleet_end_id']."' - WHERE ou.id = '".$FleetRow['fleet_owner']."';"); + + return array( + 'text' => $EventString, + 'returntime' => $Time, + 'resttime' => $Rest + ); } - - public function GetEventString($FleetRow, $Status, $Owner, $Label, $Record) + + public function getEventData($fleetRow, $Status) { global $LNG; + $Owner = $fleetRow['fleet_owner'] == $this->UserID; $FleetStyle = array ( 1 => 'attack', 2 => 'federation', @@ -188,103 +153,158 @@ public function GetEventString($FleetRow, $Status, $Owner, $Label, $Record) 8 => 'harvest', 9 => 'destroy', 10 => 'missile', + 11 => 'transport', 15 => 'transport', ); + $GoodMissions = array(3, 5); - $MissionType = $FleetRow['fleet_mission']; + $MissionType = $fleetRow['fleet_mission']; - $Names = $this->GetNames($FleetRow); $FleetPrefix = ($Owner == true) ? 'own' : ''; $FleetType = $FleetPrefix.$FleetStyle[$MissionType]; - $FleetContent = $this->CreateFleetPopupedFleetLink($FleetRow, (($MissionType == 1 || $MissionType == 2) && $FleetRow['fleet_owner'] != $_SESSION['id'] && $Status == 0 && $Owner == true) ? $LNG['cff_acs_fleet'] : $LNG['ov_fleet'], $FleetPrefix.$FleetStyle[$MissionType]); - $FleetCapacity = $this->CreateFleetPopupedMissionLink($FleetRow, $LNG['type_mission'][$MissionType], $FleetPrefix.$FleetStyle[$MissionType]); + $FleetName = (!$Owner && ($MissionType == 1 || $MissionType == 2) && $Status == FLEET_OUTWARD && $fleetRow['fleet_target_owner'] != $this->UserID) ? $LNG['cff_acs_fleet'] : $LNG['ov_fleet']; + $FleetContent = $this->CreateFleetPopupedFleetLink($fleetRow, $FleetName, $FleetPrefix.$FleetStyle[$MissionType]); + $FleetCapacity = $this->CreateFleetPopupedMissionLink($fleetRow, $LNG['type_mission'][$MissionType], $FleetPrefix.$FleetStyle[$MissionType]); $FleetStatus = array(0 => 'flight', 1 => 'return' , 2 => 'holding'); - $StartType = $LNG['type_planet'][$FleetRow['fleet_start_type']]; - $TargetType = $LNG['type_planet'][$FleetRow['fleet_end_type']]; + $StartType = $LNG['type_planet'][$fleetRow['fleet_start_type']]; + $TargetType = $LNG['type_planet'][$fleetRow['fleet_end_type']]; if ($MissionType == 8) { - if ($Status == 0) - $EventString = sprintf($LNG['cff_mission_own_recy_0'], $FleetContent, $StartType, $Names['own_planetname'], GetStartAdressLink($FleetRow, $FleetType), GetTargetAdressLink($FleetRow, $FleetType), $FleetCapacity); + if ($Status == FLEET_OUTWARD) + $EventString = sprintf($LNG['cff_mission_own_recy_0'], $FleetContent, $StartType, $fleetRow['own_planetname'], GetStartAdressLink($fleetRow, $FleetType), GetTargetAdressLink($fleetRow, $FleetType), $FleetCapacity); else - $EventString = sprintf($LNG['cff_mission_own_recy_1'], $FleetContent, GetTargetAdressLink($FleetRow, $FleetType), $StartType, $Names['own_planetname'], GetStartAdressLink($FleetRow, $FleetType), $FleetCapacity); + $EventString = sprintf($LNG['cff_mission_own_recy_1'], $FleetContent, GetTargetAdressLink($fleetRow, $FleetType), $StartType, $fleetRow['own_planetname'], GetStartAdressLink($fleetRow, $FleetType), $FleetCapacity); } elseif ($MissionType == 10) { if ($Owner) - $EventString = sprintf($LNG['cff_mission_own_mip'], $FleetRow['fleet_amount'], $StartType, $Names['own_planetname'], GetStartAdressLink($FleetRow, $FleetType), $TargetType, $Names['target_planetname'], GetTargetAdressLink($FleetRow, $FleetType)); + $EventString = sprintf($LNG['cff_mission_own_mip'], $fleetRow['fleet_amount'], $StartType, $fleetRow['own_planetname'], GetStartAdressLink($fleetRow, $FleetType), $TargetType, $fleetRow['target_planetname'], GetTargetAdressLink($fleetRow, $FleetType)); else - $EventString = sprintf($LNG['cff_mission_target_mip'], $FleetRow['fleet_amount'], $this->BuildHostileFleetPlayerLink($FleetRow, $Names), $StartType, $Names['own_planetname'], GetStartAdressLink($FleetRow, $FleetType), $TargetType, $Names['target_planetname'], GetTargetAdressLink($FleetRow, $FleetType)); + $EventString = sprintf($LNG['cff_mission_target_mip'], $fleetRow['fleet_amount'], $this->BuildHostileFleetPlayerLink($fleetRow, $fleetRow), $StartType, $fleetRow['own_planetname'], GetStartAdressLink($fleetRow, $FleetType), $TargetType, $fleetRow['target_planetname'], GetTargetAdressLink($fleetRow, $FleetType)); } elseif ($MissionType == 11 || $MissionType == 15) { - if ($Status == 0) - $EventString = sprintf($LNG['cff_mission_own_expo_0'], $FleetContent, $StartType, $Names['own_planetname'], GetStartAdressLink($FleetRow, $FleetType), GetTargetAdressLink($FleetRow, $FleetType), $FleetCapacity); - elseif ($Status == 2) - $EventString = sprintf($LNG['cff_mission_own_expo_2'], $FleetContent, $StartType, $Names['own_planetname'], GetStartAdressLink($FleetRow, $FleetType), GetTargetAdressLink($FleetRow, $FleetType), $FleetCapacity); + if ($Status == FLEET_OUTWARD) + $EventString = sprintf($LNG['cff_mission_own_expo_0'], $FleetContent, $StartType, $fleetRow['own_planetname'], GetStartAdressLink($fleetRow, $FleetType), GetTargetAdressLink($fleetRow, $FleetType), $FleetCapacity); + elseif ($Status == FLEET_HOLD) + $EventString = sprintf($LNG['cff_mission_own_expo_2'], $FleetContent, $StartType, $fleetRow['own_planetname'], GetStartAdressLink($fleetRow, $FleetType), GetTargetAdressLink($fleetRow, $FleetType), $FleetCapacity); else - $EventString = sprintf($LNG['cff_mission_own_expo_1'], $FleetContent, GetTargetAdressLink($FleetRow, $FleetType), $StartType, $Names['own_planetname'], GetStartAdressLink($FleetRow, $FleetType), $FleetCapacity); + $EventString = sprintf($LNG['cff_mission_own_expo_1'], $FleetContent, GetTargetAdressLink($fleetRow, $FleetType), $StartType, $fleetRow['own_planetname'], GetStartAdressLink($fleetRow, $FleetType), $FleetCapacity); } else { if ($Owner == true) { - if ($Status == 0) { - if (($MissionType == 1 || $MissionType == 2) && $Status == 0 && $FleetRow['fleet_owner'] != $_SESSION['id']) + if ($Status == FLEET_OUTWARD) { + if (!$Owner && ($MissionType == 1 || $MissionType == 2)) $Message = $LNG['cff_mission_acs'] ; else $Message = $LNG['cff_mission_own_0']; - $EventString = sprintf($Message, $FleetContent, $StartType, $Names['own_planetname'], GetStartAdressLink($FleetRow, $FleetType), $TargetType, $Names['target_planetname'], GetTargetAdressLink($FleetRow, $FleetType), $FleetCapacity); - } elseif($Status == 1) - $EventString = sprintf($LNG['cff_mission_own_1'], $FleetContent, $TargetType, $Names['target_planetname'], GetTargetAdressLink($FleetRow, $FleetType), $StartType, $Names['own_planetname'], GetStartAdressLink($FleetRow, $FleetType), $FleetCapacity); + $EventString = sprintf($Message, $FleetContent, $StartType, $fleetRow['own_planetname'], GetStartAdressLink($fleetRow, $FleetType), $TargetType, $fleetRow['target_planetname'], GetTargetAdressLink($fleetRow, $FleetType), $FleetCapacity); + } elseif($Status == FLEET_RETURN) + $EventString = sprintf($LNG['cff_mission_own_1'], $FleetContent, $TargetType, $fleetRow['target_planetname'], GetTargetAdressLink($fleetRow, $FleetType), $StartType, $fleetRow['own_planetname'], GetStartAdressLink($fleetRow, $FleetType), $FleetCapacity); else - $EventString = sprintf($LNG['cff_mission_own_2'], $FleetContent, $StartType, $Names['own_planetname'], GetStartAdressLink($FleetRow, $FleetType), $TargetType, $Names['target_planetname'], GetTargetAdressLink($FleetRow, $FleetType), $FleetCapacity); + $EventString = sprintf($LNG['cff_mission_own_2'], $FleetContent, $StartType, $fleetRow['own_planetname'], GetStartAdressLink($fleetRow, $FleetType), $TargetType, $fleetRow['target_planetname'], GetTargetAdressLink($fleetRow, $FleetType), $FleetCapacity); } else { - if ($Status == 2) + if ($Status == FLEET_HOLD) $Message = $LNG['cff_mission_target_stay']; elseif(in_array($MissionType, $GoodMissions)) $Message = $LNG['cff_mission_target_good']; else $Message = $LNG['cff_mission_target_bad']; - $EventString = sprintf($Message, $FleetContent, $this->BuildHostileFleetPlayerLink($FleetRow, $Names), $StartType, $Names['own_planetname'], GetStartAdressLink($FleetRow, $FleetType), $TargetType, $Names['target_planetname'], GetTargetAdressLink($FleetRow, $FleetType), $FleetCapacity); + $EventString = sprintf($Message, $FleetContent, $this->BuildHostileFleetPlayerLink($fleetRow, $fleetRow), $StartType, $fleetRow['own_planetname'], GetStartAdressLink($fleetRow, $FleetType), $TargetType, $fleetRow['target_planetname'], GetTargetAdressLink($fleetRow, $FleetType), $FleetCapacity); } } $EventString = ''.$EventString.''; - if ($Status == 0) - $Time = $FleetRow['fleet_start_time']; - elseif ($Status == 1) - $Time = $FleetRow['fleet_end_time']; - elseif ($Status == 2) - $Time = $FleetRow['fleet_end_stay']; + if ($Status == FLEET_OUTWARD) + $Time = $fleetRow['fleet_start_time']; + elseif ($Status == FLEET_RETURN) + $Time = $fleetRow['fleet_end_time']; + elseif ($Status == FLEET_HOLD) + $Time = $fleetRow['fleet_end_stay']; + $Rest = $Time - TIMESTAMP; - $time = $time; return array($Rest, $EventString, $Time); } + + private function BuildHostileFleetPlayerLink($fleetRow, $fleetRow) + { + global $LNG; + return $fleetRow['own_username'].' '.$LNG['PM'].''; + } - //For overview and phalanx - public function BuildFleetEventTable($FleetRow, $Status, $Owner, $Label, $Record, $isAKS = false) + private function CreateFleetPopupedMissionLink($fleetRow, $Texte, $FleetType) { - global $LNG, $db; - - if ($isAKS == true && $Status == 0 && ($FleetRow['fleet_mission'] == 1 || $FleetRow['fleet_mission'] == 2) && $FleetRow['fleet_group'] != 0) + global $LNG; + $FleetTotalC = $fleetRow['fleet_resource_metal'] + $fleetRow['fleet_resource_crystal'] + $fleetRow['fleet_resource_deuterium'] + $fleetRow['fleet_resource_darkmatter']; + if ($FleetTotalC != 0) { - $AKSFleets = $db->query("SELECT * FROM ".FLEETS." WHERE `fleet_group` = '".$FleetRow['fleet_group']."' ORDER BY `fleet_id` ASC;"); - $EventString = ''; - while($AKSRow = $db->fetch_array($AKSFleets)) - { - $Return = $this->GetEventString($AKSRow, $Status, $Owner, $Label, $Record); - - $Rest = $Return[0]; - $EventString .= $Return[1].'

'; - $Time = $Return[2]; - } - $db->free_result($AKSFleets); + $textForBlind = $LNG['tech'][900].': '; + $textForBlind .= floattostring($fleetRow['fleet_resource_metal']).' '.$LNG['tech'][901]; + $textForBlind .= '; '.floattostring($fleetRow['fleet_resource_crystal']).' '.$LNG['tech'][902]; + $textForBlind .= '; '.floattostring($fleetRow['fleet_resource_deuterium']).' '.$LNG['tech'][903]; + if($fleetRow['fleet_resource_darkmatter'] > 0) + $textForBlind .= '; '.floattostring($fleetRow['fleet_resource_darkmatter']).' '.$LNG['tech'][921]; + + $FRessource = ''; + $FRessource .= ''; + $FRessource .= ''; + $FRessource .= ''; + if($fleetRow['fleet_resource_darkmatter'] > 0) + $FRessource .= ''; + $FRessource .= '
'.$LNG['tech'][901].''. pretty_number($fleetRow['fleet_resource_metal']).'
'.$LNG['tech'][902].''. pretty_number($fleetRow['fleet_resource_crystal']).'
'.$LNG['tech'][903].''. pretty_number($fleetRow['fleet_resource_deuterium']).'
'.$LNG['tech'][921].''. pretty_number($fleetRow['fleet_resource_darkmatter']).'
'; + + $MissionPopup = ''.$Texte.' ('.$textForBlind.')'; } else + $MissionPopup = $Texte; + + return $MissionPopup; + } + + private function CreateFleetPopupedFleetLink($fleetRow, $Text, $FleetType) + { + global $LNG, $USER, $resource; + $SpyTech = $USER[$resource[106]]; + $Owner = $fleetRow['fleet_owner'] == $this->UserID; + $FleetRec = explode(';', $fleetRow['fleet_array']); + $FleetPopup = ''. $Text .' ('.$textForBlind.')'; + + return $FleetPopup; + } } ?> \ No newline at end of file diff --git a/includes/classes/class.GalaxyRows.php b/includes/classes/class.GalaxyRows.php index 4c2fe41..73b33ab 100644 --- a/includes/classes/class.GalaxyRows.php +++ b/includes/classes/class.GalaxyRows.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,196 +18,185 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ +require_once(ROOT_PATH . 'includes/classes/class.FleetFunctions.php'); +require_once(ROOT_PATH . 'includes/pages/game/class.ShowPhalanxPage.php'); + class GalaxyRows { - public function allowMissiles($GalaxyRowPlanet) - { - global $USER, $PLANET, $resource; - if ($PLANET[$resource[503]] == 0 || $GalaxyRowPlanet['galaxy'] != $PLANET['galaxy'] || $PLANET['planet_type'] != 1 || CheckModule(40)) - return false; - - $Range = $this->GetMissileRange($USER[$resource[117]]); - $SystemLimitMin = max($PLANET['system'] - $Range, 1); - $SystemLimitMax = $PLANET['system'] + $Range; - return $GalaxyRowPlanet['system'] <= $SystemLimitMax && $GalaxyRowPlanet['system'] >= $SystemLimitMin ? true : false; - } - public function allowPhalanx($GalaxyRowPlanet) - { - global $USER, $PLANET, $resource; - if (CheckModule(19) || $PLANET[$resource[42]] == 0) - return false; + private $Galaxy; + private $System; + private $galaxyData; + private $galaxyRow; + + const PLANET_DESTROYED = false; + + function __construct() { - $PhRange = $this->GetPhalanxRange($PLANET[$resource[42]]); - $SystemLimitMin = max(1, $PLANET['system'] - $PhRange); - $SystemLimitMax = $PLANET['system'] + $PhRange; - return $GalaxyRowPlanet['system'] <= $SystemLimitMax && $GalaxyRowPlanet['system'] >= $SystemLimitMin; - } - public function GetMissileRange($Level) - { - return max(($Level * 5) - 1, 0); + public function setGalaxy($Galaxy) { + $this->Galaxy = $Galaxy; + return $this; } - - public function GetPhalanxRange($PhalanxLevel) - { - return ($PhalanxLevel == 1) ? 1 : pow($PhalanxLevel, 2) - 1; + + public function setSystem($System) { + $this->System = $System; + return $this; } - - public function GalaxyRowActions($GalaxyRowPlanet) + + public function getGalaxyData() { - global $USER, $PLANET, $resource, $LNG; + global $UNI, $USER; - $MissileBtn = $this->allowMissiles($GalaxyRowPlanet); + $galaxyResult = $GLOBALS['DATABASE']->query("SELECT SQL_BIG_RESULT DISTINCT + p.galaxy, p.system, p.planet, p.id, p.id_owner, p.name, p.image, p.last_update, p.diameter, p.temp_min, p.destruyed, p.der_metal, p.der_crystal, p.id_luna, + u.id as userid, u.ally_id, u.username, u.onlinetime, u.urlaubs_modus, u.banaday, + m.id as m_id, m.diameter as m_diameter, m.name as m_name, m.temp_min as m_temp_min, m.last_update as m_last_update, + s.total_points, s.total_rank, + a.id as allyid, a.ally_tag, a.ally_web, a.ally_members, a.ally_name, + allys.total_rank as ally_rank, + COUNT(buddy.id) as buddy, + d.level as diploLevel + FROM ".PLANETS." p + LEFT JOIN ".USERS." u ON p.id_owner = u.id + LEFT JOIN ".PLANETS." m ON m.id = p.id_luna + LEFT JOIN ".STATPOINTS." s ON s.id_owner = u.id AND s.stat_type = '1' + LEFT JOIN ".ALLIANCE." a ON a.id = u.ally_id + LEFT JOIN ".DIPLO." as d ON (d.owner_1 = ".$USER['ally_id']." AND d.owner_2 = a.id) OR (d.owner_1 = a.id AND d.owner_2 = ".$USER['ally_id'].") AND d.accept = 1 + LEFT JOIN ".STATPOINTS." allys ON allys.stat_type = '2' AND allys.id_owner = a.id + LEFT JOIN ".BUDDY." buddy ON (buddy.sender = ".$USER['id']." AND buddy.owner = u.id ) OR (buddy.sender = u.id AND buddy.owner = ".$USER['id'].") + WHERE p.universe = ".$UNI." AND p.galaxy = ".$this->Galaxy." AND p.system = ".$this->System." AND p.planet_type = '1' + GROUP BY p.id;"); - $Result = array( - 'esp' => (!CheckModule(24) && $USER["settings_esp"] == 1) ? true : false, - 'message' => (!CheckModule(16) && $USER["settings_wri"] == 1) ? true : false, - 'buddy' => (!CheckModule(6) && $USER["settings_bud"] == 1) ? true : false, - 'missle' => ($USER["settings_mis"] == 1 && $MissileBtn == true) ? true : false, - ); + while($this->galaxyRow = $GLOBALS['DATABASE']->fetch_array($galaxyResult)) + { + if ($this->galaxyRow['destruyed'] != 0) + { + $this->galaxyData[$this->galaxyRow['planet']] = self::PLANET_DESTROYED; + continue; + } + + $this->galaxyData[$this->galaxyRow['planet']] = array(); + + $this->isOwnPlanet(); + $this->setLastActivity(); + + $this->getAllowedMissions(); + + $this->getPlayerData(); + $this->getPlanetData(); + $this->getAllianceData(); + $this->getDebrisData(); + $this->getMoonData(); + $this->getActionButtons(); + } - return $Result; + $GLOBALS['DATABASE']->free_result($galaxyResult); + + return $this->galaxyData; } - - public function GalaxyRowAlly($GalaxyRowPlanet) + + protected function setLastActivity() { - global $USER, $LNG, $db; - - $Result = array( - 'id' => $GalaxyRowPlanet['allyid'], - 'name' => htmlspecialchars($GalaxyRowPlanet['ally_name'],ENT_QUOTES,"UTF-8"), - 'member' => sprintf(($GalaxyRowPlanet['ally_members'] == 1)?$LNG['gl_member_add']:$LNG['gl_member'], $GalaxyRowPlanet['ally_members']), - 'web' => $GalaxyRowPlanet['ally_web'], - 'inally' => $USER['ally_id'] == $GalaxyRowPlanet['ally_id'], - 'tag' => $GalaxyRowPlanet['ally_tag'], - 'rank' => $GalaxyRowPlanet['ally_rank'], - ); + global $LNG; + + $lastActivity = floor((TIMESTAMP - max($this->galaxyRow['last_update'], $this->galaxyRow['m_last_update'])) / 60); - return $Result; + if ($lastActivity < 4) { + $this->galaxyData[$this->galaxyRow['planet']]['lastActivity'] = $LNG['gl_activity']; + } elseif($lastActivity < 15) { + $this->galaxyData[$this->galaxyRow['planet']]['lastActivity'] = sprintf($LNG['gl_activity_inactive'], $lastActivity); + } else { + $this->galaxyData[$this->galaxyRow['planet']]['lastActivity'] = ''; + } } - - public function GalaxyRowDebris($GalaxyRowPlanet) + + protected function isOwnPlanet() { - global $USER, $PLANET, $LNG, $pricelist, $resource; - - $GRecNeeded = min(ceil(($GalaxyRowPlanet['der_metal'] + $GalaxyRowPlanet['der_crystal']) / $pricelist[219]['capacity']), $PLANET[$resource[219]]); - $RecNeeded = min(ceil(max($GalaxyRowPlanet['der_metal'] + $GalaxyRowPlanet['der_crystal'] - ($GRecNeeded * $pricelist[219]['capacity']), 0) / $pricelist[209]['capacity']), $PLANET[$resource[209]]); - - $Result = array( - 'metal' => pretty_number($GalaxyRowPlanet["der_metal"]), - 'crystal' => pretty_number($GalaxyRowPlanet["der_crystal"]), - 'RecSended' => $RecNeeded, - 'GRecSended' => $GRecNeeded, - 'recycle' => (!CheckModule(32)) ? $LNG['type_mission'][8]:false, - ); - - return $Result; + global $USER; + + $this->galaxyData[$this->galaxyRow['planet']]['ownPlanet'] = $this->galaxyRow['id_owner'] == $USER['id']; } - - public function GalaxyRowMoon($GalaxyRowPlanet, $IsOwn) + + protected function getAllowedMissions() { - global $USER, $PLANET, $LNG, $resource; + global $PLANET, $resource; - $Result = array( - 'name' => htmlspecialchars($GalaxyRowPlanet['m_name'], ENT_QUOTES, "UTF-8"), - 'temp_min' => number_format($GalaxyRowPlanet['m_temp_min'], 0, '', '.'), - 'diameter' => number_format($GalaxyRowPlanet['m_diameter'], 0, '', '.'), - 'attack' => (!CheckModule(1) && !$IsOwn) ? $LNG['type_mission'][1]:false, - 'transport' => (!CheckModule(34)) ? $LNG['type_mission'][3]:false, - 'stay' => (!CheckModule(36) && $IsOwn) ? $LNG['type_mission'][4]:false, - 'stayally' => (!CheckModule(33) && !$IsOwn) ? $LNG['type_mission'][5]:false, - 'spionage' => (!CheckModule(24) && !$IsOwn) ? $LNG['type_mission'][6]:false, - 'destroy' => (!CheckModule(29) && !$IsOwn && $PLANET[$resource[214]] > 0) ? $LNG['type_mission'][9]:false, + $this->galaxyData[$this->galaxyRow['planet']]['missions'] = array( + 1 => !$this->galaxyData[$this->galaxyRow['planet']]['ownPlanet'] && isModulAvalible(MODULE_MISSION_ATTACK), + 3 => isModulAvalible(MODULE_MISSION_TRANSPORT), + 4 => $this->galaxyData[$this->galaxyRow['planet']]['ownPlanet'] && isModulAvalible(MODULE_MISSION_STATION), + 5 => !$this->galaxyData[$this->galaxyRow['planet']]['ownPlanet'] && isModulAvalible(MODULE_MISSION_HOLD), + 6 => !$this->galaxyData[$this->galaxyRow['planet']]['ownPlanet'] && isModulAvalible(MODULE_MISSION_SPY), + 8 => isModulAvalible(MODULE_MISSION_RECYCLE), + 9 => !$this->galaxyData[$this->galaxyRow['planet']]['ownPlanet'] && $PLANET[$resource[214]] > 0 && isModulAvalible(MODULE_MISSION_DESTROY), + 10 => !$this->galaxyData[$this->galaxyRow['planet']]['ownPlanet'] && $PLANET[$resource[503]] > 0 && isModulAvalible(MODULE_MISSION_ATTACK) && isModulAvalible(MODULE_MISSILEATTACK) && $this->inMissileRange(), ); - - return $Result; } - public function GalaxyRowPlanet($GalaxyRowPlanet, $IsOwn) + protected function inMissileRange() { - global $resource, $USER, $PLANET, $CONF, $LNG; + global $USER, $PLANET, $resource; - if(!$IsOwn && $GalaxyRowPlanet['galaxy'] == $PLANET['galaxy']) - { - $PhalanxTypeLink = $this->allowPhalanx($GalaxyRowPlanet); - $MissileBtn = $this->allowMissiles($GalaxyRowPlanet); - } else { - $PhalanxTypeLink = false; - $MissileBtn = false; - } - $Result = array( - 'id' => $GalaxyRowPlanet['id'], - 'name' => htmlspecialchars($GalaxyRowPlanet['name'],ENT_QUOTES,"UTF-8"), - 'image' => $GalaxyRowPlanet['image'], - 'phalax' => !$PhalanxTypeLink ? false : $LNG['gl_phalanx'], - 'missile' => !$MissileBtn ? false : $LNG['gl_missile_attack'], - 'transport' => (CheckModule(34)) ? false : $LNG['type_mission'][3], - 'spionage' => ($IsOwn || CheckModule(24)) ? false : $LNG['type_mission'][6], - 'attack' => ($IsOwn || CheckModule(1)) ? false : $LNG['type_mission'][1], - 'stay' => (!$IsOwn || CheckModule(36) && $IsOwn) ? false : $LNG['type_mission'][4], - 'stayally' => ($IsOwn || CheckModule(33)) ? false : $LNG['type_mission'][5], - ); - return $Result; + if ($this->galaxyRow['galaxy'] != $PLANET['galaxy']) + return false; + + $Range = FleetFunctions::GetMissileRange($USER[$resource[117]]); + $systemMin = $PLANET['system'] - $Range; + $systemMax = $PLANET['system'] + $Range; + + return $this->galaxyRow['system'] >= $systemMin && $this->galaxyRow['system'] <= $systemMax; } - - public function GalaxyRowPlanetName($GalaxyRowPlanet) + + protected function getActionButtons() { - global $USER, $LNG; - - $Onlinetime = floor((TIMESTAMP - $GalaxyRowPlanet['last_update']) / 60); - - if ($Onlinetime < 4) - $Activity = $LNG['gl_activity']; - elseif($Onlinetime < 15) - $Activity = sprintf($LNG['gl_activity_inactive'], $Onlinetime); - else - $Activity = ''; - - $Result = array( - 'name' => htmlspecialchars($GalaxyRowPlanet['name'], ENT_QUOTES, "UTF-8"), - 'activity' => $Activity, - ); - return $Result; + global $USER; + if($this->galaxyData[$this->galaxyRow['planet']]['ownPlanet']) { + $this->galaxyData[$this->galaxyRow['planet']]['action'] = false; + } else { + $this->galaxyData[$this->galaxyRow['planet']]['action'] = array( + 'esp' => $USER['settings_esp'] == 1 && $this->galaxyData[$this->galaxyRow['planet']]['missions'][6], + 'message' => $USER['settings_wri'] == 1 && isModulAvalible(MODULE_MESSAGES), + 'buddy' => $USER['settings_bud'] == 1 && isModulAvalible(MODULE_BUDDYLIST) && $this->galaxyRow['buddy'] == 0, + 'missle' => $USER['settings_mis'] == 1 && $this->galaxyData[$this->galaxyRow['planet']]['missions'][10], + ); + } } - public function GalaxyRowUser($GalaxyRowPlanet, $IsOwn) + protected function getPlayerData() { - global $USER, $LNG, $db; + global $USER, $LNG; - $CurrentPoints = $USER['total_points']; - $RowUserPoints = $GalaxyRowPlanet['total_points']; - $IsNoobProtec = CheckNoobProtec($USER, $GalaxyRowPlanet, $GalaxyRowPlanet); + $IsNoobProtec = CheckNoobProtec($USER, $this->galaxyRow, $this->galaxyRow); $Class = array(); - if ($GalaxyRowPlanet['banaday'] > TIMESTAMP && $GalaxyRowPlanet['urlaubs_modus'] == 1) + if ($this->galaxyRow['banaday'] > TIMESTAMP && $this->galaxyRow['urlaubs_modus'] == 1) { $Class = array('vacation', 'banned'); } - elseif ($GalaxyRowPlanet['banaday'] > TIMESTAMP) + elseif ($this->galaxyRow['banaday'] > TIMESTAMP) { $Class = array('banned'); } - elseif ($GalaxyRowPlanet['urlaubs_modus'] == 1) + elseif ($this->galaxyRow['urlaubs_modus'] == 1) { $Class = array('vacation'); } - elseif ($GalaxyRowPlanet['onlinetime'] < (TIMESTAMP-60 * 60 * 24 * 7) && $GalaxyRowPlanet['onlinetime'] > (TIMESTAMP-60 * 60 * 24 * 28)) + elseif ($this->galaxyRow['onlinetime'] < TIMESTAMP - INACTIVE_LONG) { - $Class = array('inactive'); + $Class = array('inactive', 'longinactive'); } - elseif ($GalaxyRowPlanet['onlinetime'] < (TIMESTAMP-60 * 60 * 24 * 28)) + elseif ($this->galaxyRow['onlinetime'] < TIMESTAMP - INACTIVE) { - $Class = array('inactive', 'longinactive'); + $Class = array('inactive'); } elseif ($IsNoobProtec['NoobPlayer']) { @@ -217,18 +206,90 @@ public function GalaxyRowUser($GalaxyRowPlanet, $IsOwn) { $Class = array('strong'); } - - $Result = array( - 'id' => $GalaxyRowPlanet['userid'], - 'username' => htmlspecialchars($GalaxyRowPlanet['username'],ENT_QUOTES,"UTF-8"), - 'rank' => $GalaxyRowPlanet['total_rank'], - 'points' => pretty_number($GalaxyRowPlanet['total_points']), - 'playerrank' => sprintf($LNG['gl_in_the_rank'], htmlspecialchars($GalaxyRowPlanet['username'],ENT_QUOTES,"UTF-8"), $GalaxyRowPlanet['total_rank']), + + $this->galaxyData[$this->galaxyRow['planet']]['user'] = array( + 'id' => $this->galaxyRow['userid'], + 'username' => htmlspecialchars($this->galaxyRow['username'], ENT_QUOTES, "UTF-8"), + 'rank' => $this->galaxyRow['total_rank'], + 'points' => pretty_number($this->galaxyRow['total_points']), + 'playerrank' => isModulAvalible(25)?sprintf($LNG['gl_in_the_rank'], htmlspecialchars($this->galaxyRow['username'],ENT_QUOTES,"UTF-8"), $this->galaxyRow['total_rank']):htmlspecialchars($this->galaxyRow['username'],ENT_QUOTES,"UTF-8"), 'class' => $Class, - 'isown' => ($GalaxyRowPlanet['userid'] != $USER['id']) ? true : false, + 'isBuddy' => $this->galaxyRow['buddy'] == 0, + ); + } + + protected function getAllianceData() + { + global $USER, $LNG; + if(empty($this->galaxyRow['allyid'])) { + $this->galaxyData[$this->galaxyRow['planet']]['alliance'] = false; + } else { + $Class = array(); + switch($this->galaxyRow['diploLevel']) + { + case 1: + case 2: + $Class = array('member'); + break; + case 4: + $Class = array('friend'); + break; + case 5: + $Class = array('enemy'); + break; + } + + if($USER['ally_id'] == $this->galaxyRow['ally_id']) + { + $Class = array('member'); + } + + $this->galaxyData[$this->galaxyRow['planet']]['alliance'] = array( + 'id' => $this->galaxyRow['allyid'], + 'name' => htmlspecialchars($this->galaxyRow['ally_name'], ENT_QUOTES, "UTF-8"), + 'member' => sprintf(($this->galaxyRow['ally_members'] == 1) ? $LNG['gl_member_add'] : $LNG['gl_member'], $this->galaxyRow['ally_members']), + 'web' => $this->galaxyRow['ally_web'], + 'tag' => $this->galaxyRow['ally_tag'], + 'rank' => $this->galaxyRow['ally_rank'], + 'class' => $Class, + ); + } + } + + protected function getDebrisData() + { + $total = $this->galaxyRow['der_metal'] + $this->galaxyRow['der_crystal']; + if($total == 0) { + $this->galaxyData[$this->galaxyRow['planet']]['debris'] = false; + } else { + $this->galaxyData[$this->galaxyRow['planet']]['debris'] = array( + 'metal' => $this->galaxyRow['der_metal'], + 'crystal' => $this->galaxyRow['der_crystal'], + ); + } + } + + protected function getMoonData() + { + if(!isset($this->galaxyRow['m_id'])) { + $this->galaxyData[$this->galaxyRow['planet']]['moon'] = false; + } else { + $this->galaxyData[$this->galaxyRow['planet']]['moon'] = array( + 'id' => $this->galaxyRow['m_id'], + 'name' => htmlspecialchars($this->galaxyRow['m_name'], ENT_QUOTES, "UTF-8"), + 'temp_min' => $this->galaxyRow['m_temp_min'], + 'diameter' => $this->galaxyRow['m_diameter'], + ); + } + } + + protected function getPlanetData() + { + $this->galaxyData[$this->galaxyRow['planet']]['planet'] = array( + 'id' => $this->galaxyRow['id'], + 'name' => htmlspecialchars($this->galaxyRow['name'], ENT_QUOTES, "UTF-8"), + 'image' => $this->galaxyRow['image'], + 'phalanx' => isModulAvalible(MODULE_PHALANX) && ShowPhalanxPage::allowPhalanx($this->galaxyRow['galaxy'], $this->galaxyRow['system']), ); - - return $Result; } -} -?> \ No newline at end of file +} \ No newline at end of file diff --git a/includes/classes/class.Lang.php b/includes/classes/class.Lang.php deleted file mode 100644 index ad02250..0000000 --- a/includes/classes/class.Lang.php +++ /dev/null @@ -1,179 +0,0 @@ -. - * - * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) - * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) - * @info $Id$ - * @link http://code.google.com/p/2moons/ - */ - -class Language -{ - public $Default = ''; - public $User = ''; - public static $Languages; - - function __construct() - { - $this->Default = DEFAULT_LANG; - $this->User = DEFAULT_LANG; - } - - static function getAllowedLangs($OnlyKey = true) - { - if(!isset(self::$Languages)) - { - if(file_exists(ROOT_PATH.'cache/cache.languages.php')) - { - self::$Languages = unserialize(file_get_contents(ROOT_PATH.'cache/cache.languages.php')); - } else { - $Langs = array_diff(scandir(ROOT_PATH.'language/'), array('..', '.', '.svn', '.htaccess', 'index.htm')); - $Languages = array(); - foreach($Langs as $Lang) { - if(!file_exists(ROOT_PATH.'language/'.$Lang.'/LANG.cfg')) - continue; - - require(ROOT_PATH.'language/'.$Lang.'/LANG.cfg'); - $Languages[$Lang] = $Language['name']; - } - if(is_writable(ROOT_PATH.'cache')) - file_put_contents(ROOT_PATH.'cache/cache.languages.php', serialize($Languages)); - self::$Languages = $Languages; - } - } - return $OnlyKey ? array_keys(self::$Languages) : self::$Languages; - } - - function setDefault($LANG) - { - if(!empty($LANG) && in_array($LANG, self::getAllowedLangs())) { - $this->Default = $LANG; - $this->User = $LANG; - } - } - - function setUser($LANG) - { - if(!empty($LANG) && in_array($LANG, self::getAllowedLangs())) - $this->User = $LANG; - } - - function getUser() - { - return $this->User; - } - - function GetLangFromBrowser($strict_mode = true) - { - if(defined('LOGIN') && isset($_COOKIE['lang']) && in_array($_COOKIE['lang'], self::getAllowedLangs())) { - $this->setUser($_COOKIE['lang']); - return $this->User; - } - - if(isset($_REQUEST['lang']) && in_array($_REQUEST['lang'], self::getAllowedLangs())) { - $this->setUser($_REQUEST['lang']); - return $this->User; - } - - if (empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { - return $this->Default; - } - - $accepted_languages = preg_split('/,\s*/', $_SERVER['HTTP_ACCEPT_LANGUAGE']); - - $current_lang = $this->Default; - $current_q = 0; - - foreach ($accepted_languages as $accepted_language) { - $res = preg_match ('/^([a-z]{1,8}(?:-[a-z]{1,8})*)'.'(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i', $accepted_language, $matches); - - if (!$res) { - continue; - } - - $LANG_code = explode ('-', $matches[1]); - $LANG_quality = isset($matches[2]) ? (float)$matches[2] : 1.0; - - while (count ($LANG_code)) { - if (in_array (strtolower (join ('-', $LANG_code)), self::getAllowedLangs())) { - if ($LANG_quality > $current_q) { - $current_lang = strtolower (join ('-', $LANG_code)); - $current_q = $LANG_quality; - break; - } - } - if ($strict_mode) { - break; - } - array_pop ($LANG_code); - } - } - $this->setUser($current_lang); - return $this->User; - } - - function includeLang($Files) - { - global $LNG; - while (list(,$File) = each($Files)){ - require(ROOT_PATH . "language/de/".$File.'.php'); - require(ROOT_PATH . "language/".$this->User."/".$File.'.php'); - } - } - - function getExtra($File) - { - if(file_exists(ROOT_PATH."language/".$this->User."/extra/".$File.".txt")) - return file_get_contents(ROOT_PATH."language/".$this->User."/extra/".$File.".txt"); - - return ""; - } - - function getMail($File) - { - if(file_exists(ROOT_PATH."language/".$this->User."/email/".$File.".txt")) - return file_get_contents(ROOT_PATH."language/".$this->User."/email/".$File.".txt"); - - return ""; - } - - function GetUserLang($ID, $Files = array()) - { - global $db, $CONF; - $LANGUAGE = is_numeric($ID) && !in_array($ID, self::getAllowedLangs()) ? $db->countquery("SELECT `lang` FROM ".USERS." WHERE `id` = '".$ID."';") : $ID; - - if(!in_array($LANGUAGE, self::getAllowedLangs())) - $LANGUAGE = $this->Default; - - if(empty($Files)) - $Files = array('L18N', 'FLEET'); - - while (list(,$File) = each($Files)){ - require(ROOT_PATH . "language/".$LANGUAGE."/".$File.'.php'); - } - - return $LNG; - } -} - -?> \ No newline at end of file diff --git a/includes/classes/class.Log.php b/includes/classes/class.Log.php index 6378a24..19997e6 100644 --- a/includes/classes/class.Log.php +++ b/includes/classes/class.Log.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,12 +18,11 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License * @version 1.3 (2011-01-21) - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class Log @@ -47,13 +46,9 @@ public function __isset($key){ return isset($this->data[$key]); } function save() { - global $db; $data = serialize(array($this->data['old'], $this->data['new'])); - $uni = ($this->data['universe'] == NULL ? $this->data['uni'] : $this->data['universe']); - //var_dump($this->data['target']); - $db->query("INSERT INTO ".LOG." (`id`,`mode`,`admin`,`target`,`time`,`data`,`universe`) VALUES - (NULL , ".$this->data['mode'].", ".$this->data['admin'].", '".$this->data['target']."', ".TIMESTAMP." , '".$data."', '".$uni."');"); + $uni = (empty($this->data['universe']) ? $this->data['uni'] : $this->data['universe']); + $GLOBALS['DATABASE']->query("INSERT INTO ".LOG." (`id`,`mode`,`admin`,`target`,`time`,`data`,`universe`) VALUES + (NULL , ".$GLOBALS['DATABASE']->sql_escape($this->data['mode']).", ".$GLOBALS['DATABASE']->sql_escape($this->data['admin']).", '".$GLOBALS['DATABASE']->sql_escape($this->data['target'])."', ".TIMESTAMP." , '".$GLOBALS['DATABASE']->sql_escape($data)."', '".$uni."');"); } } - -?> \ No newline at end of file diff --git a/includes/classes/class.MissionFunctions.php b/includes/classes/class.MissionFunctions.php index 5d0234c..02c5623 100644 --- a/includes/classes/class.MissionFunctions.php +++ b/includes/classes/class.MissionFunctions.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,47 +18,65 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ -if (!defined('INSIDE')) exit; - class MissionFunctions { - function __construct() - { - $this->kill = 0; - } - + public $kill = 0; + public $_fleet = array(); + public $_upd = array(); + function UpdateFleet($Option, $Value) { $this->_fleet[$Option] = $Value; $this->_upd[$Option] = $Value; } + + function setState($Value) + { + $this->_fleet['fleet_mess'] = $Value; + $this->_upd['fleet_mess'] = $Value; + + switch($Value) + { + case FLEET_OUTWARD: + $this->eventTime = $this->_fleet['fleet_start_time']; + break; + case FLEET_RETURN: + $this->eventTime = $this->_fleet['fleet_end_time']; + break; + case FLEET_HOLD: + $this->eventTime = $this->_fleet['fleet_end_stay']; + break; + } + } function SaveFleet() { - global $db; if($this->kill == 1) return; + $Qry = array(); + foreach($this->_upd as $Opt => $Val) { $Qry[] = "`".$Opt."` = '".$Val."'"; } - $db->query("UPDATE ".FLEETS." SET ".implode(', ',$Qry)." WHERE `fleet_id` = '".$this->_fleet['fleet_id']."';"); + if(!empty($Qry)) { + $GLOBALS['DATABASE']->multi_query("UPDATE ".FLEETS." SET ".implode(', ',$Qry)." WHERE `fleet_id` = ".$this->_fleet['fleet_id'].";UPDATE ".FLEETS_EVENT." SET time = ".$this->eventTime." WHERE `fleetID` = ".$this->_fleet['fleet_id'].";"); + } } function RestoreFleet($Start = true) { - global $resource, $db; + global $resource; $FleetRecord = explode(';', $this->_fleet['fleet_array']); $QryUpdFleet = ''; @@ -81,20 +99,19 @@ function RestoreFleet($Start = true) $Qry .= "WHERE "; $Qry .= "p.`id` = '".($Start == true ? $this->_fleet['fleet_start_id'] : $this->_fleet['fleet_end_id'])."' "; $Qry .= "AND u.id = p.id_owner;"; - $Qry .= "DELETE FROM ".FLEETS." WHERE `fleet_id` = ".$this->_fleet['fleet_id'].";"; - $db->multi_query($Qry); + $GLOBALS['DATABASE']->multi_query($Qry); + $this->KillFleet(); } function StoreGoodsToPlanet($Start = false) { - global $db; - $Qry = "UPDATE ".PLANETS." SET "; + $Qry = "UPDATE ".PLANETS." SET "; $Qry .= "`metal` = `metal` + ".$this->_fleet['fleet_resource_metal'].", "; $Qry .= "`crystal` = `crystal` + ".$this->_fleet['fleet_resource_crystal'].", "; $Qry .= "`deuterium` = `deuterium` + ".$this->_fleet['fleet_resource_deuterium']." "; $Qry .= "WHERE "; $Qry .= "`id` = ".($Start == true ? $this->_fleet['fleet_start_id'] : $this->_fleet['fleet_end_id']).";"; - $db->query($Qry); + $GLOBALS['DATABASE']->query($Qry); $this->UpdateFleet('fleet_resource_metal', '0'); $this->UpdateFleet('fleet_resource_crystal', '0'); @@ -103,9 +120,21 @@ function StoreGoodsToPlanet($Start = false) function KillFleet() { - global $db; $this->kill = 1; - $db->query("DELETE FROM ".FLEETS." WHERE `fleet_id` = ".$this->_fleet['fleet_id'].";"); - } -} -?> \ No newline at end of file + $GLOBALS['DATABASE']->multi_query("DELETE FROM ".FLEETS." WHERE `fleet_id` = ".$this->_fleet['fleet_id']."; + DELETE FROM ".FLEETS_EVENT." WHERE `fleetID` = ".$this->_fleet['fleet_id'].";"); + } + + function getLanguage($language = NULL, $userID = NULL) + { + if(is_null($language) && !is_null($userID)) + { + $language = $GLOBALS['DATABASE']->getFirstCell("SELECT lang FROM ".USERS." WHERE id = ".$this->_fleet['fleet_owner'].";"); + } + + $LNG = new Language($language); + $LNG->includeData(array('L18N', 'FLEET', 'TECH', 'CUSTOM')); + + return $LNG; + } +} \ No newline at end of file diff --git a/includes/classes/class.PlanetRessUpdate.php b/includes/classes/class.PlanetRessUpdate.php index 271f8cf..1c85185 100644 --- a/includes/classes/class.PlanetRessUpdate.php +++ b/includes/classes/class.PlanetRessUpdate.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,13 +18,12 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class ResourceUpdate @@ -35,8 +34,7 @@ function __construct($Build = true, $Tech = true) $this->Build = $Build; $this->Tech = $Tech; $this->USER = array(); - $this->PLANET = array(); - $this->DEBUG = FirePHP::getInstance(true); + $this->PLANET = array(); } public function ReturnVars() { @@ -53,21 +51,26 @@ public function ReturnVars() { public function CreateHash() { global $reslist, $resource; $Hash = array(); - $Hash[] = $this->CONF['metal_basic_income']; - $Hash[] = $this->CONF['crystal_basic_income']; - $Hash[] = $this->CONF['deuterium_basic_income']; foreach($reslist['prod'] as $ID) { $Hash[] = $this->PLANET[$resource[$ID]]; $Hash[] = $this->PLANET[$resource[$ID].'_porcent']; } + $ressource = array_merge(array(), $reslist['resstype'][1], $reslist['resstype'][2]); + foreach($ressource as $ID) { + $Hash[] = $this->CONF[$resource[$ID].'_basic_income']; + } + + $Hash[] = $this->CONF['resource_multiplier']; + $Hash[] = $this->CONF['energySpeed']; + $Hash[] = $this->USER['factor']['Resource']; + $Hash[] = $this->USER['factor']['Energy']; $Hash[] = $this->PLANET[$resource[22]]; $Hash[] = $this->PLANET[$resource[23]]; $Hash[] = $this->PLANET[$resource[24]]; - $Hash[] = $this->USER['factor']['metal']; - $Hash[] = $this->USER['factor']['crystal']; - $Hash[] = $this->USER['factor']['deuterium']; - $Hash[] = $this->USER['factor']['energy']; + $Hash[] = $this->USER[$resource[131]]; + $Hash[] = $this->USER[$resource[132]]; + $Hash[] = $this->USER[$resource[133]]; return md5(implode("::", $Hash)); } @@ -77,9 +80,10 @@ public function CalcResource($USER = NULL, $PLANET = NULL, $SAVE = false, $TIME $this->USER = $this->GLOBALS ? $GLOBALS['USER'] : $USER; $this->PLANET = $this->GLOBALS ? $GLOBALS['PLANET'] : $PLANET; $this->TIME = is_null($TIME) ? TIMESTAMP : $TIME; - $this->CONF = getConfig($this->USER['universe']); + $this->CONF = Config::getAll(NULL, $this->USER['universe']); +# $this->CONF['energySpeed'] = 1; - if(EH_ACTIVE_ECO === true || $this->USER['urlaubs_modus'] == 1) + if($this->USER['urlaubs_modus'] == 1) return $this->ReturnVars(); if($this->Build) @@ -102,14 +106,15 @@ public function CalcResource($USER = NULL, $PLANET = NULL, $SAVE = false, $TIME public function UpdateRessource($TIME, $HASH = false) { $this->ProductionTime = ($TIME - $this->PLANET['last_update']); - $this->DEBUG->log("Start UpdateRessource on Planet(ID: ".$this->PLANET['id']."): ".date("H:i:s", $this->PLANET['last_update'])." to ".date("H:i:s", $this->TIME)." (".pretty_number($this->ProductionTime)."s)"); + if($this->ProductionTime > 0) { $this->PLANET['last_update'] = $TIME; if($HASH === false) { - $this->ReBuildCache($TIME); + $this->ReBuildCache(); } else { $this->HASH = $this->CreateHash(); + if($this->PLANET['eco_hash'] !== $this->HASH) { $this->PLANET['eco_hash'] = $this->HASH; $this->ReBuildCache(); @@ -124,14 +129,11 @@ private function ExecCalc() if($this->PLANET['planet_type'] == 3) return; - $MaxMetalStorage = $this->PLANET['metal_max'] * $this->CONF['max_overflow']; - $MaxCristalStorage = $this->PLANET['crystal_max'] * $this->CONF['max_overflow']; - $MaxDeuteriumStorage = $this->PLANET['deuterium_max'] * $this->CONF['max_overflow']; - $MetalTheorical = 0; - $CristalTheorical = 0; - $DeuteriumTheorical = 0; + $MaxMetalStorage = $this->PLANET['metal_max'] * $this->CONF['max_overflow']; + $MaxCristalStorage = $this->PLANET['crystal_max'] * $this->CONF['max_overflow']; + $MaxDeuteriumStorage = $this->PLANET['deuterium_max'] * $this->CONF['max_overflow']; - $MetalTheorical = round($this->ProductionTime * (($this->CONF['metal_basic_income'] * $this->CONF['resource_multiplier']) + $this->PLANET['metal_perhour']) / 3600); + $MetalTheorical = $this->ProductionTime * (($this->CONF['metal_basic_income'] * $this->CONF['resource_multiplier']) + $this->PLANET['metal_perhour']) / 3600; if($MetalTheorical < 0) { @@ -142,7 +144,7 @@ private function ExecCalc() $this->PLANET['metal'] = min($this->PLANET['metal'] + $MetalTheorical, $MaxMetalStorage); } - $CristalTheorical = round($this->ProductionTime * (($this->CONF['crystal_basic_income'] * $this->CONF['resource_multiplier']) + $this->PLANET['crystal_perhour']) / 3600); + $CristalTheorical = $this->ProductionTime * (($this->CONF['crystal_basic_income'] * $this->CONF['resource_multiplier']) + $this->PLANET['crystal_perhour']) / 3600; if ($CristalTheorical < 0) { $this->PLANET['crystal'] = max($this->PLANET['crystal'] + $CristalTheorical, 0); @@ -152,7 +154,7 @@ private function ExecCalc() $this->PLANET['crystal'] = min($this->PLANET['crystal'] + $CristalTheorical, $MaxCristalStorage); } - $DeuteriumTheorical = round($this->ProductionTime * (($this->CONF['deuterium_basic_income'] * $this->CONF['resource_multiplier']) + $this->PLANET['deuterium_perhour']) / 3600); + $DeuteriumTheorical = $this->ProductionTime * (($this->CONF['deuterium_basic_income'] * $this->CONF['resource_multiplier']) + $this->PLANET['deuterium_perhour']) / 3600; if ($DeuteriumTheorical < 0) { $this->PLANET['deuterium'] = max($this->PLANET['deuterium'] + $DeuteriumTheorical, 0); @@ -162,101 +164,126 @@ private function ExecCalc() $this->PLANET['deuterium'] = min($this->PLANET['deuterium'] + $DeuteriumTheorical, $MaxDeuteriumStorage); } - $this->DEBUG->log("Add: Metal: ".pretty_number($MetalTheorical)." Crystal: ".pretty_number($CristalTheorical)." Deuterium: ".pretty_number($DeuteriumTheorical)); $this->PLANET['metal'] = max($this->PLANET['metal'], 0); $this->PLANET['crystal'] = max($this->PLANET['crystal'], 0); $this->PLANET['deuterium'] = max($this->PLANET['deuterium'], 0); } + public static function getProd($Calculation) + { + return 'return '.$Calculation.';'; + } + + public static function getNetworkLevel($USER, $PLANET) + { + global $resource; + + $lablevel = array(); + if($USER[$resource[123]] == 0) { + $lablevel[] = $PLANET[$resource[31]]; + } else { + $LevelRow = $GLOBALS['DATABASE']->query("SELECT ".$resource[31]." FROM ".PLANETS." WHERE id != '".$PLANET['id']."' AND id_owner = '".$USER['id']."' AND destruyed = 0 ORDER BY ".$resource[31]." DESC LIMIT ".($USER[$resource[123]]).";"); + $lablevel[] = $PLANET[$resource[31]]; + while($Levels = $GLOBALS['DATABASE']->fetch_array($LevelRow)) + { + $lablevel[] = $Levels[$resource[31]]; + } + $GLOBALS['DATABASE']->free_result($LevelRow); + } + + return $lablevel; + } + public function ReBuildCache() { global $ProdGrid, $resource, $reslist, $pricelist; - $this->PLANET['metal_max'] = floor(2.5 * pow(1.8331954764, $this->PLANET[$resource[22]])) * 5000 * (1 + ($this->USER['rpg_stockeur'] * $pricelist[607]['info'])) * $this->CONF['resource_multiplier'] * STORAGE_FACTOR; - $this->PLANET['crystal_max'] = floor(2.5 * pow(1.8331954764, $this->PLANET[$resource[23]])) * 5000 * (1 + ($this->USER['rpg_stockeur'] * $pricelist[607]['info'])) * $this->CONF['resource_multiplier'] * STORAGE_FACTOR; - $this->PLANET['deuterium_max'] = floor(2.5 * pow(1.8331954764, $this->PLANET[$resource[24]])) * 5000 * (1 + ($this->USER['rpg_stockeur'] * $pricelist[607]['info'])) * $this->CONF['resource_multiplier'] * STORAGE_FACTOR; - - $this->DEBUG->log("Storage: Metal: ".pretty_number($this->PLANET['metal_max'])." Crystal: ".pretty_number($this->PLANET['crystal_max'])." Deuterium: ".pretty_number($this->PLANET['deuterium_max'])); - if ($this->PLANET['planet_type'] == 3) { $this->CONF['metal_basic_income'] = 0; $this->CONF['crystal_basic_income'] = 0; $this->CONF['deuterium_basic_income'] = 0; - $this->PLANET['metal_perhour'] = 0; - $this->PLANET['crystal_perhour'] = 0; - $this->PLANET['deuterium_perhour'] = 0; - $this->PLANET['energy_used'] = 0; - $this->PLANET['metal_proc'] = array(0); - $this->PLANET['crystal_proc'] = array(0); - $this->PLANET['deuterium_proc'] = array(0); - $this->PLANET['deuterium_userd_proc'] = array(0); - $this->PLANET['energy_used_proc'] = array(0); - if($this->PLANET[$resource[212]] == 0) { - $this->PLANET['energy_max_proc'] = array(0); - $this->PLANET['energy_max'] = 0; - } else { - $BuildTemp = $this->PLANET['temp_max']; - $BuildLevelFactor = $this->PLANET[$resource[212].'_porcent']; - $BuildLevel = $this->PLANET[$resource[212]]; - $this->PLANET['energy_max_proc'][212] = round(eval($ProdGrid[212]['energy']) * ($this->CONF['resource_multiplier'])); - $this->PLANET['energy_max'] = $this->PLANET['energy_max_proc'][212]; - } } - else + + $temp = array( + 901 => array( + 'max' => 0, + 'plus' => 0, + 'minus' => 0, + ), + 902 => array( + 'max' => 0, + 'plus' => 0, + 'minus' => 0, + ), + 903 => array( + 'max' => 0, + 'plus' => 0, + 'minus' => 0, + ), + 911 => array( + 'plus' => 0, + 'minus' => 0, + ) + ); + + $BuildTemp = $this->PLANET['temp_max']; + $BuildEnergy = $this->USER[$resource[113]]; + + foreach($reslist['storage'] as $ProdID) { - $this->PLANET['metal_proc'] = array(); - $this->PLANET['crystal_proc'] = array(); - $this->PLANET['deuterium_proc'] = array(); - $this->PLANET['deuterium_userd_proc'] = array(); - $this->PLANET['energy_used_proc'] = array(); - $this->PLANET['energy_max_proc'] = array(); - $BuildTemp = $this->PLANET['temp_max']; - $BuildEnergy = $this->USER[$resource[113]]; - - foreach($reslist['prod'] as $id => $ProdID) - { - $BuildLevelFactor = $this->PLANET[$resource[$ProdID].'_porcent']; - $BuildLevel = $this->PLANET[$resource[$ProdID]]; - $this->PLANET['metal_proc'][$ProdID] = round(eval($ProdGrid[$ProdID]['metal']) * $this->CONF['resource_multiplier']); - $this->PLANET['crystal_proc'][$ProdID] = round(eval($ProdGrid[$ProdID]['crystal']) * $this->CONF['resource_multiplier']); + foreach($reslist['resstype'][1] as $ID) + { + if(!isset($ProdGrid[$ProdID]['storage'][$ID])) + continue; + + $BuildLevel = $this->PLANET[$resource[$ProdID]]; + $temp[$ID]['max'] += round(eval(self::getProd($ProdGrid[$ProdID]['storage'][$ID]))); + } + } + + $ressIDs = array_merge(array(), $reslist['resstype'][1], $reslist['resstype'][2]); + + foreach($reslist['prod'] as $ProdID) + { + $BuildLevelFactor = $this->PLANET[$resource[$ProdID].'_porcent']; + $BuildLevel = $this->PLANET[$resource[$ProdID]]; + + foreach($ressIDs as $ID) + { + if(!isset($ProdGrid[$ProdID]['production'][$ID])) + continue; - $Energy = round(eval($ProdGrid[$ProdID]['energy']) * ($this->CONF['resource_multiplier'])); - if ($Energy < 0) { - $this->PLANET['deuterium_proc'][$ProdID] = round(eval($ProdGrid[$ProdID]['deuterium']) * $this->CONF['resource_multiplier']); - $this->PLANET['energy_used_proc'][$ProdID] = $Energy; + $Production = eval(self::getProd($ProdGrid[$ProdID]['production'][$ID])); + + if($Production > 0) { + $temp[$ID]['plus'] += $Production; } else { - if($ProdID == 12 && $this->PLANET['deuterium'] == 0) - continue; - - $this->PLANET['deuterium_userd_proc'][$ProdID] = round(eval($ProdGrid[$ProdID]['deuterium']) * ($this->CONF['resource_multiplier'])); - $this->PLANET['energy_max_proc'][$ProdID] = $Energy; + if(in_array($ID, $reslist['resstype'][1]) && $this->PLANET[$resource[$ID]] == 0) { + continue; + } + + $temp[$ID]['minus'] += $Production; } } + } + + $this->PLANET['metal_max'] = $temp[901]['max'] * $this->CONF['resource_multiplier'] * STORAGE_FACTOR * (1 + $this->USER['factor']['ResourceStorage']); + $this->PLANET['crystal_max'] = $temp[902]['max'] * $this->CONF['resource_multiplier'] * STORAGE_FACTOR * (1 + $this->USER['factor']['ResourceStorage']); + $this->PLANET['deuterium_max'] = $temp[903]['max'] * $this->CONF['resource_multiplier'] * STORAGE_FACTOR * (1 + $this->USER['factor']['ResourceStorage']); - $this->PLANET['energy_used'] = array_sum($this->PLANET['energy_used_proc']); - $this->PLANET['energy_max'] = round(array_sum($this->PLANET['energy_max_proc']) * $this->USER['factor']['energy']); - - if ($this->PLANET['energy_max'] == 0) - { - $this->PLANET['metal_perhour'] = $this->CONF['metal_basic_income']; - $this->PLANET['crystal_perhour'] = $this->CONF['crystal_basic_income']; - $this->PLANET['deuterium_perhour'] = $this->CONF['deuterium_basic_income']; - $this->PLANET['level_proc'] = 0; - } - elseif ($this->PLANET['energy_max'] >= abs($this->PLANET['energy_used'] )) - $this->PLANET['level_proc'] = 1; - else - $this->PLANET['level_proc'] = $this->PLANET['energy_max'] / abs($this->PLANET['energy_used']); - - if($this->PLANET['level_proc'] > 100) - $this->PLANET['level_proc'] = 1; - elseif ($this->PLANET['level_proc'] < 0) - $this->PLANET['level_proc'] = 0; + $this->PLANET['energy'] = round($temp[911]['plus'] * $this->CONF['energySpeed'] * (1 + $this->USER['factor']['Energy'])); + $this->PLANET['energy_used'] = $temp[911]['minus']; + if($this->PLANET['energy_used'] == 0) { + $this->PLANET['metal_perhour'] = 0; + $this->PLANET['crystal_perhour'] = 0; + $this->PLANET['deuterium_perhour'] = 0; + } else { + $prodLevel = min(1, $this->PLANET['energy'] / abs($this->PLANET['energy_used'])); - $this->PLANET['metal_perhour'] = round(array_sum($this->PLANET['metal_proc']) * $this->USER['factor']['metal'] * $this->PLANET['level_proc']); - $this->PLANET['crystal_perhour'] = round(array_sum($this->PLANET['crystal_proc']) * $this->USER['factor']['crystal'] * $this->PLANET['level_proc']); - $this->PLANET['deuterium_perhour'] = round(array_sum($this->PLANET['deuterium_proc']) * $this->USER['factor']['deuterium'] * $this->PLANET['level_proc'] + array_sum($this->PLANET['deuterium_userd_proc'])); + $this->PLANET['metal_perhour'] = ($temp[901]['plus'] * (1 + $this->USER['factor']['Resource'] + 0.02 * $this->USER[$resource[131]]) * $prodLevel + $temp[901]['minus']) * $this->CONF['resource_multiplier']; + $this->PLANET['crystal_perhour'] = ($temp[902]['plus'] * (1 + $this->USER['factor']['Resource'] + 0.02 * $this->USER[$resource[132]]) * $prodLevel + $temp[902]['minus']) * $this->CONF['resource_multiplier']; + $this->PLANET['deuterium_perhour'] = ($temp[903]['plus'] * (1 + $this->USER['factor']['Resource'] + 0.02 * $this->USER[$resource[133]]) * $prodLevel + $temp[903]['minus']) * $this->CONF['resource_multiplier']; } } @@ -276,7 +303,7 @@ private function ShipyardQueue() $BuildArray = array(); foreach($BuildQueue as $Item) { - $AcumTime = GetBuildingTime($this->USER, $this->PLANET, $Item[0]); + $AcumTime = BuildFunctions::getBuildingTime($this->USER, $this->PLANET, $Item[0]); $BuildArray[] = array($Item[0], $Item[1], $AcumTime); } @@ -307,8 +334,6 @@ private function ShipyardQueue() continue; } - $this->DEBUG->log("Done(Ship[ID:".$Element."]): ".pretty_number($Build)); - if(!isset($this->Builded[$Element])) $this->Builded[$Element] = 0; @@ -325,7 +350,7 @@ private function ShipyardQueue() $NewQueue[] = array($Element, $Count); } $this->PLANET['b_hangar_id'] = !empty($NewQueue) ? serialize($NewQueue) : ''; - $this->DEBUG->log("Queue(Hanger): ".$this->PLANET['b_hangar_id']); + } private function BuildingQueue() @@ -336,7 +361,7 @@ private function BuildingQueue() private function CheckPlanetBuildingQueue() { - global $resource, $db, $reslist; + global $resource, $reslist; if (empty($this->PLANET['b_building_id']) || $this->PLANET['b_building'] > $this->TIME) return false; @@ -364,7 +389,7 @@ private function CheckPlanetBuildingQueue() $this->Builded[$Element] -= 1; } - $this->DEBUG->log("Done: Build(ID: ".$Element."): ".($this->PLANET[$resource[$Element]] - ($BuildMode == 'build' ? 1 : -1))." -> ".$this->PLANET[$resource[$Element]]); + array_shift($CurrentQueue); $OnHash = in_array($Element, $reslist['prod']); $this->UpdateRessource($BuildEndTime, !$OnHash); @@ -372,7 +397,7 @@ private function CheckPlanetBuildingQueue() if (count($CurrentQueue) == 0) { $this->PLANET['b_building'] = 0; $this->PLANET['b_building_id'] = ''; - $this->DEBUG->log("Queue(Builds): ".$this->PLANET['b_building_id']); + return false; } else { $this->PLANET['b_building_id'] = serialize($CurrentQueue); @@ -382,7 +407,7 @@ private function CheckPlanetBuildingQueue() public function SetNextQueueElementOnTop() { - global $resource, $db, $LNG; + global $resource, $LNG; if (empty($this->PLANET['b_building_id'])) { $this->PLANET['b_building'] = 0; @@ -394,41 +419,43 @@ public function SetNextQueueElementOnTop() $Loop = true; while ($Loop == true) { - $ListIDArray = $CurrentQueue[0]; - $Element = $ListIDArray[0]; - $Level = $ListIDArray[1]; - $BuildMode = $ListIDArray[4]; - $ForDestroy = ($BuildMode == 'destroy') ? true : false; - $BuildTime = GetBuildingTime($this->USER, $this->PLANET, $Element, $ForDestroy); - $BuildEndTime = $this->PLANET['b_building'] + $BuildTime; - $CurrentQueue[0] = array($Element, $Level, $BuildTime, $BuildEndTime, $BuildMode); - $HaveNoMoreLevel = false; - - $HaveRessources = IsElementBuyable($this->USER, $this->PLANET, $Element, true, $ForDestroy); + $ListIDArray = $CurrentQueue[0]; + $Element = $ListIDArray[0]; + $Level = $ListIDArray[1]; + $BuildMode = $ListIDArray[4]; + $ForDestroy = ($BuildMode == 'destroy') ? true : false; + $costRessources = BuildFunctions::getElementPrice($this->USER, $this->PLANET, $Element, $ForDestroy); + $BuildTime = BuildFunctions::getBuildingTime($this->USER, $this->PLANET, $Element, $costRessources); + $HaveRessources = BuildFunctions::isElementBuyable($this->USER, $this->PLANET, $Element, $costRessources); + $BuildEndTime = $this->PLANET['b_building'] + $BuildTime; + $CurrentQueue[0] = array($Element, $Level, $BuildTime, $BuildEndTime, $BuildMode); + $HaveNoMoreLevel = false; if($ForDestroy && $this->PLANET[$resource[$Element]] == 0) { $HaveRessources = false; $HaveNoMoreLevel = true; } - if($HaveRessources == true) { - $Needed = GetBuildingPrice ($this->USER, $this->PLANET, $Element, true, $ForDestroy); - $this->PLANET['metal'] -= $Needed['metal']; - $this->PLANET['crystal'] -= $Needed['crystal']; - $this->PLANET['deuterium'] -= $Needed['deuterium']; - $this->USER['darkmatter'] -= $Needed['darkmatter']; + if($HaveRessources === true) { + if(isset($costRessources[901])) { $this->PLANET[$resource[901]] -= $costRessources[901]; } + if(isset($costRessources[902])) { $this->PLANET[$resource[902]] -= $costRessources[902]; } + if(isset($costRessources[903])) { $this->PLANET[$resource[903]] -= $costRessources[903]; } + if(isset($costRessources[921])) { $this->USER[$resource[921]] -= $costRessources[921]; } $NewQueue = serialize($CurrentQueue); $Loop = false; } else { if($this->USER['hof'] == 1){ - if ($ForDestroy || $HaveNoMoreLevel) + if ($HaveNoMoreLevel) { $Message = sprintf($LNG['sys_nomore_level'], $LNG['tech'][$Element]); - else - { - $Needed = GetBuildingPrice($this->USER, $this->PLANET, $Element, true, $ForDestroy); - $Message = sprintf($LNG['sys_notenough_money'], $this->PLANET['name'], $this->PLANET['id'], $this->PLANET['galaxy'], $this->PLANET['system'], $this->PLANET['planet'], $LNG['tech'][$Element], pretty_number ($this->PLANET['metal']), $LNG['Metal'], pretty_number ($this->PLANET['crystal']), $LNG['Crystal'], pretty_number ($this->PLANET['deuterium']), $LNG['Deuterium'], pretty_number ($Needed['metal']), $LNG['Metal'], pretty_number ($Needed['crystal']), $LNG['Crystal'], pretty_number ($Needed['deuterium']), $LNG['Deuterium']); + } else { + if(!isset($costRessources[901])) { $costRessources[901] = 0; } + if(!isset($costRessources[902])) { $costRessources[902] = 0; } + if(!isset($costRessources[903])) { $costRessources[903] = 0; } + + $Message = sprintf($LNG['sys_notenough_money'], $this->PLANET['name'], $this->PLANET['id'], $this->PLANET['galaxy'], $this->PLANET['system'], $this->PLANET['planet'], $LNG['tech'][$Element], pretty_number ($this->PLANET['metal']), $LNG['tech'][901], pretty_number($this->PLANET['crystal']), $LNG['tech'][902], pretty_number ($this->PLANET['deuterium']), $LNG['tech'][903], pretty_number($costRessources[901]), $LNG['tech'][901], pretty_number ($costRessources[902]), $LNG['tech'][902], pretty_number ($costRessources[903]), $LNG['tech'][903]); } - SendSimpleMessage($this->USER['id'], '', $this->TIME, 99, $LNG['sys_buildlist'], $LNG['sys_buildlist_fail'], $Message); + + SendSimpleMessage($this->USER['id'], 0, $this->TIME, 99, $LNG['sys_buildlist'], $LNG['sys_buildlist_fail'], $Message); } array_shift($CurrentQueue); @@ -442,7 +469,7 @@ public function SetNextQueueElementOnTop() $NewQueue = array(); foreach($CurrentQueue as $ListIDArray) { - $ListIDArray[2] = GetBuildingTime($this->USER, $this->PLANET, $ListIDArray[0], $ListIDArray[4] == 'destroy'); + $ListIDArray[2] = BuildFunctions::getBuildingTime($this->USER, $this->PLANET, $ListIDArray[0], NULL, $ListIDArray[4] == 'destroy'); $BaseTime += $ListIDArray[2]; $ListIDArray[3] = $BaseTime; $NewQueue[] = $ListIDArray; @@ -454,7 +481,6 @@ public function SetNextQueueElementOnTop() $this->PLANET['b_building'] = $BuildEndTime; $this->PLANET['b_building_id'] = $NewQueue; - $this->DEBUG->log("Queue(Builds): ".$this->PLANET['b_building_id']); } private function ResearchQueue() @@ -465,7 +491,7 @@ private function ResearchQueue() private function CheckUserTechQueue() { - global $resource, $db; + global $resource; if (empty($this->USER['b_tech_id']) || $this->USER['b_tech'] > $this->TIME) return false; @@ -476,7 +502,7 @@ private function CheckUserTechQueue() $this->Builded[$this->USER['b_tech_id']] += 1; $this->USER[$resource[$this->USER['b_tech_id']]] += 1; - $this->DEBUG->log("Done: Ship(ID:".$Element."): ".($this->USER[$resource[$this->USER['b_tech_id']]] - 1)." -> ".$this->USER[$resource[$this->USER['b_tech_id']]]); + $CurrentQueue = unserialize($this->USER['b_tech_queue']); array_shift($CurrentQueue); @@ -486,7 +512,7 @@ private function CheckUserTechQueue() $this->USER['b_tech_id'] = 0; $this->USER['b_tech_planet'] = 0; $this->USER['b_tech_queue'] = ''; - $this->DEBUG->log("Queue(Tech): ".$this->USER['b_tech_queue']); + return false; } else { $this->USER['b_tech_queue'] = serialize(array_values($CurrentQueue)); @@ -496,7 +522,7 @@ private function CheckUserTechQueue() public function SetNextQueueTechOnTop() { - global $resource, $db, $LNG; + global $resource, $LNG; if (empty($this->USER['b_tech_queue'])) { $this->USER['b_tech'] = 0; @@ -512,48 +538,47 @@ public function SetNextQueueTechOnTop() { $ListIDArray = $CurrentQueue[0]; if($ListIDArray[4] != $this->PLANET['id']) - $PLANET = $db->uniquequery("SELECT * FROM ".PLANETS." WHERE `id` = '".$ListIDArray[4]."';"); + $PLANET = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".PLANETS." WHERE id = '".$ListIDArray[4]."';"); else $PLANET = $this->PLANET; - $PLANET[$resource[31].'_inter'] = $this->CheckAndGetLabLevel($this->USER, $PLANET); + $PLANET[$resource[31].'_inter'] = self::getNetworkLevel($this->USER, $PLANET); $Element = $ListIDArray[0]; $Level = $ListIDArray[1]; - $BuildTime = GetBuildingTime($this->USER, $PLANET, $Element); + $costRessources = BuildFunctions::getElementPrice($this->USER, $PLANET, $Element); + $BuildTime = BuildFunctions::getBuildingTime($this->USER, $PLANET, $Element, $costRessources); + $HaveRessources = BuildFunctions::isElementBuyable($this->USER, $PLANET, $Element, $costRessources); $BuildEndTime = $this->USER['b_tech'] + $BuildTime; $CurrentQueue[0] = array($Element, $Level, $BuildTime, $BuildEndTime, $PLANET['id']); - if($PLANET['id'] != $this->PLANET['id']) { - $IsHash = in_array($Element, array(131, 132, 133)); + $isAnotherPlanet = $ListIDArray[4] != $this->PLANET['id']; + + if($isAnotherPlanet) { + $IsHash = !in_array($Element, array(131, 132, 133)); $RPLANET = new ResourceUpdate(true, false); list(, $PLANET) = $RPLANET->CalcResource($this->USER, $PLANET, false, $this->USER['b_tech'], $IsHash); } - $HaveRessources = IsElementBuyable($this->USER, $PLANET, $Element, true, false); - if($HaveRessources == true) { - $Needed = GetBuildingPrice($this->USER, $PLANET, $Element); - $PLANET['metal'] -= $Needed['metal']; - $PLANET['crystal'] -= $Needed['crystal']; - $PLANET['deuterium'] -= $Needed['deuterium']; - $this->USER['darkmatter'] -= $Needed['darkmatter']; + if(isset($costRessources[901])) { $PLANET[$resource[901]] -= $costRessources[901]; } + if(isset($costRessources[902])) { $PLANET[$resource[902]] -= $costRessources[902]; } + if(isset($costRessources[903])) { $PLANET[$resource[903]] -= $costRessources[903]; } + if(isset($costRessources[921])) { $this->USER[$resource[921]] -= $costRessources[921]; } $this->USER['b_tech_id'] = $Element; $this->USER['b_tech'] = $BuildEndTime; $this->USER['b_tech_planet'] = $PLANET['id']; $this->USER['b_tech_queue'] = serialize($CurrentQueue); $Loop = false; - - if($ListIDArray[4] != $this->PLANET['id']) - $RPLANET->SavePlanetToDB($this->USER, $PLANET); - else - $this->PLANET = $PLANET; } else { if($this->USER['hof'] == 1){ - $Needed = GetBuildingPrice($this->USER, $RPLANET->PLANET, $Element, true, $ForDestroy); - $Message = sprintf($LNG['sys_notenough_money'], $PLANET['name'], $PLANET['id'], $PLANET['galaxy'], $PLANET['system'], $PLANET['planet'], $LNG['tech'][$Element], pretty_number($RPLANET->PLANET['metal']), $LNG['Metal'], pretty_number($RPLANET->PLANET['crystal']), $LNG['Crystal'], pretty_number($RPLANET->PLANET['deuterium']), $LNG['Deuterium'], pretty_number ($Needed['metal']), $LNG['Metal'], pretty_number ($Needed['crystal']), $LNG['Crystal'], pretty_number ($Needed['deuterium']), $LNG['Deuterium']); - SendSimpleMessage($this->USER['id'], '', $this->TIME, 99, $LNG['sys_techlist'], $LNG['sys_buildlist_fail'], $Message); + if(!isset($costRessources[901])) { $costRessources[901] = 0; } + if(!isset($costRessources[902])) { $costRessources[902] = 0; } + if(!isset($costRessources[903])) { $costRessources[903] = 0; } + + $Message = sprintf($LNG['sys_notenough_money'], $PLANET['name'], $PLANET['id'], $PLANET['galaxy'], $PLANET['system'], $PLANET['planet'], $LNG['tech'][$Element], pretty_number ($PLANET['metal']), $LNG['tech'][901], pretty_number($PLANET['crystal']), $LNG['tech'][902], pretty_number ($PLANET['deuterium']), $LNG['tech'][903], pretty_number($costRessources[901]), $LNG['tech'][901], pretty_number ($costRessources[902]), $LNG['tech'][902], pretty_number ($costRessources[903]), $LNG['tech'][903]); + SendSimpleMessage($this->USER['id'], 0, $this->USER['b_tech'], 99, $LNG['sys_techlist'], $LNG['sys_buildlist_fail'], $Message); } array_shift($CurrentQueue); @@ -570,7 +595,7 @@ public function SetNextQueueTechOnTop() $NewQueue = array(); foreach($CurrentQueue as $ListIDArray) { - $ListIDArray[2] = GetBuildingTime($this->USER, $Planet, $ListIDArray[0]); + $ListIDArray[2] = BuildFunctions::getBuildingTime($this->USER, $PLANET, $ListIDArray[0]); $BaseTime += $ListIDArray[2]; $ListIDArray[3] = $BaseTime; $NewQueue[] = $ListIDArray; @@ -578,31 +603,18 @@ public function SetNextQueueTechOnTop() $CurrentQueue = $NewQueue; } } + + if($isAnotherPlanet) + $RPLANET->SavePlanetToDB($this->USER, $PLANET); + else + $this->PLANET = $PLANET; } - $this->DEBUG->log("Queue(Tech): ".$this->USER['b_tech_queue']); - } - - public function CheckAndGetLabLevel() - { - global $resource, $db, $USER, $PLANET; - if($USER[$resource[123]] == 0) - $lablevel = $PLANET[$resource[31]]; - else { - $LevelRow = $db->query("SELECT ".$resource[31]." FROM ".PLANETS." WHERE `id` != '".$PLANET['id']."' AND `id_owner` = '".$USER['id']."' AND `destruyed` = 0 ORDER BY ".$resource[31]." DESC LIMIT ".($USER[$resource[123]]).";"); - $lablevel[] = $PLANET[$resource[31]]; - while($Levels = $db->fetch_array($LevelRow)) - { - $lablevel[] = $Levels[$resource[31]]; - } - $db->free_result($LevelRow); - } - return $lablevel; } public function SavePlanetToDB($USER = NULL, $PLANET = NULL) { - global $resource, $db, $reslist; + global $resource, $reslist; if(is_null($USER)) global $USER; @@ -610,57 +622,58 @@ public function SavePlanetToDB($USER = NULL, $PLANET = NULL) if(is_null($PLANET)) global $PLANET; - $Qry = "LOCK TABLE ".PLANETS." as p WRITE, ".USERS." as u WRITE, ".SESSION." as s WRITE; - UPDATE ".PLANETS." as p, ".USERS." as u, ".SESSION." as s SET - `p`.`metal` = '".floattostring($PLANET['metal'])."', - `p`.`crystal` = '".floattostring($PLANET['crystal'])."', - `p`.`deuterium` = '".floattostring($PLANET['deuterium'])."', - `p`.`eco_hash` = '".$PLANET['eco_hash']."', - `p`.`last_update` = '".$PLANET['last_update']."', - `p`.`b_building` = '".$PLANET['b_building']."', - `p`.`b_building_id` = '".$PLANET['b_building_id']."', - `p`.`field_current` = '".$PLANET['field_current']."', - `p`.`b_hangar_id` = '".$PLANET['b_hangar_id']."', - `p`.`metal_perhour` = '".$PLANET['metal_perhour']."', - `p`.`crystal_perhour` = '".$PLANET['crystal_perhour']."', - `p`.`deuterium_perhour` = '".$PLANET['deuterium_perhour']."', - `p`.`metal_max` = '".$PLANET['metal_max']."', - `p`.`crystal_max` = '".$PLANET['crystal_max']."', - `p`.`deuterium_max` = '".$PLANET['deuterium_max']."', - `p`.`energy_used` = '".$PLANET['energy_used']."', - `p`.`energy_max` = '".$PLANET['energy_max']."', - `p`.`b_hangar` = '". $PLANET['b_hangar'] ."', "; + $Qry = "LOCK TABLE ".PLANETS." as p WRITE, ".USERS." as u WRITE; + UPDATE ".PLANETS." as p, ".USERS." as u SET + p.metal = ".$PLANET['metal'].", + p.crystal = ".$PLANET['crystal'].", + p.deuterium = ".$PLANET['deuterium'].", + p.eco_hash = '".$PLANET['eco_hash']."', + p.last_update = ".$PLANET['last_update'].", + p.b_building = '".$PLANET['b_building']."', + p.b_building_id = '".$PLANET['b_building_id']."', + p.field_current = ".$PLANET['field_current'].", + p.b_hangar_id = '".$PLANET['b_hangar_id']."', + p.metal_perhour = ".$PLANET['metal_perhour'].", + p.crystal_perhour = ".$PLANET['crystal_perhour'].", + p.deuterium_perhour = ".$PLANET['deuterium_perhour'].", + p.metal_max = ".$PLANET['metal_max'].", + p.crystal_max = ".$PLANET['crystal_max'].", + p.deuterium_max = ".$PLANET['deuterium_max'].", + p.energy_used = ".$PLANET['energy_used'].", + p.energy = ".$PLANET['energy'].", + p.b_hangar = ". $PLANET['b_hangar'] .", "; if (!empty($this->Builded)) { foreach($this->Builded as $Element => $Count) { - $Element = (int)$Element; - if(empty($resource[$Element]) || empty($Count)) + $Element = (int) $Element; + + if(empty($resource[$Element]) || empty($Count)) { continue; + } - if(in_array($Element, $reslist['one'])) - $Qry .= "`p`.`".$resource[$Element]."` = '1', "; - elseif(isset($PLANET[$resource[$Element]])) - $Qry .= "`p`.`".$resource[$Element]."` = `p`.`".$resource[$Element]."` + '".$Count."', "; - elseif(isset($USER[$resource[$Element]])) - $Qry .= "`u`.`".$resource[$Element]."` = `u`.`".$resource[$Element]."` + '".$Count."', "; + if(in_array($Element, $reslist['one'])) { + $Qry .= "p.".$resource[$Element]." = '1', "; + } elseif(isset($PLANET[$resource[$Element]])) { + $Qry .= "p.".$resource[$Element]." = p.".$resource[$Element]." + ".floattostring($Count).", "; + } elseif(isset($USER[$resource[$Element]])) { + $Qry .= "u.".$resource[$Element]." = u.".$resource[$Element]." + ".floattostring($Count).", "; + } } } - $Qry .= "`u`.`darkmatter` = '".$USER['darkmatter']."', - `u`.`b_tech` = '".$USER['b_tech']."', - `u`.`b_tech_id` = '".$USER['b_tech_id']."', - `u`.`b_tech_planet` = '".$USER['b_tech_planet']."', - `u`.`b_tech_queue` = '".$USER['b_tech_queue']."' + $Qry .= "u.darkmatter = ".$USER['darkmatter'].", + u.b_tech = '".$USER['b_tech']."', + u.b_tech_id = '".$USER['b_tech_id']."', + u.b_tech_planet = '".$USER['b_tech_planet']."', + u.b_tech_queue = '".$USER['b_tech_queue']."' WHERE - `p`.`id` = '". $PLANET['id'] ."' AND - `u`.`id` = '".$USER['id']."' AND - `s`.`sess_id` = '".session_id()."'; + p.id = ".$PLANET['id']." AND + u.id = ".$USER['id']."; UNLOCK TABLES;"; - $db->multi_query($Qry); + $GLOBALS['DATABASE']->multi_query($Qry); $this->Builded = array(); - $this->DEBUG->log("Total: Metal: ".pretty_number($PLANET['metal'])." Crystal: ".pretty_number($PLANET['crystal'])." Deuterium: ".pretty_number($PLANET['deuterium'])); + return array($USER, $PLANET); } -} -?> \ No newline at end of file +} \ No newline at end of file diff --git a/includes/classes/class.Records.php b/includes/classes/class.Records.php deleted file mode 100644 index b0577b6..0000000 --- a/includes/classes/class.Records.php +++ /dev/null @@ -1,86 +0,0 @@ -. - * - * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) - * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) - * @info $Id$ - * @link http://code.google.com/p/2moons/ - */ - -class records -{ - public static $File = "cache/CacheRecords.php"; - public $maxinfos = array(); - - function SetIfRecord($ID, $Data) - { - global $CONF, $resource; - if(($CONF['stat'] == 1 && $Data['authlevel'] >= $CONF['stat_level']) || !empty($Data['bana'])) - return; - - if(!isset($this->maxinfos[$Data['universe']])) - $this->maxinfos[$Data['universe']] = array(); - - if(!isset($this->maxinfos[$Data['universe']][$ID])) - $this->maxinfos[$Data['universe']][$ID] = array('maxlvl' => 0, 'username' => ''); - - if($Data[$resource[$ID]] == 0) - return; - - if($this->maxinfos[$Data['universe']][$ID]['maxlvl'] < $Data[$resource[$ID]]) - $this->maxinfos[$Data['universe']][$ID] = array('maxlvl' => $Data[$resource[$ID]], 'username' => $this->GetPlayerCardLink($Data)); - elseif($this->maxinfos[$Data['universe']][$ID]['maxlvl'] == $Data[$resource[$ID]] && strpos($this->maxinfos[$Data['universe']][$ID]['username'], '>'.$Data['username'].'<') === false) - $this->maxinfos[$Data['universe']][$ID]['username'] = implode(array($this->maxinfos[$Data['universe']][$ID]['username'], $this->GetPlayerCardLink($Data)), '
'); - } - - function GetPlayerCardLink($Data) - { - return ''.$Data['username'].''; - } - - function BuildRecordCache() - { - $Elements = array_merge($GLOBALS['reslist']['build'], $GLOBALS['reslist']['tech'], $GLOBALS['reslist']['fleet'], $GLOBALS['reslist']['defense']); - $PHP = "maxinfos as $Uni => $Records) { - $PHP .= "\t".$Uni." => array(\n"; - foreach($Elements as $ElementID) { - $PHP .= "\t\t".$ElementID." => array('username' => '".(isset($Records[$ElementID]['username']) ? $Records[$ElementID]['username'] : '')."', 'maxlvl' => '".(isset($Records[$ElementID]['maxlvl']) ? pretty_number($Records[$ElementID]['maxlvl']) : '0')."'),\n"; - } - $PHP .= "\t),\n"; - } - $PHP .= "\n);\n?>"; - file_put_contents(ROOT_PATH.self::$File, $PHP); - } - - function GetRecords($Uni) - { - if(!file_exists(ROOT_PATH.self::$File)) - return array(); - - require(ROOT_PATH.self::$File); - return $RecordsArray[$Uni]; - } -} - -?> \ No newline at end of file diff --git a/includes/classes/class.Session.php b/includes/classes/class.Session.php index bc696f3..287a0ca 100644 --- a/includes/classes/class.Session.php +++ b/includes/classes/class.Session.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,46 +18,93 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan + * @copyright 2006 Perberos (UGamela) + * @copyright 2008 Chlorel (XNova) + * @copyright 2012 Jan (2Moons) * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 2.0 (2012-11-31) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class Session { - function IsUserLogin() + private static $obj; + + function __construct() { - return !empty($_SESSION['id']); + ini_set('session.use_cookies', '1'); + ini_set('session.use_only_cookies', '1'); + ini_set('session.use_trans_sid', 0); + ini_set('session.auto_start', '0'); + ini_set('session.serialize_handler', 'php'); + ini_set('session.gc_maxlifetime', SESSION_LIFETIME); + ini_set('session.gc_probability', '1'); + ini_set('session.gc_divisor', '1000'); + ini_set('session.bug_compat_warn', '0'); + ini_set('session.bug_compat_42', '0'); + ini_set('session.cookie_httponly', true); + + //session_set_cookie_params(SESSION_LIFETIME, HTTP_ROOT, HTTP_HOST, HTTPS, true); + + $HTTP_ROOT = MODE === 'INSTALL' ? dirname(HTTP_ROOT) : HTTP_ROOT; + + session_set_cookie_params(SESSION_LIFETIME, $HTTP_ROOT, NULL, HTTPS, true); + session_cache_limiter('nocache'); + session_name('2Moons'); } - function GetSessionFromDB() + static function redirectCode($Code) { - global $db; - return $db->uniquequery("SELECT * FROM ".SESSION." WHERE `sess_id` = '".session_id()."' AND `user_id` = '".$_SESSION['id']."';"); + HTTP::redirectTo('index.php?code='.$Code); } - function ErrorMessage($Code) + static function create($userID, $planetID = 0) { - redirectTo('index.php?code='.$Code); + self::$obj = new self; + + if(!isset($_SESSION)) { + session_start(); + } + + $GLOBALS['DATABASE']->query("REPLACE INTO ".SESSION." SET + sessionID = '".session_id()."', + userID = ".$userID.", + lastonline = ".TIMESTAMP.", + userIP = '".$_SERVER['REMOTE_ADDR']."';"); + + $_SESSION['id'] = $userID; + $_SESSION['agent'] = $_SERVER['HTTP_USER_AGENT']; + $_SESSION['planet'] = $planetID; + + return self::$obj; } - function CreateSession($ID, $Username, $MainPlanet, $Universe, $Authlevel = 0, $dpath = DEFAULT_THEME) + function CreateSession($userID, $userName, $planetID = 0, $uni, $authlevel, $dpath) { - global $db; - $Path = $this->GetPath(); - $db->query("INSERT INTO ".SESSION." (`sess_id`, `user_id`, `user_ip`, `user_side`, `user_lastactivity`) VALUES ('".session_id()."', '".$ID."', '".$_SERVER['REMOTE_ADDR']."', '".$db->sql_escape($Path)."', '".TIMESTAMP."') ON DUPLICATE KEY UPDATE `sess_id` = '".session_id()."', `user_id` = '".$ID."', `user_ip` = '".$_SERVER['REMOTE_ADDR']."', `user_side` = '".$db->sql_escape($Path)."';"); - $_SESSION['id'] = $ID; - $_SESSION['username'] = $Username; - $_SESSION['authlevel'] = $Authlevel; - $_SESSION['path'] = $Path; - $_SESSION['dpath'] = $dpath; - $_SESSION['planet'] = $MainPlanet; - $_SESSION['uni'] = $Universe; - $_SESSION['agent'] = $_SERVER['HTTP_USER_AGENT']; + self::create($userID, $planetID = 0); + $_SESSIOn['authlevel'] = $authlevel; + $_SESSIOn['uni'] = $uni; + $_SESSIOn['dpath'] = $dpath; + } + + function IsUserLogin() + { + return $this->isActiveSession(); + } + + function isActiveSession() + { + if(!isset($_SESSION)) { + session_start(); + } + return !empty($_SESSION['id']); + } + + function GetSessionFromDB() + { + return $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".SESSION." WHERE sessionID = '".session_id()."' AND userID = ".$_SESSION['id'].";"); } function GetPath() @@ -65,36 +112,31 @@ function GetPath() return basename($_SERVER['SCRIPT_NAME']).(!empty($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : ''); } - function UpdateSession() - { - global $CONF, $db; - - if(request_var('ajax', 0) == 1) - return true; - + function updateSession() + { $_SESSION['last'] = $this->GetSessionFromDB(); - if(empty($_SESSION['last']) || !$this->CompareIPs($_SESSION['last']['user_ip'])) { + if(empty($_SESSION['last']) || !$this->CompareIPs($_SESSION['last']['userIP'])) + { $this->DestroySession(); - $this->ErrorMessage(2); + self::redirectCode(2); } - $SelectPlanet = request_var('cp',0); + $SelectPlanet = HTTP::_GP('cp',0); + if(!empty($SelectPlanet)) - $IsPlanetMine = $db->uniquequery("SELECT `id` FROM ".PLANETS." WHERE `id` = '".$SelectPlanet."' AND `id_owner` = '".$_SESSION['id']."';"); - + { + $IsPlanetMine = $GLOBALS['DATABASE']->getFirstRow("SELECT id FROM ".PLANETS." WHERE id = '".$SelectPlanet."' AND id_owner = '".$_SESSION['id']."';"); + } $_SESSION['path'] = $this->GetPath(); $_SESSION['planet'] = !empty($IsPlanetMine['id']) ? $IsPlanetMine['id'] : $_SESSION['planet']; - $SQL = "UPDATE ".USERS." as u, ".SESSION." as s SET "; - $SQL .= "u.`onlinetime` = '".TIMESTAMP."', "; - $SQL .= "u.`user_lastip` = '".$_SERVER['REMOTE_ADDR'] ."', "; - $SQL .= "s.`user_ip` = '".$_SERVER['REMOTE_ADDR']."', "; - $SQL .= "s.`user_side` = '".$db->sql_escape($_SESSION['path'])."', "; - $SQL .= "s.`user_lastactivity` = '".TIMESTAMP."' "; - $SQL .= "WHERE "; - $SQL .= "u.`id` = '".$_SESSION['id']."' AND s.`sess_id` = '".session_id()."';"; - $db->query($SQL); - + $GLOBALS['DATABASE']->query("UPDATE ".USERS." u, ".SESSION." s SET + u.onlinetime = ".TIMESTAMP.", + s.lastonline = ".TIMESTAMP.", + u.user_lastip = '".$_SERVER['REMOTE_ADDR']."', + s.userIP = '".$_SERVER['REMOTE_ADDR']."' + WHERE + sessionID = '".session_id()."' AND u.id = s.userID;"); return true; } @@ -140,10 +182,9 @@ function short_ipv6($ip, $length) function DestroySession() { - global $db; - $db->query("DELETE FROM ".SESSION." WHERE sess_id = '".session_id()."'"); - session_destroy(); - setcookie(session_name(), '', time() - 42000); + $GLOBALS['DATABASE']->query("DELETE FROM ".SESSION." WHERE sessionID = '".session_id()."';"); + @session_destroy(); } -} -?> \ No newline at end of file + + +} \ No newline at end of file diff --git a/includes/classes/class.StatBanner.php b/includes/classes/class.StatBanner.php index b01eb53..22aba07 100644 --- a/includes/classes/class.StatBanner.php +++ b/includes/classes/class.StatBanner.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,91 +18,80 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class StatBanner { - private $textcolor = "FFFFFF"; - private $source = "styles/images/banner.jpg"; + private $source = "styles/resource/images/banner.jpg"; // Function to center text in the created banner - private function CenterTextBanner($z,$y,$zone) { - $a = strlen($z); - $b = imagefontwidth($y); - $c = $a*$b; - $d = $zone-$c; - $e = $d/2; - return $e; + private function CenterTextBanner($X, $String, $Font, $Size) { + + $boxSize = imagettfbbox($Size, 0, $Font, $String); + + $minX = min(array($boxSize[0], $boxSize[2], $boxSize[4], $boxSize[6])); + $maxX = max(array($boxSize[0], $boxSize[2], $boxSize[4], $boxSize[6])); + + $boxWidth = $maxX - $minX; + return $X - ($boxWidth * 0.7); } public function GetData($id) { - global $db; - return $db->uniquequery("SELECT a.username, b.build_points, b.fleet_points, b.defs_points, b.tech_points, b.total_points, b.total_rank, c.name, c.galaxy, c.system, c.planet, d.game_name, d.users_amount, d.ttf_file FROM ".USERS." as a, ".STATPOINTS." as b, ".PLANETS." as c ,".CONFIG." as d WHERE a.id = '".$id."' AND b.stat_type = '1' AND b.id_owner = '".$id."' AND c.id = a.id_planet AND d.uni = a.universe;"); + return $GLOBALS['DATABASE']->getFirstRow("SELECT a.username, a.wons, a.loos, a.draws, b.total_points, b.total_rank, c.name, c.galaxy, c.system, c.planet, d.game_name, d.users_amount, d.ttf_file FROM ".USERS." as a, ".STATPOINTS." as b, ".PLANETS." as c ,".CONFIG." as d WHERE a.id = '".$id."' AND b.stat_type = '1' AND b.id_owner = '".$id."' AND c.id = a.id_planet AND d.uni = a.universe;"); } - public function CreateUTF8Banner($Query) { - global $LNG, $LANG; + public function CreateUTF8Banner($data) { + global $LNG; $image = imagecreatefromjpeg($this->source); - $date = date($LNG['php_dateformat'], TIMESTAMP); + $date = _date($LNG['php_dateformat'], TIMESTAMP); - $Font = $Query['ttf_file']; + $Font = $data['ttf_file']; if(!file_exists($Font)) $this->BannerError('TTF Font missing!'); - // Variables - $b_univ = $Query['game_name']; - $b_user = $Query['username']; - $b_planet = $Query['name']; - $b_xyz = "[".$Query['galaxy'].":".$Query['system'].":".$Query['planet']."]"; - $b_lvl = $Query['total_rank'] ."/".$Query['users_amount']; - $b_build = $LNG['ub_buildings'] .": ".shortly_number($Query['build_points']); - $b_fleet = $LNG['ub_fleets'] .": ".shortly_number($Query['fleet_points']); - $b_def = $LNG['ub_defenses'] .": ".shortly_number($Query['defs_points']); - $b_search = $LNG['ub_researh'] .": ".shortly_number($Query['tech_points']); - $b_total = $LNG['ub_points'] .": ".shortly_number($Query['total_points']); - - - // Colors - $red = hexdec(substr($this->textcolor,0,2)); - $green = hexdec(substr($this->textcolor,2,4)); - $blue = hexdec(substr($this->textcolor,4,6)); - $select = imagecolorallocate($image,$red,$green,$blue); - - // Display - // Univers name - imagettftext($image, 7, 0, $this->CenterTextBanner($b_univ, 1, 630), 65, $select, $Font, $b_univ); - // Today date - imagettftext($image, 7, 0, $this->CenterTextBanner($date, 1, 630), 75, $select, $Font, $date); - // Player name - imagettftext($image, 10, 0, 15, 18, $select, $Font, $b_user); - // Player b_planet - imagettftext($image, 10, 0, 150, 18, $select, $Font, $b_planet." ".$b_xyz); - // Player level - imagettftext($image, 14, 0, $this->CenterTextBanner($b_lvl,10,795), 46, $select, $Font, $b_lvl); - // Player stats - imagettftext($image, 10, 0, 15, 36, $select, $Font, $b_build); - imagettftext($image, 10, 0, 15, 51, $select, $Font, $b_fleet); - imagettftext($image, 10, 0, 230, 36, $select, $Font, $b_search); - imagettftext($image, 10, 0, 230, 51, $select, $Font, $b_def); - imagettftext($image, 10, 0, 15, 66, $select, $Font, $b_total); + // Colors + $color = imagecolorallocate($image, 255, 255, 225); + $shadow = imagecolorallocate($image, 33, 33, 33); + + $total = $data['wons'] + $data['loos'] + $data['draws']; + + $quote = $total != 0 ? $data['wons'] / $total * 100 : 0; + + // Username + imagettftext($image, 20, 0, 20, 31, $shadow, $Font, $data['username']); + imagettftext($image, 20, 0, 20, 30, $color, $Font, $data['username']); + + imagettftext($image, 16, 0, 250, 31, $shadow, $Font, $data['game_name']); + imagettftext($image, 16, 0, 250, 30, $color, $Font, $data['game_name']); + + imagettftext($image, 11, 0, 20, 60, $shadow, $Font, $LNG['ub_rank'].': '.$data['total_rank']); + imagettftext($image, 11, 0, 20, 59, $color, $Font, $LNG['ub_rank'].': '.$data['total_rank']); + + imagettftext($image, 11, 0, 20, 81, $shadow, $Font, $LNG['ub_points'].': '.html_entity_decode(shortly_number($data['total_points']))); + imagettftext($image, 11, 0, 20, 80, $color, $Font, $LNG['ub_points'].': '.html_entity_decode(shortly_number($data['total_points']))); + + imagettftext($image, 11, 0, 250, 60, $shadow, $Font, $LNG['ub_fights'].': '.html_entity_decode(shortly_number($total, 0))); + imagettftext($image, 11, 0, 250, 59, $color, $Font, $LNG['ub_fights'].': '.html_entity_decode(shortly_number($total, 0))); + + imagettftext($image, 11, 0, 250, 81, $shadow, $Font, $LNG['ub_quote'].': '.html_entity_decode(shortly_number($quote, 2)).'%'); + imagettftext($image, 11, 0, 250, 80, $color, $Font, $LNG['ub_quote'].': '.html_entity_decode(shortly_number($quote, 2)).'%'); if(!isset($_GET['debug'])) - header("Content-type: image/jpg"); + HTTP::sendHeader('Content-type', 'image/jpg'); ImageJPEG($image); imagedestroy($image); } function BannerError($Message) { - header("Content-type: image/jpg"); + HTTP::sendHeader('Content-type', 'image/jpg'); $im = ImageCreate(450, 80); $background_color = ImageColorAllocate ($im, 255, 255, 255); $text_color = ImageColorAllocate($im, 233, 14, 91); @@ -111,5 +100,4 @@ function BannerError($Message) { imagedestroy($im); exit; } -} -?> \ No newline at end of file +} \ No newline at end of file diff --git a/includes/classes/class.StringParser.php b/includes/classes/class.StringParser.php index 87c2d32..c3a4bcb 100644 --- a/includes/classes/class.StringParser.php +++ b/includes/classes/class.StringParser.php @@ -1540,5 +1540,3 @@ function _dumpToString () { return "text \"".substr (preg_replace ('/\s+/', ' ', $this->content), 0, 40)."\" [f:".preg_replace ('/\s+/', ' ', join(':', array_keys ($this->_flags)))."]"; } } - -?> \ No newline at end of file diff --git a/includes/classes/class.SupportTickets.php b/includes/classes/class.SupportTickets.php new file mode 100644 index 0000000..bacb546 --- /dev/null +++ b/includes/classes/class.SupportTickets.php @@ -0,0 +1,70 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + +class SupportTickets +{ + function __construct() + { + + } + + function createTicket($ownerID, $categoryID, $subject) { + global $UNI; + + $GLOBALS['DATABASE']->query("INSERT INTO ".TICKETS." SET ownerID = ".$ownerID.", universe = ".$UNI.", categoryID = ".$categoryID.", subject = '".$GLOBALS['DATABASE']->sql_escape($subject)."', time = ".TIMESTAMP.";"); + + return $GLOBALS['DATABASE']->GetInsertID(); + } + + function createAnswer($ticketID, $ownerID, $ownerName, $subject, $message, $status) { + + $GLOBALS['DATABASE']->query("INSERT INTO ".TICKETS_ANSWER." SET ticketID = ".$ticketID.", + ownerID = ".$ownerID.", + ownerName = '".$GLOBALS['DATABASE']->sql_escape($ownerName)."', + subject = '".$GLOBALS['DATABASE']->sql_escape($subject)."', + message = '".$GLOBALS['DATABASE']->sql_escape($message)."', + time = ".TIMESTAMP.";"); + $GLOBALS['DATABASE']->query("UPDATE ".TICKETS." SET status = ".$status." WHERE ticketID = ".$ticketID.";"); + + return $GLOBALS['DATABASE']->GetInsertID(); + } + + function getCategoryList() { + + $categoryResult = $GLOBALS['DATABASE']->query("SELECT * FROM ".TICKETS_CATEGORY.";"); + $categoryList = array(); + + while($categoryRow = $GLOBALS['DATABASE']->fetch_array($categoryResult)) { + $categoryList[$categoryRow['categoryID']] = $categoryRow['name']; + } + + $GLOBALS['DATABASE']->free_result($categoryResult); + + return $categoryList; + } +} diff --git a/includes/classes/class.phpmailer.php b/includes/classes/class.phpmailer.php deleted file mode 100644 index ae227a8..0000000 --- a/includes/classes/class.phpmailer.php +++ /dev/null @@ -1,2320 +0,0 @@ -exceptions = ($exceptions == true); - } - - /** - * Sets message type to HTML. - * @param bool $ishtml - * @return void - */ - public function IsHTML($ishtml = true) { - if ($ishtml) { - $this->ContentType = 'text/html'; - } else { - $this->ContentType = 'text/plain'; - } - } - - /** - * Sets Mailer to send message using SMTP. - * @return void - */ - public function IsSMTP() { - $this->Mailer = 'smtp'; - } - - /** - * Sets Mailer to send message using PHP mail() function. - * @return void - */ - public function IsMail() { - $this->Mailer = 'mail'; - } - - /** - * Sets Mailer to send message using the $Sendmail program. - * @return void - */ - public function IsSendmail() { - if (!stristr(ini_get('sendmail_path'), 'sendmail')) { - $this->Sendmail = '/var/qmail/bin/sendmail'; - } - $this->Mailer = 'sendmail'; - } - - /** - * Sets Mailer to send message using the qmail MTA. - * @return void - */ - public function IsQmail() { - if (stristr(ini_get('sendmail_path'), 'qmail')) { - $this->Sendmail = '/var/qmail/bin/sendmail'; - } - $this->Mailer = 'sendmail'; - } - - ///////////////////////////////////////////////// - // METHODS, RECIPIENTS - ///////////////////////////////////////////////// - - /** - * Adds a "To" address. - * @param string $address - * @param string $name - * @return boolean true on success, false if address already used - */ - public function AddAddress($address, $name = '') { - return $this->AddAnAddress('to', $address, $name); - } - - /** - * Adds a "Cc" address. - * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. - * @param string $address - * @param string $name - * @return boolean true on success, false if address already used - */ - public function AddCC($address, $name = '') { - return $this->AddAnAddress('cc', $address, $name); - } - - /** - * Adds a "Bcc" address. - * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. - * @param string $address - * @param string $name - * @return boolean true on success, false if address already used - */ - public function AddBCC($address, $name = '') { - return $this->AddAnAddress('bcc', $address, $name); - } - - /** - * Adds a "Reply-to" address. - * @param string $address - * @param string $name - * @return boolean - */ - public function AddReplyTo($address, $name = '') { - return $this->AddAnAddress('ReplyTo', $address, $name); - } - - /** - * Adds an address to one of the recipient arrays - * Addresses that have been added already return false, but do not throw exceptions - * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo' - * @param string $address The email address to send to - * @param string $name - * @return boolean true on success, false if address already used or invalid in some way - * @access private - */ - private function AddAnAddress($kind, $address, $name = '') { - if (!preg_match('/^(to|cc|bcc|ReplyTo)$/', $kind)) { - echo 'Invalid recipient array: ' . kind; - return false; - } - $address = trim($address); - $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim - if (!self::ValidateAddress($address)) { - $this->SetError($this->Lang('invalid_address').': '. $address); - if ($this->exceptions) { - throw new phpmailerException($this->Lang('invalid_address').': '.$address); - } - echo $this->Lang('invalid_address').': '.$address; - return false; - } - if ($kind != 'ReplyTo') { - if (!isset($this->all_recipients[strtolower($address)])) { - array_push($this->$kind, array($address, $name)); - $this->all_recipients[strtolower($address)] = true; - return true; - } - } else { - if (!array_key_exists(strtolower($address), $this->ReplyTo)) { - $this->ReplyTo[strtolower($address)] = array($address, $name); - return true; - } - } - return false; -} - -/** - * Set the From and FromName properties - * @param string $address - * @param string $name - * @return boolean - */ - public function SetFrom($address, $name = '',$auto=1) { - $address = trim($address); - $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim - if (!self::ValidateAddress($address)) { - $this->SetError($this->Lang('invalid_address').': '. $address); - if ($this->exceptions) { - throw new phpmailerException($this->Lang('invalid_address').': '.$address); - } - echo $this->Lang('invalid_address').': '.$address; - return false; - } - $this->From = $address; - $this->FromName = $name; - if ($auto) { - if (empty($this->ReplyTo)) { - $this->AddAnAddress('ReplyTo', $address, $name); - } - if (empty($this->Sender)) { - $this->Sender = $address; - } - } - return true; - } - - /** - * Check that a string looks roughly like an email address should - * Static so it can be used without instantiation - * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator - * Conforms approximately to RFC2822 - * @link http://www.hexillion.com/samples/#Regex Original pattern found here - * @param string $address The email address to check - * @return boolean - * @static - * @access public - */ - public static function ValidateAddress($address) { - if (function_exists('filter_var')) { //Introduced in PHP 5.2 - if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) { - return false; - } else { - return true; - } - } else { - return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address); - } - } - - ///////////////////////////////////////////////// - // METHODS, MAIL SENDING - ///////////////////////////////////////////////// - - /** - * Creates message and assigns Mailer. If the message is - * not sent successfully then it returns false. Use the ErrorInfo - * variable to view description of the error. - * @return bool - */ - public function Send() { - try { - if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { - throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL); - } - - // Set whether the message is multipart/alternative - if(!empty($this->AltBody)) { - $this->ContentType = 'multipart/alternative'; - } - - $this->error_count = 0; // reset errors - $this->SetMessageType(); - $header = $this->CreateHeader(); - $body = $this->CreateBody(); - - if (empty($this->Body)) { - throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL); - } - - // digitally sign with DKIM if enabled - if ($this->DKIM_domain && $this->DKIM_private) { - $header_dkim = $this->DKIM_Add($header,$this->Subject,$body); - $header = str_replace("\r\n","\n",$header_dkim) . $header; - } - - // Choose the mailer and send through it - switch($this->Mailer) { - case 'sendmail': - return $this->SendmailSend($header, $body); - case 'smtp': - return $this->SmtpSend($header, $body); - default: - return $this->MailSend($header, $body); - } - - } catch (phpmailerException $e) { - $this->SetError($e->getMessage()); - if ($this->exceptions) { - throw $e; - } - echo $e->getMessage()."\n"; - return false; - } - } - - /** - * Sends mail using the $Sendmail program. - * @param string $header The message headers - * @param string $body The message body - * @access protected - * @return bool - */ - protected function SendmailSend($header, $body) { - if ($this->Sender != '') { - $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender)); - } else { - $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail)); - } - if ($this->SingleTo === true) { - foreach ($this->SingleToArray as $key => $val) { - if(!@$mail = popen($sendmail, 'w')) { - throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - fputs($mail, "To: " . $val . "\n"); - fputs($mail, $header); - fputs($mail, $body); - $result = pclose($mail); - // implement call back function if it exists - $isSent = ($result == 0) ? 1 : 0; - $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body); - if($result != 0) { - throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - } - } else { - if(!@$mail = popen($sendmail, 'w')) { - throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - fputs($mail, $header); - fputs($mail, $body); - $result = pclose($mail); - // implement call back function if it exists - $isSent = ($result == 0) ? 1 : 0; - $this->doCallback($isSent,$this->to,$this->cc,$this->bcc,$this->Subject,$body); - if($result != 0) { - throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - } - return true; - } - - /** - * Sends mail using the PHP mail() function. - * @param string $header The message headers - * @param string $body The message body - * @access protected - * @return bool - */ - protected function MailSend($header, $body) { - $toArr = array(); - foreach($this->to as $t) { - $toArr[] = $this->AddrFormat($t); - } - $to = implode(', ', $toArr); - - $params = sprintf("-oi -f %s", $this->Sender); - if ($this->Sender != '' && strlen(ini_get('safe_mode'))< 1) { - $old_from = ini_get('sendmail_from'); - ini_set('sendmail_from', $this->Sender); - if ($this->SingleTo === true && count($toArr) > 1) { - foreach ($toArr as $key => $val) { - $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); - // implement call back function if it exists - $isSent = ($rt == 1) ? 1 : 0; - $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body); - } - } else { - $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); - // implement call back function if it exists - $isSent = ($rt == 1) ? 1 : 0; - $this->doCallback($isSent,$to,$this->cc,$this->bcc,$this->Subject,$body); - } - } else { - if ($this->SingleTo === true && count($toArr) > 1) { - foreach ($toArr as $key => $val) { - $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); - // implement call back function if it exists - $isSent = ($rt == 1) ? 1 : 0; - $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body); - } - } else { - $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header); - // implement call back function if it exists - $isSent = ($rt == 1) ? 1 : 0; - $this->doCallback($isSent,$to,$this->cc,$this->bcc,$this->Subject,$body); - } - } - if (isset($old_from)) { - ini_set('sendmail_from', $old_from); - } - if(!$rt) { - throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL); - } - return true; - } - - /** - * Sends mail via SMTP using PhpSMTP - * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. - * @param string $header The message headers - * @param string $body The message body - * @uses SMTP - * @access protected - * @return bool - */ - protected function SmtpSend($header, $body) { - require_once $this->PluginDir . 'class.smtp.php'; - $bad_rcpt = array(); - - if(!$this->SmtpConnect()) { - throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL); - } - $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender; - if(!$this->smtp->Mail($smtp_from)) { - throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL); - } - - // Attempt to send attach all recipients - foreach($this->to as $to) { - if (!$this->smtp->Recipient($to[0])) { - $bad_rcpt[] = $to[0]; - // implement call back function if it exists - $isSent = 0; - $this->doCallback($isSent,$to[0],'','',$this->Subject,$body); - } else { - // implement call back function if it exists - $isSent = 1; - $this->doCallback($isSent,$to[0],'','',$this->Subject,$body); - } - } - foreach($this->cc as $cc) { - if (!$this->smtp->Recipient($cc[0])) { - $bad_rcpt[] = $cc[0]; - // implement call back function if it exists - $isSent = 0; - $this->doCallback($isSent,'',$cc[0],'',$this->Subject,$body); - } else { - // implement call back function if it exists - $isSent = 1; - $this->doCallback($isSent,'',$cc[0],'',$this->Subject,$body); - } - } - foreach($this->bcc as $bcc) { - if (!$this->smtp->Recipient($bcc[0])) { - $bad_rcpt[] = $bcc[0]; - // implement call back function if it exists - $isSent = 0; - $this->doCallback($isSent,'','',$bcc[0],$this->Subject,$body); - } else { - // implement call back function if it exists - $isSent = 1; - $this->doCallback($isSent,'','',$bcc[0],$this->Subject,$body); - } - } - - - if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses - $badaddresses = implode(', ', $bad_rcpt); - throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses); - } - if(!$this->smtp->Data($header . $body)) { - throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL); - } - if($this->SMTPKeepAlive == true) { - $this->smtp->Reset(); - } - return true; - } - - /** - * Initiates a connection to an SMTP server. - * Returns false if the operation failed. - * @uses SMTP - * @access public - * @return bool - */ - public function SmtpConnect() { - if(is_null($this->smtp)) { - $this->smtp = new SMTP(); - } - - $this->smtp->do_debug = $this->SMTPDebug; - $hosts = explode(';', $this->Host); - $index = 0; - $connection = $this->smtp->Connected(); - - // Retry while there is no connection - try { - while($index < count($hosts) && !$connection) { - $hostinfo = array(); - if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) { - $host = $hostinfo[1]; - $port = $hostinfo[2]; - } else { - $host = $hosts[$index]; - $port = $this->Port; - } - - $tls = ($this->SMTPSecure == 'tls'); - $ssl = ($this->SMTPSecure == 'ssl'); - - if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) { - - $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname()); - $this->smtp->Hello($hello); - - if ($tls) { - if (!$this->smtp->StartTLS()) { - throw new phpmailerException($this->Lang('tls')); - } - - //We must resend HELO after tls negotiation - $this->smtp->Hello($hello); - } - - $connection = true; - if ($this->SMTPAuth) { - if (!$this->smtp->Authenticate($this->Username, $this->Password)) { - throw new phpmailerException($this->Lang('authenticate')); - } - } - } - $index++; - if (!$connection) { - throw new phpmailerException($this->Lang('connect_host')); - } - } - } catch (phpmailerException $e) { - $this->smtp->Reset(); - throw $e; - } - return true; - } - - /** - * Closes the active SMTP session if one exists. - * @return void - */ - public function SmtpClose() { - if(!is_null($this->smtp)) { - if($this->smtp->Connected()) { - $this->smtp->Quit(); - $this->smtp->Close(); - } - } - } - - /** - * Sets the language for all class error messages. - * Returns false if it cannot load the language file. The default language is English. - * @param string $LNGcode ISO 639-1 2-character language code (e.g. Portuguese: "br") - * @param string $LNG_path Path to the language file directory - * @access public - */ - function SetLanguage($LNGcode = 'en', $LNG_path = 'language/') { - //Define full set of translatable strings - $PHPMAILER_LANG = array( - 'provide_address' => 'You must provide at least one recipient email address.', - 'mailer_not_supported' => ' mailer is not supported.', - 'execute' => 'Could not execute: ', - 'instantiate' => 'Could not instantiate mail function.', - 'authenticate' => 'SMTP Error: Could not authenticate.', - 'from_failed' => 'The following From address failed: ', - 'recipients_failed' => 'SMTP Error: The following recipients failed: ', - 'data_not_accepted' => 'SMTP Error: Data not accepted.', - 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', - 'file_access' => 'Could not access file: ', - 'file_open' => 'File Error: Could not open file: ', - 'encoding' => 'Unknown encoding: ', - 'signing' => 'Signing Error: ', - 'smtp_error' => 'SMTP server error: ', - 'empty_message' => 'Message body empty', - 'invalid_address' => 'Invalid address', - 'variable_set' => 'Cannot set or reset variable: ' - ); - //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"! - $l = true; - if ($LNGcode != 'en') { //There is no English translation file - $l = @include $LNG_path.'phpmailer.lang-'.$LNGcode.'.php'; - } - $this->language = $PHPMAILER_LANG; - return ($l == true); //Returns false if language not found - } - - /** - * Return the current array of language strings - * @return array - */ - public function GetTranslations() { - return $this->language; - } - - ///////////////////////////////////////////////// - // METHODS, MESSAGE CREATION - ///////////////////////////////////////////////// - - /** - * Creates recipient headers. - * @access public - * @return string - */ - public function AddrAppend($type, $addr) { - $addr_str = $type . ': '; - $addresses = array(); - foreach ($addr as $a) { - $addresses[] = $this->AddrFormat($a); - } - $addr_str .= implode(', ', $addresses); - $addr_str .= $this->LE; - - return $addr_str; - } - - /** - * Formats an address correctly. - * @access public - * @return string - */ - public function AddrFormat($addr) { - if (empty($addr[1])) { - return $this->SecureHeader($addr[0]); - } else { - return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">"; - } - } - - /** - * Wraps message for use with mailers that do not - * automatically perform wrapping and for quoted-printable. - * Original written by philippe. - * @param string $message The message to wrap - * @param integer $length The line length to wrap to - * @param boolean $qp_mode Whether to run in Quoted-Printable mode - * @access public - * @return string - */ - public function WrapText($message, $length, $qp_mode = false) { - $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE; - // If utf-8 encoding is used, we will need to make sure we don't - // split multibyte characters when we wrap - $is_utf8 = (strtolower($this->CharSet) == "utf-8"); - - $message = $this->FixEOL($message); - if (substr($message, -1) == $this->LE) { - $message = substr($message, 0, -1); - } - - $line = explode($this->LE, $message); - $message = ''; - for ($i=0 ;$i < count($line); $i++) { - $line_part = explode(' ', $line[$i]); - $buf = ''; - for ($e = 0; $e $length)) { - $space_left = $length - strlen($buf) - 1; - if ($e != 0) { - if ($space_left > 20) { - $len = $space_left; - if ($is_utf8) { - $len = $this->UTF8CharBoundary($word, $len); - } elseif (substr($word, $len - 1, 1) == "=") { - $len--; - } elseif (substr($word, $len - 2, 1) == "=") { - $len -= 2; - } - $part = substr($word, 0, $len); - $word = substr($word, $len); - $buf .= ' ' . $part; - $message .= $buf . sprintf("=%s", $this->LE); - } else { - $message .= $buf . $soft_break; - } - $buf = ''; - } - while (strlen($word) > 0) { - $len = $length; - if ($is_utf8) { - $len = $this->UTF8CharBoundary($word, $len); - } elseif (substr($word, $len - 1, 1) == "=") { - $len--; - } elseif (substr($word, $len - 2, 1) == "=") { - $len -= 2; - } - $part = substr($word, 0, $len); - $word = substr($word, $len); - - if (strlen($word) > 0) { - $message .= $part . sprintf("=%s", $this->LE); - } else { - $buf = $part; - } - } - } else { - $buf_o = $buf; - $buf .= ($e == 0) ? $word : (' ' . $word); - - if (strlen($buf) > $length and $buf_o != '') { - $message .= $buf_o . $soft_break; - $buf = $word; - } - } - } - $message .= $buf . $this->LE; - } - - return $message; - } - - /** - * Finds last character boundary prior to maxLength in a utf-8 - * quoted (printable) encoded string. - * Original written by Colin Brown. - * @access public - * @param string $encodedText utf-8 QP text - * @param int $maxLength find last character boundary prior to this length - * @return int - */ - public function UTF8CharBoundary($encodedText, $maxLength) { - $foundSplitPos = false; - $lookBack = 3; - while (!$foundSplitPos) { - $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); - $encodedCharPos = strpos($lastChunk, "="); - if ($encodedCharPos !== false) { - // Found start of encoded character byte within $lookBack block. - // Check the encoded byte value (the 2 chars after the '=') - $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); - $dec = hexdec($hex); - if ($dec < 128) { // Single byte character. - // If the encoded char was found at pos 0, it will fit - // otherwise reduce maxLength to start of the encoded char - $maxLength = ($encodedCharPos == 0) ? $maxLength : - $maxLength - ($lookBack - $encodedCharPos); - $foundSplitPos = true; - } elseif ($dec >= 192) { // First byte of a multi byte character - // Reduce maxLength to split at start of character - $maxLength = $maxLength - ($lookBack - $encodedCharPos); - $foundSplitPos = true; - } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back - $lookBack += 3; - } - } else { - // No encoded character found - $foundSplitPos = true; - } - } - return $maxLength; - } - - - /** - * Set the body wrapping. - * @access public - * @return void - */ - public function SetWordWrap() { - if($this->WordWrap < 1) { - return; - } - - switch($this->message_type) { - case 'alt': - case 'alt_attachments': - $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap); - break; - default: - $this->Body = $this->WrapText($this->Body, $this->WordWrap); - break; - } - } - - /** - * Assembles message header. - * @access public - * @return string The assembled header - */ - public function CreateHeader() { - $result = ''; - - // Set the boundaries - $uniq_id = md5(uniqid(TIMESTAMP)); - $this->boundary[1] = 'b1_' . $uniq_id; - $this->boundary[2] = 'b2_' . $uniq_id; - - $result .= $this->HeaderLine('Date', self::RFCDate()); - if($this->Sender == '') { - $result .= $this->HeaderLine('Return-Path', trim($this->From)); - } else { - $result .= $this->HeaderLine('Return-Path', trim($this->Sender)); - } - - // To be created automatically by mail() - if($this->Mailer != 'mail') { - if ($this->SingleTo === true) { - foreach($this->to as $t) { - $this->SingleToArray[] = $this->AddrFormat($t); - } - } else { - if(count($this->to) > 0) { - $result .= $this->AddrAppend('To', $this->to); - } elseif (count($this->cc) == 0) { - $result .= $this->HeaderLine('To', 'undisclosed-recipients:;'); - } - } - } - - $from = array(); - $from[0][0] = trim($this->From); - $from[0][1] = $this->FromName; - $result .= $this->AddrAppend('From', $from); - - // sendmail and mail() extract Cc from the header before sending - if(count($this->cc) > 0) { - $result .= $this->AddrAppend('Cc', $this->cc); - } - - // sendmail and mail() extract Bcc from the header before sending - if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) { - $result .= $this->AddrAppend('Bcc', $this->bcc); - } - - if(count($this->ReplyTo) > 0) { - $result .= $this->AddrAppend('Reply-to', $this->ReplyTo); - } - - // mail() sets the subject itself - if($this->Mailer != 'mail') { - $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject))); - } - - if($this->MessageID != '') { - $result .= $this->HeaderLine('Message-ID',$this->MessageID); - } else { - $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE); - } - $result .= $this->HeaderLine('X-Priority', $this->Priority); - $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (phpmailer.sourceforge.net)'); - - if($this->ConfirmReadingTo != '') { - $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>'); - } - - // Add custom headers - for($index = 0; $index < count($this->CustomHeader); $index++) { - $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1]))); - } - if (!$this->sign_key_file) { - $result .= $this->HeaderLine('MIME-Version', '1.0'); - $result .= $this->GetMailMIME(); - } - - return $result; - } - - /** - * Returns the message MIME. - * @access public - * @return string - */ - public function GetMailMIME() { - $result = ''; - switch($this->message_type) { - case 'plain': - $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding); - $result .= sprintf("Content-Type: %s; charset=\"%s\"", $this->ContentType, $this->CharSet); - break; - case 'attachments': - case 'alt_attachments': - if($this->InlineImageExists()){ - $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s", 'multipart/related', $this->LE, $this->LE, $this->boundary[1], $this->LE); - } else { - $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;'); - $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); - } - break; - case 'alt': - $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); - $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); - break; - } - - if($this->Mailer != 'mail') { - $result .= $this->LE.$this->LE; - } - - return $result; - } - - /** - * Assembles the message body. Returns an empty string on failure. - * @access public - * @return string The assembled message body - */ - public function CreateBody() { - $body = ''; - - if ($this->sign_key_file) { - $body .= $this->GetMailMIME(); - } - - $this->SetWordWrap(); - - switch($this->message_type) { - case 'alt': - $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); - $body .= $this->EncodeString($this->AltBody, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', ''); - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->EndBoundary($this->boundary[1]); - break; - case 'plain': - $body .= $this->EncodeString($this->Body, $this->Encoding); - break; - case 'attachments': - $body .= $this->GetBoundary($this->boundary[1], '', '', ''); - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE; - $body .= $this->AttachAll(); - break; - case 'alt_attachments': - $body .= sprintf("--%s%s", $this->boundary[1], $this->LE); - $body .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE.$this->LE); - $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '') . $this->LE; // Create text body - $body .= $this->EncodeString($this->AltBody, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '') . $this->LE; // Create the HTML body - $body .= $this->EncodeString($this->Body, $this->Encoding); - $body .= $this->LE.$this->LE; - $body .= $this->EndBoundary($this->boundary[2]); - $body .= $this->AttachAll(); - break; - } - - if ($this->IsError()) { - $body = ''; - } elseif ($this->sign_key_file) { - try { - $file = tempnam('', 'mail'); - file_put_contents($file, $body); //TODO check this worked - $signed = tempnam("", "signed"); - if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) { - @unlink($file); - @unlink($signed); - $body = file_get_contents($signed); - } else { - @unlink($file); - @unlink($signed); - throw new phpmailerException($this->Lang("signing").openssl_error_string()); - } - } catch (phpmailerException $e) { - $body = ''; - if ($this->exceptions) { - throw $e; - } - } - } - - return $body; - } - - /** - * Returns the start of a message boundary. - * @access private - */ - private function GetBoundary($boundary, $charSet, $contentType, $encoding) { - $result = ''; - if($charSet == '') { - $charSet = $this->CharSet; - } - if($contentType == '') { - $contentType = $this->ContentType; - } - if($encoding == '') { - $encoding = $this->Encoding; - } - $result .= $this->TextLine('--' . $boundary); - $result .= sprintf("Content-Type: %s; charset = \"%s\"", $contentType, $charSet); - $result .= $this->LE; - $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding); - $result .= $this->LE; - - return $result; - } - - /** - * Returns the end of a message boundary. - * @access private - */ - private function EndBoundary($boundary) { - return $this->LE . '--' . $boundary . '--' . $this->LE; - } - - /** - * Sets the message type. - * @access private - * @return void - */ - private function SetMessageType() { - if(count($this->attachment) < 1 && strlen($this->AltBody) < 1) { - $this->message_type = 'plain'; - } else { - if(count($this->attachment) > 0) { - $this->message_type = 'attachments'; - } - if(strlen($this->AltBody) > 0 && count($this->attachment) < 1) { - $this->message_type = 'alt'; - } - if(strlen($this->AltBody) > 0 && count($this->attachment) > 0) { - $this->message_type = 'alt_attachments'; - } - } - } - - /** - * Returns a formatted header line. - * @access public - * @return string - */ - public function HeaderLine($name, $value) { - return $name . ': ' . $value . $this->LE; - } - - /** - * Returns a formatted mail line. - * @access public - * @return string - */ - public function TextLine($value) { - return $value . $this->LE; - } - - ///////////////////////////////////////////////// - // CLASS METHODS, ATTACHMENTS - ///////////////////////////////////////////////// - - /** - * Adds an attachment from a path on the filesystem. - * Returns false if the file could not be found - * or accessed. - * @param string $path Path to the attachment. - * @param string $name Overrides the attachment name. - * @param string $encoding File encoding (see $Encoding). - * @param string $type File extension (MIME) type. - * @return bool - */ - public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { - try { - if ( !@is_file($path) ) { - throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE); - } - $filename = basename($path); - if ( $name == '' ) { - $name = $filename; - } - - $this->attachment[] = array( - 0 => $path, - 1 => $filename, - 2 => $name, - 3 => $encoding, - 4 => $type, - 5 => false, // isStringAttachment - 6 => 'attachment', - 7 => 0 - ); - - } catch (phpmailerException $e) { - $this->SetError($e->getMessage()); - if ($this->exceptions) { - throw $e; - } - echo $e->getMessage()."\n"; - if ( $e->getCode() == self::STOP_CRITICAL ) { - return false; - } - } - return true; - } - - /** - * Return the current array of attachments - * @return array - */ - public function GetAttachments() { - return $this->attachment; - } - - /** - * Attaches all fs, string, and binary attachments to the message. - * Returns an empty string on failure. - * @access private - * @return string - */ - private function AttachAll() { - // Return text of body - $mime = array(); - $cidUniq = array(); - $incl = array(); - - // Add all attachments - foreach ($this->attachment as $attachment) { - // Check for string attachment - $bString = $attachment[5]; - if ($bString) { - $string = $attachment[0]; - } else { - $path = $attachment[0]; - } - - if (in_array($attachment[0], $incl)) { continue; } - $filename = $attachment[1]; - $name = $attachment[2]; - $encoding = $attachment[3]; - $type = $attachment[4]; - $disposition = $attachment[6]; - $cid = $attachment[7]; - $incl[] = $attachment[0]; - if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; } - $cidUniq[$cid] = true; - - $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE); - $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE); - $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE); - - if($disposition == 'inline') { - $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE); - } - - $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE); - - // Encode as string attachment - if($bString) { - $mime[] = $this->EncodeString($string, $encoding); - if($this->IsError()) { - return ''; - } - $mime[] = $this->LE.$this->LE; - } else { - $mime[] = $this->EncodeFile($path, $encoding); - if($this->IsError()) { - return ''; - } - $mime[] = $this->LE.$this->LE; - } - } - - $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE); - - return join('', $mime); - } - - /** - * Encodes attachment in requested format. - * Returns an empty string on failure. - * @param string $path The full path to the file - * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' - * @see EncodeFile() - * @access private - * @return string - */ - private function EncodeFile($path, $encoding = 'base64') { - try { - if (!is_readable($path)) { - throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE); - } - if (function_exists('get_magic_quotes')) { - function get_magic_quotes() { - return false; - } - } - if (PHP_VERSION < 6) { - $magic_quotes = get_magic_quotes_runTIMESTAMP; - set_magic_quotes_runtime(0); - } - $file_buffer = file_get_contents($path); - $file_buffer = $this->EncodeString($file_buffer, $encoding); - if (PHP_VERSION < 6) { set_magic_quotes_runtime($magic_quotes); } - return $file_buffer; - } catch (Exception $e) { - $this->SetError($e->getMessage()); - return ''; - } - } - - /** - * Encodes string to requested format. - * Returns an empty string on failure. - * @param string $str The text to encode - * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' - * @access public - * @return string - */ - public function EncodeString ($str, $encoding = 'base64') { - $encoded = ''; - switch(strtolower($encoding)) { - case 'base64': - $encoded = chunk_split(base64_encode($str), 76, $this->LE); - break; - case '7bit': - case '8bit': - $encoded = $this->FixEOL($str); - //Make sure it ends with a line break - if (substr($encoded, -(strlen($this->LE))) != $this->LE) - $encoded .= $this->LE; - break; - case 'binary': - $encoded = $str; - break; - case 'quoted-printable': - $encoded = $this->EncodeQP($str); - break; - default: - $this->SetError($this->Lang('encoding') . $encoding); - break; - } - return $encoded; - } - - /** - * Encode a header string to best (shortest) of Q, B, quoted or none. - * @access public - * @return string - */ - public function EncodeHeader($str, $position = 'text') { - $x = 0; - - switch (strtolower($position)) { - case 'phrase': - if (!preg_match('/[\200-\377]/', $str)) { - // Can't use addslashes as we don't know what value has magic_quotes_sybase - $encoded = addcslashes($str, "\0..\37\177\\\""); - if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { - return ($encoded); - } else { - return ("\"$encoded\""); - } - } - $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); - break; - case 'comment': - $x = preg_match_all('/[()"]/', $str, $matches); - // Fall-through - case 'text': - default: - $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); - break; - } - - if ($x == 0) { - return ($str); - } - - $maxlen = 75 - 7 - strlen($this->CharSet); - // Try to select the encoding which should produce the shortest output - if (strlen($str)/3 < $x) { - $encoding = 'B'; - if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) { - // Use a custom function which correctly encodes and wraps long - // multibyte strings without breaking lines within a character - $encoded = $this->Base64EncodeWrapMB($str); - } else { - $encoded = base64_encode($str); - $maxlen -= $maxlen % 4; - $encoded = trim(chunk_split($encoded, $maxlen, "\n")); - } - } else { - $encoding = 'Q'; - $encoded = $this->EncodeQ($str, $position); - $encoded = $this->WrapText($encoded, $maxlen, true); - $encoded = str_replace('='.$this->LE, "\n", trim($encoded)); - } - - $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded); - $encoded = trim(str_replace("\n", $this->LE, $encoded)); - - return $encoded; - } - - /** - * Checks if a string contains multibyte characters. - * @access public - * @param string $str multi-byte text to wrap encode - * @return bool - */ - public function HasMultiBytes($str) { - if (function_exists('mb_strlen')) { - return (strlen($str) > mb_strlen($str, $this->CharSet)); - } else { // Assume no multibytes (we can't handle without mbstring functions anyway) - return false; - } - } - - /** - * Correctly encodes and wraps long multibyte strings for mail headers - * without breaking lines within a character. - * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php - * @access public - * @param string $str multi-byte text to wrap encode - * @return string - */ - public function Base64EncodeWrapMB($str) { - $start = "=?".$this->CharSet."?B?"; - $end = "?="; - $encoded = ""; - - $mb_length = mb_strlen($str, $this->CharSet); - // Each line must have length <= 75, including $start and $end - $length = 75 - strlen($start) - strlen($end); - // Average multi-byte ratio - $ratio = $mb_length / strlen($str); - // Base64 has a 4:3 ratio - $offset = $avgLength = floor($length * $ratio * .75); - - for ($i = 0; $i < $mb_length; $i += $offset) { - $lookBack = 0; - - do { - $offset = $avgLength - $lookBack; - $chunk = mb_substr($str, $i, $offset, $this->CharSet); - $chunk = base64_encode($chunk); - $lookBack++; - } - while (strlen($chunk) > $length); - - $encoded .= $chunk . $this->LE; - } - - // Chomp the last linefeed - $encoded = substr($encoded, 0, -strlen($this->LE)); - return $encoded; - } - - /** - * Encode string to quoted-printable. - * Only uses standard PHP, slow, but will always work - * @access public - * @param string $string the text to encode - * @param integer $line_max Number of chars allowed on a line before wrapping - * @return string - */ - public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) { - $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'); - $lines = preg_split('/(?:\r\n|\r|\n)/', $input); - $eol = "\r\n"; - $escape = '='; - $output = ''; - while( list(, $line) = each($lines) ) { - $linlen = strlen($line); - $newline = ''; - for($i = 0; $i < $linlen; $i++) { - $c = substr( $line, $i, 1 ); - $dec = ord( $c ); - if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E - $c = '=2E'; - } - if ( $dec == 32 ) { - if ( $i == ( $linlen - 1 ) ) { // convert space at eol only - $c = '=20'; - } else if ( $space_conv ) { - $c = '=20'; - } - } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required - $h2 = floor($dec/16); - $h1 = floor($dec%16); - $c = $escape.$hex[$h2].$hex[$h1]; - } - if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted - $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay - $newline = ''; - // check if newline first character will be point or not - if ( $dec == 46 ) { - $c = '=2E'; - } - } - $newline .= $c; - } // end of for - $output .= $newline.$eol; - } // end of while - return $output; - } - - /** - * Encode string to RFC2045 (6.7) quoted-printable format - * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version - * Also results in same content as you started with after decoding - * @see EncodeQPphp() - * @access public - * @param string $string the text to encode - * @param integer $line_max Number of chars allowed on a line before wrapping - * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function - * @return string - * @author Marcus Bointon - */ - public function EncodeQP($string, $line_max = 76, $space_conv = false) { - if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3) - return quoted_printable_encode($string); - } - $filters = stream_get_filters(); - if (!in_array('convert.*', $filters)) { //Got convert stream filter? - return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation - } - $fp = fopen('php://temp/', 'r+'); - $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks - $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE); - $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params); - fputs($fp, $string); - rewind($fp); - $out = stream_get_contents($fp); - stream_filter_remove($s); - $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange - fclose($fp); - return $out; - } - - /** - * Encode string to q encoding. - * @link http://tools.ietf.org/html/rfc2047 - * @param string $str the text to encode - * @param string $position Where the text is going to be used, see the RFC for what that means - * @access public - * @return string - */ - public function EncodeQ ($str, $position = 'text') { - // There should not be any EOL in the string - $encoded = preg_replace('/[\r\n]*/', '', $str); - - switch (strtolower($position)) { - case 'phrase': - $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded); - break; - case 'comment': - $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded); - case 'text': - default: - // Replace every high ascii, control =, ? and _ characters - //TODO using /e (equivalent to eval()) is probably not a good idea - $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e', - "'='.sprintf('%02X', ord('\\1'))", $encoded); - break; - } - - // Replace every spaces to _ (more readable than =20) - $encoded = str_replace(' ', '_', $encoded); - - return $encoded; - } - - /** - * Adds a string or binary attachment (non-filesystem) to the list. - * This method can be used to attach ascii or binary data, - * such as a BLOB record from a database. - * @param string $string String attachment data. - * @param string $filename Name of the attachment. - * @param string $encoding File encoding (see $Encoding). - * @param string $type File extension (MIME) type. - * @return void - */ - public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') { - // Append to $attachment array - $this->attachment[] = array( - 0 => $string, - 1 => $filename, - 2 => basename($filename), - 3 => $encoding, - 4 => $type, - 5 => true, // isStringAttachment - 6 => 'attachment', - 7 => 0 - ); - } - - /** - * Adds an embedded attachment. This can include images, sounds, and - * just about any other document. Make sure to set the $type to an - * image type. For JPEG images use "image/jpeg" and for GIF images - * use "image/gif". - * @param string $path Path to the attachment. - * @param string $cid Content ID of the attachment. Use this to identify - * the Id for accessing the image in an HTML form. - * @param string $name Overrides the attachment name. - * @param string $encoding File encoding (see $Encoding). - * @param string $type File extension (MIME) type. - * @return bool - */ - public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { - - if ( !@is_file($path) ) { - $this->SetError($this->Lang('file_access') . $path); - return false; - } - - $filename = basename($path); - if ( $name == '' ) { - $name = $filename; - } - - // Append to $attachment array - $this->attachment[] = array( - 0 => $path, - 1 => $filename, - 2 => $name, - 3 => $encoding, - 4 => $type, - 5 => false, // isStringAttachment - 6 => 'inline', - 7 => $cid - ); - - return true; - } - - /** - * Returns true if an inline attachment is present. - * @access public - * @return bool - */ - public function InlineImageExists() { - foreach($this->attachment as $attachment) { - if ($attachment[6] == 'inline') { - return true; - } - } - return false; - } - - ///////////////////////////////////////////////// - // CLASS METHODS, MESSAGE RESET - ///////////////////////////////////////////////// - - /** - * Clears all recipients assigned in the TO array. Returns void. - * @return void - */ - public function ClearAddresses() { - foreach($this->to as $to) { - unset($this->all_recipients[strtolower($to[0])]); - } - $this->to = array(); - } - - /** - * Clears all recipients assigned in the CC array. Returns void. - * @return void - */ - public function ClearCCs() { - foreach($this->cc as $cc) { - unset($this->all_recipients[strtolower($cc[0])]); - } - $this->cc = array(); - } - - /** - * Clears all recipients assigned in the BCC array. Returns void. - * @return void - */ - public function ClearBCCs() { - foreach($this->bcc as $bcc) { - unset($this->all_recipients[strtolower($bcc[0])]); - } - $this->bcc = array(); - } - - /** - * Clears all recipients assigned in the ReplyTo array. Returns void. - * @return void - */ - public function ClearReplyTos() { - $this->ReplyTo = array(); - } - - /** - * Clears all recipients assigned in the TO, CC and BCC - * array. Returns void. - * @return void - */ - public function ClearAllRecipients() { - $this->to = array(); - $this->cc = array(); - $this->bcc = array(); - $this->all_recipients = array(); - } - - /** - * Clears all previously set filesystem, string, and binary - * attachments. Returns void. - * @return void - */ - public function ClearAttachments() { - $this->attachment = array(); - } - - /** - * Clears all custom headers. Returns void. - * @return void - */ - public function ClearCustomHeaders() { - $this->CustomHeader = array(); - } - - ///////////////////////////////////////////////// - // CLASS METHODS, MISCELLANEOUS - ///////////////////////////////////////////////// - - /** - * Adds the error message to the error container. - * @access protected - * @return void - */ - protected function SetError($msg) { - $this->error_count++; - if ($this->Mailer == 'smtp' and !is_null($this->smtp)) { - $lasterror = $this->smtp->getError(); - if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) { - $msg .= '

' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "

\n"; - } - } - $this->ErrorInfo = $msg; - } - - /** - * Returns the proper RFC 822 formatted date. - * @access public - * @return string - * @static - */ - public static function RFCDate() { - $tz = date('Z'); - $tzs = ($tz < 0) ? '-' : '+'; - $tz = abs($tz); - $tz = (int)($tz/3600)*100 + ($tz%3600)/60; - $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz); - - return $result; - } - - /** - * Returns the server hostname or 'localhost.localdomain' if unknown. - * @access private - * @return string - */ - private function ServerHostname() { - if (!empty($this->Hostname)) { - $result = $this->Hostname; - } elseif (isset($_SERVER['SERVER_NAME'])) { - $result = $_SERVER['SERVER_NAME']; - } else { - $result = 'localhost.localdomain'; - } - - return $result; - } - - /** - * Returns a message in the appropriate language. - * @access private - * @return string - */ - private function Lang($key) { - if(count($this->language) < 1) { - $this->SetLanguage('en'); // set the default language - } - - if(isset($this->language[$key])) { - return $this->language[$key]; - } else { - return 'Language string failed to load: ' . $key; - } - } - - /** - * Returns true if an error occurred. - * @access public - * @return bool - */ - public function IsError() { - return ($this->error_count > 0); - } - - /** - * Changes every end of line from CR or LF to CRLF. - * @access private - * @return string - */ - private function FixEOL($str) { - $str = str_replace("\r\n", "\n", $str); - $str = str_replace("\r", "\n", $str); - $str = str_replace("\n", $this->LE, $str); - return $str; - } - - /** - * Adds a custom header. - * @access public - * @return void - */ - public function AddCustomHeader($custom_header) { - $this->CustomHeader[] = explode(':', $custom_header, 2); - } - - /** - * Evaluates the message and returns modifications for inline images and backgrounds - * @access public - * @return $message - */ - public function MsgHTML($message, $basedir = '') { - preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images); - if(isset($images[2])) { - foreach($images[2] as $i => $url) { - // do not change urls for absolute images (thanks to corvuscorax) - if (!preg_match('#^[A-z]+://#',$url)) { - $filename = basename($url); - $directory = dirname($url); - ($directory == '.')?$directory='':''; - $cid = 'cid:' . md5($filename); - $ext = pathinfo($filename, PATHINFO_EXTENSION); - $mimeType = self::_mime_types($ext); - if ( strlen($basedir) > 1 && substr($basedir,-1) != '/') { $basedir .= '/'; } - if ( strlen($directory) > 1 && substr($directory,-1) != '/') { $directory .= '/'; } - if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64',$mimeType) ) { - $message = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $message); - } - } - } - } - $this->IsHTML(true); - $this->Body = $message; - $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message))); - if (!empty($textMsg) && empty($this->AltBody)) { - $this->AltBody = html_entity_decode($textMsg); - } - if (empty($this->AltBody)) { - $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n"; - } - } - - /** - * Gets the MIME type of the embedded or inline image - * @param string File extension - * @access public - * @return string MIME type of ext - * @static - */ - public static function _mime_types($ext = '') { - $mimes = array( - 'hqx' => 'application/mac-binhex40', - 'cpt' => 'application/mac-compactpro', - 'doc' => 'application/msword', - 'bin' => 'application/macbinary', - 'dms' => 'application/octet-stream', - 'lha' => 'application/octet-stream', - 'lzh' => 'application/octet-stream', - 'exe' => 'application/octet-stream', - 'class' => 'application/octet-stream', - 'psd' => 'application/octet-stream', - 'so' => 'application/octet-stream', - 'sea' => 'application/octet-stream', - 'dll' => 'application/octet-stream', - 'oda' => 'application/oda', - 'pdf' => 'application/pdf', - 'ai' => 'application/postscript', - 'eps' => 'application/postscript', - 'ps' => 'application/postscript', - 'smi' => 'application/smil', - 'smil' => 'application/smil', - 'mif' => 'application/vnd.mif', - 'xls' => 'application/vnd.ms-excel', - 'ppt' => 'application/vnd.ms-powerpoint', - 'wbxml' => 'application/vnd.wap.wbxml', - 'wmlc' => 'application/vnd.wap.wmlc', - 'dcr' => 'application/x-director', - 'dir' => 'application/x-director', - 'dxr' => 'application/x-director', - 'dvi' => 'application/x-dvi', - 'gtar' => 'application/x-gtar', - 'php' => 'application/x-httpd-php', - 'php4' => 'application/x-httpd-php', - 'php3' => 'application/x-httpd-php', - 'phtml' => 'application/x-httpd-php', - 'phps' => 'application/x-httpd-php-source', - 'js' => 'application/x-javascript', - 'swf' => 'application/x-shockwave-flash', - 'sit' => 'application/x-stuffit', - 'tar' => 'application/x-tar', - 'tgz' => 'application/x-tar', - 'xhtml' => 'application/xhtml+xml', - 'xht' => 'application/xhtml+xml', - 'zip' => 'application/zip', - 'mid' => 'audio/midi', - 'midi' => 'audio/midi', - 'mpga' => 'audio/mpeg', - 'mp2' => 'audio/mpeg', - 'mp3' => 'audio/mpeg', - 'aif' => 'audio/x-aiff', - 'aiff' => 'audio/x-aiff', - 'aifc' => 'audio/x-aiff', - 'ram' => 'audio/x-pn-realaudio', - 'rm' => 'audio/x-pn-realaudio', - 'rpm' => 'audio/x-pn-realaudio-plugin', - 'ra' => 'audio/x-realaudio', - 'rv' => 'video/vnd.rn-realvideo', - 'wav' => 'audio/x-wav', - 'bmp' => 'image/bmp', - 'gif' => 'image/gif', - 'jpeg' => 'image/jpeg', - 'jpg' => 'image/jpeg', - 'jpe' => 'image/jpeg', - 'png' => 'image/png', - 'tiff' => 'image/tiff', - 'tif' => 'image/tiff', - 'css' => 'text/css', - 'html' => 'text/html', - 'htm' => 'text/html', - 'shtml' => 'text/html', - 'txt' => 'text/plain', - 'text' => 'text/plain', - 'log' => 'text/plain', - 'rtx' => 'text/richtext', - 'rtf' => 'text/rtf', - 'xml' => 'text/xml', - 'xsl' => 'text/xml', - 'mpeg' => 'video/mpeg', - 'mpg' => 'video/mpeg', - 'mpe' => 'video/mpeg', - 'qt' => 'video/quicktime', - 'mov' => 'video/quicktime', - 'avi' => 'video/x-msvideo', - 'movie' => 'video/x-sgi-movie', - 'doc' => 'application/msword', - 'word' => 'application/msword', - 'xl' => 'application/excel', - 'eml' => 'message/rfc822' - ); - return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)]; - } - - /** - * Set (or reset) Class Objects (variables) - * - * Usage Example: - * $page->set('X-Priority', '3'); - * - * @access public - * @param string $name Parameter Name - * @param mixed $value Parameter Value - * NOTE: will not work with arrays, there are no arrays to set/reset - * @todo Should this not be using __set() magic function? - */ - public function set($name, $value = '') { - try { - if (isset($this->$name) ) { - $this->$name = $value; - } else { - throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL); - } - } catch (Exception $e) { - $this->SetError($e->getMessage()); - if ($e->getCode() == self::STOP_CRITICAL) { - return false; - } - } - return true; - } - - /** - * Strips newlines to prevent header injection. - * @access public - * @param string $str String - * @return string - */ - public function SecureHeader($str) { - $str = str_replace("\r", '', $str); - $str = str_replace("\n", '', $str); - return trim($str); - } - - /** - * Set the private key file and password to sign the message. - * - * @access public - * @param string $key_filename Parameter File Name - * @param string $key_pass Password for private key - */ - public function Sign($cert_filename, $key_filename, $key_pass) { - $this->sign_cert_file = $cert_filename; - $this->sign_key_file = $key_filename; - $this->sign_key_pass = $key_pass; - } - - /** - * Set the private key file and password to sign the message. - * - * @access public - * @param string $key_filename Parameter File Name - * @param string $key_pass Password for private key - */ - public function DKIM_QP($txt) { - $tmp=""; - $line=""; - for ($i=0;$iDKIM_private); - if ($this->DKIM_passphrase!='') { - $privKey = openssl_pkey_get_private($privKeyStr,$this->DKIM_passphrase); - } else { - $privKey = $privKeyStr; - } - if (openssl_sign($s, $signature, $privKey)) { - return base64_encode($signature); - } - } - - /** - * Generate DKIM Canonicalization Header - * - * @access public - * @param string $s Header - */ - public function DKIM_HeaderC($s) { - $s=preg_replace("/\r\n\s+/"," ",$s); - $lines=explode("\r\n",$s); - foreach ($lines as $key=>$line) { - list($heading,$value)=explode(":",$line,2); - $heading=strtolower($heading); - $value=preg_replace("/\s+/"," ",$value) ; // Compress useless spaces - $lines[$key]=$heading.":".trim($value) ; // Don't forget to remove WSP around the value - } - $s=implode("\r\n",$lines); - return $s; - } - - /** - * Generate DKIM Canonicalization Body - * - * @access public - * @param string $body Message Body - */ - public function DKIM_BodyC($body) { - if ($body == '') return "\r\n"; - // stabilize line endings - $body=str_replace("\r\n","\n",$body); - $body=str_replace("\n","\r\n",$body); - // END stabilize line endings - while (substr($body,strlen($body)-4,4) == "\r\n\r\n") { - $body=substr($body,0,strlen($body)-2); - } - return $body; - } - - /** - * Create the DKIM header, body, as new header - * - * @access public - * @param string $headers_line Header lines - * @param string $subject Subject - * @param string $body Body - */ - public function DKIM_Add($headers_line,$subject,$body) { - $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms - $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body - $DKIMquery = 'dns/txt'; // Query method - $DKIMtime = TIMESTAMP ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone) - $subject_header = "Subject: $subject"; - $headers = explode("\r\n",$headers_line); - foreach($headers as $header) { - if (strpos($header,'From:') === 0) { - $from_header=$header; - } elseif (strpos($header,'To:') === 0) { - $to_header=$header; - } - } - $from = str_replace('|','=7C',$this->DKIM_QP($from_header)); - $to = str_replace('|','=7C',$this->DKIM_QP($to_header)); - $subject = str_replace('|','=7C',$this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable - $body = $this->DKIM_BodyC($body); - $DKIMlen = strlen($body) ; // Length of body - $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body - $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";"; - $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n". - "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n". - "\th=From:To:Subject;\r\n". - "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n". - "\tz=$from\r\n". - "\t|$to\r\n". - "\t|$subject;\r\n". - "\tbh=" . $DKIMb64 . ";\r\n". - "\tb="; - $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs); - $signed = $this->DKIM_Sign($toSign); - return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n".$dkimhdrs.$signed."\r\n"; - } - - protected function doCallback($isSent,$to,$cc,$bcc,$subject,$body) { - if (!empty($this->action_function) && function_exists($this->action_function)) { - $params = array($isSent,$to,$cc,$bcc,$subject,$body); - call_user_func_array($this->action_function,$params); - } - } -} - -class phpmailerException extends Exception { - public function errorMessage() { - $errorMsg = '' . $this->getMessage() . "
\n"; - return $errorMsg; - } -} -?> \ No newline at end of file diff --git a/includes/classes/class.smtp.php b/includes/classes/class.smtp.php deleted file mode 100644 index 47c012f..0000000 --- a/includes/classes/class.smtp.php +++ /dev/null @@ -1,814 +0,0 @@ -smtp_conn = 0; - $this->error = null; - $this->helo_rply = null; - - $this->do_debug = 0; - } - - ///////////////////////////////////////////////// - // CONNECTION FUNCTIONS - ///////////////////////////////////////////////// - - /** - * Connect to the server specified on the port specified. - * If the port is not specified use the default SMTP_PORT. - * If tval is specified then a connection will try and be - * established with the server for that number of seconds. - * If tval is not specified the default is 30 seconds to - * try on the connection. - * - * SMTP CODE SUCCESS: 220 - * SMTP CODE FAILURE: 421 - * @access public - * @return bool - */ - public function Connect($host, $port = 0, $tval = 30) { - // set the error val to null so there is no confusion - $this->error = null; - - // make sure we are __not__ connected - if($this->connected()) { - // already connected, generate error - $this->error = array("error" => "Already connected to a server"); - return false; - } - - if(empty($port)) { - $port = $this->SMTP_PORT; - } - - // connect to the smtp server - $this->smtp_conn = @fsockopen($host, // the host of the server - $port, // the port to use - $errno, // error number if any - $errstr, // error message if any - $tval); // give up after ? secs - // verify we connected properly - if(empty($this->smtp_conn)) { - $this->error = array("error" => "Failed to connect to server", - "errno" => $errno, - "errstr" => $errstr); - if($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '
'; - } - return false; - } - - // SMTP server can take longer to respond, give longer timeout for first read - // Windows does not have support for this timeout function - if(substr(PHP_OS, 0, 3) != "WIN") - socket_set_timeout($this->smtp_conn, $tval, 0); - - // get any announcement - $announce = $this->get_lines(); - - if($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $announce . $this->CRLF . '
'; - } - - return true; - } - - /** - * Initiate a TLS communication with the server. - * - * SMTP CODE 220 Ready to start TLS - * SMTP CODE 501 Syntax error (no parameters allowed) - * SMTP CODE 454 TLS not available due to temporary reason - * @access public - * @return bool success - */ - public function StartTLS() { - $this->error = null; # to avoid confusion - - if(!$this->connected()) { - $this->error = array("error" => "Called StartTLS() without being connected"); - return false; - } - - fputs($this->smtp_conn,"STARTTLS" . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply,0,3); - - if($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; - } - - if($code != 220) { - $this->error = - array("error" => "STARTTLS not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply,4)); - if($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - return false; - } - - // Begin encrypted connection - if(!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) { - return false; - } - - return true; - } - - /** - * Performs SMTP authentication. Must be run after running the - * Hello() method. Returns true if successfully authenticated. - * @access public - * @return bool - */ - public function Authenticate($USERname, $password) { - // Start authentication - fputs($this->smtp_conn,"AUTH LOGIN" . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply,0,3); - - if($code != 334) { - $this->error = - array("error" => "AUTH not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply,4)); - if($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - return false; - } - - // Send encoded username - fputs($this->smtp_conn, base64_encode($USERname) . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply,0,3); - - if($code != 334) { - $this->error = - array("error" => "Username not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply,4)); - if($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - return false; - } - - // Send encoded password - fputs($this->smtp_conn, base64_encode($password) . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply,0,3); - - if($code != 235) { - $this->error = - array("error" => "Password not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply,4)); - if($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - return false; - } - - return true; - } - - /** - * Returns true if connected to a server otherwise false - * @access public - * @return bool - */ - public function Connected() { - if(!empty($this->smtp_conn)) { - $sock_status = socket_get_status($this->smtp_conn); - if($sock_status["eof"]) { - // the socket is valid but we are not connected - if($this->do_debug >= 1) { - echo "SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected"; - } - $this->Close(); - return false; - } - return true; // everything looks good - } - return false; - } - - /** - * Closes the socket and cleans up the state of the class. - * It is not considered good to use this function without - * first trying to use QUIT. - * @access public - * @return void - */ - public function Close() { - $this->error = null; // so there is no confusion - $this->helo_rply = null; - if(!empty($this->smtp_conn)) { - // close the connection and cleanup - fclose($this->smtp_conn); - $this->smtp_conn = 0; - } - } - - ///////////////////////////////////////////////// - // SMTP COMMANDS - ///////////////////////////////////////////////// - - /** - * Issues a data command and sends the msg_data to the server - * finializing the mail transaction. $msg_data is the message - * that is to be send with the headers. Each header needs to be - * on a single line followed by a with the message headers - * and the message body being seperated by and additional . - * - * Implements rfc 821: DATA - * - * SMTP CODE INTERMEDIATE: 354 - * [data] - * . - * SMTP CODE SUCCESS: 250 - * SMTP CODE FAILURE: 552,554,451,452 - * SMTP CODE FAILURE: 451,554 - * SMTP CODE ERROR : 500,501,503,421 - * @access public - * @return bool - */ - public function Data($msg_data) { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array( - "error" => "Called Data() without being connected"); - return false; - } - - fputs($this->smtp_conn,"DATA" . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply,0,3); - - if($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; - } - - if($code != 354) { - $this->error = - array("error" => "DATA command not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply,4)); - if($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - return false; - } - - /* the server is ready to accept data! - * according to rfc 821 we should not send more than 1000 - * including the CRLF - * characters on a single line so we will break the data up - * into lines by \r and/or \n then if needed we will break - * each of those into smaller lines to fit within the limit. - * in addition we will be looking for lines that start with - * a period '.' and append and additional period '.' to that - * line. NOTE: this does not count towards limit. - */ - - // normalize the line breaks so we know the explode works - $msg_data = str_replace("\r\n","\n",$msg_data); - $msg_data = str_replace("\r","\n",$msg_data); - $lines = explode("\n",$msg_data); - - /* we need to find a good way to determine is headers are - * in the msg_data or if it is a straight msg body - * currently I am assuming rfc 822 definitions of msg headers - * and if the first field of the first line (':' sperated) - * does not contain a space then it _should_ be a header - * and we can process all lines before a blank "" line as - * headers. - */ - - $field = substr($lines[0],0,strpos($lines[0],":")); - $in_headers = false; - if(!empty($field) && !strstr($field," ")) { - $in_headers = true; - } - - $max_line_length = 998; // used below; set here for ease in change - - while(list(,$line) = @each($lines)) { - $lines_out = null; - if($line == "" && $in_headers) { - $in_headers = false; - } - // ok we need to break this line up into several smaller lines - while(strlen($line) > $max_line_length) { - $pos = strrpos(substr($line,0,$max_line_length)," "); - - // Patch to fix DOS attack - if(!$pos) { - $pos = $max_line_length - 1; - $lines_out[] = substr($line,0,$pos); - $line = substr($line,$pos); - } else { - $lines_out[] = substr($line,0,$pos); - $line = substr($line,$pos + 1); - } - - /* if processing headers add a LWSP-char to the front of new line - * rfc 822 on long msg headers - */ - if($in_headers) { - $line = "\t" . $line; - } - } - $lines_out[] = $line; - - // send the lines to the server - while(list(,$line_out) = @each($lines_out)) { - if(strlen($line_out) > 0) - { - if(substr($line_out, 0, 1) == ".") { - $line_out = "." . $line_out; - } - } - fputs($this->smtp_conn,$line_out . $this->CRLF); - } - } - - // message data has been sent - fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply,0,3); - - if($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; - } - - if($code != 250) { - $this->error = - array("error" => "DATA not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply,4)); - if($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - return false; - } - return true; - } - - /** - * Sends the HELO command to the smtp server. - * This makes sure that we and the server are in - * the same known state. - * - * Implements from rfc 821: HELO - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE ERROR : 500, 501, 504, 421 - * @access public - * @return bool - */ - public function Hello($host = '') { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array( - "error" => "Called Hello() without being connected"); - return false; - } - - // if hostname for HELO was not specified send default - if(empty($host)) { - // determine appropriate default to send to server - $host = "localhost"; - } - - // Send extended hello first (RFC 2821) - if(!$this->SendHello("EHLO", $host)) { - if(!$this->SendHello("HELO", $host)) { - return false; - } - } - - return true; - } - - /** - * Sends a HELO/EHLO command. - * @access private - * @return bool - */ - private function SendHello($hello, $host) { - fputs($this->smtp_conn, $hello . " " . $host . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply,0,3); - - if($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER: " . $rply . $this->CRLF . '
'; - } - - if($code != 250) { - $this->error = - array("error" => $hello . " not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply,4)); - if($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - return false; - } - - $this->helo_rply = $rply; - - return true; - } - - /** - * Starts a mail transaction from the email address specified in - * $from. Returns true if successful or false otherwise. If True - * the mail transaction is started and then one or more Recipient - * commands may be called followed by a Data command. - * - * Implements rfc 821: MAIL FROM: - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE SUCCESS: 552,451,452 - * SMTP CODE SUCCESS: 500,501,421 - * @access public - * @return bool - */ - public function Mail($from) { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array( - "error" => "Called Mail() without being connected"); - return false; - } - - $useVerp = ($this->do_verp ? "XVERP" : ""); - fputs($this->smtp_conn,"MAIL FROM:<" . $from . ">" . $useVerp . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply,0,3); - - if($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; - } - - if($code != 250) { - $this->error = - array("error" => "MAIL not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply,4)); - if($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - return false; - } - return true; - } - - /** - * Sends the quit command to the server and then closes the socket - * if there is no error or the $close_on_error argument is true. - * - * Implements from rfc 821: QUIT - * - * SMTP CODE SUCCESS: 221 - * SMTP CODE ERROR : 500 - * @access public - * @return bool - */ - public function Quit($close_on_error = true) { - $this->error = null; // so there is no confusion - - if(!$this->connected()) { - $this->error = array( - "error" => "Called Quit() without being connected"); - return false; - } - - // send the quit command to the server - fputs($this->smtp_conn,"quit" . $this->CRLF); - - // get any good-bye messages - $byemsg = $this->get_lines(); - - if($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $byemsg . $this->CRLF . '
'; - } - - $rval = true; - $e = null; - - $code = substr($byemsg,0,3); - if($code != 221) { - // use e as a tmp var cause Close will overwrite $this->error - $e = array("error" => "SMTP server rejected quit command", - "smtp_code" => $code, - "smtp_rply" => substr($byemsg,4)); - $rval = false; - if($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '
'; - } - } - - if(empty($e) || $close_on_error) { - $this->Close(); - } - - return $rval; - } - - /** - * Sends the command RCPT to the SMTP server with the TO: argument of $to. - * Returns true if the recipient was accepted false if it was rejected. - * - * Implements from rfc 821: RCPT TO: - * - * SMTP CODE SUCCESS: 250,251 - * SMTP CODE FAILURE: 550,551,552,553,450,451,452 - * SMTP CODE ERROR : 500,501,503,421 - * @access public - * @return bool - */ - public function Recipient($to) { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array( - "error" => "Called Recipient() without being connected"); - return false; - } - - fputs($this->smtp_conn,"RCPT TO:<" . $to . ">" . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply,0,3); - - if($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; - } - - if($code != 250 && $code != 251) { - $this->error = - array("error" => "RCPT not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply,4)); - if($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - return false; - } - return true; - } - - /** - * Sends the RSET command to abort and transaction that is - * currently in progress. Returns true if successful false - * otherwise. - * - * Implements rfc 821: RSET - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE ERROR : 500,501,504,421 - * @access public - * @return bool - */ - public function Reset() { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array( - "error" => "Called Reset() without being connected"); - return false; - } - - fputs($this->smtp_conn,"RSET" . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply,0,3); - - if($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; - } - - if($code != 250) { - $this->error = - array("error" => "RSET failed", - "smtp_code" => $code, - "smtp_msg" => substr($rply,4)); - if($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - return false; - } - - return true; - } - - /** - * Starts a mail transaction from the email address specified in - * $from. Returns true if successful or false otherwise. If True - * the mail transaction is started and then one or more Recipient - * commands may be called followed by a Data command. This command - * will send the message to the users terminal if they are logged - * in and send them an email. - * - * Implements rfc 821: SAML FROM: - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE SUCCESS: 552,451,452 - * SMTP CODE SUCCESS: 500,501,502,421 - * @access public - * @return bool - */ - public function SendAndMail($from) { - $this->error = null; // so no confusion is caused - - if(!$this->connected()) { - $this->error = array( - "error" => "Called SendAndMail() without being connected"); - return false; - } - - fputs($this->smtp_conn,"SAML FROM:" . $from . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply,0,3); - - if($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; - } - - if($code != 250) { - $this->error = - array("error" => "SAML not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply,4)); - if($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - return false; - } - return true; - } - - /** - * This is an optional command for SMTP that this class does not - * support. This method is here to make the RFC821 Definition - * complete for this class and __may__ be implimented in the future - * - * Implements from rfc 821: TURN - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE FAILURE: 502 - * SMTP CODE ERROR : 500, 503 - * @access public - * @return bool - */ - public function Turn() { - $this->error = array("error" => "This method, TURN, of the SMTP ". - "is not implemented"); - if($this->do_debug >= 1) { - echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF . '
'; - } - return false; - } - - /** - * Get the current error - * @access public - * @return array - */ - public function getError() { - return $this->error; - } - - ///////////////////////////////////////////////// - // INTERNAL FUNCTIONS - ///////////////////////////////////////////////// - - /** - * Read in as many lines as possible - * either before eof or socket timeout occurs on the operation. - * With SMTP we can tell if we have more lines to read if the - * 4th character is '-' symbol. If it is a space then we don't - * need to read anything else. - * @access private - * @return string - */ - private function get_lines() { - $data = ""; - while($str = @fgets($this->smtp_conn,515)) { - if($this->do_debug >= 4) { - echo "SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '
'; - echo "SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '
'; - } - $data .= $str; - if($this->do_debug >= 4) { - echo "SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '
'; - } - // if 4th character is a space, we are done reading, break the loop - if(substr($str,3,1) == " ") { break; } - } - return $data; - } - -} - -?> \ No newline at end of file diff --git a/includes/classes/class.statbuilder.php b/includes/classes/class.statbuilder.php index 62775f6..21723c8 100644 --- a/includes/classes/class.statbuilder.php +++ b/includes/classes/class.statbuilder.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,97 +18,60 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ -require(ROOT_PATH.'includes/classes/class.Records.php'); - -class statbuilder extends records +class statbuilder { function __construct() { - global $db, $CONF; + global $CONF; $this->starttime = microtime(true); $this->memory = array(round(memory_get_usage() / 1024,1),round(memory_get_usage(1) / 1024,1)); $this->time = TIMESTAMP; + + $this->recordData = array(); - $this->Unis = array($CONF['uni']); - $Query = $db->query("SELECT `uni` FROM ".CONFIG." WHERE `uni` != '".$CONF['uni']."' ORDER BY `uni` ASC;"); - while($Uni = $db->fetch_array($Query)) + $this->Unis = array(Config::get('uni')); + $Query = $GLOBALS['DATABASE']->query("SELECT uni FROM ".CONFIG." WHERE uni != '".Config::get('uni')."' ORDER BY uni ASC;"); + while($Uni = $GLOBALS['DATABASE']->fetch_array($Query)) { $this->Unis[] = $Uni['uni']; + } } private function SomeStatsInfos() { - global $db; return array( 'stats_time' => $this->time, 'totaltime' => round(microtime(true) - $this->starttime, 7), 'memory_peak' => array(round(memory_get_peak_usage() / 1024,1), round(memory_get_peak_usage(1) / 1024,1)), 'initial_memory' => $this->memory, 'end_memory' => array(round(memory_get_usage() / 1024,1), round(memory_get_usage(1) / 1024,1)), - 'sql_count' => $db->get_sql(), + 'sql_count' => $GLOBALS['DATABASE']->get_sql(), ); } private function AnotherCronJobs() { - + } private function CheckUniverseAccounts($UniData) { + $UniData = $UniData + array_combine($this->Unis, array_fill(1, count($this->Unis), 0)); foreach($UniData as $Uni => $Amount) { - update_config(array('users_amount' => $Amount), $Uni); + Config::update(array('users_amount' => $Amount), $Uni); } - } - - private function DeleteSome() - { - global $db, $CONF; - - $db->query("LOCK TABLES ".ALLIANCE." WRITE, ".BUDDY." WRITE, ".CONFIG." WRITE, ".FLEETS." WRITE, ".NOTES." WRITE, ".MESSAGES." WRITE, ".PLANETS." WRITE, ".RW." WRITE, ".SESSION." WRITE, ".SUPP." WRITE, ".STATPOINTS." WRITE, ".TOPKB." WRITE, ".TOPKB_USERS." WRITE, ".USERS." WRITE;"); - - //Delete old messages - $del_before = TIMESTAMP - ($CONF['del_oldstuff'] * 86400); - $del_inactive = TIMESTAMP - ($CONF['del_user_automatic'] * 86400); - $del_deleted = TIMESTAMP - ($CONF['del_user_manually'] * 86400); - - $db->multi_query("DELETE FROM `".MESSAGES."` WHERE `message_time` < '". $del_before ."';DELETE FROM ".SUPP." WHERE `time` < '".$del_before."' AND `status` = 0;DELETE FROM ".ALLIANCE." WHERE `ally_members` = '0';DELETE FROM ".PLANETS." WHERE `destruyed` < ".TIMESTAMP." AND `destruyed` != 0;UPDATE ".USERS." SET `email_2` = `email` WHERE `setmail` < '".TIMESTAMP."';DELETE FROM ".SESSION." WHERE `user_lastactivity` < '".(TIMESTAMP - SESSION_LIFETIME)."';UPDATE ".USERS." SET `banaday` = '0', `bana` = '0' WHERE `banaday` <= '".TIMESTAMP."';"); - - $ChooseToDelete = $db->query("SELECT `id` FROM `".USERS."` WHERE `authlevel` = '".AUTH_USR."' AND ((`db_deaktjava` != 0 AND `db_deaktjava` < '".$del_deleted."')".($del_inactive == TIMESTAMP ? "" : " OR `onlinetime` < '".$del_inactive."'").");"); - - if(isset($ChooseToDelete)) - { - include_once(ROOT_PATH.'includes/functions/DeleteSelectedUser.php'); - while($delete = $db->fetch_array($ChooseToDelete)) - { - DeleteSelectedUser($delete['id']); - } - } - - $db->free_result($ChooseToDelete); - - foreach($this->Unis as $Uni) - { - $TopKBLow = $db->countquery("SELECT units FROM ".TOPKB." WHERE `universe` = ".$Uni." ORDER BY units DESC LIMIT 99,1;"); - if(isset($TopKBLow)) - $db->query("DELETE ".TOPKB.", ".TOPKB_USERS." FROM ".TOPKB." INNER JOIN ".TOPKB_USERS." USING (rid) WHERE `universe` = ".$Uni." AND `units` < ".$TopKBLow.";"); - } - - $db->query("DELETE FROM ".RW." WHERE `time` < ". $del_before ." AND `rid` NOT IN (SELECT `rid` FROM ".TOPKB.");"); - $db->query("UNLOCK TABLES;"); } private function GetUsersInfosFromDB() { - global $db, $resource, $reslist; + global $resource, $reslist; $select_defenses = ''; $select_buildings = ''; $selected_tech = ''; @@ -128,10 +91,11 @@ private function GetUsersInfosFromDB() foreach($reslist['defense'] as $Defense){ $select_defenses .= " SUM(p.".$resource[$Defense].") as ".$resource[$Defense].","; - } + } + $FlyingFleets = array(); - $SQLFleets = $db->query('SELECT fleet_array, fleet_owner FROM '.FLEETS.';'); - while ($CurFleets = $db->fetch_array($SQLFleets)) + $SQLFleets = $GLOBALS['DATABASE']->query('SELECT fleet_array, fleet_owner FROM '.FLEETS.';'); + while ($CurFleets = $GLOBALS['DATABASE']->fetch_array($SQLFleets)) { $FleetRec = explode(";", $CurFleets['fleet_array']); @@ -148,24 +112,48 @@ private function GetUsersInfosFromDB() } } - $db->free_result($SQLFleets); + $GLOBALS['DATABASE']->free_result($SQLFleets); $Return['Fleets'] = $FlyingFleets; - $Return['Planets'] = $db->query('SELECT SQL_BIG_RESULT DISTINCT '.$select_buildings.' p.id, p.universe, p.id_owner, u.authlevel, u.bana, u.username FROM '.PLANETS.' as p LEFT JOIN '.USERS.' as u ON u.id = p.id_owner;'); - $Return['Users'] = $db->query('SELECT SQL_BIG_RESULT DISTINCT '.$selected_tech.$select_fleets.$select_defenses.' u.id, u.ally_id, u.authlevel, u.bana, u.universe, u.username, s.tech_rank AS old_tech_rank, s.build_rank AS old_build_rank, s.defs_rank AS old_defs_rank, s.fleet_rank AS old_fleet_rank, s.total_rank AS old_total_rank FROM '.USERS.' as u LEFT JOIN '.STATPOINTS.' as s ON s.stat_type = 1 AND s.id_owner = u.id LEFT JOIN '.PLANETS.' as p ON u.id = p.id_owner GROUP BY s.id_owner, u.id, u.authlevel;'); - $Return['Alliance'] = $db->query('SELECT SQL_BIG_RESULT DISTINCT a.id, a.ally_universe, s.tech_rank AS old_tech_rank, s.build_rank AS old_build_rank, s.defs_rank AS old_defs_rank, s.fleet_rank AS old_fleet_rank, s.total_rank AS old_total_rank FROM '.ALLIANCE.' as a LEFT JOIN '.STATPOINTS.' as s ON s.stat_type = 2 AND s.id_owner = a.id;'); + $Return['Planets'] = $GLOBALS['DATABASE']->query('SELECT SQL_BIG_RESULT DISTINCT '.$select_buildings.' p.id, p.universe, p.id_owner, u.authlevel, u.bana, u.username FROM '.PLANETS.' as p LEFT JOIN '.USERS.' as u ON u.id = p.id_owner;'); + $Return['Users'] = $GLOBALS['DATABASE']->query('SELECT SQL_BIG_RESULT DISTINCT '.$selected_tech.$select_fleets.$select_defenses.' u.id, u.ally_id, u.authlevel, u.bana, u.universe, u.username, s.tech_rank AS old_tech_rank, s.build_rank AS old_build_rank, s.defs_rank AS old_defs_rank, s.fleet_rank AS old_fleet_rank, s.total_rank AS old_total_rank FROM '.USERS.' as u LEFT JOIN '.STATPOINTS.' as s ON s.stat_type = 1 AND s.id_owner = u.id LEFT JOIN '.PLANETS.' as p ON u.id = p.id_owner GROUP BY s.id_owner, u.id, u.authlevel;'); + $Return['Alliance'] = $GLOBALS['DATABASE']->query('SELECT SQL_BIG_RESULT DISTINCT a.id, a.ally_universe, s.tech_rank AS old_tech_rank, s.build_rank AS old_build_rank, s.defs_rank AS old_defs_rank, s.fleet_rank AS old_fleet_rank, s.total_rank AS old_total_rank FROM '.ALLIANCE.' as a LEFT JOIN '.STATPOINTS.' as s ON s.stat_type = 2 AND s.id_owner = a.id;'); return $Return; } + private function setRecords($userID, $elementID, $amount) + { + $this->recordData[$elementID][$amount][] = $userID; + } + + private function writeRecordData() + { + $QueryData = array(); + foreach($this->recordData as $elementID => $elementArray) { + krsort($elementArray, SORT_NUMERIC); + $userWinner = reset($elementArray); + $maxAmount = key($elementArray); + $userWinner = array_unique($userWinner); + foreach($userWinner as $userID) { + $QueryData[] = "(".$userID.",".$elementID.",".$maxAmount.")"; + } + } + + if(!empty($QueryData)) { + $SQL = "TRUNCATE TABLE ".RECORDS.";"; + $SQL .= "INSERT INTO ".RECORDS." (userID, elementID, level) VALUES ".implode(', ', $QueryData).";"; + $this->SaveDataIntoDB($SQL); + } + } + private function SaveDataIntoDB($Data) { - global $db; if(!empty($Data)) - $db->multi_query($Data); + $GLOBALS['DATABASE']->multi_query($Data); } - private function GetTechnoPoints($CurrentUser) + private function GetTechnoPoints($USER) { global $resource, $reslist, $pricelist, $CONF; $TechCounts = 0; @@ -173,22 +161,23 @@ private function GetTechnoPoints($CurrentUser) foreach($reslist['tech'] as $Techno) { - if($CurrentUser[$resource[$Techno]] == 0) continue; + if($USER[$resource[$Techno]] == 0) continue; - $this->SetIfRecord($Techno, $CurrentUser); - - $Units = $pricelist[$Techno]['metal'] + $pricelist[$Techno]['crystal'] + $pricelist[$Techno]['deuterium']; - for($Level = 1; $Level <= $CurrentUser[$resource[$Techno]]; $Level++) + $Units = $pricelist[$Techno]['cost'][901] + $pricelist[$Techno]['cost'][902] + $pricelist[$Techno]['cost'][903]; + for($Level = 1; $Level <= $USER[$resource[$Techno]]; $Level++) { $TechPoints += $Units * pow($pricelist[$Techno]['factor'], $Level); } - $TechCounts += $CurrentUser[$resource[$Techno]]; + + $TechCounts += $USER[$resource[$Techno]]; + + $this->setRecords($USER['id'], $Techno, $USER[$resource[$Techno]]); } - return array('count' => $TechCounts, 'points' => ($TechPoints / $CONF['stat_settings'])); + return array('count' => $TechCounts, 'points' => ($TechPoints / Config::get('stat_settings'))); } - private function GetBuildPoints($CurrentPlanet) + private function GetBuildPoints($PLANET) { global $resource, $reslist, $pricelist, $CONF; $BuildCounts = 0; @@ -196,210 +185,214 @@ private function GetBuildPoints($CurrentPlanet) foreach($reslist['build'] as $Build) { - if($CurrentPlanet[$resource[$Build]] == 0) continue; - - $this->SetIfRecord($Build, $CurrentPlanet); + if($PLANET[$resource[$Build]] == 0) continue; - $Units = $pricelist[$Build]['metal'] + $pricelist[$Build]['crystal'] + $pricelist[$Build]['deuterium']; - for($Level = 1; $Level <= $CurrentPlanet[$resource[$Build]]; $Level++) + $Units = $pricelist[$Build]['cost'][901] + $pricelist[$Build]['cost'][902] + $pricelist[$Build]['cost'][903]; + for($Level = 1; $Level <= $PLANET[$resource[$Build]]; $Level++) { $BuildPoints += $Units * pow($pricelist[$Build]['factor'], $Level); } - $BuildCounts += $CurrentPlanet[$resource[$Build]]; + + $BuildCounts += $PLANET[$resource[$Build]]; + + $this->setRecords($PLANET['id_owner'], $Build, $PLANET[$resource[$Build]]); } - return array('count' => $BuildCounts, 'points' => ($BuildPoints / $CONF['stat_settings'])); + return array('count' => $BuildCounts, 'points' => ($BuildPoints / Config::get('stat_settings'))); } - private function GetDefensePoints($CurrentPlanet) + private function GetDefensePoints($USER) { global $resource, $reslist, $pricelist, $CONF; $DefenseCounts = 0; $DefensePoints = 0; foreach($reslist['defense'] as $Defense) { - $this->SetIfRecord($Defense, $CurrentPlanet); + if($USER[$resource[$Defense]] == 0) continue; - $Units = $pricelist[$Defense]['metal'] + $pricelist[$Defense]['crystal'] + $pricelist[$Defense]['deuterium']; - $DefensePoints += $Units * $CurrentPlanet[$resource[$Defense]]; - $DefenseCounts += $CurrentPlanet[$resource[$Defense]]; + $Units = $pricelist[$Defense]['cost'][901] + $pricelist[$Defense]['cost'][902] + $pricelist[$Defense]['cost'][903]; + $DefensePoints += $Units * $USER[$resource[$Defense]]; + $DefenseCounts += $USER[$resource[$Defense]]; + + $this->setRecords($USER['id'], $Defense, $USER[$resource[$Defense]]); } - return array('count' => $DefenseCounts, 'points' => ($DefensePoints / $CONF['stat_settings'])); + return array('count' => $DefenseCounts, 'points' => ($DefensePoints / Config::get('stat_settings'))); } - private function GetFleetPoints($CurrentPlanet) + private function GetFleetPoints($USER) { global $resource, $reslist, $pricelist, $CONF; $FleetCounts = 0; $FleetPoints = 0; - foreach($reslist['fleet'] as $Fleet) { - - $this->SetIfRecord($Fleet, $CurrentPlanet); + foreach($reslist['fleet'] as $Fleet) { + if($USER[$resource[$Fleet]] == 0) continue; - $Units = $pricelist[$Fleet]['metal'] + $pricelist[$Fleet]['crystal'] + $pricelist[$Fleet]['deuterium']; - $FleetPoints += $Units * $CurrentPlanet[$resource[$Fleet]]; - $FleetCounts += $CurrentPlanet[$resource[$Fleet]]; + $Units = $pricelist[$Fleet]['cost'][901] + $pricelist[$Fleet]['cost'][902] + $pricelist[$Fleet]['cost'][903]; + $FleetPoints += $Units * $USER[$resource[$Fleet]]; + $FleetCounts += $USER[$resource[$Fleet]]; + + $this->setRecords($USER['id'], $Fleet, $USER[$resource[$Fleet]]); } - return array('count' => $FleetCounts, 'points' => ($FleetPoints / $CONF['stat_settings'])); + return array('count' => $FleetCounts, 'points' => ($FleetPoints / Config::get('stat_settings'))); } private function SetNewRanks() { - global $db, $CONF; + global $CONF; $QryUpdateStats = ""; foreach($this->Unis as $Uni) { $tech = array(); $Rank = 1; - $RankQry = $db->query("SELECT s.`id_owner` FROM ".STATPOINTS." as s, ".USERS." as u WHERE s.`universe` = '".$Uni."' AND s.`stat_type` = '1' AND s.`id_owner` = `u`.id ".(($CONF['stat'] == 2)?'AND u.`authlevel` < '.$CONF['stat_level'].' ':'')." ORDER BY `tech_points` DESC;"); - while ($CurUser = $db->fetch_array($RankQry)) + $RankQry = $GLOBALS['DATABASE']->query("SELECT s.id_owner FROM ".STATPOINTS." as s, ".USERS." as u WHERE s.universe = '".$Uni."' AND s.stat_type = '1' AND s.id_owner = u.id ".((Config::get('stat') == 2)?'AND u.authlevel < '.Config::get('stat_level').' ':'')." ORDER BY tech_points DESC;"); + while ($CurUser = $GLOBALS['DATABASE']->fetch_array($RankQry)) { $tech[$CurUser['id_owner']] = $Rank; $Rank++; } - $db->free_result($RankQry); + $GLOBALS['DATABASE']->free_result($RankQry); $build = array(); $Rank = 1; - $RankQry = $db->query("SELECT s.`id_owner` FROM ".STATPOINTS." as s, ".USERS." as u WHERE s.`universe` = '".$Uni."' AND s.`stat_type` = '1' AND s.`id_owner` = `u`.id ".(($CONF['stat'] == 2)?'AND u.`authlevel` < '.$CONF['stat_level'].' ':'')." ORDER BY `build_points` DESC;"); - while ($CurUser = $db->fetch_array($RankQry)) + $RankQry = $GLOBALS['DATABASE']->query("SELECT s.id_owner FROM ".STATPOINTS." as s, ".USERS." as u WHERE s.universe = '".$Uni."' AND s.stat_type = '1' AND s.id_owner = u.id ".((Config::get('stat') == 2)?'AND u.authlevel < '.Config::get('stat_level').' ':'')." ORDER BY build_points DESC;"); + while ($CurUser = $GLOBALS['DATABASE']->fetch_array($RankQry)) { $build[$CurUser['id_owner']] = $Rank; $Rank++; } - $db->free_result($RankQry); + $GLOBALS['DATABASE']->free_result($RankQry); $defs = array(); $Rank = 1; - $RankQry = $db->query("SELECT s.`id_owner` FROM ".STATPOINTS." as s, ".USERS." as u WHERE s.`universe` = '".$Uni."' AND s.`stat_type` = '1' AND s.`id_owner` = `u`.id ".(($CONF['stat'] == 2)?'AND u.`authlevel` < '.$CONF['stat_level'].' ':'')." ORDER BY `defs_points` DESC;"); - while ($CurUser = $db->fetch_array($RankQry)) + $RankQry = $GLOBALS['DATABASE']->query("SELECT s.id_owner FROM ".STATPOINTS." as s, ".USERS." as u WHERE s.universe = '".$Uni."' AND s.stat_type = '1' AND s.id_owner = u.id ".((Config::get('stat') == 2)?'AND u.authlevel < '.Config::get('stat_level').' ':'')." ORDER BY defs_points DESC;"); + while ($CurUser = $GLOBALS['DATABASE']->fetch_array($RankQry)) { $defs[$CurUser['id_owner']] = $Rank; $Rank++; } - $db->free_result($RankQry); + $GLOBALS['DATABASE']->free_result($RankQry); $fleet = array(); $Rank = 1; - $RankQry = $db->query("SELECT s.`id_owner` FROM ".STATPOINTS." as s, ".USERS." as u WHERE s.`universe` = '".$Uni."' AND s.`stat_type` = '1' AND s.`id_owner` = `u`.id ".(($CONF['stat'] == 2)?'AND u.`authlevel` < '.$CONF['stat_level'].' ':'')." ORDER BY `fleet_points` DESC;"); - while ($CurUser = $db->fetch_array($RankQry)) + $RankQry = $GLOBALS['DATABASE']->query("SELECT s.id_owner FROM ".STATPOINTS." as s, ".USERS." as u WHERE s.universe = '".$Uni."' AND s.stat_type = '1' AND s.id_owner = u.id ".((Config::get('stat') == 2)?'AND u.authlevel < '.Config::get('stat_level').' ':'')." ORDER BY fleet_points DESC;"); + while ($CurUser = $GLOBALS['DATABASE']->fetch_array($RankQry)) { $fleet[$CurUser['id_owner']] = $Rank; $Rank++; } - $db->free_result($RankQry); + $GLOBALS['DATABASE']->free_result($RankQry); $Rank = 1; - $RankQry = $db->query("SELECT s.`id_owner` FROM ".STATPOINTS." as s, ".USERS." as u WHERE s.`universe` = '".$Uni."' AND s.`stat_type` = '1' AND s.`id_owner` = `u`.id ".(($CONF['stat'] == 2)?'AND u.`authlevel` < '.$CONF['stat_level'].' ':'')." ORDER BY `total_points` DESC;"); + $RankQry = $GLOBALS['DATABASE']->query("SELECT s.id_owner FROM ".STATPOINTS." as s, ".USERS." as u WHERE s.universe = '".$Uni."' AND s.stat_type = '1' AND s.id_owner = u.id ".((Config::get('stat') == 2)?'AND u.authlevel < '.Config::get('stat_level').' ':'')." ORDER BY total_points DESC;"); - while($CurUser = $db->fetch_array($RankQry)) + while($CurUser = $GLOBALS['DATABASE']->fetch_array($RankQry)) { - $QryUpdateStats .= "UPDATE ".STATPOINTS." SET `tech_rank` = '". $tech[$CurUser['id_owner']] ."', `build_rank` = '". $build[$CurUser['id_owner']] ."', `defs_rank` = '". $defs[$CurUser['id_owner']] ."', `fleet_rank` = '". $fleet[$CurUser['id_owner']] ."', `total_rank` = '". $Rank ."' WHERE `stat_type` = '1' AND `id_owner` = '". $CurUser['id_owner'] ."';"; + $QryUpdateStats .= "UPDATE ".STATPOINTS." SET tech_rank = '". $tech[$CurUser['id_owner']] ."', build_rank = '". $build[$CurUser['id_owner']] ."', defs_rank = '". $defs[$CurUser['id_owner']] ."', fleet_rank = '". $fleet[$CurUser['id_owner']] ."', total_rank = '". $Rank ."' WHERE stat_type = '1' AND id_owner = '". $CurUser['id_owner'] ."';"; $Rank++; } - $db->free_result($RankQry); + $GLOBALS['DATABASE']->free_result($RankQry); $tech = array(); $Rank = 1; - $RankQry = $db->query("SELECT s.`id_owner` FROM ".STATPOINTS." as s WHERE s.`universe` = '".$Uni."' AND s.`stat_type` = '2' ORDER BY `tech_points` DESC;"); - while ($CurUser = $db->fetch_array($RankQry)) + $RankQry = $GLOBALS['DATABASE']->query("SELECT s.id_owner FROM ".STATPOINTS." as s WHERE s.universe = '".$Uni."' AND s.stat_type = '2' ORDER BY tech_points DESC;"); + while ($CurUser = $GLOBALS['DATABASE']->fetch_array($RankQry)) { $tech[$CurUser['id_owner']] = $Rank; $Rank++; } - $db->free_result($RankQry); + $GLOBALS['DATABASE']->free_result($RankQry); $build = array(); $Rank = 1; - $RankQry = $db->query("SELECT s.`id_owner` FROM ".STATPOINTS." as s WHERE s.`universe` = '".$Uni."' AND s.`stat_type` = '2' ORDER BY `build_points` DESC;"); - while ($CurUser = $db->fetch_array($RankQry)) + $RankQry = $GLOBALS['DATABASE']->query("SELECT s.id_owner FROM ".STATPOINTS." as s WHERE s.universe = '".$Uni."' AND s.stat_type = '2' ORDER BY build_points DESC;"); + while ($CurUser = $GLOBALS['DATABASE']->fetch_array($RankQry)) { $build[$CurUser['id_owner']] = $Rank; $Rank++; } - $db->free_result($RankQry); + $GLOBALS['DATABASE']->free_result($RankQry); $defs = array(); $Rank = 1; - $RankQry = $db->query("SELECT s.`id_owner` FROM ".STATPOINTS." as s WHERE s.`universe` = '".$Uni."' AND s.`stat_type` = '2' ORDER BY `defs_points` DESC;"); - while ($CurUser = $db->fetch_array($RankQry)) + $RankQry = $GLOBALS['DATABASE']->query("SELECT s.id_owner FROM ".STATPOINTS." as s WHERE s.universe = '".$Uni."' AND s.stat_type = '2' ORDER BY defs_points DESC;"); + while ($CurUser = $GLOBALS['DATABASE']->fetch_array($RankQry)) { $defs[$CurUser['id_owner']] = $Rank; $Rank++; } - $db->free_result($RankQry); + $GLOBALS['DATABASE']->free_result($RankQry); $fleet = array(); $Rank = 1; - $RankQry = $db->query("SELECT s.`id_owner` FROM ".STATPOINTS." as s WHERE s.`universe` = '".$Uni."' AND s.`stat_type` = '2' ORDER BY `fleet_points` DESC;"); - while ($CurUser = $db->fetch_array($RankQry)) + $RankQry = $GLOBALS['DATABASE']->query("SELECT s.id_owner FROM ".STATPOINTS." as s WHERE s.universe = '".$Uni."' AND s.stat_type = '2' ORDER BY fleet_points DESC;"); + while ($CurUser = $GLOBALS['DATABASE']->fetch_array($RankQry)) { $fleet[$CurUser['id_owner']] = $Rank; $Rank++; } - $db->free_result($RankQry); + $GLOBALS['DATABASE']->free_result($RankQry); $Rank = 1; - $RankQry = $db->query("SELECT s.`id_owner` FROM ".STATPOINTS." as s WHERE s.`universe` = '".$Uni."' AND s.`stat_type` = '2' ORDER BY `total_points` DESC;"); + $RankQry = $GLOBALS['DATABASE']->query("SELECT s.id_owner FROM ".STATPOINTS." as s WHERE s.universe = '".$Uni."' AND s.stat_type = '2' ORDER BY total_points DESC;"); - while($CurUser = $db->fetch_array($RankQry)) + while($CurUser = $GLOBALS['DATABASE']->fetch_array($RankQry)) { - $QryUpdateStats .= "UPDATE ".STATPOINTS." SET `tech_rank` = '". $tech[$CurUser['id_owner']] ."', `build_rank` = '". $build[$CurUser['id_owner']] ."', `defs_rank` = '". $defs[$CurUser['id_owner']] ."', `fleet_rank` = '". $fleet[$CurUser['id_owner']] ."', `total_rank` = '". $Rank ."' WHERE `stat_type` = '2' AND `id_owner` = '". $CurUser['id_owner'] ."';"; + $QryUpdateStats .= "UPDATE ".STATPOINTS." SET tech_rank = '". $tech[$CurUser['id_owner']] ."', build_rank = '". $build[$CurUser['id_owner']] ."', defs_rank = '". $defs[$CurUser['id_owner']] ."', fleet_rank = '". $fleet[$CurUser['id_owner']] ."', total_rank = '". $Rank ."' WHERE stat_type = '2' AND id_owner = '". $CurUser['id_owner'] ."';"; $Rank++; } - $db->free_result($RankQry); + $GLOBALS['DATABASE']->free_result($RankQry); } return $QryUpdateStats; } final public function MakeStats() { - global $db, $CONF, $resource; - $this->DeleteSome(); + global $CONF, $resource; $AllyPoints = array(); $UserPoints = array(); $TotalData = $this->GetUsersInfosFromDB(); $FinalSQL = 'TRUNCATE TABLE '.STATPOINTS.';'; - $FinalSQL .= "INSERT INTO ".STATPOINTS." (`id_owner`, `id_ally`, `stat_type`, `universe`, `tech_old_rank`, `tech_points`, `tech_count`, `build_old_rank`, `build_points`, `build_count`, `defs_old_rank`, `defs_points`, `defs_count`, `fleet_old_rank`, `fleet_points`, `fleet_count`, `total_old_rank`, `total_points`, `total_count`) VALUES "; + $FinalSQL .= "INSERT INTO ".STATPOINTS." (id_owner, id_ally, stat_type, universe, tech_old_rank, tech_points, tech_count, build_old_rank, build_points, build_count, defs_old_rank, defs_points, defs_count, fleet_old_rank, fleet_points, fleet_count, total_old_rank, total_points, total_count) VALUES "; - while($PlanetData = $db->fetch_array($TotalData['Planets'])) + while($PlanetData = $GLOBALS['DATABASE']->fetch_array($TotalData['Planets'])) { - if((in_array($CONF['stat'], array(1, 2)) && $PlanetData['authlevel'] >= $CONF['stat_level']) || !empty($PlanetData['bana'])) continue; + if((in_array(Config::get('stat'), array(1, 2)) && $PlanetData['authlevel'] >= Config::get('stat_level')) || !empty($PlanetData['bana'])) continue; - if(!isset($UserPoints[$PlanetData['id_owner']])) + if(!isset($UserPoints[$PlanetData['id_owner']])) { $UserPoints[$PlanetData['id_owner']]['build']['count'] = $UserPoints[$PlanetData['id_owner']]['build']['points'] = 0; + } - $BuildPoints = $this->GetBuildPoints($PlanetData); + $BuildPoints = $this->GetBuildPoints($PlanetData); $UserPoints[$PlanetData['id_owner']]['build']['count'] += $BuildPoints['count']; $UserPoints[$PlanetData['id_owner']]['build']['points'] += $BuildPoints['points']; } - $db->free_result($TotalData['Planets']); + $GLOBALS['DATABASE']->free_result($TotalData['Planets']); $UniData = array(); - while($UserData = $db->fetch_array($TotalData['Users'])) + while($UserData = $GLOBALS['DATABASE']->fetch_array($TotalData['Users'])) { if(!isset($UniData[$UserData['universe']])) $UniData[$UserData['universe']] = 0; $UniData[$UserData['universe']]++; - if ((in_array($CONF['stat'], array(1, 2)) && $UserData['authlevel'] >= $CONF['stat_level']) || !empty($UserData['bana'])) + if ((in_array(Config::get('stat'), array(1, 2)) && $UserData['authlevel'] >= Config::get('stat_level')) || !empty($UserData['bana'])) { $FinalSQL .= "(".$UserData['id'].",".$UserData['ally_id'].",1,".$UserData['universe'].",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), "; continue; @@ -421,14 +414,32 @@ final public function MakeStats() $UserPoints[$UserData['id']]['techno']['count'] = $TechnoPoints['count']; $UserPoints[$UserData['id']]['techno']['points'] = $TechnoPoints['points']; - $UserPoints[$UserData['id']]['total']['count'] = $UserPoints[$UserData['id']]['techno']['count'] + $UserPoints[$UserData['id']]['build']['count'] + $UserPoints[$UserData['id']]['defense']['count'] + $UserPoints[$UserData['id']]['fleet']['count']; - $UserPoints[$UserData['id']]['total']['points'] = $UserPoints[$UserData['id']]['techno']['points'] + $UserPoints[$UserData['id']]['build']['points'] + $UserPoints[$UserData['id']]['defense']['points'] + $UserPoints[$UserData['id']]['fleet']['points']; + $UserPoints[$UserData['id']]['total']['count'] = $UserPoints[$UserData['id']]['techno']['count'] + + $UserPoints[$UserData['id']]['build']['count'] + + $UserPoints[$UserData['id']]['defense']['count'] + + $UserPoints[$UserData['id']]['fleet']['count']; + + $UserPoints[$UserData['id']]['total']['points'] = $UserPoints[$UserData['id']]['techno']['points'] + + $UserPoints[$UserData['id']]['build']['points'] + + $UserPoints[$UserData['id']]['defense']['points'] + + $UserPoints[$UserData['id']]['fleet']['points']; if($UserData['ally_id'] != 0) { if(!isset($AllyPoints[$UserData['ally_id']])) - $AllyPoints[$UserData['ally_id']]['build']['count'] = $AllyPoints[$UserData['ally_id']]['build']['points'] = $AllyPoints[$UserData['ally_id']]['fleet']['count'] = $AllyPoints[$UserData['ally_id']]['fleet']['points'] = $AllyPoints[$UserData['ally_id']]['defense']['count'] = $AllyPoints[$UserData['ally_id']]['defense']['points'] = $AllyPoints[$UserData['ally_id']]['techno']['count'] = $AllyPoints[$UserData['ally_id']]['techno']['points'] = $AllyPoints[$UserData['ally_id']]['total']['count'] = $AllyPoints[$UserData['ally_id']]['total']['points'] = 0; - + { + $AllyPoints[$UserData['ally_id']]['build']['count'] = 0; + $AllyPoints[$UserData['ally_id']]['build']['points'] = 0; + $AllyPoints[$UserData['ally_id']]['fleet']['count'] = 0; + $AllyPoints[$UserData['ally_id']]['fleet']['points'] = 0; + $AllyPoints[$UserData['ally_id']]['defense']['count'] = 0; + $AllyPoints[$UserData['ally_id']]['defense']['points'] = 0; + $AllyPoints[$UserData['ally_id']]['techno']['count'] = 0; + $AllyPoints[$UserData['ally_id']]['techno']['points'] = 0; + $AllyPoints[$UserData['ally_id']]['total']['count'] = 0; + $AllyPoints[$UserData['ally_id']]['total']['points'] = 0; + } + $AllyPoints[$UserData['ally_id']]['build']['count'] += $UserPoints[$UserData['id']]['build']['count']; $AllyPoints[$UserData['ally_id']]['build']['points'] += $UserPoints[$UserData['id']]['build']['points']; $AllyPoints[$UserData['ally_id']]['fleet']['count'] += $UserPoints[$UserData['id']]['fleet']['count']; @@ -441,10 +452,28 @@ final public function MakeStats() $AllyPoints[$UserData['ally_id']]['total']['points'] += $UserPoints[$UserData['id']]['total']['points']; } - $FinalSQL .= "('".$UserData['id']."','".$UserData['ally_id']."', 1, ".$UserData['universe'].", '".(int)$UserData['old_tech_rank']."', '".floattostring($UserPoints[$UserData['id']]['techno']['points'])."', '".floattostring($UserPoints[$UserData['id']]['techno']['count'])."', '".(int)$UserData['old_build_rank']."','".floattostring($UserPoints[$UserData['id']]['build']['points'])."', '".floattostring($UserPoints[$UserData['id']]['build']['count'])."', '".(int)$UserData['old_defs_rank']."', '".floattostring($UserPoints[$UserData['id']]['defense']['points'])."', '".floattostring($UserPoints[$UserData['id']]['defense']['count'])."', '".(int)$UserData['old_fleet_rank']."', '".floattostring($UserPoints[$UserData['id']]['fleet']['points'])."', '".floattostring($UserPoints[$UserData['id']]['fleet']['count'])."', '".(int)$UserData['old_total_rank']."', '".floattostring($UserPoints[$UserData['id']]['total']['points'])."', '".floattostring($UserPoints[$UserData['id']]['total']['count'])."'), "; + $FinalSQL .= "(". + $UserData['id'].", ". + $UserData['ally_id'].", 1, ". + $UserData['universe'].", ". + (isset($UserData['old_tech_rank']) ? $UserData['old_tech_rank'] : 0).", ". + (isset($UserPoints[$UserData['id']]['techno']['points']) ? min($UserPoints[$UserData['id']]['techno']['points'], 1E50) : 0).", ". + (isset($UserPoints[$UserData['id']]['techno']['count']) ? $UserPoints[$UserData['id']]['techno']['count'] : 0).", ". + (isset($UserData['old_build_rank']) ? $UserData['old_build_rank'] : 0).", ". + (isset($UserPoints[$UserData['id']]['build']['points']) ? min($UserPoints[$UserData['id']]['build']['points'], 1E50) : 0).", ". + (isset($UserPoints[$UserData['id']]['build']['count']) ? $UserPoints[$UserData['id']]['build']['count'] : 0).", ". + (isset($UserData['old_defs_rank']) ? $UserData['old_defs_rank'] : 0).", ". + (isset($UserPoints[$UserData['id']]['defense']['points']) ? min($UserPoints[$UserData['id']]['defense']['points'], 1E50) : 0).", ". + (isset($UserPoints[$UserData['id']]['defense']['count']) ? $UserPoints[$UserData['id']]['defense']['count'] : 0).", ". + (isset($UserData['old_fleet_rank']) ? $UserData['old_fleet_rank'] : 0).", ". + (isset($UserPoints[$UserData['id']]['fleet']['points']) ? min($UserPoints[$UserData['id']]['fleet']['points'], 1E50) : 0).", ". + (isset($UserPoints[$UserData['id']]['fleet']['count']) ? $UserPoints[$UserData['id']]['fleet']['count'] : 0).", ". + (isset($UserData['old_total_rank']) ? $UserData['old_total_rank'] : 0).", ". + (isset($UserPoints[$UserData['id']]['total']['points']) ? min($UserPoints[$UserData['id']]['total']['points'], 1E50) : 0).", ". + (isset($UserPoints[$UserData['id']]['total']['count']) ? $UserPoints[$UserData['id']]['total']['count'] : 0)."), "; } - $db->free_result($TotalData['Users']); + $GLOBALS['DATABASE']->free_result($TotalData['Users']); $FinalSQL = substr($FinalSQL, 0, -2).';'; @@ -453,26 +482,41 @@ final public function MakeStats() if(count($AllyPoints) != 0) { - $AllySQL = "INSERT INTO ".STATPOINTS." (`id_owner`, `id_ally`, `stat_type`, `universe`, `tech_old_rank`, `tech_points`, `tech_count`, `build_old_rank`, `build_points`, `build_count`, `defs_old_rank`, `defs_points`, `defs_count`, `fleet_old_rank`, `fleet_points`, `fleet_count`, `total_old_rank`, `total_points`, `total_count`) VALUES "; - while($AllianceData = $db->fetch_array($TotalData['Alliance'])) + $AllySQL = "INSERT INTO ".STATPOINTS." (id_owner, id_ally, stat_type, universe, tech_old_rank, tech_points, tech_count, build_old_rank, build_points, build_count, defs_old_rank, defs_points, defs_count, fleet_old_rank, fleet_points, fleet_count, total_old_rank, total_points, total_count) VALUES "; + while($AllianceData = $GLOBALS['DATABASE']->fetch_array($TotalData['Alliance'])) { - $AllySQL .= "('".$AllianceData['id']."', 0, 2, ".$AllianceData['ally_universe'].",'".(int)$AllyPoints['old_tech_rank']."', '".floattostring($AllyPoints[$AllianceData['id']]['techno']['points'])."', '".floattostring($AllyPoints[$AllianceData['id']]['techno']['count'])."', '".(int)$AllianceData['old_build_rank']."', '".floattostring($AllyPoints[$AllianceData['id']]['build']['points'])."', '".floattostring($AllyPoints[$AllianceData['id']]['build']['count'])."', '".(int)$AllianceData['old_defs_rank']."', '".floattostring($AllyPoints[$AllianceData['id']]['defense']['points'])."', '".floattostring($AllyPoints[$AllianceData['id']]['defense']['count'])."', '".(int)$AllianceData['old_fleet_rank']."', '".floattostring($AllyPoints[$AllianceData['id']]['fleet']['points'])."', '".floattostring($AllyPoints[$AllianceData['id']]['fleet']['count'])."', '".(int)$AllianceData['old_total_rank']."', '".floattostring($AllyPoints[$AllianceData['id']]['total']['points'])."', '".floattostring($AllyPoints[$AllianceData['id']]['total']['count'])."'), "; + $AllySQL .= "(". + $AllianceData['id'].", 0, 2, ". + $AllianceData['ally_universe'].", ". + (isset($AllyPoints['old_tech_rank']) ? $AllyPoints['old_tech_rank'] : 0).", ". + (isset($AllyPoints[$AllianceData['id']]['techno']['points']) ? min($AllyPoints[$AllianceData['id']]['techno']['points'], 1E50) : 0).", ". + (isset($AllyPoints[$AllianceData['id']]['techno']['count']) ? $AllyPoints[$AllianceData['id']]['techno']['count'] : 0).", ". + (isset($AllianceData['old_build_rank']) ? $AllianceData['old_build_rank'] : 0).", ". + (isset($AllyPoints[$AllianceData['id']]['build']['points']) ? min($AllyPoints[$AllianceData['id']]['build']['points'], 1E50) : 0).", ". + (isset($AllyPoints[$AllianceData['id']]['build']['count']) ? $AllyPoints[$AllianceData['id']]['build']['count'] : 0).", ". + (isset($AllianceData['old_defs_rank']) ? $AllianceData['old_defs_rank'] : 0).", ". + (isset($AllyPoints[$AllianceData['id']]['defense']['points']) ? min($AllyPoints[$AllianceData['id']]['defense']['points'], 1E50) : 0).", ". + (isset($AllyPoints[$AllianceData['id']]['defense']['count']) ? $AllyPoints[$AllianceData['id']]['defense']['count'] : 0).", ". + (isset($AllianceData['old_fleet_rank']) ? $AllianceData['old_fleet_rank'] : 0).", ". + (isset($AllyPoints[$AllianceData['id']]['fleet']['points']) ? min($AllyPoints[$AllianceData['id']]['fleet']['points'], 1E50) : 0).", ". + (isset($AllyPoints[$AllianceData['id']]['fleet']['count']) ? $AllyPoints[$AllianceData['id']]['fleet']['count'] : 0).", ". + (isset($AllianceData['old_total_rank']) ? $AllianceData['old_total_rank'] : 0).", ". + (isset($AllyPoints[$AllianceData['id']]['total']['points']) ? min($AllyPoints[$AllianceData['id']]['total']['points'], 1E50) : 0).", ". + (isset($AllyPoints[$AllianceData['id']]['total']['count']) ? $AllyPoints[$AllianceData['id']]['total']['count'] : 0)."), "; } unset($AllyPoints); $AllySQL = substr($AllySQL, 0, -2).';'; $this->SaveDataIntoDB($AllySQL); - } + } - $db->free_result($TotalData['Alliance']); + $GLOBALS['DATABASE']->free_result($TotalData['Alliance']); $RankSQL = $this->SetNewRanks(); $this->SaveDataIntoDB($RankSQL); - $this->CheckUniverseAccounts($UniData); - $this->BuildRecordCache(); + $this->CheckUniverseAccounts($UniData); + $this->writeRecordData(); $this->AnotherCronJobs(); return $this->SomeStatsInfos(); } } - -?> \ No newline at end of file diff --git a/includes/classes/class.template.php b/includes/classes/class.template.php index c63e137..1678590 100644 --- a/includes/classes/class.template.php +++ b/includes/classes/class.template.php @@ -31,18 +31,28 @@ class template extends Smarty { + protected $window = 'full'; + protected $jsscript = array(); + protected $script = array(); + function __construct() { parent::__construct(); - $this->force_compile = false; - $this->caching = false; - $this->compile_check = true; #Set false for production! - $this->jsscript = array(); - $this->script = array(); - $this->compile_dir = is_writable(ROOT_PATH.'cache/') ? ROOT_PATH.'cache/' : $this->getTempPath(); - $this->template_dir = ROOT_PATH.'/styles/templates/'; - $this->Popup = false; - $this->Dialog = false; + $this->smartySettings(); + } + + function smartySettings() + { + $this->force_compile = false; + $this->caching = true; #Set true for production! + $this->merge_compiled_includes = true; + $this->compile_check = true; #Set false for production! + $this->php_handling = Smarty::PHP_REMOVE; + + $this->setCompileDir(is_writable(ROOT_PATH.'cache/') ? ROOT_PATH.'cache/' : $this->getTempPath()); + $this->setCacheDir(ROOT_PATH.'cache/templates'); + $this->setTemplateDir(ROOT_PATH.'styles/templates/'); + #$this->loadFilter('output', 'trimwhitespace'); } public function loadscript($script) @@ -62,213 +72,74 @@ public function getTempPath() return BasicFileUtil::getTempFolder(); } - public function assign_vars(array $var = array()) + public function assign_vars($var, $nocache = true) { - parent::assign($var); + parent::assign($var, NULL, $nocache); } - private function Menus() + private function adm_main() { - global $PLANET, $LNG, $USER, $CONF, $resource, $db; - - //PlanetMenu - if(isset($USER['PLANETS'])) - $USER['PLANETS'] = getPlanets($USER); + global $LNG, $CONF, $USER; - if($PLANET[$resource[43]] > 0) - $this->loadscript("gate.js"); - - $this->loadscript("topnav.js"); - $this->loadscript("planetmenu.js"); - $this->phpself = "?page=".request_var('page', '')."&mode=".request_var('mode', ''); - $PlanetSelect = array(); - $Scripttime = array(); - foreach($USER['PLANETS'] as $CurPlanetID => $PlanetQuery) - { - if(!empty($PlanetQuery['b_building_id'])) - { - $QueueArray = unserialize($PlanetQuery['b_building_id']); - foreach($QueueArray as $ListIDArray) - { - if($ListIDArray[3] > TIMESTAMP) - $Scripttime[$PlanetQuery['id']][] = $ListIDArray[3] - TIMESTAMP; - } + $dateTimeServer = new DateTime("now"); + if(isset($USER['timezone'])) { + try { + $dateTimeUser = new DateTime("now", new DateTimeZone($USER['timezone'])); + } catch (Exception $e) { + $dateTimeUser = $dateTimeServer; } - $Planetlist[$PlanetQuery['id']] = array( - 'url' => $this->phpself."&cp=".$PlanetQuery['id'], - 'name' => $PlanetQuery['name'].(($PlanetQuery['planet_type'] == 3) ? " (".$LNG['fcm_moon'].")":""), - 'image' => $PlanetQuery['image'], - 'galaxy' => $PlanetQuery['galaxy'], - 'system' => $PlanetQuery['system'], - 'planet' => $PlanetQuery['planet'], - 'ptype' => $PlanetQuery['planet_type'], - ); - - $PlanetSelect[$this->phpself."&cp=".$PlanetQuery['id']] = $PlanetQuery['name'].(($PlanetQuery['planet_type'] == 3) ? " (" . $LNG['fcm_moon'] . ")":"")." [".$PlanetQuery['galaxy'].":".$PlanetQuery['system'].":".$PlanetQuery['planet']."]  "; - } - - if($USER['urlaubs_modus'] == 1) { - $CONF['metal_basic_income'] = 0; - $CONF['crystal_basic_income'] = 0; - $CONF['deuterium_basic_income'] = 0; + } else { + $dateTimeUser = $dateTimeServer; } - $Messages = $db->countquery("SELECT COUNT(*) FROM ".MESSAGES." WHERE `message_owner` = ".$USER['id']." AND `message_unread` = '1'"); - - $this->assign_vars(array( - 'PlanetMenu' => $Planetlist, - 'show_planetmenu' => $LNG['show_planetmenu'], - 'current_pid' => $PLANET['id'], - 'Scripttime' => json_encode($Scripttime), - 'new_message' => $Messages, - 'forum_url' => $CONF['forum_url'], - 'topnav' => true, - 'metal' => $PLANET['metal'], - 'crystal' => $PLANET['crystal'], - 'deuterium' => $PLANET['deuterium'], - 'energy' => (($PLANET['energy_max'] + $PLANET['energy_used']) < 0) ? colorRed(shortly_number($PLANET['energy_max'] + $PLANET['energy_used']).'/'.shortly_number($PLANET['energy_max'])) : shortly_number($PLANET['energy_max'] + $PLANET['energy_used']) . '/' . shortly_number($PLANET['energy_max']), - 'energy_alt' => pretty_number($PLANET['energy_max'] + $PLANET['energy_used']).'/'.pretty_number($PLANET['energy_max']), - 'darkmatter' => $USER['darkmatter'], - 'metal_max' => $PLANET['metal_max'], - 'crystal_max' => $PLANET['crystal_max'], - 'deuterium_max' => $PLANET['deuterium_max'], - 'js_metal_max' => floattostring($PLANET['metal_max']), - 'js_crystal_max' => floattostring($PLANET['crystal_max']), - 'js_deuterium_max' => floattostring($PLANET['deuterium_max']), - 'js_metal_hr' => $PLANET['planet_type'] == 1 ? floattostring($PLANET['metal_perhour'] + $CONF['metal_basic_income'] * $CONF['resource_multiplier']) : 0, - 'js_crystal_hr' => $PLANET['planet_type'] == 1 ? floattostring($PLANET['crystal_perhour'] + $CONF['crystal_basic_income'] * $CONF['resource_multiplier']) : 0, - 'js_deuterium_hr' => $PLANET['planet_type'] == 1 ? floattostring($PLANET['deuterium_perhour'] + $CONF['deuterium_basic_income'] * $CONF['resource_multiplier']) : 0, - 'current_planet' => $this->phpself."&cp=".$PLANET['id'], - 'tn_vacation_mode' => $LNG['tn_vacation_mode'], - 'closed' => !$CONF['game_disable'] ? $LNG['ov_closed'] : false, - 'vacation' => $USER['urlaubs_modus'] ? tz_date($USER['urlaubs_until']) : false, - 'delete' => $USER['db_deaktjava'] ? sprintf($LNG['tn_delete_mode'], tz_date($USER['db_deaktjava'] + ($CONF['del_user_manually'] * 86400))) : false, - 'image' => $PLANET['image'], - 'settings_tnstor' => $USER['settings_tnstor'], - 'PlanetSelect' => $PlanetSelect, - 'Metal' => $LNG['Metal'], - 'Crystal' => $LNG['Crystal'], - 'Deuterium' => $LNG['Deuterium'], - 'Darkmatter' => $LNG['Darkmatter'], - 'Energy' => $LNG['Energy'], - 'class' => 'normal', - )); - } - - private function main() - { - global $USER, $CONF, $LANG, $LNG, $THEME; - $this->assign_vars(array( - 'title' => $CONF['game_name'], - 'uni_name' => $CONF['uni_name'], - 'dpath' => $THEME->getTheme(), - 'vmode' => $USER['urlaubs_modus'], - 'is_pmenu' => $USER['settings_planetmenu'], - 'authlevel' => $USER['authlevel'], - 'lang' => $LANG->getUser(), - 'ready' => $LNG['ready'], - 'date' => explode("|", date('Y\|n\|j\|G\|i\|s\|Z', TIMESTAMP)), - 'cron' => GetCrons(), - 'ga_active' => $CONF['ga_active'], - 'ga_key' => $CONF['ga_key'], - 'debug' => $CONF['debug'], - 'fcm_info' => $LNG['fcm_info'], - 'VERSION' => $CONF['VERSION'], - 'REV' => substr($CONF['VERSION'], -4), - 'js_tdformat' => $LNG['js_tdformat'], - 'week_day' => json_encode($LNG['week_day']), - 'months' => json_encode($LNG['months']), - 'TimeZone' => ($USER['timezone'] + $USER['dst']) * 3600, - 'Offset' => tz_diff(), - )); - } - - private function adm_main() - { - global $LNG, $CONF; $this->assign_vars(array( 'scripts' => $this->script, - 'title' => $CONF['game_name'].' - '.$LNG['adm_cp_title'], + 'title' => Config::get('game_name').' - '.$LNG['adm_cp_title'], 'fcm_info' => $LNG['fcm_info'], + 'lang' => $LNG->getLanguage(), + 'REV' => substr(Config::get('VERSION'), -4), + 'date' => explode("|", date('Y\|n\|j\|G\|i\|s\|Z', TIMESTAMP)), + 'Offset' => $dateTimeUser->getOffset() - $dateTimeServer->getOffset(), + 'VERSION' => Config::get('VERSION'), + 'dpath' => 'styles/theme/gow/', + 'bodyclass' => 'full' )); } - public function login_main() - { - global $USER, $CONF, $LNG, $LANG, $UNI; - $this->assign_vars(array( - 'cappublic' => $CONF['cappublic'], - 'servername' => $CONF['game_name'], - 'forum_url' => $CONF['forum_url'], - 'fb_active' => $CONF['fb_on'], - 'fb_key' => $CONF['fb_apikey'], - 'mail_active' => $CONF['mail_active'], - 'forum' => $LNG['forum'], - 'register_closed' => $LNG['register_closed'], - 'fb_perm' => sprintf($LNG['fb_perm'], $CONF['game_name']), - 'menu_index' => $LNG['menu_index'], - 'menu_news' => $LNG['menu_news'], - 'menu_rules' => $LNG['menu_rules'], - 'menu_agb' => $LNG['menu_agb'], - 'menu_pranger' => $LNG['menu_pranger'], - 'menu_top100' => $LNG['menu_top100'], - 'menu_disclamer' => $LNG['menu_disclamer'], - 'game_captcha' => $CONF['capaktiv'], - 'reg_close' => $CONF['reg_closed'], - 'ref_active' => $CONF['ref_active'], - 'ga_active' => $CONF['ga_active'], - 'ga_key' => $CONF['ga_key'], - 'getajax' => request_var('getajax', 0), - 'lang' => $LANG->getUser(), - 'UNI' => $UNI, - 'VERSION' => $CONF['VERSION'], - 'REV' => substr($CONF['VERSION'], -4), - 'langs' => json_encode(Language::getAllowedLangs(false)), - )); - } - - public function isPopup() - { - $this->assign_vars(array( - 'class' => 'popup', - )); - $this->Popup = true; - } - - public function isDialog() - { - $this->Dialog = true; - } - public function show($file) { - global $USER, $PLANET, $CONF, $LNG, $db, $THEME; + global $USER, $PLANET, $CONF, $LNG, $THEME; if($THEME->isCustomTPL($file)) - $this->template_dir = $THEME->getTemplatePath(); + $this->setTemplateDir($THEME->getTemplatePath()); - if(!defined('INSTALL')) { - if(defined('IN_ADMIN')) { - $this->adm_main(); - } elseif(defined('LOGIN')) { - $this->template_dir .= 'index/'; - $this->login_main(); - } elseif(!$this->Dialog) { - if(!defined('AJAX')) { - $_SESSION['USER'] = $USER; - $_SESSION['PLANET'] = $PLANET; - } - $this->main(); - if($this->Popup === false) - $this->Menus(); - } + $tplDir = $this->getTemplateDir(); + + if(MODE === 'INSTALL') { + $this->setTemplateDir($tplDir[0].'install/'); + } elseif(MODE === 'ADMIN') { + $this->setTemplateDir($tplDir[0].'adm/'); + $this->adm_main(); } $this->assign_vars(array( - 'scripts' => $this->jsscript, - 'execscript' => implode("\n", $this->script), + 'scripts' => $this->jsscript, + 'execscript' => implode("\n", $this->script), )); - + + $this->assign_vars(array( + 'LNG' => $LNG, + ), false); + + $this->compile_id = $LNG->getLanguage(); + + parent::display($file); + } + + public function display($file) + { + global $LNG; + $this->compile_id = $LNG->getLanguage(); parent::display($file); } @@ -283,8 +154,6 @@ public function gotoside($dest, $time = 3) public function message($mes, $dest = false, $time = 3, $Fatal = false) { global $LNG, $THEME; - if($Fatal) - $this->isPopup(true); $this->assign_vars(array( 'mes' => $mes, @@ -294,12 +163,19 @@ public function message($mes, $dest = false, $time = 3, $Fatal = false) )); $this->gotoside($dest, $time); - if (defined('IN_ADMIN')) { - $this->show('adm/error_message_body.tpl'); - exit; - } $this->show('error_message_body.tpl'); } + + public static function printMessage($Message, $fullSide = true, $redirect = NULL) { + $template = new self; + if(!isset($redirect)) { + $redirect = array(false, 0); + } + + $template->message($Message, $redirect[0], $redirect[1], !$fullSide); + exit; + } + /** * Workaround for new Smarty Method to add custom props... */ @@ -338,5 +214,3 @@ public function __set($name, $value) } } } - -?> \ No newline at end of file diff --git a/includes/classes/class.theme.php b/includes/classes/class.theme.php index 06aafcf..314528e 100644 --- a/includes/classes/class.theme.php +++ b/includes/classes/class.theme.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,13 +18,12 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class Theme @@ -49,6 +48,7 @@ function setUserTheme($Theme) { $this->skin = $Theme; $this->parseStyleCFG(); + $this->setStyleSettings(); } function getTheme() { @@ -76,6 +76,24 @@ function parseStyleCFG() { $this->customtpls = (array) $Skin['templates']; } + function setStyleSettings() { + if(file_exists(ROOT_PATH.'styles/theme/'.$this->skin.'/settings.cfg')) { + require(ROOT_PATH.'styles/theme/'.$this->skin.'/settings.cfg'); + } + + $this->THEMESETTINGS = array_merge(array( + 'PLANET_ROWS_ON_OVERVIEW' => 2, + 'SHORTCUT_ROWS_ON_FLEET1' => 2, + 'COLONY_ROWS_ON_FLEET1' => 2, + 'ACS_ROWS_ON_FLEET1' => 1, + 'TOPNAV_SHORTLY_NUBMER' => 0, + ), $THEMESETTINGS); + } + + function getStyleSettings() { + return $this->THEMESETTINGS; + } + static function getAvalibleSkins() { if(!isset(self::$Themes)) { @@ -99,5 +117,3 @@ static function getAvalibleSkins() { return self::$Themes; } } - -?> \ No newline at end of file diff --git a/includes/classes/cronjob/CleanerCronjob.class.php b/includes/classes/cronjob/CleanerCronjob.class.php new file mode 100644 index 0000000..51eb2b2 --- /dev/null +++ b/includes/classes/cronjob/CleanerCronjob.class.php @@ -0,0 +1,81 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2009 Lucky + * @copyright 2011 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2011-12-10) + * @info $Id$ + * @link http://code.google.com/p/2moons/ + */ + +class CleanerCronjob +{ + function run() + { + $CONF = Config::getAll(NULL, ROOT_UNI); + + $unis = array_keys(Config::getAll(NULL)); + + $GLOBALS['DATABASE']->query("LOCK TABLES ".ALLIANCE." WRITE, ".ALLIANCE_REQUEST." WRITE, + ".BUDDY." WRITE, ".CONFIG." WRITE, ".FLEETS." WRITE, ".FLEETS_EVENT." WRITE, + ".NOTES." WRITE, ".MESSAGES." WRITE, ".PLANETS." WRITE, + ".RW." WRITE, ".SESSION." WRITE, ".STATPOINTS." WRITE, + ".TOPKB." WRITE, ".TOPKB_USERS." WRITE, ".USERS." WRITE;"); + + //Delete old messages + $del_before = TIMESTAMP - ($CONF['del_oldstuff'] * 86400); + $del_inactive = TIMESTAMP - ($CONF['del_user_automatic'] * 86400); + $del_deleted = TIMESTAMP - ($CONF['del_user_manually'] * 86400); + + $GLOBALS['DATABASE']->multi_query("DELETE FROM ".MESSAGES." WHERE `message_time` < '". $del_before ."'; + DELETE FROM ".ALLIANCE." WHERE `ally_members` = '0'; + DELETE FROM ".PLANETS." WHERE `destruyed` < ".TIMESTAMP." AND `destruyed` != 0; + DELETE FROM ".SESSION." WHERE `lastonline` < '".(TIMESTAMP - SESSION_LIFETIME)."'; + DELETE FROM ".FLEETS_EVENT." WHERE fleetID NOT IN (SELECT fleet_id FROM ".FLEETS."); + UPDATE ".USERS." SET `email_2` = `email` WHERE `setmail` < '".TIMESTAMP."';"); + + $ChooseToDelete = $GLOBALS['DATABASE']->query("SELECT `id` FROM `".USERS."` WHERE `authlevel` = '".AUTH_USR."' AND ((`db_deaktjava` != 0 AND `db_deaktjava` < '".$del_deleted."')".($del_inactive == TIMESTAMP ? "" : " OR `onlinetime` < '".$del_inactive."'").");"); + + if(isset($ChooseToDelete)) + { + include_once(ROOT_PATH.'includes/functions/DeleteSelectedUser.php'); + while($delete = $GLOBALS['DATABASE']->fetch_array($ChooseToDelete)) + { + DeleteSelectedUser($delete['id']); + } + } + + $GLOBALS['DATABASE']->free_result($ChooseToDelete); + + foreach($unis as $uni) + { + $battleHallLowest = $GLOBALS['DATABASE']->getFirstCell("SELECT units FROM ".TOPKB." WHERE `universe` = ".$uni." ORDER BY units DESC LIMIT 99,1;"); + if(isset($battleHallLowest)) + { + $GLOBALS['DATABASE']->query("DELETE ".TOPKB.", ".TOPKB_USERS." FROM ".TOPKB." INNER JOIN ".TOPKB_USERS." USING (rid) WHERE `universe` = ".$uni." AND `units` < ".$battleHallLowest.";"); + } + } + + $GLOBALS['DATABASE']->query("DELETE FROM ".RW." WHERE `time` < ". $del_before ." AND `rid` NOT IN (SELECT `rid` FROM ".TOPKB.");"); + $GLOBALS['DATABASE']->query("UNLOCK TABLES;"); + } +} \ No newline at end of file diff --git a/includes/classes/cronjob/DailyCronjob.class.php b/includes/classes/cronjob/DailyCronjob.class.php new file mode 100644 index 0000000..9ffe768 --- /dev/null +++ b/includes/classes/cronjob/DailyCronjob.class.php @@ -0,0 +1,68 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2009 Lucky + * @copyright 2011 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2011-12-10) + * @info $Id$ + * @link http://code.google.com/p/2moons/ + */ + +class DailyCronJob +{ + function run() + { + $this->optimizeTables(); + $this->clearCache(); + $this->reCalculateCronjobs(); + $this->clearEcoCache(); + } + + function optimizeTables() + { + $tables = $GLOBALS['DATABASE']->query("SHOW TABLE STATUS FROM ".DB_NAME.";"); + $SQL = array(); + while($table = $GLOBALS['DATABASE']->fetch_array($tables)){ + $prefix = explode("_", $table['Name']); + + if($prefix[0].'_' === DB_PREFIX && $prefix[1] !== 'session') + $SQL[] = $table['Name']; + } + + $GLOBALS['DATABASE']->query("OPTIMIZE TABLE ".implode(', ',$SQL).";"); + } + + function clearCache() + { + ClearCache(); + } + + function reCalculateCronjobs() + { + Cronjob::reCalculateCronjobs(); + } + + function clearEcoCache() + { + $GLOBALS['DATABASE']->query("UPDATE ".PLANETS." SET eco_hash = '';"); + } +} diff --git a/includes/classes/cronjob/DumpCronjob.class.php b/includes/classes/cronjob/DumpCronjob.class.php new file mode 100644 index 0000000..781824f --- /dev/null +++ b/includes/classes/cronjob/DumpCronjob.class.php @@ -0,0 +1,60 @@ + +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2009 Lucky + * @copyright 2011 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2011-12-10) + * @info $Id$ + * @link http://code.google.com/p/2moons/ + */ + +class DumpCronjob +{ + function run() + { + $prefixCounts = strlen(DB_PREFIX); + $dbTables = array(); + $sqlTableRaw = $GLOBALS['DATABASE']->query("SHOW TABLE STATUS FROM `".DB_NAME."`;"); + + while($table = $GLOBALS['DATABASE']->fetchArray($sqlTableRaw)) + { + if(DB_PREFIX == substr($table['Name'], 0, $prefixCounts)) + { + $dbTables[] = $table['Name']; + } + } + + if(empty($dbTables)) + { + throw new Exception('No tables found for dump.'); + } + + $fileName = '2MoonsBackup_'.date('d_m_Y_H_i_s', TIMESTAMP).'.sql'; + $filePath = ROOT_PATH.'includes/backups/'.$fileName; + + require ROOT_PATH.'includes/classes/SQLDumper.class.php'; + + $dump = new SQLDumper; + $dump->dumpTablesToFile($dbTables, $filePath); + } +} \ No newline at end of file diff --git a/includes/classes/cronjob/InactiveMailCronjob.class.php b/includes/classes/cronjob/InactiveMailCronjob.class.php new file mode 100644 index 0000000..3e4473b --- /dev/null +++ b/includes/classes/cronjob/InactiveMailCronjob.class.php @@ -0,0 +1,63 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2009 Lucky + * @copyright 2011 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2011-12-10) + * @info $Id$ + * @link http://code.google.com/p/2moons/ + */ + +class InactiveMailCronjob +{ + function run() + { + global $LNG; + + $CONFIG = Config::getAll(NULL); + $CONF = $CONFIG[ROOT_UNI]; + $langObjects = array(); + + require_once ROOT_PATH.'includes/classes/Mail.class.php'; + + if($CONF['mail_active'] == 1) { + $Users = $GLOBALS['DATABASE']->query("SELECT `id`, `username`, `lang`, `email`, `onlinetime`, `universe` FROM ".USERS." WHERE `inactive_mail` = '0' AND `onlinetime` < '".(TIMESTAMP - $CONF['del_user_sendmail'] * 24 * 60 * 60)."';"); + while($User = $GLOBALS['DATABASE']->fetch_array($Users)) + { + if(!isset($langObjects[$User['lang']])) + { + $langObjects[$User['lang']] = new Language($User['lang']); + $langObjects[$User['lang']]->includeData(array('L18N', 'INGAME', 'PUBLIC', 'CUSTOM')); + } + + $LNG = $langObjects[$User['lang']]; + + $MailSubject = sprintf($LNG['spec_mail_inactive_title'], $CONF['game_name'].' - '.$CONFIG[$User['universe']]['uni_name']); + $MailRAW = $LNG->getTemplate('email_inactive'); + $MailContent = sprintf($MailRAW, $User['username'], $CONF['game_name'].' - '.$CONFIG[$User['universe']]['uni_name'], _date($LNG['php_tdformat'], $User['onlinetime']), PROTOCOL.$_SERVER['HTTP_HOST'].HTTP_ROOT); + + Mail::send($User['email'], $User['username'], $MailSubject, $MailContent); + $GLOBALS['DATABASE']->query("UPDATE ".USERS." SET `inactive_mail` = '1' WHERE `id` = '".$User['id']."';"); + } + } + } +} \ No newline at end of file diff --git a/includes/classes/cronjob/ReferralCronjob.class.php b/includes/classes/cronjob/ReferralCronjob.class.php new file mode 100644 index 0000000..c36912d --- /dev/null +++ b/includes/classes/cronjob/ReferralCronjob.class.php @@ -0,0 +1,65 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2009 Lucky + * @copyright 2011 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2011-12-10) + * @info $Id$ + * @link http://code.google.com/p/2moons/ + */ + +class ReferralCronJob +{ + function run() + { + $CONF = Config::getAll(NULL, ROOT_UNI); + + if($CONF['ref_active'] != 1) + { + return; + } + + $Users = $GLOBALS['DATABASE']->query("SELECT user.`username`, user.`ref_id`, user.`id`, user.`lang` + FROM ".USERS." user + INNER JOIN ".STATPOINTS." as stats + ON stats.`id_owner` = user.`id` AND stats.`stat_type` = '1' AND stats.`total_points` >= ".$CONF['ref_minpoints']." + WHERE user.`ref_bonus` = 1;"); + + $langObjects = array(); + + while($User = $GLOBALS['DATABASE']->fetch_array($Users)) + { + if(!isset($langObjects[$User['lang']])) + { + $langObjects[$User['lang']] = new Language($User['lang']); + $langObjects[$User['lang']]->includeData(array('L18N', 'INGAME', 'TECH', 'CUSTOM')); + } + + $LNG = $langObjects[$User['lang']]; + $GLOBALS['DATABASE']->multi_query("UPDATE ".USERS." SET `darkmatter` = `darkmatter` + ".$CONF['ref_bonus']." WHERE `id` = ".$User['ref_id']."; + UPDATE ".USERS." SET `ref_bonus` = `ref_bonus` = '0' WHERE `id` = ".$User['id'].";"); + + $Message = sprintf($LNG['sys_refferal_text'], $User['username'], pretty_number($CONF['ref_minpoints']), pretty_number($CONF['ref_bonus']), $LNG['tech'][921]); + SendSimpleMessage($User['ref_id'], '', TIMESTAMP, 4, $LNG['sys_refferal_from'], sprintf($LNG['sys_refferal_title'], $User['username']), $Message); + } + } +} \ No newline at end of file diff --git a/includes/pages/ShowFAQ.php b/includes/classes/cronjob/StatisticCronjob.class.php similarity index 57% rename from includes/pages/ShowFAQ.php rename to includes/classes/cronjob/StatisticCronjob.class.php index 4bbc263..1f459bc 100644 --- a/includes/pages/ShowFAQ.php +++ b/includes/classes/cronjob/StatisticCronjob.class.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2011 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,30 +18,25 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2009 Lucky + * @copyright 2011 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2011-12-10) * @info $Id$ * @link http://code.google.com/p/2moons/ */ - -function ShowFAQPage() -{ - global $USER, $PLANET, $LNG, $LANG; - $PlanetRess = new ResourceUpdate(); - $PlanetRess->CalcResource(); - $PlanetRess->SavePlanetToDB(); - $template = new template(); - $LANG->includeLang(array('FAQ')); - $template->assign_vars(array( - 'FAQList' => $LNG['faq'], - 'faq_overview' => $LNG['faq_overview'], - )); - - $template->show("faq_overview.tpl"); -} -?> \ No newline at end of file +class StatisticCronjob +{ + function run() + { + require_once(ROOT_PATH.'includes/classes/class.statbuilder.php'); + $stat = new Statbuilder(); + $result = $stat->MakeStats(); + Config::update(array( + 'stat_last_update' => TIMESTAMP + )); + } +} \ No newline at end of file diff --git a/includes/pages/ShowLogoutPage.php b/includes/classes/cronjob/TeamSpeakCronjob.class.php similarity index 55% rename from includes/pages/ShowLogoutPage.php rename to includes/classes/cronjob/TeamSpeakCronjob.class.php index c0f16d7..97e25af 100644 --- a/includes/pages/ShowLogoutPage.php +++ b/includes/classes/cronjob/TeamSpeakCronjob.class.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2011 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,31 +18,20 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2009 Lucky + * @copyright 2011 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2011-12-10) * @info $Id$ * @link http://code.google.com/p/2moons/ */ -function ShowLogoutPage() +class TeamSpeakCronjob { - global $LNG, $SESSION; - - $SESSION->DestroySession(); - - $template = new template(); - $template->cache = true; - $template->isPopup(true); - $template->assign_vars(array( - 'lo_title' => $LNG['lo_title'], - 'lo_logout' => $LNG['lo_logout'], - 'lo_redirect' => $LNG['lo_redirect'], - 'lo_notify' => $LNG['lo_notify'], - 'lo_continue' => $LNG['lo_continue'], - )); - $template->show("logout_overview.tpl"); -} -?> \ No newline at end of file + function run() + { + $GLOBALS['CACHE']->add('teamspeak', 'TeamspeakBuildCache'); + $GLOBALS['CACHE']->flush('teamspeak'); + } +} \ No newline at end of file diff --git a/includes/classes/cronjob/TrackingCronjob.class.php b/includes/classes/cronjob/TrackingCronjob.class.php new file mode 100644 index 0000000..0b5130a --- /dev/null +++ b/includes/classes/cronjob/TrackingCronjob.class.php @@ -0,0 +1,71 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2009 Lucky + * @copyright 2011 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2011-12-10) + * @info $Id$ + * @link http://code.google.com/p/2moons/ + */ + +class TrackingCronjob +{ + function run() + { + $serverData['php'] = PHP_VERSION; + + try { + $serverData['installSince'] = $GLOBALS['DATABASE']->getFirstCell("SELECT register_time FROM ".USERS." WHERE id = ".ROOT_USER); + } catch (Exception $e) { + $serverData['installSince'] = NULL; + } + + try { + $serverData['users'] = $GLOBALS['DATABASE']->getFirstCell("SELECT COUNT(*) FROM ".USERS.";"); + } catch (Exception $e) { + $serverData['users'] = NULL; + } + + try { + $serverData['unis'] = $GLOBALS['DATABASE']->getFirstCell("SELECT COUNT(*) FROM ".CONFIG.";"); + } catch (Exception $e) { + $serverData['unis'] = NULL; + } + + try { + $serverData['version'] = Config::get('VERSION'); + } catch (Exception $e) { + $serverData['version'] = NULL; + } + + $this->ch = curl_init('http://tracking.2moons.cc/'); + curl_setopt($this->ch, CURLOPT_HTTPGET, true); + curl_setopt($this->ch, CURLOPT_AUTOREFERER, true); + curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($this->ch, CURLOPT_POSTFIELDS, $serverData); + curl_setopt($this->ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; 2Moons/".Config::get('VERSION')."; +http://2moons.cc)"); + + curl_exec($this->ch); + curl_close($this->ch); + } +} \ No newline at end of file diff --git a/includes/classes/missions/GenerateReport.php b/includes/classes/missions/GenerateReport.php index 89c9f36..c565c7c 100644 --- a/includes/classes/missions/GenerateReport.php +++ b/includes/classes/missions/GenerateReport.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,96 +18,97 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ -function GenerateReport($RESULT, $INFO) +function GenerateReport($combatResult, $raportInfo) { - $des = array('att' => 0, 'def' => 0); + $Destroy = array('att' => 0, 'def' => 0); $DATA = array(); - $DATA['mode'] = (int) $INFO['moon']['des']; - $DATA['time'] = $INFO['fleet_start_time']; - $DATA['start'] = array($INFO['fleet_start_galaxy'], $INFO['fleet_start_system'], $INFO['fleet_start_planet'], $INFO['fleet_start_type']); - $DATA['koords'] = array($INFO['fleet_end_galaxy'], $INFO['fleet_end_system'], $INFO['fleet_end_planet'], $INFO['fleet_end_type']); - $DATA['units'] = array($RESULT['lost']['att'], $RESULT['lost']['def']); - $DATA['debris'] = array($RESULT['debree']['att'][0] + $RESULT['debree']['def'][0], $RESULT['debree']['att'][1] + $RESULT['debree']['def'][1]); - $DATA['steal'] = array($INFO['steal']['metal'], $INFO['steal']['crystal'], $INFO['steal']['deuterium']); - $DATA['result'] = $RESULT['won']; + $DATA['mode'] = (int) $raportInfo['moonDestroy']; + $DATA['time'] = $raportInfo['thisFleet']['fleet_start_time']; + $DATA['start'] = array($raportInfo['thisFleet']['fleet_start_galaxy'], $raportInfo['thisFleet']['fleet_start_system'], $raportInfo['thisFleet']['fleet_start_planet'], $raportInfo['thisFleet']['fleet_start_type']); + $DATA['koords'] = array($raportInfo['thisFleet']['fleet_end_galaxy'], $raportInfo['thisFleet']['fleet_end_system'], $raportInfo['thisFleet']['fleet_end_planet'], $raportInfo['thisFleet']['fleet_end_type']); + $DATA['units'] = array($combatResult['unitLost']['attacker'], $combatResult['unitLost']['defender']); + $DATA['debris'] = $raportInfo['debris']; + $DATA['steal'] = $raportInfo['stealResource']; + $DATA['result'] = $combatResult['won']; $DATA['moon'] = array( - $INFO['moon']['chance'], - $INFO['moon']['name'], - $INFO['moon']['desfail'], - $INFO['moon']['chance2'], - $INFO['moon']['fleetfail'] + 'moonName' => $raportInfo['moonName'], + 'moonChance' => (int) $raportInfo['moonChance'], + 'moonDestroyChance' => (int) $raportInfo['moonDestroyChance'], + 'moonDestroySuccess' => (int) $raportInfo['moonDestroySuccess'], + 'fleetDestroyChance' => (int) $raportInfo['fleetDestroyChance'], + 'fleetDestroySuccess' => (int) $raportInfo['fleetDestroySuccess'] ); - $DATA['simu'] = isset($INFO['battlesim']) ? $INFO['battlesim'] : ""; - + if(isset($raportInfo['additionalInfo'])) + { + $DATA['additionalInfo'] = $raportInfo['additionalInfo']; + } + else + { + $DATA['additionalInfo'] = ""; + } - foreach($RESULT['rw'][0]['attackers'] as $Player) + foreach($combatResult['rw'][0]['attackers'] as $player) { - $DATA['players'][$Player['user']['id']] = array( - 'name' => $Player['user']['username'], - 'koords' => array($Player['fleet']['fleet_start_galaxy'], $Player['fleet']['fleet_start_system'], $Player['fleet']['fleet_start_planet']), - 'tech' => array($Player['techs'][0] * 100, $Player['techs'][1] * 100, $Player['techs'][2] * 100), + $DATA['players'][$player['player']['id']] = array( + 'name' => $player['player']['username'], + 'koords' => array($player['fleetDetail']['fleet_start_galaxy'], $player['fleetDetail']['fleet_start_system'], $player['fleetDetail']['fleet_start_planet'], $player['fleetDetail']['fleet_start_type']), + 'tech' => array($player['techs'][0] * 100, $player['techs'][1] * 100, $player['techs'][2] * 100), ); } - foreach($RESULT['rw'][0]['defenders'] as $FleetID => $Player) + foreach($combatResult['rw'][0]['defenders'] as $FleetID => $player) { - if($FleetID == 0) { - $Koords = $DATA['koords']; - } else { - $Koords = array( - $Player['fleet']['fleet_start_galaxy'], - $Player['fleet']['fleet_start_system'], - $Player['fleet']['fleet_start_planet'] - ); - } - - $DATA['players'][$Player['user']['id']] = array( - 'name' => $Player['user']['username'], - 'koords' => $Koords, - 'tech' => array($Player['techs'][0] * 100, $Player['techs'][1] * 100, $Player['techs'][2] * 100), + $DATA['players'][$player['player']['id']] = array( + 'name' => $player['player']['username'], + 'koords' => array($player['fleetDetail']['fleet_start_galaxy'], $player['fleetDetail']['fleet_start_system'], $player['fleetDetail']['fleet_start_planet'], $player['fleetDetail']['fleet_start_type']), + 'tech' => array($player['techs'][0] * 100, $player['techs'][1] * 100, $player['techs'][2] * 100), ); } - foreach($RESULT['rw'] as $Round => $RoundInfo) + foreach($combatResult['rw'] as $Round => $RoundInfo) { - foreach($RoundInfo['attackers'] as $FleetID => $Player) + foreach($RoundInfo['attackers'] as $FleetID => $player) { - $DATA['rounds'][$Round]['attacker'][$Player['user']['id']] = array(); + $playerData = array('userID' => $player['player']['id'], 'ships' => array()); - if(array_sum($Player['detail']) == 0) { + if(array_sum($player['unit']) == 0) { + $DATA['rounds'][$Round]['attacker'][] = $playerData; $Destroy['att']++; continue; } - foreach($Player['detail'] as $ShipID => $Amount) + foreach($player['unit'] as $ShipID => $Amount) { if ($Amount <= 0) continue; + $ShipInfo = $RoundInfo['infoA'][$FleetID][$ShipID]; - $DATA['rounds'][$Round]['attacker'][$Player['user']['id']][$ShipID] = array( + $playerData['ships'][$ShipID] = array( $Amount, $ShipInfo['att'], $ShipInfo['def'], $ShipInfo['shield'] ); } + + $DATA['rounds'][$Round]['attacker'][] = $playerData; } - foreach($RoundInfo['defenders'] as $FleetID => $Player) + foreach($RoundInfo['defenders'] as $FleetID => $player) { - $DATA['rounds'][$Round]['defender'][$Player['user']['id']] = array(); - if(array_sum($Player['def']) == 0) { + $playerData = array('userID' => $player['player']['id'], 'ships' => array()); + if(array_sum($player['unit']) == 0) { + $DATA['rounds'][$Round]['defender'][] = $playerData; $Destroy['def']++; continue; } - foreach($Player['def'] as $ShipID => $Amount) + foreach($player['unit'] as $ShipID => $Amount) { if ($Amount <= 0) { $Destroy['def']++; @@ -115,18 +116,21 @@ function GenerateReport($RESULT, $INFO) } $ShipInfo = $RoundInfo['infoD'][$FleetID][$ShipID]; - $DATA['rounds'][$Round]['defender'][$Player['user']['id']][$ShipID] = array( + $playerData['ships'][$ShipID] = array( $Amount, $ShipInfo['att'], $ShipInfo['def'], $ShipInfo['shield'] ); } + $DATA['rounds'][$Round]['defender'][] = $playerData; } - if ($Round >= MAX_ATTACK_ROUNDS || $des['att'] == count($RoundInfo['attackers']) || $des['def'] == count($RoundInfo['defenders'])) + if ($Round >= MAX_ATTACK_ROUNDS || $Destroy['att'] == count($RoundInfo['attackers']) || $Destroy['def'] == count($RoundInfo['defenders'])) break; - - $DATA['rounds'][$Round]['info'] = array($RoundInfo['attack'], $RoundInfo['attackShield'], $RoundInfo['defense'], $RoundInfo['defShield']); + + if(isset($RoundInfo['attack'], $RoundInfo['attackShield'], $RoundInfo['defense'], $RoundInfo['defShield'])) + $DATA['rounds'][$Round]['info'] = array($RoundInfo['attack'], $RoundInfo['attackShield'], $RoundInfo['defense'], $RoundInfo['defShield']); + else + $DATA['rounds'][$Round]['info'] = array(NULL, NULL, NULL, NULL); } return $DATA; } - -?> \ No newline at end of file + \ No newline at end of file diff --git a/includes/classes/missions/MissionCaseACS.php b/includes/classes/missions/MissionCaseACS.php index d6e9d9c..e19d110 100644 --- a/includes/classes/missions/MissionCaseACS.php +++ b/includes/classes/missions/MissionCaseACS.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,13 +18,12 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class MissionCaseACS extends MissionFunctions @@ -37,6 +36,8 @@ function __construct($Fleet) function TargetEvent() { + $this->setState(FLEET_RETURN); + $this->SaveFleet(); return; } @@ -47,14 +48,11 @@ function EndStayEvent() function ReturnEvent() { - global $LANG; - $LNG = $LANG->GetUserLang($this->_fleet['fleet_owner']); - - $Message = sprintf($LNG['sys_fleet_won'], $TargetName, GetTargetAdressLink($this->_fleet, ''), pretty_number($this->_fleet['fleet_resource_metal']), $LNG['Metal'], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['Crystal'], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['Deuterium'] ); + $LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']); + $TargetName = $GLOBALS['DATABASE']->getFirstCell("SELECT name FROM ".PLANETS." WHERE id = ".$this->_fleet['fleet_start_id'].";"); + $Message = sprintf($LNG['sys_fleet_won'], $TargetName, GetTargetAdressLink($this->_fleet, ''), pretty_number($this->_fleet['fleet_resource_metal']), $LNG['tech'][901], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['tech'][902], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['tech'][903] ); SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_end_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_mess_fleetback'], $Message); $this->RestoreFleet(); } } - -?> \ No newline at end of file diff --git a/includes/classes/missions/MissionCaseAttack.php b/includes/classes/missions/MissionCaseAttack.php index 070aceb..b45dc22 100644 --- a/includes/classes/missions/MissionCaseAttack.php +++ b/includes/classes/missions/MissionCaseAttack.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,13 +18,12 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class MissionCaseAttack extends MissionFunctions @@ -36,300 +35,463 @@ function __construct($Fleet) function TargetEvent() { - global $pricelist, $resource, $reslist, $db, $LANG; + global $resource, $reslist; - $targetPlanet = $db->uniquequery("SELECT * FROM ".PLANETS." WHERE `id` = '". $this->_fleet['fleet_end_id'] ."';"); - $targetUser = $db->uniquequery("SELECT * FROM ".USERS." WHERE id = '".$targetPlanet['id_owner']."';"); - - require_once(ROOT_PATH.'includes/classes/class.PlanetRessUpdate.php'); - - $targetUser['factor'] = getFactors($targetUser, 'basic', $this->_fleet['fleet_start_time']); - $PlanetRess = new ResourceUpdate(); - list($targetUser, $targetPlanet) = $PlanetRess->CalcResource($targetUser, $targetPlanet, true, $this->_fleet['fleet_start_time']); - $TargetUserID = $targetUser['id']; - $attackFleets = array(); - $AttackerRow['id'] = array(); - $AttackerRow['name'] = array(); - $DefenderRow['id'] = array(); - $DefenderRow['name'] = array(); - - if ($this->_fleet['fleet_group'] != 0) + $fleetAttack = array(); + $fleetDefend = array(); + + $userAttack = array(); + $userDefend = array(); + + $stealResource = array( + 901 => 0, + 902 => 0, + 903 => 0, + ); + + $debris = array(); + $planetDebris = array(); + + $raportInfo = array(); + + $debrisRessource = array(901, 902); + + $messageHTML = << + + + + + + + + + + + + + +
%s %s (%s)
%s%s: %s %s: %s
%s%s: %s %s: %s %s: %s
%s%s: %s %s: %s
+
+HTML; + //Minize HTML + $messageHTML = str_replace(array("\n", "\t", "\r"), "", $messageHTML); + + $targetPlanet = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".PLANETS." WHERE id = '".$this->_fleet['fleet_end_id']."';"); + $targetUser = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".USERS." WHERE id = '".$targetPlanet['id_owner']."';"); + + $targetUser['factor'] = getFactors($targetUser, 'basic', $this->_fleet['fleet_start_time']); + $planetUpdater = new ResourceUpdate(); + + list($targetUser, $targetPlanet) = $planetUpdater->CalcResource($targetUser, $targetPlanet, true, $this->_fleet['fleet_start_time']); + + if($this->_fleet['fleet_group'] != 0) { - $db->query("DELETE FROM ".AKS." WHERE `id` = '".$this->_fleet['fleet_group']."';"); - $fleets = $db->query("SELECT * FROM ".FLEETS." WHERE fleet_group = '".$this->_fleet['fleet_group']."';"); - while ($fleet = $db->fetch_array($fleets)) + $GLOBALS['DATABASE']->query("DELETE FROM ".AKS." WHERE id = '".$this->_fleet['fleet_group']."';"); + $incomingFleetsResult = $GLOBALS['DATABASE']->query("SELECT * FROM ".FLEETS." WHERE fleet_group = '".$this->_fleet['fleet_group']."';"); + + while ($incomingFleetsRow = $GLOBALS['DATABASE']->fetch_array($incomingFleetsResult)) { - $attackFleets[$fleet['fleet_id']]['fleet'] = $fleet; - $attackFleets[$fleet['fleet_id']]['user'] = $db->uniquequery("SELECT `id`, `username`, `military_tech`, `defence_tech`, `shield_tech`, `rpg_amiral`, `dm_defensive`, `dm_attack` FROM ".USERS." WHERE `id` = '".$fleet['fleet_owner']."';"); - $attackFleets[$fleet['fleet_id']]['user']['factor'] = getFactors($attackFleets[$fleet['fleet_id']]['user'], 'attack', $this->_fleet['fleet_start_time']); - $attackFleets[$fleet['fleet_id']]['detail'] = array(); - $temp = explode(';', $fleet['fleet_array']); - foreach ($temp as $temp2) - { - $temp2 = explode(',', $temp2); - if ($temp2[0] < 100) continue; - - if (!isset($attackFleets[$fleet['fleet_id']]['detail'][$temp2[0]])) - $attackFleets[$fleet['fleet_id']]['detail'][$temp2[0]] = 0; - - $attackFleets[$fleet['fleet_id']]['detail'][$temp2[0]] += $temp2[1]; - } - $AttackerRow['id'][] = $attackFleets[$fleet['fleet_id']]['user']['id']; + $incomingFleets[$incomingFleetsRow['fleet_id']] = $incomingFleetsRow; } + + $GLOBALS['DATABASE']->free_result($incomingFleetsResult); } else { - $attackFleets[$this->_fleet['fleet_id']]['fleet'] = $this->_fleet; - $attackFleets[$this->_fleet['fleet_id']]['user'] = $db->uniquequery("SELECT `id`, `username`, `military_tech`, `defence_tech`, `shield_tech`, `rpg_amiral`, `dm_defensive`, `dm_attack` FROM ".USERS." WHERE id = '".$this->_fleet['fleet_owner']."';"); - $attackFleets[$this->_fleet['fleet_id']]['user']['factor'] = getFactors($attackFleets[$this->_fleet['fleet_id']]['user'], 'attack', $this->_fleet['fleet_start_time']); - $attackFleets[$this->_fleet['fleet_id']]['detail'] = array(); - $temp = explode(';', $this->_fleet['fleet_array']); - foreach ($temp as $temp2) - { - $temp2 = explode(',', $temp2); - if ($temp2[0] < 100) continue; - - if (!isset($attackFleets[$this->_fleet['fleet_id']]['detail'][$temp2[0]])) - $attackFleets[$this->_fleet['fleet_id']]['detail'][$temp2[0]] = 0; - - $attackFleets[$this->_fleet['fleet_id']]['detail'][$temp2[0]] += $temp2[1]; - } - $AttackerRow['id'][] = $attackFleets[$this->_fleet['fleet_id']]['user']['id']; + $incomingFleets = array($this->_fleet['fleet_id'] => $this->_fleet); } - - $defense = array(); - - $def = $db->query("SELECT * FROM ".FLEETS." WHERE `fleet_mission` = '5' AND `fleet_end_id` = '".$this->_fleet['fleet_end_id']."' AND fleet_start_time <= '".TIMESTAMP."' AND fleet_end_stay >= '".TIMESTAMP."';"); - while ($defRow = $db->fetch_array($def)) + + foreach($incomingFleets as $fleetID => $fleetDetail) { - $defense[$defRow['fleet_id']]['user'] = $db->uniquequery("SELECT `id`, `username`, `military_tech`, `defence_tech`, `shield_tech`, `rpg_amiral`, `dm_defensive`, `dm_attack` FROM ".USERS." WHERE id = '".$defRow['fleet_owner']."';"); - $attackFleets[$this->_fleet['fleet_id']]['user']['factor'] = getFactors($defense[$defRow['fleet_id']]['user'], 'attack', $this->_fleet['fleet_start_time']); - $defRowDef = explode(';', $defRow['fleet_array']); - foreach ($defRowDef as $Element) - { - $Element = explode(',', $Element); - - if ($Element[0] < 100) continue; - - if (!isset($defense[$defRow['fleet_id']]['def'][$Element[0]])) - $defense[$defRow['fleet_id']][$Element[0]] = 0; - - $defense[$defRow['fleet_id']]['def'][$Element[0]] += $Element[1]; - } - $DefenderRow['id'][] = $defense[$defRow['fleet_id']]['user']['id']; + $fleetAttack[$fleetID]['fleetDetail'] = $fleetDetail; + $fleetAttack[$fleetID]['player'] = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".USERS." WHERE id = '".$fleetDetail['fleet_owner']."';"); + $fleetAttack[$fleetID]['player']['factor'] = getFactors($fleetAttack[$fleetID]['player'], 'attack', $this->_fleet['fleet_start_time']); + $fleetAttack[$fleetID]['unit'] = fleetAmountToArray($fleetDetail['fleet_array']); + + $userAttack[$fleetAttack[$fleetID]['player']['id']] = $fleetAttack[$fleetID]['player']['username']; } - - $defense[0]['def'] = array(); - $defense[0]['user'] = $targetUser; - $defense[0]['user']['factor'] = getFactors($defense[0]['user'], 'attack', $this->_fleet['fleet_start_time']); - $DefenderRow['id'][] = $defense[0]['user']['id']; + + $targetFleetsResult = $GLOBALS['DATABASE']->query("SELECT * FROM ".FLEETS." WHERE fleet_mission = '5' AND fleet_end_id = '".$this->_fleet['fleet_end_id']."' AND fleet_start_time <= '".TIMESTAMP."' AND fleet_end_stay >= '".TIMESTAMP."';"); + while ($fleetDetail = $GLOBALS['DATABASE']->fetch_array($targetFleetsResult)) + { + $fleetID = $fleetDetail['fleet_id']; + + $fleetDefend[$fleetID]['fleetDetail'] = $fleetDetail; + $fleetDefend[$fleetID]['player'] = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".USERS." WHERE id = '".$fleetDetail['fleet_owner']."';"); + $fleetDefend[$fleetID]['player']['factor'] = getFactors($fleetDefend[$fleetID]['player'], 'attack', $this->_fleet['fleet_start_time']); + $fleetDefend[$fleetID]['unit'] = fleetAmountToArray($fleetDetail['fleet_array']); + + $userDefend[$fleetDefend[$fleetID]['player']['id']] = $fleetDefend[$fleetID]['player']['username']; + } + + $GLOBALS['DATABASE']->free_result($targetFleetsResult); + + $fleetDefend[0]['player'] = $targetUser; + $fleetDefend[0]['player']['factor'] = getFactors($fleetDefend[0]['player'], 'attack', $this->_fleet['fleet_start_time']); + $fleetDefend[0]['fleetDetail'] = array( + 'fleet_start_galaxy' => $targetPlanet['galaxy'], + 'fleet_start_system' => $targetPlanet['system'], + 'fleet_start_planet' => $targetPlanet['planet'], + 'fleet_start_type' => $targetPlanet['planet_type'], + ); - foreach(array_merge($reslist['fleet'], $reslist['defense']) as $ID) + $fleetDefend[0]['unit'] = array(); + + foreach(array_merge($reslist['fleet'], $reslist['defense']) as $elementID) { - if ($ID >= 500) - continue; + if (empty($targetPlanet[$resource[$elementID]])) continue; - $defense[0]['def'][$ID] = $targetPlanet[$resource[$ID]]; + $fleetDefend[0]['unit'][$elementID] = $targetPlanet[$resource[$elementID]]; } - - $Attacker['id'] = array_unique($AttackerRow['id']); - $Defender['id'] = array_unique($DefenderRow['id']); + + $userDefend[$fleetDefend[0]['player']['id']] = $fleetDefend[0]['player']['username']; require_once('calculateAttack.php'); - $result = calculateAttack($attackFleets, $defense, $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['Fleet_Cdr'], $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['Defs_Cdr']); - $SQL = ""; - - foreach ($attackFleets as $fleetID => $attacker) + + $fleetIntoDebris = $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['Fleet_Cdr']; + $defIntoDebris = $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['Defs_Cdr']; + + $combatResult = calculateAttack($fleetAttack, $fleetDefend, $fleetIntoDebris, $defIntoDebris); + + $sqlQuery = ""; + + foreach ($fleetAttack as $fleetID => $fleetDetail) { $fleetArray = ''; $totalCount = 0; - foreach ($attacker['detail'] as $element => $amount) + + $fleetDetail['unit'] = array_filter($fleetDetail['unit']); + foreach ($fleetDetail['unit'] as $elementID => $amount) { - if ($amount) - $fleetArray .= $element.','.floattostring($amount).';'; - + $fleetArray .= $elementID.','.floattostring($amount).';'; $totalCount += $amount; } - $SQL .= $totalCount <= 0 ? "DELETE FROM ".FLEETS." WHERE `fleet_id`= '".$fleetID."';UPDATE ".LOG_FLEETS." SET `fleet_state` = 1 WHERE `fleet_id`= '".$fleetID."';" : "UPDATE ".FLEETS." SET `fleet_mess` = '1', `fleet_array` = '".substr($fleetArray, 0, -1)."', `fleet_amount` = '".$totalCount."' WHERE `fleet_id` = '".$fleetID."';UPDATE ".LOG_FLEETS." SET `fleet_mess` = '1', `fleet_array` = '".substr($fleetArray, 0, -1)."', `fleet_amount` = '".$totalCount."', `fleet_state` = 1 WHERE `fleet_id` = '".$fleetID."';"; - } - - if ($result['won'] == "a") - { - require_once('calculateSteal.php'); - $steal = calculateSteal($attackFleets, $targetPlanet); + if($totalCount == 0) + { + if($this->_fleet['fleet_id'] == $fleetID) + { + $this->KillFleet(); + } + else + { + $sqlQuery .= "DELETE FROM ".FLEETS." WHERE fleet_id = ".$fleetID.";"; + $sqlQuery .= "DELETE FROM ".FLEETS_EVENT." WHERE fleetID = ".$fleetID.";"; + } + + $sqlQuery .= "UPDATE ".LOG_FLEETS." SET fleet_state = 2 WHERE fleet_id = '".$fleetID."';"; + } + elseif($totalCount > 0) + { + $sqlQuery .= "UPDATE ".FLEETS." SET fleet_array = '".substr($fleetArray, 0, -1)."', fleet_amount = '".$totalCount."' WHERE fleet_id = '".$fleetID."';"; + $sqlQuery .= "UPDATE ".LOG_FLEETS." SET fleet_array = '".substr($fleetArray, 0, -1)."', fleet_amount = '".$totalCount."', fleet_state = 1 WHERE fleet_id = '".$fleetID."';"; + } + else + { + throw new Exception("Negative Fleet amount ...."); + } } - foreach ($defense as $fleetID => $defender) + foreach ($fleetDefend as $fleetID => $fleetDetail) { - if ($fleetID != 0) + if($fleetID != 0) { $fleetArray = ''; $totalCount = 0; - - foreach ($defender['def'] as $element => $amount) - { - if ($amount) - $fleetArray .= $element.','.floattostring($amount).';'; - + + $fleetDetail['unit'] = array_filter($fleetDetail['unit']); + + foreach ($fleetDetail['unit'] as $elementID => $amount) + { + $fleetArray .= $elementID.','.floattostring($amount).';'; $totalCount += $amount; } - $SQL .= $totalCount <= 0 ? "DELETE FROM ".FLEETS." WHERE `fleet_id`= '".$fleetID."';UPDATE ".LOG_FLEETS." SET `fleet_state` = 1 WHERE `fleet_id`= '".$fleetID."';" : "UPDATE ".FLEETS." SET `fleet_array` = '".substr($fleetArray, 0, -1)."', `fleet_amount` = '".$totalCount."' WHERE `fleet_id` = '".$fleetID."';UPDATE ".LOG_FLEETS." SET `fleet_array` = '".substr($fleetArray, 0, -1)."', `fleet_amount` = '".$totalCount."' , `fleet_state` = 1 WHERE `fleet_id` = '".$fleetID."';"; + if($totalCount == 0) + { + $sqlQuery .= "DELETE FROM ".FLEETS." WHERE fleet_id = ".$fleetID.";"; + $sqlQuery .= "DELETE FROM ".FLEETS_EVENT." WHERE fleetID = ".$fleetID.";"; + $sqlQuery .= "UPDATE ".LOG_FLEETS." SET fleet_state = 2 WHERE fleet_id = '".$fleetID."';"; + } + elseif($totalCount > 0) + { + $sqlQuery .= "UPDATE ".FLEETS." SET fleet_array = '".substr($fleetArray, 0, -1)."', fleet_amount = '".$totalCount."' WHERE fleet_id = '".$fleetID."';"; + $sqlQuery .= "UPDATE ".LOG_FLEETS." SET fleet_array = '".substr($fleetArray, 0, -1)."', fleet_amount = '".$totalCount."', fleet_state = 1 WHERE fleet_id = '".$fleetID."';"; + } + else + { + throw new Exception("Negative Fleet amount ...."); + } } else { - $fleetArray = ''; - foreach ($defender['def'] as $element => $amount) - { - $fleetArray .= "`".$resource[$element]."` = '".floattostring($amount)."', "; + $fleetArray = array(); + foreach ($fleetDetail['unit'] as $elementID => $amount) + { + $fleetArray[] = $resource[$elementID]." = ".$amount; } - $SQL .= "UPDATE ".PLANETS." SET "; - $SQL .= $fleetArray; - $SQL .= "`metal` = `metal` - '".$steal['metal']."', "; - $SQL .= "`crystal` = `crystal` - '".$steal['crystal']."', "; - $SQL .= "`deuterium` = `deuterium` - '".$steal['deuterium']."' "; - $SQL .= "WHERE "; - $SQL .= "`id` = '".$this->_fleet['fleet_end_id']."';"; + if(!empty($fleetArray)) + { + $sqlQuery .= "UPDATE ".PLANETS." SET ".implode(', ', $fleetArray)." WHERE id = '".$this->_fleet['fleet_end_id']."';"; + } } } - $db->multi_query($SQL); + $GLOBALS['DATABASE']->multi_query($sqlQuery); + + if ($combatResult['won'] == "a") + { + require_once('calculateSteal.php'); + $stealResource = calculateSteal($fleetAttack, $targetPlanet); + } if($this->_fleet['fleet_end_type'] == 3) - $targetPlanet = array_merge($targetPlanet, $db->uniquequery("SELECT `der_metal`, `der_crystal` FROM ".PLANETS." WHERE `id_luna` = '".$this->_fleet['fleet_end_id']."';")); - - $ShootMetal = $result['debree']['att'][0] + $result['debree']['def'][0]; - $ShootCrystal = $result['debree']['att'][1] + $result['debree']['def'][1]; - $FleetDebris = $ShootMetal + $ShootCrystal; - $DerbisMetal = $targetPlanet['der_metal'] + $ShootMetal; - $DerbisCrystal = $targetPlanet['der_crystal'] + $ShootCrystal; - $MoonChance = min(round($FleetDebris / 100000 * $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['moon_factor'], 0), $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['moon_chance']); - $UserChance = mt_rand(1, 100); - - $INFO = $this->_fleet; - if ($targetPlanet['planet_type'] == 1 && $targetPlanet['id_luna'] == 0 && $MoonChance > 0 && $UserChance <= $MoonChance) + { + // Use planet debris, if attack on moons + $targetPlanet = array_merge( + $targetPlanet, + $GLOBALS['DATABASE']->getFirstRow("SELECT der_metal, der_crystal FROM ".PLANETS." WHERE id_luna = ".$this->_fleet['fleet_end_id'].";") + ); + } + + foreach($debrisRessource as $elementID) + { + $debris[$elementID] = $combatResult['debris']['attacker'][$elementID] + $combatResult['debris']['defender'][$elementID]; + $planetDebris[$elementID] = $targetPlanet['der_'.$resource[$elementID]] + $debris[$elementID]; + } + + $debrisTotal = array_sum($debris); + + $moonFactor = $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['moon_factor']; + $maxMoonChance = $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['moon_chance']; + + if($targetPlanet['id_luna'] == 0 && $targetPlanet['planet_type'] == 1) + { + $chanceCreateMoon = round($debrisTotal / 100000 * $moonFactor); + $chanceCreateMoon = min($chanceCreateMoon, $maxMoonChance); + } + else + { + $chanceCreateMoon = 0; + } + + $raportInfo = array( + 'thisFleet' => $this->_fleet, + 'debris' => $debris, + 'stealResource' => $stealResource, + 'moonChance' => $chanceCreateMoon, + 'moonDestroy' => false, + 'moonName' => null, + 'moonDestroyChance' => null, + 'moonDestroySuccess' => null, + 'fleetDestroyChance' => null, + 'fleetDestroySuccess' => null, + ); + + $randChance = mt_rand(1, 100); + if ($randChance <= $chanceCreateMoon) { require_once(ROOT_PATH.'includes/functions/CreateOneMoonRecord.php'); - $INFO['moon']['name'] = CreateOneMoonRecord($this->_fleet['fleet_end_galaxy'], $this->_fleet['fleet_end_system'], $this->_fleet['fleet_end_planet'], $this->_fleet['fleet_universe'], $TargetUserID, $this->_fleet['fleet_start_time'], '', $MoonChance); - $INFO['end_galaxy'] = $this->_fleet['fleet_end_galaxy']; - $INFO['end_system'] = $this->_fleet['fleet_end_system']; - $INFO['end_planet'] = $this->_fleet['fleet_end_planet']; - if($GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['debris_moon'] == 1) { - $DerbisMetal = 0; - $DerbisCrystal = 0; + $LNG = $this->getLanguage($targetUser['lang']); + $raportInfo['moonName'] = $LNG['type_planet'][3]; + + CreateOneMoonRecord( + $this->_fleet['fleet_end_galaxy'], + $this->_fleet['fleet_end_system'], + $this->_fleet['fleet_end_planet'], + $this->_fleet['fleet_universe'], + $targetUser['id'], + $raportInfo['moonName'], + $chanceCreateMoon, + $this->_fleet['fleet_start_time'] + ); + + if($GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['debris_moon'] == 1) + { + foreach($debrisRessource as $elementID) + { + $planetDebris[$elementID] = 0; + } } } - - $INFO['steal'] = $steal; - $INFO['moon']['des'] = 0; - $INFO['moon']['chance'] = $MoonChance; - $INFO['moon']['desfail'] = false; - $INFO['moon']['chance2'] = false; - $INFO['moon']['fleetfail'] = false; + require_once('GenerateReport.php'); - $raport = GenerateReport($result, $INFO); - - $Won = 0; - $Lose = 0; - $Draw = 0; + $raportData = GenerateReport($combatResult, $raportInfo); - switch($result['won']) + switch($combatResult['won']) { case "a": - $Won = 1; - $ColorAtt = "green"; - $ColorDef = "red"; + $attackStatus = 'wons'; + $defendStatus = 'loos'; + $attackClass = 'raportWin'; + $defendClass = 'raportLose'; break; case "w": - $Draw = 1; - $ColorAtt = "orange"; - $ColorDef = "orange"; + $attackStatus = 'draws'; + $defendStatus = 'draws'; + $attackClass = 'raportDraw'; + $defendClass = 'raportDraw'; break; case "r": - $Lose = 1; - $ColorAtt = "red"; - $ColorDef = "green"; + $attackStatus = 'loos'; + $defendStatus = 'wons'; + $attackClass = 'raportLose'; + $defendClass = 'raportWin'; break; } + $raportID = md5(uniqid('', true).TIMESTAMP); - $SQL = "INSERT INTO ".RW." SET "; - $SQL .= "`raport` = '".serialize($raport)."', "; - $SQL .= "`time` = '".$this->_fleet['fleet_start_time']."';"; - $db->query($SQL); - - $WhereAtt = ""; - $WhereDef = ""; - - $rid = $db->GetInsertID(); - $SQL = ""; + $sqlQuery = "INSERT INTO ".RW." SET + rid = '".$raportID."', + raport = '".serialize($raportData)."', + time = '".$this->_fleet['fleet_start_time']."', + attacker = '".implode(',', array_keys($userAttack))."', + defender = '".implode(',', array_keys($userDefend))."';"; + $GLOBALS['DATABASE']->query($sqlQuery); - foreach ($Attacker['id'] as $AttackersID) + $sqlQuery = ""; + foreach($userAttack as $userID => $userName) { - if(empty($AttackersID)) - continue; - - $LNG = $LANG->GetUserLang($AttackersID); - $MessageAtt = sprintf('
%s %s

%s: %s %s: %s
%s %s:%s %s:%s %s:%s
%s %s:%s %s:%s
', $rid, $ColorAtt, $LNG['sys_mess_attack_report'], sprintf($LNG['sys_adress_planet'], $this->_fleet['fleet_end_galaxy'], $this->_fleet['fleet_end_system'], $this->_fleet['fleet_end_planet']), $ColorAtt, $LNG['sys_perte_attaquant'], pretty_number($result['lost']['att']), $ColorDef, $LNG['sys_perte_defenseur'], pretty_number($result['lost']['def']), $LNG['sys_gain'], $LNG['Metal'], pretty_number($steal['metal']), $LNG['Crystal'], pretty_number($steal['crystal']), $LNG['Deuterium'], pretty_number($steal['deuterium']), $LNG['sys_debris'], $LNG['Metal'], pretty_number($result['debree']['att'][0]+$result['debree']['def'][0]), $LNG['Crystal'], pretty_number($result['debree']['att'][1]+$result['debree']['def'][1])); - SendSimpleMessage($AttackersID, 0, $this->_fleet['fleet_start_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_mess_attack_report'], $MessageAtt); - $SQL .= "INSERT INTO ".TOPKB_USERS." SET "; - $SQL .= "`rid` = ".$rid.", "; - $SQL .= "`role` = 1, "; - $SQL .= "`uid` = ".$AttackersID.";"; - $WhereAtt .= "`id` = '".$AttackersID."' OR "; + $LNG = $this->getLanguage(NULL, $userID); + + $message = sprintf($messageHTML, + $raportID, + $attackClass, + $LNG['sys_mess_attack_report'], + sprintf( + $LNG['sys_adress_planet'], + $this->_fleet['fleet_end_galaxy'], + $this->_fleet['fleet_end_system'], + $this->_fleet['fleet_end_planet'] + ), + $LNG['type_planet_short'][$this->_fleet['fleet_end_type']], + $LNG['sys_lost'], + $attackClass, + $LNG['sys_attack_attacker_pos'], + pretty_number($combatResult['unitLost']['attacker']), + $defendClass, + $LNG['sys_attack_defender_pos'], + pretty_number($combatResult['unitLost']['defender']), + $LNG['sys_gain'], + $LNG['tech'][901], + pretty_number($stealResource[901]), + $LNG['tech'][902], + pretty_number($stealResource[902]), + $LNG['tech'][903], + pretty_number($stealResource[903]), + $LNG['sys_debris'], + $LNG['tech'][901], + pretty_number($debris[901]), + $LNG['tech'][902], + pretty_number($debris[902]) + ); + + SendSimpleMessage($userID, 0, $this->_fleet['fleet_start_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_mess_attack_report'], $message); + + $sqlQuery .= "INSERT INTO ".TOPKB_USERS." SET "; + $sqlQuery .= "rid = '".$raportID."', "; + $sqlQuery .= "role = 1, "; + $sqlQuery .= "username = '".$GLOBALS['DATABASE']->escape($userName)."', "; + $sqlQuery .= "uid = ".$userID.";"; } - - foreach ($Defender['id'] as $DefenderID) + + + foreach($userDefend as $userID => $userName) { - if(empty($DefenderID)) - continue; + $LNG = $this->getLanguage(NULL, $userID); + + $message = sprintf($messageHTML, + $raportID, + $defendClass, + $LNG['sys_mess_attack_report'], + sprintf( + $LNG['sys_adress_planet'], + $this->_fleet['fleet_end_galaxy'], + $this->_fleet['fleet_end_system'], + $this->_fleet['fleet_end_planet'] + ), + $LNG['type_planet_short'][$this->_fleet['fleet_end_type']], + $LNG['sys_lost'], + $defendClass, + $LNG['sys_attack_attacker_pos'], + pretty_number($combatResult['unitLost']['attacker']), + $attackClass, + $LNG['sys_attack_defender_pos'], + pretty_number($combatResult['unitLost']['defender']), + $LNG['sys_gain'], + $LNG['tech'][901], + pretty_number($stealResource[901]), + $LNG['tech'][902], + pretty_number($stealResource[902]), + $LNG['tech'][903], + pretty_number($stealResource[903]), + $LNG['sys_debris'], + $LNG['tech'][901], + pretty_number($debris[901]), + $LNG['tech'][902], + pretty_number($debris[902]) + ); - $LNG = $LANG->GetUserLang($DefenderID); - $MessageDef = sprintf('
%s %s

%s: %s %s: %s
%s %s:%s %s:%s %s:%s
%s %s:%s %s:%s
', $rid, $ColorDef, $LNG['sys_mess_attack_report'], sprintf($LNG['sys_adress_planet'], $this->_fleet['fleet_end_galaxy'], $this->_fleet['fleet_end_system'], $this->_fleet['fleet_end_planet']), $ColorDef, $LNG['sys_perte_attaquant'], pretty_number($result['lost']['att']), $ColorAtt, $LNG['sys_perte_defenseur'], pretty_number($result['lost']['def']), $LNG['sys_gain'], $LNG['Metal'], pretty_number($steal['metal']), $LNG['Crystal'], pretty_number($steal['crystal']), $LNG['Deuterium'], pretty_number($steal['deuterium']), $LNG['sys_debris'], $LNG['Metal'], pretty_number($result['debree']['att'][0]+$result['debree']['def'][0]), $LNG['Crystal'], pretty_number($result['debree']['att'][1]+$result['debree']['def'][1])); - SendSimpleMessage($DefenderID, 0, $this->_fleet['fleet_start_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_mess_attack_report'], $MessageDef); - $SQL .= "INSERT INTO ".TOPKB_USERS." SET "; - $SQL .= "`rid` = ".$rid.", "; - $SQL .= "`role` = 2, "; - $SQL .= "`uid` = ".$DefenderID.";"; - $WhereDef .= "`id` = '".$DefenderID."' OR "; + SendSimpleMessage($userID, 0, $this->_fleet['fleet_start_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_mess_attack_report'], $message); + + $sqlQuery .= "INSERT INTO ".TOPKB_USERS." SET "; + $sqlQuery .= "rid = '".$raportID."', "; + $sqlQuery .= "role = 2, "; + $sqlQuery .= "username = '".$GLOBALS['DATABASE']->escape($userName)."', "; + $sqlQuery .= "uid = ".$userID.";"; + } + + if($this->_fleet['fleet_end_type'] == 3) + { + $debrisType = 'id_luna'; } + else + { + $debrisType = 'id'; + } + + $sqlQuery .= "UPDATE ".PLANETS." SET + der_metal = ".$planetDebris[901].", + der_crystal = ".$planetDebris[902]." + WHERE + ".$debrisType." = ".$this->_fleet['fleet_end_id']."; + UPDATE ".PLANETS." SET + metal = metal - ".$stealResource[901].", + crystal = crystal - ".$stealResource[902].", + deuterium = deuterium - ".$stealResource[903]." + WHERE + id = ".$this->_fleet['fleet_end_id']."; + INSERT INTO ".TOPKB." SET + units = ".($combatResult['unitLost']['attacker'] + $combatResult['unitLost']['defender']).", + rid = '".$raportID."', + time = ".$this->_fleet['fleet_start_time'].", + universe = ".$this->_fleet['fleet_universe'].", + result = '".$combatResult['won'] ."'; + UPDATE ".USERS." SET + ".$attackStatus." = ".$attackStatus." + 1, + kbmetal = kbmetal + ".$debris[901].", + kbcrystal = kbcrystal + ".$debris[902].", + lostunits = lostunits + ".$combatResult['unitLost']['attacker'].", + desunits = desunits + ".$combatResult['unitLost']['defender']." + WHERE + id IN (".implode(',', array_keys($userAttack))."); + UPDATE ".USERS." SET + ".$defendStatus." = ".$defendStatus." + 1, + kbmetal = kbmetal + ".$debris[901].", + kbcrystal = kbcrystal + ".$debris[902].", + lostunits = lostunits + ".$combatResult['unitLost']['attacker'].", + desunits = desunits + ".$combatResult['unitLost']['defender']." + WHERE + id IN (".implode(',', array_keys($userDefend)).");"; + + $GLOBALS['DATABASE']->multi_query($sqlQuery); - $WhereCol = $this->_fleet['fleet_end_type'] == 3 ? "id_luna" : "id"; - $SQL .= "UPDATE ".PLANETS." SET "; - $SQL .= "`der_metal` = ".$DerbisMetal.", "; - $SQL .= "`der_crystal` = ".$DerbisCrystal." "; - $SQL .= "WHERE "; - $SQL .= "`".$WhereCol."` = ".$this->_fleet['fleet_end_id'].";"; - $SQL .= "INSERT INTO ".TOPKB." SET "; - $SQL .= "`units` = ".($result['lost']['att'] + $result['lost']['def']).", "; - $SQL .= "`rid` = ".$rid.", "; - $SQL .= "`time` = ".$this->_fleet['fleet_start_time'].", "; - $SQL .= "`universe` = ".$this->_fleet['fleet_universe'].", "; - $SQL .= "`result` = '".$result['won'] ."';"; - $SQL .= "UPDATE ".USERS." SET "; - $SQL .= "`wons` = wons + ".$Won.", "; - $SQL .= "`loos` = loos + ".$Lose.", "; - $SQL .= "`draws` = draws + ".$Draw.", "; - $SQL .= "`kbmetal` = kbmetal + ".$ShootMetal.", "; - $SQL .= "`kbcrystal` = kbcrystal + ".$ShootCrystal.", "; - $SQL .= "`lostunits` = lostunits + ".$result['lost']['att'].", "; - $SQL .= "`desunits` = desunits + ".$result['lost']['def']." "; - $SQL .= "WHERE "; - $SQL .= substr($WhereAtt, 0, -4).";"; - $SQL .= "UPDATE ".USERS." SET "; - $SQL .= "`wons` = wons + ". $Lose .", "; - $SQL .= "`loos` = loos + ". $Won .", "; - $SQL .= "`draws` = draws + ". $Draw .", "; - $SQL .= "`kbmetal` = kbmetal + ".$ShootMetal.", "; - $SQL .= "`kbcrystal` = kbcrystal + ".$ShootCrystal.", "; - $SQL .= "`lostunits` = lostunits + ".$result['lost']['def'].", "; - $SQL .= "`desunits` = desunits + ".$result['lost']['att']." "; - $SQL .= "WHERE "; - $SQL .= substr($WhereDef, 0, -4).";"; - $db->multi_query($SQL); + $this->setState(FLEET_RETURN); + $this->SaveFleet(); } function EndStayEvent() @@ -339,14 +501,13 @@ function EndStayEvent() function ReturnEvent() { - global $LANG; - $LNG = $LANG->GetUserLang($this->_fleet['fleet_owner']); - - $Message = sprintf( $LNG['sys_fleet_won'], $TargetName, GetTargetAdressLink($this->_fleet, ''), pretty_number($this->_fleet['fleet_resource_metal']), $LNG['Metal'], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['Crystal'], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['Deuterium']); + $LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']); + $TargetName = $GLOBALS['DATABASE']->getFirstCell("SELECT name FROM ".PLANETS." WHERE id = ".$this->_fleet['fleet_start_id'].";"); + $Message = sprintf( $LNG['sys_fleet_won'], $TargetName, GetTargetAdressLink($this->_fleet, ''), pretty_number($this->_fleet['fleet_resource_metal']), $LNG['tech'][901], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['tech'][902], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['tech'][903]); + SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_end_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_mess_fleetback'], $Message); $this->RestoreFleet(); } } - -?> \ No newline at end of file + \ No newline at end of file diff --git a/includes/classes/missions/MissionCaseColonisation.php b/includes/classes/missions/MissionCaseColonisation.php index 6521758..52b62c0 100644 --- a/includes/classes/missions/MissionCaseColonisation.php +++ b/includes/classes/missions/MissionCaseColonisation.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,13 +18,12 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class MissionCaseColonisation extends MissionFunctions @@ -36,30 +35,39 @@ function __construct($Fleet) function TargetEvent() { - global $db, $resource, $LANG; - $iPlanetCount = $db->countquery("SELECT count(*) FROM ".PLANETS." WHERE `id_owner` = '". $this->_fleet['fleet_owner'] ."' AND `planet_type` = '1' AND `destruyed` = '0';"); - $iGalaxyPlace = $db->countquery("SELECT count(*) AS plani FROM ".PLANETS." WHERE `id` = '".$this->_fleet['fleet_end_id']."';"); - $Player = $db->uniquequery("SELECT `lang`, `authlevel`, `".$resource[124]."` FROM ".USERS." WHERE `id` = '".$this->_fleet['fleet_owner']."';"); - $LNG = $LANG->GetUserLang($Player['lang']); - $MaxPlanets = MaxPlanets($Player[$resource[124]], $this->_fleet['fleet_universe']); + global $resource; + $iPlanetCount = $GLOBALS['DATABASE']->getFirstCell("SELECT COUNT(*) FROM ".PLANETS." WHERE `id_owner` = '". $this->_fleet['fleet_owner'] ."' AND `planet_type` = '1' AND `destruyed` = '0';"); + $iGalaxyPlace = $GLOBALS['DATABASE']->getFirstCell("SELECT COUNT(*) FROM ".PLANETS." WHERE `id` = '".$this->_fleet['fleet_end_id']."';"); + $senderUser = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".USERS." WHERE `id` = '".$this->_fleet['fleet_owner']."';"); + $senderPlanet = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".PLANETS." WHERE `id` = '".$this->_fleet['fleet_start_id']."';"); + $senderUser['factor'] = getFactors($senderUser, 'basic', $this->_fleet['fleet_start_time']); + $LNG = $this->getLanguage($senderUser['lang']); + + $MaxPlanets = PlayerUtil::maxPlanetCount($senderUser); + if ($iGalaxyPlace != 0) { $TheMessage = sprintf($LNG['sys_colo_notfree'], GetTargetAdressLink($this->_fleet, '')); - $this->UpdateFleet('fleet_mess', 1); + $this->setState(FLEET_RETURN); } elseif($iPlanetCount >= $MaxPlanets) { $TheMessage = sprintf($LNG['sys_colo_maxcolo'] , GetTargetAdressLink($this->_fleet, ''), $MaxPlanets); - $this->UpdateFleet('fleet_mess', 1); + $this->setState(FLEET_RETURN); } + elseif(PlayerUtil::allowPlanetPosition($this->_fleet['fleet_end_planet'],$senderUser) == false) + { + $TheMessage = sprintf($LNG['sys_colo_notech'] , GetTargetAdressLink($this->_fleet, ''), $MaxPlanets); + $this->setState(FLEET_RETURN); + } else { require_once(ROOT_PATH.'includes/functions/CreateOnePlanetRecord.php'); - $NewOwnerPlanet = CreateOnePlanetRecord($this->_fleet['fleet_end_galaxy'], $this->_fleet['fleet_end_system'], $this->_fleet['fleet_end_planet'], $this->_fleet['fleet_universe'], $this->_fleet['fleet_owner'], $LNG['fcp_colony'], false, $Player['authlevel']); + $NewOwnerPlanet = CreateOnePlanetRecord($this->_fleet['fleet_end_galaxy'], $this->_fleet['fleet_end_system'], $this->_fleet['fleet_end_planet'], $this->_fleet['fleet_universe'], $this->_fleet['fleet_owner'], $LNG['fcp_colony'], false, $senderUser['authlevel']); if($NewOwnerPlanet === false) { $TheMessage = sprintf($LNG['sys_colo_badpos'], GetTargetAdressLink($this->_fleet, '')); - $this->UpdateFleet('fleet_mess', 1); + $this->setState(FLEET_RETURN); } else { @@ -86,7 +94,7 @@ function TargetEvent() $this->UpdateFleet('fleet_resource_metal', 0); $this->UpdateFleet('fleet_resource_crystal', 0); $this->UpdateFleet('fleet_resource_deuterium', 0); - $this->UpdateFleet('fleet_mess', 1); + $this->setState(FLEET_RETURN); } } } @@ -103,5 +111,4 @@ function ReturnEvent() { $this->RestoreFleet(); } -} -?> \ No newline at end of file +} \ No newline at end of file diff --git a/includes/classes/missions/MissionCaseDestruction.php b/includes/classes/missions/MissionCaseDestruction.php index d91dd04..fa35b06 100644 --- a/includes/classes/missions/MissionCaseDestruction.php +++ b/includes/classes/missions/MissionCaseDestruction.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,13 +18,12 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class MissionCaseDestruction extends MissionFunctions @@ -35,280 +34,474 @@ function __construct($Fleet) } function TargetEvent() - { - global $pricelist, $resource, $reslist, $db, $LANG; - $TargetPlanet = $db->uniquequery("SELECT * FROM ".PLANETS." WHERE `id` = '".$this->_fleet['fleet_end_id']."' ;"); - $TargetUser = $db->uniquequery("SELECT * FROM ".USERS." WHERE `id` = '".$TargetPlanet['id_owner']."';"); - $TargetUserID = $TargetUser['id']; - $attackFleets = array(); - - require_once(ROOT_PATH.'includes/classes/class.PlanetRessUpdate.php'); + { + global $resource, $reslist; - $TargetUser['factor'] = getFactors($targetUser, 'basic', $this->_fleet['fleet_start_time']); - $PlanetRess = new ResourceUpdate(); - list($TargetUser, $TargetPlanet) = $PlanetRess->CalcResource($TargetUser, $TargetPlanet, true, $this->_fleet['fleet_start_time']); - + $fleetAttack = array(); + $fleetDefend = array(); - $attackFleets[$this->_fleet['fleet_id']]['fleet'] = $this->_fleet; - $attackFleets[$this->_fleet['fleet_id']]['user'] = $db->uniquequery("SELECT `id`, `username`, `military_tech`, `defence_tech`, `shield_tech`, `rpg_amiral`, `dm_defensive`, `dm_attack` FROM ".USERS." WHERE id = '".$this->_fleet['fleet_owner']."';"); - $attackFleets[$this->_fleet['fleet_id']]['user']['factor'] = getFactors($attackFleets[$this->_fleet['fleet_id']]['user'], 'attack', $this->_fleet['fleet_start_time']); - $attackFleets[$this->_fleet['fleet_id']]['detail'] = array(); - $temp = explode(';', $this->_fleet['fleet_array']); - foreach ($temp as $temp2) - { - $temp2 = explode(',', $temp2); - if ($temp2[0] < 100) continue; - - if (!isset($attackFleets[$this->_fleet['fleet_id']]['detail'][$temp2[0]])) - $attackFleets[$this->_fleet['fleet_id']]['detail'][$temp2[0]] = 0; - - $attackFleets[$this->_fleet['fleet_id']]['detail'][$temp2[0]] += $temp2[1]; - $AttackerRow['id'][] = $attackFleets[$this->_fleet['fleet_id']]['user']['id']; - } + $userAttack = array(); + $userDefend = array(); - $defense = array(); - - $def = $db->query('SELECT * FROM '.FLEETS.' WHERE `fleet_end_galaxy` = '. $this->_fleet['fleet_end_galaxy'] .' AND `fleet_end_system` = '. $this->_fleet['fleet_end_system'] .' AND `fleet_end_type` = '. $this->_fleet['fleet_end_type'] .' AND `fleet_end_planet` = '. $this->_fleet['fleet_end_planet'] .' AND fleet_start_time<'.TIMESTAMP.' AND fleet_end_stay>='.TIMESTAMP.';'); - while ($defRow = $db->fetch_array($def)) + $stealResource = array( + 901 => 0, + 902 => 0, + 903 => 0, + ); + + $debris = array(); + $planetDebris = array(); + + $raportInfo = array(); + + $debrisRessource = array(901, 902); + + $messageHTML = << + + + + + + + + + + + + + +
%s %s (%s)
%s%s: %s %s: %s
%s%s: %s %s: %s %s: %s
%s%s: %s %s: %s
+
+HTML; + //Minize HTML + $messageHTML = str_replace(array("\n", "\t", "\r"), "", $messageHTML); + + $targetPlanet = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".PLANETS." WHERE id = '".$this->_fleet['fleet_end_id']."';"); + $targetUser = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".USERS." WHERE id = '".$targetPlanet['id_owner']."';"); + + $targetUser['factor'] = getFactors($targetUser, 'basic', $this->_fleet['fleet_start_time']); + $planetUpdater = new ResourceUpdate(); + + list($targetUser, $targetPlanet) = $planetUpdater->CalcResource($targetUser, $targetPlanet, true, $this->_fleet['fleet_start_time']); + + if($this->_fleet['fleet_group'] != 0) { - $defRowDef = explode(';', $defRow['fleet_array']); - foreach ($defRowDef as $Element) + $GLOBALS['DATABASE']->query("DELETE FROM ".AKS." WHERE id = '".$this->_fleet['fleet_group']."';"); + $incomingFleetsResult = $GLOBALS['DATABASE']->query("SELECT * FROM ".FLEETS." WHERE fleet_group = '".$this->_fleet['fleet_group']."';"); + + while ($incomingFleetsRow = $GLOBALS['DATABASE']->fetch_array($incomingFleetsResult)) { - $Element = explode(',', $Element); - if ($Element[0] < 100) continue; - - if (!isset($defense[$defRow['fleet_id']]['def'][$Element[0]])) - $defense[$defRow['fleet_id']][$Element[0]] = 0; - - $defense[$defRow['fleet_id']]['def'][$Element[0]] += $Element[1]; - $defense[$defRow['fleet_id']]['user'] = $db->uniquequery("SELECT `id`, `username`, `military_tech`, `defence_tech`, `shield_tech`, `rpg_amiral`, `dm_defensive`, `dm_attack` FROM ".USERS." WHERE id = '".$defRow['fleet_owner']."';"); - $defense[$defRow['fleet_id']]['user']['factor'] = getFactors($defense[$defRow['fleet_id']]['user'], 'attack', $this->_fleet['fleet_start_time']); + $incomingFleets[$incomingFleetsRow['fleet_id']] = $incomingFleetsRow; } - $DefenderRow['id'][] = $defense[$defRow['fleet_id']]['user']['id']; + + $GLOBALS['DATABASE']->free_result($incomingFleetsResult); } - - $defense[0]['def'] = array(); - $defense[0]['user'] = $TargetUser; - $defense[0]['user']['factor'] = getFactors($defense[0]['user'], 'attack', $this->_fleet['fleet_start_time']); - $DefenderRow['id'][] = $defense[0]['user']['id']; - for ($i = 200; $i < 500; $i++) + else { - if (isset($resource[$i]) && isset($TargetPlanet[$resource[$i]])) - { - $defense[0]['def'][$i] = $TargetPlanet[$resource[$i]]; - } + $incomingFleets = array($this->_fleet['fleet_id'] => $this->_fleet); } - - $Attacker['id'] = array_unique($AttackerRow['id']); - $Defender['id'] = array_unique($DefenderRow['id']); - require_once('calculateAttack.php'); - $result = calculateAttack($attackFleets, $defense, $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['Fleet_Cdr'], $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['Defs_Cdr']); + foreach($incomingFleets as $fleetID => $fleetDetail) + { + $fleetAttack[$fleetID]['fleetDetail'] = $fleetDetail; + $fleetAttack[$fleetID]['player'] = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".USERS." WHERE id = '".$fleetDetail['fleet_owner']."';"); + $fleetAttack[$fleetID]['player']['factor'] = getFactors($fleetAttack[$fleetID]['player'], 'attack', $this->_fleet['fleet_start_time']); + $fleetAttack[$fleetID]['unit'] = fleetAmountToArray($fleetDetail['fleet_array']); + + $userAttack[$fleetAttack[$fleetID]['player']['id']] = $fleetAttack[$fleetID]['player']['username']; + } + + $targetFleetsResult = $GLOBALS['DATABASE']->query("SELECT * FROM ".FLEETS." WHERE fleet_mission = '5' AND fleet_end_id = '".$this->_fleet['fleet_end_id']."' AND fleet_start_time <= '".TIMESTAMP."' AND fleet_end_stay >= '".TIMESTAMP."';"); + while ($fleetDetail = $GLOBALS['DATABASE']->fetch_array($targetFleetsResult)) + { + $fleetID = $fleetDetail['fleet_id']; + + $fleetDefend[$fleetID]['fleetDetail'] = $fleetDetail; + $fleetDefend[$fleetID]['player'] = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".USERS." WHERE id = '".$fleetDetail['fleet_owner']."';"); + $fleetDefend[$fleetID]['player']['factor'] = getFactors($fleetDefend[$fleetID]['player'], 'attack', $this->_fleet['fleet_start_time']); + $fleetDefend[$fleetID]['unit'] = fleetAmountToArray($fleetDetail['fleet_array']); + + $userDefend[$fleetDefend[$fleetID]['player']['id']] = $fleetDefend[$fleetID]['player']['username']; + } + + $GLOBALS['DATABASE']->free_result($targetFleetsResult); + + $fleetDefend[0]['player'] = $targetUser; + $fleetDefend[0]['player']['factor'] = getFactors($fleetDefend[0]['player'], 'attack', $this->_fleet['fleet_start_time']); + $fleetDefend[0]['fleetDetail'] = array( + 'fleet_start_galaxy' => $targetPlanet['galaxy'], + 'fleet_start_system' => $targetPlanet['system'], + 'fleet_start_planet' => $targetPlanet['planet'], + 'fleet_start_type' => $targetPlanet['planet_type'], + ); + + $fleetDefend[0]['unit'] = array(); + + foreach(array_merge($reslist['fleet'], $reslist['defense']) as $elementID) + { + if (empty($targetPlanet[$resource[$elementID]])) continue; - $SQL = ""; + $fleetDefend[0]['unit'][$elementID] = $targetPlanet[$resource[$elementID]]; + } - foreach ($attackFleets as $fleetID => $attacker) + $userDefend[$fleetDefend[0]['player']['id']] = $fleetDefend[0]['player']['username']; + + require_once('calculateAttack.php'); + + $fleetIntoDebris = $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['Fleet_Cdr']; + $defIntoDebris = $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['Defs_Cdr']; + + $combatResult = calculateAttack($fleetAttack, $fleetDefend, $fleetIntoDebris, $defIntoDebris); + + $sqlQuery = ""; + + foreach ($fleetAttack as $fleetID => $fleetDetail) { $fleetArray = ''; $totalCount = 0; - foreach ($attacker['detail'] as $element => $amount) + + $fleetDetail['unit'] = array_filter($fleetDetail['unit']); + foreach ($fleetDetail['unit'] as $elementID => $amount) { - if ($amount) - $fleetArray .= $element.','.floattostring($amount).';'; - + $fleetArray .= $elementID.','.floattostring($amount).';'; $totalCount += $amount; } - $SQL .= $totalCount <= 0 ? "DELETE FROM ".FLEETS." WHERE `fleet_id`= '".$fleetID."';UPDATE ".LOG_FLEETS." SET `fleet_state` = 1 WHERE `fleet_id`= '".$fleetID."';" : "UPDATE ".FLEETS." SET `fleet_mess` = '1', `fleet_array` = '".substr($fleetArray, 0, -1)."', `fleet_amount` = '".$totalCount."' WHERE `fleet_id` = '".$fleetID."';UPDATE ".LOG_FLEETS." SET `fleet_mess` = '1', `fleet_array` = '".substr($fleetArray, 0, -1)."', `fleet_amount` = '".$totalCount."', `fleet_state` = 1 WHERE `fleet_id` = '".$fleetID."';"; - } - - $db->multi_query($SQL); - $SQL = ""; - - if ($result['won'] == "a") - { - require_once('calculateSteal.php'); - $steal = calculateSteal($attackFleets, $TargetPlanet); + if($totalCount == 0) + { + if($this->_fleet['fleet_id'] == $fleetID) + { + $this->KillFleet(); + } + else + { + $sqlQuery .= "DELETE FROM ".FLEETS." WHERE fleet_id = ".$fleetID.";"; + $sqlQuery .= "DELETE FROM ".FLEETS_EVENT." WHERE fleetID = ".$fleetID.";"; + } + + $sqlQuery .= "UPDATE ".LOG_FLEETS." SET fleet_state = 2 WHERE fleet_id = '".$fleetID."';"; + } + elseif($totalCount > 0) + { + $sqlQuery .= "UPDATE ".FLEETS." SET fleet_array = '".substr($fleetArray, 0, -1)."', fleet_amount = '".$totalCount."' WHERE fleet_id = '".$fleetID."';"; + $sqlQuery .= "UPDATE ".LOG_FLEETS." SET fleet_array = '".substr($fleetArray, 0, -1)."', fleet_amount = '".$totalCount."', fleet_state = 1 WHERE fleet_id = '".$fleetID."';"; + } + else + { + throw new Exception("Negative Fleet amount ...."); + } } - foreach ($defense as $fleetID => $defender) + foreach ($fleetDefend as $fleetID => $fleetDetail) { - if ($fleetID != 0) + if($fleetID != 0) { $fleetArray = ''; $totalCount = 0; - - foreach ($defender['def'] as $element => $amount) - { - if ($amount) - $fleetArray .= $element.','.floattostring($amount).';'; - + + $fleetDetail['unit'] = array_filter($fleetDetail['unit']); + foreach ($fleetDetail['unit'] as $elementID => $amount) + { + $fleetArray .= $elementID.','.floattostring($amount).';'; $totalCount += $amount; } - $SQL .= $totalCount <= 0 ? "DELETE FROM ".FLEETS." WHERE `fleet_id`= '".$fleetID."';UPDATE ".LOG_FLEETS." SET `fleet_state` = 1 WHERE `fleet_id`= '".$fleetID."';" : "UPDATE ".FLEETS." SET `fleet_array` = '".substr($fleetArray, 0, -1)."', `fleet_amount` = '".$totalCount."' WHERE `fleet_id` = '".$fleetID."';UPDATE ".LOG_FLEETS." SET `fleet_array` = '".substr($fleetArray, 0, -1)."', `fleet_amount` = '".$totalCount."' , `fleet_state` = 1 WHERE `fleet_id` = '".$fleetID."';"; + + if($totalCount == 0) + { + $sqlQuery .= "DELETE FROM ".FLEETS." WHERE fleet_id = ".$fleetID.";"; + $sqlQuery .= "DELETE FROM ".FLEETS_EVENT." WHERE fleetID = ".$fleetID.";"; + $sqlQuery .= "UPDATE ".LOG_FLEETS." SET fleet_state = 2 WHERE fleet_id = '".$fleetID."';"; + } + elseif($totalCount > 0) + { + $sqlQuery .= "UPDATE ".FLEETS." SET fleet_array = '".substr($fleetArray, 0, -1)."', fleet_amount = '".$totalCount."' WHERE fleet_id = '".$fleetID."';"; + $sqlQuery .= "UPDATE ".LOG_FLEETS." SET fleet_array = '".substr($fleetArray, 0, -1)."', fleet_amount = '".$totalCount."', fleet_state = 1 WHERE fleet_id = '".$fleetID."';"; + } + else + { + throw new Exception("Negative Fleet amount ...."); + } } else { - $fleetArray = ''; - $totalCount = 0; - - foreach ($defender['def'] as $element => $amount) + $fleetArray = array(); + foreach ($fleetDetail['unit'] as $elementID => $amount) + { + $fleetArray[] = $resource[$elementID]." = ".$amount; + } + + if(!empty($fleetArray)) { - $fleetArray .= "`".$resource[$element]."` = '".floattostring($amount)."', "; + $sqlQuery .= "UPDATE ".PLANETS." SET ".implode(', ', $fleetArray)." WHERE id = '".$this->_fleet['fleet_end_id']."';"; } - - $SQL .= "UPDATE ".PLANETS." SET "; - $SQL .= $fleetArray; - $SQL .= "`metal` = `metal` - '".floattostring($steal['metal'])."', `crystal` = `crystal` - '".floattostring($steal['crystal'])."', `deuterium` = `deuterium` - '".floattostring($steal['deuterium'])."' WHERE `id` = '".$this->_fleet['fleet_end_id']."';"; } } - $db->multi_query($SQL); - $INFO = $this->_fleet; + $GLOBALS['DATABASE']->multi_query($sqlQuery); - switch ($result['won']) { - case "a": - $chance = max(min(round((100 - sqrt($TargetPlanet['diameter'])) * sqrt($attackFleets[$this->_fleet['fleet_id']]['detail'][214]), 1), 100), 0); - $chance2 = round(sqrt($TargetPlanet['diameter'])/2); - - $tirage = rand(0, 100); - $tirage2 = rand(0, 100); + if ($combatResult['won'] == "a") + { + require_once('calculateSteal.php'); + $stealResource = calculateSteal($fleetAttack, $targetPlanet); + } + + if($this->_fleet['fleet_end_type'] == 3) + { + // Use planet debris, if attack on moons + $targetPlanet = array_merge( + $targetPlanet, + $GLOBALS['DATABASE']->getFirstRow("SELECT der_metal, der_crystal FROM ".PLANETS." WHERE id_luna = ".$this->_fleet['fleet_end_id'].";") + ); + } + + foreach($debrisRessource as $elementID) + { + $debris[$elementID] = $combatResult['debris']['attacker'][$elementID] + $combatResult['debris']['defender'][$elementID]; + $planetDebris[$elementID] = $targetPlanet['der_'.$resource[$elementID]] + $debris[$elementID]; + } + + $debrisTotal = array_sum($debris); + + $raportInfo = array( + 'thisFleet' => $this->_fleet, + 'debris' => $debris, + 'stealResource' => $stealResource, + 'moonChance' => null, + 'moonDestroy' => true, + 'moonName' => null, + 'moonDestroyChance' => null, + 'moonDestroySuccess' => null, + 'fleetDestroyChance' => null, + 'fleetDestroySuccess' => false, + ); - $INFO['moon']['chance'] = $chance; - $INFO['moon']['chance2'] = $chance2; + $destext = ""; + + switch($combatResult['won']) + { + case "a": + $moonDestroyChance = round((100 - sqrt($targetPlanet['diameter'])) * sqrt($fleetAttack[$this->_fleet['fleet_id']]['unit'][214]), 1); - if($tirage <= $chance) { - $EndPlanet = $db->uniquequery("SELECT `id` FROM ".PLANETS." WHERE `id_luna` = '".$this->_fleet['fleet_end_id']."';"); - $db->multi_query("DELETE FROM ".PLANETS." WHERE `id` = '".$TargetPlanet['id']."';UPDATE ".PLANETS." SET `id_luna` = '0' WHERE `id_luna` = '".$TargetPlanet['id']."';UPDATE ".FLEETS." SET `fleet_start_type` = '1', `fleet_start_id` = '".$EndPlanet['id']."' WHERE `fleet_start_id` = '".$this->_fleet['fleet_end_id']."';UPDATE ".FLEETS." SET `fleet_end_type` = '1', `fleet_end_id` = '".$EndPlanet['id']."', `fleet_mission` = IF(`fleet_mission` = 9, 1, `fleet_mission`) WHERE `fleet_end_id` = '".$this->_fleet['fleet_end_id']."' AND `fleet_id` != '".$this->_fleet['fleet_id']."';"); - $INFO['moon']['desfail'] = 0; + // Max 100% | Min 0% + $moonDestroyChance = min($moonDestroyChance, 100); + $moonDestroyChance = max($moonDestroyChance, 0); + + $randChance = mt_rand(1, 100); + if ($randChance <= $moonDestroyChance) + { + $planetID = $GLOBALS['DATABASE']->getFirstCell("SELECT id FROM ".PLANETS." WHERE id_luna = ".$targetPlanet['id'].";"); + $GLOBALS['DATABASE']->multi_query(" + UPDATE ".FLEETS." SET + fleet_start_type = 1, + fleet_start_id = ".$planetID." + WHERE fleet_start_id = ".$targetPlanet['id']."; + UPDATE ".FLEETS." SET + fleet_end_type = 1, + fleet_end_id = ".$planetID.", + fleet_mission = IF(fleet_mission = 9, 1, fleet_mission) + WHERE fleet_end_id = ".$this->_fleet['fleet_end_id']." + AND fleet_id != ".$this->_fleet['fleet_id']."; + UPDATE ".PLANETS." + SET id_luna = 0 + WHERE id_luna = ".$targetPlanet['id']."; + DELETE FROM ".PLANETS." + WHERE id = ".$targetPlanet['id'].";"); + + $raportInfo['moonDestroySuccess'] = 1; } else { - $INFO['moon']['desfail'] = 2; + $raportInfo['moonDestroySuccess'] = 0; } - if($tirage2 <= $chance2) { - $INFO['moon']['fleetfail'] = 1; - $db->query("DELETE FROM ".FLEETS." WHERE `fleet_id` = '". $this->_fleet["fleet_id"] ."';"); - } else { - $INFO['moon']['fleetfail'] = 0; + $fleetDestroyChance = round(sqrt($targetPlanet['diameter']) / 2); + + $randChance = mt_rand(1, 100); + if ($randChance <= $fleetDestroyChance) + { + $this->KillFleet(); + $raportInfo['fleetDestroySuccess'] = true; } - break; - case "r": - $INFO['moon']['desfail'] = 1; - $destext .= sprintf ($LNG['sys_destruc_mess'], $this->_fleet['fleet_start_galaxy'], $this->_fleet['fleet_start_system'], $this->_fleet['fleet_start_planet'], $this->_fleet['fleet_end_galaxy'], $this->_fleet['fleet_end_system'], $this->_fleet['fleet_end_planet'])."
"; - $destext .= $LNG['sys_destruc_stop'] ."
"; + else + { + $raportInfo['fleetDestroySuccess'] = false; + } + + + $raportInfo['moonDestroyChance'] = $moonDestroyChance; + $raportInfo['fleetDestroyChance'] = $fleetDestroyChance; + + $attackStatus = 'wons'; + $defendStatus = 'loos'; + $attackClass = 'raportWin'; + $defendClass = 'raportLose'; break; case "w": - $INFO['moon']['desfail'] = 1; - $destext .= sprintf ($LNG['sys_destruc_mess'], $this->_fleet['fleet_start_galaxy'], $this->_fleet['fleet_start_system'], $this->_fleet['fleet_start_planet'], $this->_fleet['fleet_end_galaxy'], $this->_fleet['fleet_end_system'], $this->_fleet['fleet_end_planet'])."
"; - $destext .= $LNG['sys_destruc_stop'] ."
"; + $attackStatus = 'draws'; + $defendStatus = 'draws'; + $attackClass = 'raportDraw'; + $defendClass = 'raportDraw'; + $raportInfo['moonDestroySuccess'] = -1; + break; + case "r": + $attackStatus = 'loos'; + $defendStatus = 'wons'; + $attackClass = 'raportLose'; + $defendClass = 'raportWin'; + $raportInfo['moonDestroySuccess'] = -1; break; } - $INFO['steal'] = $steal; - $INFO['moon']['des'] = 1; - require_once('GenerateReport.php'); - $raport = GenerateReport($result, $INFO); + $raportData = GenerateReport($combatResult, $raportInfo); - $WhereAtt = ""; - $WhereDef = ""; - $Won = 0; - $Lose = 0; - $Draw = 0; + $raportID = md5(uniqid('', true).TIMESTAMP); + $sqlQuery = "INSERT INTO ".RW." SET + rid = '".$raportID."', + raport = '".serialize($raportData)."', + time = '".$this->_fleet['fleet_start_time']."', + attacker = '".implode(',', array_keys($userAttack))."', + defender = '".implode(',', array_keys($userDefend))."';"; + $GLOBALS['DATABASE']->query($sqlQuery); - switch($result['won']) + $sqlQuery = ""; + foreach($userAttack as $userID => $userName) { - case "a": - $Won = 1; - $ColorAtt = "green"; - $ColorDef = "red"; - break; - case "w": - $Draw = 1; - $ColorAtt = "orange"; - $ColorDef = "orange"; - break; - case "r": - $Lose = 1; - $ColorAtt = "red"; - $ColorDef = "green"; - break; - } - - $ShootMetal = $result['debree']['att'][0] + $result['debree']['def'][0]; - $ShootCrystal = $result['debree']['att'][1] + $result['debree']['def'][1]; + $LNG = $this->getLanguage(NULL, $userID); + + $message = sprintf($messageHTML, + $raportID, + $attackClass, + $LNG['sys_mess_attack_report'], + sprintf( + $LNG['sys_adress_planet'], + $this->_fleet['fleet_end_galaxy'], + $this->_fleet['fleet_end_system'], + $this->_fleet['fleet_end_planet'] + ), + $LNG['type_planet_short'][$this->_fleet['fleet_end_type']], + $LNG['sys_lost'], + $attackClass, + $LNG['sys_attack_attacker_pos'], + pretty_number($combatResult['unitLost']['attacker']), + $defendClass, + $LNG['sys_attack_defender_pos'], + pretty_number($combatResult['unitLost']['defender']), + $LNG['sys_gain'], + $LNG['tech'][901], + pretty_number($stealResource[901]), + $LNG['tech'][902], + pretty_number($stealResource[902]), + $LNG['tech'][903], + pretty_number($stealResource[903]), + $LNG['sys_debris'], + $LNG['tech'][901], + pretty_number($debris[901]), + $LNG['tech'][902], + pretty_number($debris[902]) + ); + + SendSimpleMessage($userID, 0, $this->_fleet['fleet_start_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_mess_attack_report'], $message); - $SQL = "INSERT INTO ".RW." SET "; - $SQL .= "`raport` = '".serialize($raport)."', "; - $SQL .= "`time` = '".$this->_fleet['fleet_start_time']."';"; - $db->query($SQL); + $sqlQuery .= "INSERT INTO ".TOPKB_USERS." SET "; + $sqlQuery .= "rid = '".$raportID."', "; + $sqlQuery .= "role = 1, "; + $sqlQuery .= "username = '".$GLOBALS['DATABASE']->escape($userName)."', "; + $sqlQuery .= "uid = ".$userID.";"; + } - $rid = $db->GetInsertID(); - $SQL = ""; - foreach ($Attacker['id'] as $AttackersID) + foreach($userDefend as $userID => $userName) { - if(empty($AttackersID)) - continue; + $LNG = $this->getLanguage(NULL, $userID); + + $message = sprintf($messageHTML, + $raportID, + $defendClass, + $LNG['sys_mess_attack_report'], + sprintf( + $LNG['sys_adress_planet'], + $this->_fleet['fleet_end_galaxy'], + $this->_fleet['fleet_end_system'], + $this->_fleet['fleet_end_planet'] + ), + $LNG['type_planet_short'][$this->_fleet['fleet_end_type']], + $LNG['sys_lost'], + $defendClass, + $LNG['sys_attack_attacker_pos'], + pretty_number($combatResult['unitLost']['attacker']), + $attackClass, + $LNG['sys_attack_defender_pos'], + pretty_number($combatResult['unitLost']['defender']), + $LNG['sys_gain'], + $LNG['tech'][901], + pretty_number($stealResource[901]), + $LNG['tech'][902], + pretty_number($stealResource[902]), + $LNG['tech'][903], + pretty_number($stealResource[903]), + $LNG['sys_debris'], + $LNG['tech'][901], + pretty_number($debris[901]), + $LNG['tech'][902], + pretty_number($debris[902]) + ); - $LNG = $LANG->GetUserLang($AttackersID); - $MessageAtt = sprintf('
%s %s

%s: %s %s: %s
%s %s:%s %s:%s %s:%s
%s %s:%s %s:%s
', $rid, $ColorAtt, $LNG['sys_mess_attack_report'], sprintf($LNG['sys_adress_planet'], $this->_fleet['fleet_end_galaxy'], $this->_fleet['fleet_end_system'], $this->_fleet['fleet_end_planet']), $ColorAtt, $LNG['sys_perte_attaquant'], pretty_number($result['lost']['att']), $ColorDef, $LNG['sys_perte_defenseur'], pretty_number($result['lost']['def']), $LNG['sys_gain'], $LNG['Metal'], pretty_number($steal['metal']), $LNG['Crystal'], pretty_number($steal['crystal']), $LNG['Deuterium'], pretty_number($steal['deuterium']), $LNG['sys_debris'], $LNG['Metal'], pretty_number($result['debree']['att'][0]+$result['debree']['def'][0]), $LNG['Crystal'], pretty_number($result['debree']['att'][1]+$result['debree']['def'][1])); - SendSimpleMessage($AttackersID, 0, $this->_fleet['fleet_start_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_mess_attack_report'], $MessageAtt); - $SQL .= "INSERT INTO ".TOPKB_USERS." SET "; - $SQL .= "`rid` = ".$rid.", "; - $SQL .= "`role` = 1, "; - $SQL .= "`uid` = ".$AttackersID.";"; - $WhereAtt .= "`id` = '".$AttackersID."' OR "; + SendSimpleMessage($userID, 0, $this->_fleet['fleet_start_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_mess_attack_report'], $message); + + $sqlQuery .= "INSERT INTO ".TOPKB_USERS." SET "; + $sqlQuery .= "rid = '".$raportID."', "; + $sqlQuery .= "role = 2, "; + $sqlQuery .= "username = '".$GLOBALS['DATABASE']->escape($userName)."', "; + $sqlQuery .= "uid = ".$userID.";"; } - - foreach ($Defender['id'] as $DefenderID) + + if($this->_fleet['fleet_end_type'] == 3) { - if(empty($DefenderID)) - continue; - - $LNG = $LANG->GetUserLang($DefenderID); - $MessageDef = sprintf('
%s %s

%s: %s %s: %s
%s %s:%s %s:%s %s:%s
%s %s:%s %s:%s
', $rid, $ColorDef, $LNG['sys_mess_attack_report'], sprintf($LNG['sys_adress_planet'], $this->_fleet['fleet_end_galaxy'], $this->_fleet['fleet_end_system'], $this->_fleet['fleet_end_planet']), $ColorDef, $LNG['sys_perte_attaquant'], pretty_number($result['lost']['att']), $ColorAtt, $LNG['sys_perte_defenseur'], pretty_number($result['lost']['def']), $LNG['sys_gain'], $LNG['Metal'], pretty_number($steal['metal']), $LNG['Crystal'], pretty_number($steal['crystal']), $LNG['Deuterium'], pretty_number($steal['deuterium']), $LNG['sys_debris'], $LNG['Metal'], pretty_number($result['debree']['att'][0]+$result['debree']['def'][0]), $LNG['Crystal'], pretty_number($result['debree']['att'][1]+$result['debree']['def'][1])); - SendSimpleMessage($DefenderID, 0, $this->_fleet['fleet_start_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_mess_attack_report'], $MessageDef); - $SQL .= "INSERT INTO ".TOPKB_USERS." SET "; - $SQL .= "`rid` = ".$rid.", "; - $SQL .= "`role` = 2, "; - $SQL .= "`uid` = ".$DefenderID.";"; - $WhereDef .= "`id` = '".$DefenderID."' OR "; + $debrisType = 'id_luna'; + } + else + { + $debrisType = 'id'; } - $WhereCol = $this->_fleet['fleet_end_type'] == 3 ? "id_luna" : "id"; - $SQL .= "UPDATE ".PLANETS." SET "; - $SQL .= "`der_metal` = `der_metal` + ".$ShootMetal.", "; - $SQL .= "`der_crystal` = `der_crystal` + ".$ShootCrystal." "; - $SQL .= "WHERE "; - $SQL .= "`".$WhereCol."` = ".$this->_fleet['fleet_end_id'].";"; - $SQL .= "INSERT INTO ".TOPKB." SET "; - $SQL .= "`units` = '".($result['lost']['att'] + $result['lost']['def'])."', "; - $SQL .= "`rid` = ".$rid.", "; - $SQL .= "`time` = '".$this->_fleet['fleet_start_time']."', "; - $SQL .= "`universe` = '".$this->_fleet['fleet_universe']."', "; - $SQL .= "`result` = '". $result['won'] ."';"; - $SQL .= "UPDATE ".USERS." SET "; - $SQL .= "`wons` = wons + ".$Won.", "; - $SQL .= "`loos` = loos + ".$Lose.", "; - $SQL .= "`draws` = draws + ".$Draw.", "; - $SQL .= "`kbmetal` = kbmetal + ".$ShootMetal.", "; - $SQL .= "`kbcrystal` = kbcrystal + ".$ShootCrystal.", "; - $SQL .= "`lostunits` = lostunits + ".$result['lost']['att'].", "; - $SQL .= "`desunits` = desunits + ".$result['lost']['def']." "; - $SQL .= "WHERE "; - $SQL .= substr($WhereAtt, 0, -4).";"; - $SQL .= "UPDATE ".USERS." SET "; - $SQL .= "`wons` = wons + ".$Lose.", "; - $SQL .= "`loos` = loos + ".$Won.", "; - $SQL .= "`draws` = draws + ".$Draw .", "; - $SQL .= "`kbmetal` = kbmetal + ".$ShootMetal.", "; - $SQL .= "`kbcrystal` = kbcrystal + ".$ShootCrystal.", "; - $SQL .= "`lostunits` = lostunits + ".$result['lost']['def'].", "; - $SQL .= "`desunits` = desunits + ".$result['lost']['att']." "; - $SQL .= "WHERE "; - $SQL .= substr($WhereDef, 0, -4).";"; - $db->multi_query($SQL); + $sqlQuery .= "UPDATE ".PLANETS." SET + der_metal = ".$planetDebris[901].", + der_crystal = ".$planetDebris[902]." + WHERE + ".$debrisType." = ".$this->_fleet['fleet_end_id']."; + UPDATE ".PLANETS." SET + metal = metal - ".$stealResource[901].", + crystal = crystal - ".$stealResource[902].", + deuterium = deuterium - ".$stealResource[903]." + WHERE + id = ".$this->_fleet['fleet_end_id']."; + INSERT INTO ".TOPKB." SET + units = ".($combatResult['unitLost']['attacker'] + $combatResult['unitLost']['defender']).", + rid = '".$raportID."', + time = ".$this->_fleet['fleet_start_time'].", + universe = ".$this->_fleet['fleet_universe'].", + result = '".$combatResult['won'] ."'; + UPDATE ".USERS." SET + ".$attackStatus." = ".$attackStatus." + 1, + kbmetal = kbmetal + ".$debris[901].", + kbcrystal = kbcrystal + ".$debris[902].", + lostunits = lostunits + ".$combatResult['unitLost']['attacker'].", + desunits = desunits + ".$combatResult['unitLost']['defender']." + WHERE + id IN (".implode(',', array_keys($userAttack))."); + UPDATE ".USERS." SET + ".$defendStatus." = ".$defendStatus." + 1, + kbmetal = kbmetal + ".$debris[901].", + kbcrystal = kbcrystal + ".$debris[902].", + lostunits = lostunits + ".$combatResult['unitLost']['attacker'].", + desunits = desunits + ".$combatResult['unitLost']['defender']." + WHERE + id IN (".implode(',', array_keys($userDefend)).");"; + + $GLOBALS['DATABASE']->multi_query($sqlQuery); + + $this->setState(FLEET_RETURN); + $this->SaveFleet(); } function EndStayEvent() @@ -318,13 +511,13 @@ function EndStayEvent() function ReturnEvent() { - global $LANG; - $LNG = $LANG->GetUserLang($this->_fleet['fleet_owner']); - $Message = sprintf($LNG['sys_fleet_won'], $TargetName, GetTargetAdressLink($this->_fleet, ''),pretty_number($this->_fleet['fleet_resource_metal']), $LNG['Metal'],pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['Crystal'],pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['Deuterium'] ); + $LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']); + $TargetName = $GLOBALS['DATABASE']->getFirstCell("SELECT name FROM ".PLANETS." WHERE id = ".$this->_fleet['fleet_start_id'].";"); + $Message = sprintf($LNG['sys_fleet_won'], $TargetName, GetTargetAdressLink($this->_fleet, ''), pretty_number($this->_fleet['fleet_resource_metal']), $LNG['tech'][901], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['tech'][902], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['tech'][903]); + SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_end_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_mess_fleetback'], $Message); $this->RestoreFleet(); } } - -?> \ No newline at end of file + \ No newline at end of file diff --git a/includes/classes/missions/MissionCaseExpedition.php b/includes/classes/missions/MissionCaseExpedition.php index 370c8e4..ac701fa 100644 --- a/includes/classes/missions/MissionCaseExpedition.php +++ b/includes/classes/missions/MissionCaseExpedition.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,86 +18,90 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class MissionCaseExpedition extends MissionFunctions { - function __construct($Fleet) + function __construct($fleet) { - $this->_fleet = $Fleet; + $this->_fleet = $fleet; } function TargetEvent() { - $this->UpdateFleet('fleet_mess', 2); + $this->setState(FLEET_HOLD); $this->SaveFleet(); } function EndStayEvent() { - global $pricelist, $db, $reslist, $LANG; - $LNG = $LANG->GetUserLang($this->_fleet['fleet_owner']); + global $pricelist, $reslist; + $LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']); + + $expeditionPoints = array(); + foreach($reslist['fleet'] as $ID) { - $Expowert[$ID] = ($pricelist[$ID]['metal'] + $pricelist[$ID]['crystal']) / 1000; + $expeditionPoints[$ID] = ($pricelist[$ID]['cost'][901] + $pricelist[$ID]['cost'][902]) / 1000; } - $Expowert[202] = 12; - $Expowert[203] = 47; - $Expowert[204] = 12; - $Expowert[205] = 110; - $Expowert[206] = 47; - $Expowert[207] = 160; - - $farray = explode(";", $this->_fleet['fleet_array']); - $FleetPoints = 0; - $FleetCapacity = 0; + $expeditionPoints[202] = 12; + $expeditionPoints[203] = 47; + $expeditionPoints[204] = 12; + $expeditionPoints[205] = 110; + $expeditionPoints[206] = 47; + $expeditionPoints[207] = 160; - foreach ($farray as $Item => $Group) + $fleetRaw = explode(";", $this->_fleet['fleet_array']); + $fleetPoints = 0; + $fleetCapacity = 0; + $fleetArray = array(); + + foreach ($fleetRaw as $Group) { if (empty($Group)) continue; - + $Class = explode (",", $Group); - $FleetCount[$Class[0]] = $Class[1]; - $FleetCapacity += $Class[1] * $pricelist[$Class[0]]['capacity']; - $FleetPoints += $Class[1] * $Expowert[$Class[0]]; + $fleetArray[$Class[0]] = $Class[1]; + $fleetCapacity += $Class[1] * $pricelist[$Class[0]]['capacity']; + $fleetPoints += $Class[1] * $expeditionPoints[$Class[0]]; } - - $FleetCapacity -= $this->_fleet['fleet_resource_metal'] + $this->_fleet['fleet_resource_crystal'] + $this->_fleet['fleet_resource_deuterium'] + $this->_fleet['fleet_resource_darkmatter']; - - $GetEvent = mt_rand(1, 9); - + + $fleetCapacity -= $this->_fleet['fleet_resource_metal'] + $this->_fleet['fleet_resource_crystal'] + $this->_fleet['fleet_resource_deuterium'] + $this->_fleet['fleet_resource_darkmatter']; + + $GetEvent = mt_rand(1, 9); + + $Message = $LNG['sys_expe_nothing_'.mt_rand(1,8)]; + switch($GetEvent) { case 1: $WitchFound = mt_rand(1,3); - $FindSize = mt_rand(0, 100); + $FindSize = mt_rand(0, 100); + $Factor = 0; + if(10 < $FindSize) { - $WitchSize = 1; $Factor = (mt_rand(10, 50) / $WitchFound) * $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['resource_multiplier']; $Message = $LNG['sys_expe_found_ress_1_'.mt_rand(1,4)]; } elseif(0 < $FindSize && 10 >= $FindSize) { - $WitchSize = 2; $Factor = (mt_rand(52, 100) / $WitchFound) * $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['resource_multiplier']; $Message = $LNG['sys_expe_found_ress_2_'.mt_rand(1,3)]; } elseif(0 == $FindSize) { - $WitchSize = 3; $Factor = (mt_rand(102, 200) / $WitchFound) * $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['resource_multiplier']; $Message = $LNG['sys_expe_found_ress_3_'.mt_rand(1,2)]; - } - - $StatFactor = $db->uniquequery("SELECT MAX(total_points) as total FROM `".STATPOINTS."` WHERE `stat_type` = 1 AND `universe` = '".$this->_fleet['fleet_universe']."';"); - + } + + $StatFactor = $GLOBALS['DATABASE']->getFirstRow("SELECT MAX(total_points) as total FROM `".STATPOINTS."` WHERE `stat_type` = 1 AND `universe` = '".$this->_fleet['fleet_universe']."';"); + $MaxPoints = ($StatFactor['total'] < 5000000) ? 9000 : 12000; - $Size = min($Factor * MAX(MIN($FleetPoints / 1000, $MaxPoints), 200), $FleetCapacity); - + $Size = min($Factor * MAX(MIN($fleetPoints / 1000, $MaxPoints), 200), $fleetCapacity); + switch($WitchFound) { case 1: @@ -113,54 +117,54 @@ function EndStayEvent() break; case 2: - $FindSize = mt_rand(0, 100); + $FindSize = mt_rand(0, 100); + $Size = 0; + if(10 < $FindSize) { $Size = mt_rand(100, 300); $Message = $LNG['sys_expe_found_dm_1_'.mt_rand(1,5)]; } elseif(0 < $FindSize && 10 >= $FindSize) { $Size = mt_rand(301, 600); - $Message = $LNG['sys_expe_found_dm_2_'.mt_rand(1,4)]; + $Message = $LNG['sys_expe_found_dm_2_'.mt_rand(1,3)]; } elseif(0 == $FindSize) { $Size = mt_rand(601, 3000); $Message = $LNG['sys_expe_found_dm_3_'.mt_rand(1,2)]; } - + $this->UpdateFleet('fleet_resource_darkmatter', $this->_fleet['fleet_resource_darkmatter'] + $Size); break; case 3: - default: - $FindSize = mt_rand(0, 100); + $FindSize = mt_rand(0, 100); + $Size = 0; + $Message = ""; + if(10 < $FindSize) { $Size = mt_rand(10, 50); $Message = $LNG['sys_expe_found_ships_1_'.mt_rand(1,4)]; - $MaxFound = 300000; } elseif(0 < $FindSize && 10 >= $FindSize) { $Size = mt_rand(52, 100); $Message = $LNG['sys_expe_found_ships_2_'.mt_rand(1,2)]; - $MaxFound = 600000; } elseif(0 == $FindSize) { $Size = mt_rand(102, 200); $Message = $LNG['sys_expe_found_ships_3_'.mt_rand(1,2)]; - $MaxFound = 1200000; } - - $StatFactor = $db->countquery("SELECT MAX(total_points) FROM `".STATPOINTS."` WHERE `stat_type` = 1 AND `universe` = '".$this->_fleet['fleet_universe']."';"); - + + $StatFactor = $GLOBALS['DATABASE']->getFirstCell("SELECT MAX(total_points) FROM `".STATPOINTS."` WHERE `stat_type` = 1 AND `universe` = '".$this->_fleet['fleet_universe']."';"); + $MaxPoints = ($StatFactor < 5000000) ? 4500 : 6000; - - $FoundShips = max(round($Size * min($FleetPoints, $MaxPoints)), 10000); + + $FoundShips = max(round($Size * min($fleetPoints, $MaxPoints)), 10000); $FoundShipMess = ""; $NewFleetArray = ""; - - $LNG += $LANG->GetUserLang($this->_fleet['fleet_owner'], array('TECH')); + $Found = array(); foreach($reslist['fleet'] as $ID) { - if(!isset($FleetCount[$ID]) || $ID == 208 || $ID == 209 || $ID == 214) + if(!isset($fleetArray[$ID]) || $ID == 208 || $ID == 209 || $ID == 214) continue; - $MaxFound = floor($FoundShips / ($pricelist[$ID]['metal'] + $pricelist[$ID]['crystal'])); + $MaxFound = floor($FoundShips / ($pricelist[$ID]['cost'][901] + $pricelist[$ID]['cost'][902])); if($MaxFound <= 0) continue; @@ -168,23 +172,34 @@ function EndStayEvent() if($Count <= 0) continue; - $Found[$ID] += $Count; - $FoundShips -= $Count * ($pricelist[$ID]['metal'] + $pricelist[$ID]['crystal']); + $Found[$ID] = $Count; + $FoundShips -= $Count * ($pricelist[$ID]['cost'][901] + $pricelist[$ID]['cost'][902]); $FoundShipMess .= '
'.$LNG['tech'][$ID].': '.pretty_number($Count); if($FoundShips <= 0) break; } - foreach($FleetCount as $ID => $Count) - $NewFleetArray .= $ID.",".floattostring($Count + $Found[$ID]).";"; + if (empty($Found)) { + $FoundShipMess .= '

'.$LNG['sys_expe_found_ships_nothing']; + } + + foreach($fleetArray as $ID => $Count) + { + if(!empty($Found[$ID])) + { + $Count += $Found[$ID]; + } + $NewFleetArray .= $ID.",".floattostring($Count).';'; + } + $Message .= $FoundShipMess; $this->UpdateFleet('fleet_array', $NewFleetArray); - $this->UpdateFleet('fleet_amount', array_sum($FleetCount)); + $this->UpdateFleet('fleet_amount', array_sum($fleetArray)); break; case 4: - $Chance = mt_rand(1,2); + $Chance = mt_rand(1,2); if($Chance == 1) { $Points = array(-3,-5,-8); $Which = 1; @@ -202,43 +217,86 @@ function EndStayEvent() $Rand = array(4,3,2); $DefenderFleetArray = "205,5;215,3;213,2;"; } - $LNG += $LANG->GetUserLang($this->_fleet['fleet_owner'], array('L18N')); - - $FindSize = mt_rand(0, 100); + + $messageHTML = << + + + + + + + + + + + + + +
%s %s (%s)
%s%s: %s %s: %s
%s%s: %s %s: %s %s: %s
%s%s: %s %s: %s
+ +HTML; + //Minize HTML + $messageHTML = str_replace(array("\n", "\t", "\r"), "", $messageHTML); + + + $FindSize = mt_rand(0, 100); + $maxAttack = 0; + if(10 < $FindSize) { - $Message = $LNG['sys_expe_attack_'.$Which.'_1_'.$Rand[0]]; - $MaxAttackerPoints = 0.3 + $Add + (mt_rand($Points[0], abs($Points[0])) * 0.01); + $Message = $LNG['sys_expe_attack_'.$Which.'_1_'.$Rand[0]]; + $maxAttack = 0.3 + $Add + (mt_rand($Points[0], abs($Points[0])) * 0.01); } elseif(0 < $FindSize && 10 >= $FindSize) { - $Message = $LNG['sys_expe_attack_'.$Which.'_2_'.$Rand[1]]; - $MaxAttackerPoints = 0.3 + $Add + (mt_rand($Points[1], abs($Points[1])) * 0.01); + $Message = $LNG['sys_expe_attack_'.$Which.'_2_'.$Rand[1]]; + $maxAttack = 0.3 + $Add + (mt_rand($Points[1], abs($Points[1])) * 0.01); } elseif(0 == $FindSize) { - $Message = $LNG['sys_expe_attack_'.$Which.'_3_'.$Rand[2]]; - $MaxAttackerPoints = 0.3 + $Add + (mt_rand($Points[2], abs($Points[2])) * 0.01); + $Message = $LNG['sys_expe_attack_'.$Which.'_3_'.$Rand[2]]; + $maxAttack = 0.3 + $Add + (mt_rand($Points[2], abs($Points[2])) * 0.01); } - foreach($FleetCount as $ID => $count) + foreach($fleetArray as $ID => $count) { - $DefenderFleetArray .= $ID.",".round($count * $MaxAttackerPoints).";"; + $DefenderFleetArray .= $ID.",".round($count * $maxAttack).";"; } - $AttackerTechno = $db->uniquequery('SELECT id,username,military_tech,defence_tech,shield_tech,rpg_amiral,dm_defensive,dm_attack FROM '.USERS.' WHERE id='.$this->_fleet['fleet_owner'].";"); - $DefenderTechno = array('id' => 0, 'username' => $Name, 'military_tech' => (min($AttackerTechno['military_tech'] + $Def,0)), 'defence_tech' => (min($AttackerTechno['defence_tech'] + $Def,0)), 'shield_tech' => (min($AttackerTechno['shield_tech'] + $Def,0)), 'rpg_amiral' => 0, 'dm_defensive' => 0, 'dm_attack' => 0); + $AttackerTechno = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".USERS." WHERE id = ".$this->_fleet['fleet_owner'].";"); + $DefenderTechno = array( + 'id' => 0, + 'username' => $Name, + 'military_tech' => (min($AttackerTechno['military_tech'] + $Def,0)), + 'defence_tech' => (min($AttackerTechno['defence_tech'] + $Def,0)), + 'shield_tech' => (min($AttackerTechno['shield_tech'] + $Def,0)), + 'rpg_amiral' => 0, + 'dm_defensive' => 0, + 'dm_attack' => 0 + ); + + $fleetID = $this->_fleet['fleet_id']; + + $fleetAttack[$fleetID]['fleetDetail'] = $this->_fleet; + $fleetAttack[$fleetID]['player'] = $AttackerTechno; + $fleetAttack[$fleetID]['player']['factor'] = getFactors($fleetAttack[$this->_fleet['fleet_id']]['player'], 'attack', $this->_fleet['fleet_start_time']); + $fleetAttack[$fleetID]['unit'] = array(); - $attackFleets[$this->_fleet['fleet_id']]['fleet'] = $this->_fleet; - $attackFleets[$this->_fleet['fleet_id']]['user'] = $AttackerTechno; - $attackFleets[$this->_fleet['fleet_id']]['user']['factor'] = getFactors($attackFleets[$this->_fleet['fleet_id']]['user'], 'attack', $this->_fleet['fleet_start_time']); - $attackFleets[$this->_fleet['fleet_id']]['detail'] = array(); $temp = explode(';', $this->_fleet['fleet_array']); foreach ($temp as $temp2) { $temp2 = explode(',', $temp2); - if ($temp2[0] < 100) continue; - if (!isset($attackFleets[$this->_fleet['fleet_id']]['detail'][$temp2[0]])) - $attackFleets[$this->_fleet['fleet_id']]['detail'][$temp2[0]] = 0; - - $attackFleets[$this->_fleet['fleet_id']]['detail'][$temp2[0]] += $temp2[1]; + + if ($temp2[0] < 100) + { + continue; + } + + if (!isset($fleetAttack[$fleetID]['unit'][$temp2[0]])) + { + $fleetAttack[$fleetID]['unit'][$temp2[0]] = 0; + } + + $fleetAttack[$fleetID]['unit'][$temp2[0]] += $temp2[1]; } - $defense = array(); + + $fleetDefend = array(); $defRowDef = explode(';', $DefenderFleetArray); foreach ($defRowDef as $Element) @@ -246,73 +304,135 @@ function EndStayEvent() $Element = explode(',', $Element); if ($Element[0] < 100) continue; - if (!isset($defense[$defRow['fleet_id']]['def'][$Element[0]])) - $defense[0][$Element[0]] = 0; - $defense[0]['def'][$Element[0]] += $Element[1]; + if (!isset($fleetDefend[0]['unit'][$Element[0]])) + $fleetDefend[0]['unit'][$Element[0]] = 0; + + $fleetDefend[0]['unit'][$Element[0]] += $Element[1]; } - $defense[0]['user'] = $DefenderTechno; - $defense[0]['user']['factor'] = 0; + + $fleetDefend[0]['fleetDetail'] = array( + 'fleet_start_galaxy' => $this->_fleet['fleet_end_galaxy'], + 'fleet_start_system' => $this->_fleet['fleet_end_system'], + 'fleet_start_planet' => $this->_fleet['fleet_end_planet'], + 'fleet_start_type' => 1, + 'fleet_end_galaxy' => $this->_fleet['fleet_end_galaxy'], + 'fleet_end_system' => $this->_fleet['fleet_end_system'], + 'fleet_end_planet' => $this->_fleet['fleet_end_planet'], + 'fleet_end_type' => 1, + 'fleet_resource_metal' => 0, + 'fleet_resource_crystal' => 0, + 'fleet_resource_deuterium' => 0 + ); + $fleetDefend[0]['player'] = $DefenderTechno; + $fleetDefend[0]['player']['factor'] = 0; require_once('calculateAttack.php'); + + $fleetIntoDebris = $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['Fleet_Cdr']; + $defIntoDebris = $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['Defs_Cdr']; + + $combatResult = calculateAttack($fleetAttack, $fleetDefend, $fleetIntoDebris, $defIntoDebris); - $start = microtime(true); - $result = calculateAttack($attackFleets, $defense, $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['Fleet_Cdr'], $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['Defs_Cdr']); - $totaltime = microtime(true) - $start; - - foreach ($attackFleets as $fleetID => $attacker) + $fleetArray = ''; + $totalCount = 0; + + $fleetAttack[$fleetID]['unit'] = array_filter($fleetAttack[$fleetID]['unit']); + foreach ($fleetAttack[$fleetID]['unit'] as $element => $amount) { - $fleetArray = ''; - $totalCount = 0; - foreach ($attacker['detail'] as $element => $amount) - { - if ($amount) - $fleetArray .= $element.','.$amount.';'; - - $totalCount += $amount; - } + $fleetArray .= $element.','.$amount.';'; + $totalCount += $amount; + } - if ($totalCount <= 0) - $this->KillFleet(); - else - { - $this->UpdateFleet('fleet_array', substr($fleetArray, 0, -1)); - $this->UpdateFleet('fleet_amount', $totalCount); - } + if ($totalCount <= 0) + { + $this->KillFleet(); + } + else + { + $this->UpdateFleet('fleet_array', substr($fleetArray, 0, -1)); + $this->UpdateFleet('fleet_amount', $totalCount); } require_once('GenerateReport.php'); + + + $debrisRessource = array(901, 902); + foreach($debrisRessource as $elementID) + { + $debris[$elementID] = 0; + } - - $INFO = $this->_fleet; - $INFO['steal'] = array('metal' => 0, 'crystal' => 0, 'deuterium' => 0); - $INFO['moon']['des'] = 0; - $INFO['moon']['chance'] = 0; - $raport = GenerateReport($result, $INFO); - - $SQL = "INSERT INTO ".RW." SET "; - $SQL .= "`raport` = '".serialize($raport)."', "; - $SQL .= "`time` = '".$this->_fleet['fleet_start_time']."', "; - $SQL .= "`rid` = '".$rid."';"; - $db->query($SQL); - $rid = $db->GetInsertID(); - switch($result['won']) + $stealResource = array(901 => 0, 902 => 0, 903 => 0); + + $raportInfo = array( + 'thisFleet' => $this->_fleet, + 'debris' => $debris, + 'stealResource' => $stealResource, + 'moonChance' => 0, + 'moonDestroy' => false, + 'moonName' => null, + 'moonDestroyChance' => null, + 'moonDestroySuccess' => null, + 'fleetDestroyChance' => null, + 'fleetDestroySuccess' => null, + ); + + $raportData = GenerateReport($combatResult, $raportInfo); + + $raportID = md5(uniqid('', true).TIMESTAMP); + $sqlQuery = "INSERT INTO ".RW." SET rid = '".$raportID."', raport = '".serialize($raportData)."', time = '".$this->_fleet['fleet_start_time']."', attacker = '".$this->_fleet['fleet_owner']."';"; + $GLOBALS['DATABASE']->query($sqlQuery); + + switch($combatResult['won']) { - case "r": - $ColorAtt = "red"; - $ColorDef = "green"; + case "a": + $attackClass = 'raportWin'; + $defendClass = 'raportLose'; break; case "w": - $ColorAtt = "orange"; - $ColorDef = "orange"; - case "a": - $ColorAtt = "green"; - $ColorDef = "red"; + $attackClass = 'raportDraw'; + $defendClass = 'raportDraw'; + break; + case "r": + $attackClass = 'raportLose'; + $defendClass = 'raportWin'; break; } - $MessageAtt = sprintf('
%s %s

%s: %s %s: %s
%s %s:%s %s:%s %s:%s
%s %s:%s %s:%s
', $rid, $ColorAtt, $LNG['sys_mess_attack_report'], sprintf($LNG['sys_adress_planet'], $this->_fleet['fleet_end_galaxy'], $this->_fleet['fleet_end_system'], $this->_fleet['fleet_end_planet']), $ColorAtt, $LNG['sys_perte_attaquant'], pretty_number($result['lost']['att']), $ColorDef, $LNG['sys_perte_defenseur'], pretty_number($result['lost']['def']), $LNG['sys_gain'], $LNG['Metal'], pretty_number($steal['metal']), $LNG['Crystal'], pretty_number($steal['crystal']), $LNG['Deuterium'], pretty_number($steal['deuterium']), $LNG['sys_debris'], $LNG['Metal'], pretty_number($result['debree']['att'][0]+$result['debree']['def'][0]), $LNG['Crystal'], pretty_number($result['debree']['att'][1]+$result['debree']['def'][1])); - - SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_start_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_mess_attack_report'], $MessageAtt); + + $message = sprintf($messageHTML, + $raportID, + $attackClass, + $LNG['sys_mess_attack_report'], + sprintf( + $LNG['sys_adress_planet'], + $this->_fleet['fleet_end_galaxy'], + $this->_fleet['fleet_end_system'], + $this->_fleet['fleet_end_planet'] + ), + $LNG['type_planet_short'][$this->_fleet['fleet_end_type']], + $LNG['sys_lost'], + $attackClass, + $LNG['sys_attack_attacker_pos'], + pretty_number($combatResult['unitLost']['attacker']), + $defendClass, + $LNG['sys_attack_defender_pos'], + pretty_number($combatResult['unitLost']['defender']), + $LNG['sys_gain'], + $LNG['tech'][901], + pretty_number($stealResource[901]), + $LNG['tech'][902], + pretty_number($stealResource[902]), + $LNG['tech'][903], + pretty_number($stealResource[903]), + $LNG['sys_debris'], + $LNG['tech'][901], + pretty_number($debris[901]), + $LNG['tech'][902], + pretty_number($debris[902]) + ); + + SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_end_stay'], 3, $LNG['sys_mess_tower'], $LNG['sys_mess_attack_report'], $message); break; case 5: $this->KillFleet(); @@ -332,32 +452,27 @@ function EndStayEvent() $Wrapper[] = 3; $Wrapper[] = 3; $Wrapper[] = 5; + if($MoreTime < 75) { - $this->UpdateFleet('fleet_end_time', ($this->_fleet['fleet_end_time'] - $this->_fleet['fleet_end_stay']) + ($this->_fleet['fleet_end_stay'] - $this->_fleet['fleet_start_time']) * $Wrapper[mt_rand(0, 9)]); + $this->UpdateFleet('fleet_end_time', $this->_fleet['fleet_end_stay'] + (($this->_fleet['fleet_end_time'] - $this->_fleet['fleet_end_stay']) + ($this->_fleet['fleet_end_stay'] - $this->_fleet['fleet_start_time']) * $Wrapper[mt_rand(0, 9)])); $Message = $LNG['sys_expe_time_slow_'.mt_rand(1,6)]; } else { - $this->UpdateFleet('fleet_end_time', max(1, ($this->_fleet['fleet_end_time'] - $this->_fleet['fleet_end_stay']) - ($this->_fleet['fleet_end_stay'] - $this->_fleet['fleet_start_time']) / 3 * $Wrapper[mt_rand(0, 9)])); + $this->UpdateFleet('fleet_end_time', $this->_fleet['fleet_end_stay'] + max(1, ($this->_fleet['fleet_end_time'] - $this->_fleet['fleet_end_stay']) - ($this->_fleet['fleet_end_stay'] - $this->_fleet['fleet_start_time']) / 3 * $Wrapper[mt_rand(0, 9)])); $Message = $LNG['sys_expe_time_fast_'.mt_rand(1,3)]; } break; - default: - $Message = $LNG['sys_expe_nothing_'.mt_rand(1,8)]; - break; } SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_end_stay'], 15, $LNG['sys_mess_tower'], $LNG['sys_expe_report'], $Message); - $this->UpdateFleet('fleet_mess', 1); + $this->setState(FLEET_RETURN); $this->SaveFleet(); } function ReturnEvent() { - global $LANG; - $LNG = $LANG->GetUserLang($this->_fleet['fleet_owner']); - $Message = sprintf($LNG['sys_expe_back_home'], $LNG['Metal'], pretty_number($this->_fleet['fleet_resource_metal']), $LNG['Crystal'], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['Deuterium'], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['Darkmatter'], pretty_number($this->_fleet['fleet_resource_darkmatter'])); + $LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']); + $Message = sprintf($LNG['sys_expe_back_home'], $LNG['tech'][901], pretty_number($this->_fleet['fleet_resource_metal']), $LNG['tech'][902], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['tech'][903], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['tech'][921], pretty_number($this->_fleet['fleet_resource_darkmatter'])); SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_end_time'], 15, $LNG['sys_mess_tower'], $LNG['sys_expe_report'], $Message); $this->RestoreFleet(); } } - -?> \ No newline at end of file diff --git a/includes/classes/missions/MissionCaseFoundDM.php b/includes/classes/missions/MissionCaseFoundDM.php index 5b2d2b3..fc9174d 100644 --- a/includes/classes/missions/MissionCaseFoundDM.php +++ b/includes/classes/missions/MissionCaseFoundDM.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,13 +18,12 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class MissionCaseFoundDM extends MissionFunctions @@ -42,15 +41,14 @@ function __construct($Fleet) function TargetEvent() { - $this->UpdateFleet('fleet_mess', 2); + $this->setState(FLEET_HOLD); $this->SaveFleet(); } function EndStayEvent() { - global $LANG; - $LNG = $LANG->GetUserLang($this->_fleet['fleet_owner']); - $chance = mt_rand(0, 100); + $LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']); + $chance = mt_rand(0, 100); if($chance <= min(self::MAX_CHANCE, (self::CHANCE + $this->_fleet['fleet_amount'] * self::CHANCE_SHIP))) { $FoundDark = mt_rand(self::MIN_FOUND, self::MAX_FOUND); $this->UpdateFleet('fleet_resource_darkmatter', $FoundDark); @@ -58,17 +56,16 @@ function EndStayEvent() } else { $Message = $LNG['sys_expe_nothing_'.mt_rand(1, 9)]; } - $this->UpdateFleet('fleet_mess', 1); + $this->setState(FLEET_RETURN); $this->SaveFleet(); SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_end_stay'], 15, $LNG['sys_mess_tower'], $LNG['sys_expe_report'], $Message); } function ReturnEvent() { - global $LANG; - $LNG = $LANG->GetUserLang($this->_fleet['fleet_owner']); + $LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']); if($this->_fleet['fleet_resource_darkmatter'] > 0) { - SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_end_time'], 15, $LNG['sys_mess_tower'], $LNG['sys_expe_report'], sprintf($LNG['sys_expe_back_home_with_dm'], $LNG['Darkmatter'], pretty_number($this->_fleet['fleet_resource_darkmatter']), $LNG['Darkmatter'])); + SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_end_time'], 15, $LNG['sys_mess_tower'], $LNG['sys_expe_report'], sprintf($LNG['sys_expe_back_home_with_dm'], $LNG['tech'][921], pretty_number($this->_fleet['fleet_resource_darkmatter']), $LNG['tech'][921])); $this->UpdateFleet('fleet_array', '220,0;'); } else { SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_end_time'], 15, $LNG['sys_mess_tower'], $LNG['sys_expe_report'], $LNG['sys_expe_back_home_without_dm']); @@ -76,5 +73,3 @@ function ReturnEvent() $this->RestoreFleet(); } } - -?> \ No newline at end of file diff --git a/includes/classes/missions/MissionCaseMIP.php b/includes/classes/missions/MissionCaseMIP.php index d48f78c..0e504f5 100644 --- a/includes/classes/missions/MissionCaseMIP.php +++ b/includes/classes/missions/MissionCaseMIP.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,13 +18,12 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class MissionCaseMIP extends MissionFunctions @@ -36,87 +35,93 @@ function __construct($Fleet) function TargetEvent() { - global $db, $resource, $reslist, $LANG; + global $resource, $reslist; $SQL = ""; - foreach($reslist['defense'] as $Element) + + $elementIDs = array_merge($reslist['defense'], $reslist['missile']); + foreach($elementIDs as $elementID) { - $SQL .= PLANETS.".".$resource[$Element].", "; + $SQL .= PLANETS.".".$resource[$elementID].", "; } - $QryTarget = "SELECT ".USERS.".lang, ".USERS.".defence_tech, ".PLANETS.".id, ".PLANETS.".id_owner, ".substr($SQL, 0, -2)." + $QryTarget = "SELECT ".USERS.".lang, ".USERS.".shield_tech, ".PLANETS.".id, ".PLANETS.".name, ".PLANETS.".id_owner, ".substr($SQL, 0, -2)." FROM ".PLANETS.", ".USERS." - WHERE ".PLANETS.".`id` = '".$this->_fleet['fleet_end_id']."' AND + WHERE ".PLANETS.".id = '".$this->_fleet['fleet_end_id']."' AND ".PLANETS.".id_owner = ".USERS.".id;"; - $TargetInfo = $db->uniquequery($QryTarget); + $targetData = $GLOBALS['DATABASE']->getFirstRow($QryTarget); + if($this->_fleet['fleet_end_type'] == 3) { - $TargetInfo[$resource[502]] = $db->countquery("SELECT ".$resource[502]." FROM ".PLANETS." WHERE id_luna = ".$this->_fleet['fleet_end_id'].";"); - } - $OwnerInfo = $db->uniquequery("SELECT `lang`, `military_tech` FROM ".USERS." WHERE `id` = '".$this->_fleet['fleet_owner']."';"); + $targetData[$resource[502]] = $GLOBALS['DATABASE']->getFirstCell("SELECT ".$resource[502]." FROM ".PLANETS." WHERE id_luna = ".$this->_fleet['fleet_end_id'].";"); + } + + $OwnerInfo = $GLOBALS['DATABASE']->getFirstRow("SELECT lang, military_tech FROM ".USERS." WHERE id = '".$this->_fleet['fleet_owner']."';"); $Target = (!in_array($this->_fleet['fleet_target_obj'], $reslist['defense']) || $this->_fleet['fleet_target_obj'] == 502 || $this->_fleet['fleet_target_obj'] == 0) ? 401 : $this->_fleet['fleet_target_obj']; - foreach($reslist['defense'] as $Element) + $targetDefensive = array(); + + foreach($elementIDs as $elementID) { - $TargetDefensive[$Element] = $TargetInfo[$resource[$Element]]; + $targetDefensive[$elementID] = $targetData[$resource[$elementID]]; } - - $message = ""; - $SQL = ""; - - $LNG = $LANG->GetUserLang($GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['lang'], array('L18N', 'FLEET', 'TECH')); + + unset($targetDefensive[502]); + + $SQL = ""; + $LNG = $this->getLanguage($GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['lang'], array('L18N', 'FLEET', 'TECH')); - require_once('calculateMIPAttack.php'); - if ($TargetInfo[$resource[502]] >= $this->_fleet['fleet_amount']) + if ($targetData[$resource[502]] >= $this->_fleet['fleet_amount']) { $message = $LNG['sys_irak_no_att']; - if($this->_fleet['fleet_end_type'] == 3) - $SQL .= "UPDATE ".PLANETS." SET ".$resource[502]." = ".$resource[502]." - ".$this->_fleet['fleet_amount']." WHERE id_luna = ".$TargetInfo['id'].";"; - else - $SQL .= "UPDATE ".PLANETS." SET ".$resource[502]." = ".$resource[502]." - ".$this->_fleet['fleet_amount']." WHERE id = ".$TargetInfo['id'].";"; + $where = $this->_fleet['fleet_end_type'] == 3 ? 'id_luna' : 'id'; + + $SQL .= "UPDATE ".PLANETS." SET ".$resource[502]." = ".$resource[502]." - ".$this->_fleet['fleet_amount']." WHERE ".$where." = ".$targetData['id'].";"; } else { - if ($TargetInfo[$resource[502]] > 0) + if ($targetData[$resource[502]] > 0) { - if($this->_fleet['fleet_end_type'] == 3) - $db->query("UPDATE ".PLANETS." SET ".$resource[502]." = 0 WHERE id_luna = " . $TargetInfo['id'].";"); - else - $db->query("UPDATE ".PLANETS." SET ".$resource[502]." = 0 WHERE id = " . $TargetInfo['id'].";"); - $message .= sprintf($LNG['sys_irak_def'], $TargetInfo[$resource[502]]); + $where = $this->_fleet['fleet_end_type'] == 3 ? 'id_luna' : 'id'; + $GLOBALS['DATABASE']->query("UPDATE ".PLANETS." SET ".$resource[502]." = 0 WHERE ".$where." = ".$targetData['id'].";"); } - $irak = calculateMIPAttack($TargetInfo["defence_tech"], $OwnerInfo["military_tech"], $this->_fleet['fleet_amount'], $TargetDefensive, $Target, $TargetInfo[$resource[502]]); - ksort($irak, SORT_NUMERIC); - $Count = 0; - foreach ($irak as $Element => $destroy) + $targetDefensive = array_filter($targetDefensive); + + if(!empty($targetDefensive)) { - if(empty($Element)) - continue; - - if ($id != 502) - $message .= $LNG['tech'][$Element]." (- ".$destroy.")
"; + require_once 'calculateMIPAttack.php'; + $irak = calculateMIPAttack($targetData["shield_tech"], $OwnerInfo["military_tech"], $this->_fleet['fleet_amount'], $targetDefensive, $Target, $targetData[$resource[502]]); + $irak = array_filter($irak); + + $message = sprintf($LNG['sys_irak_def'], $targetData[$resource[502]]).'

'; + + ksort($irak, SORT_NUMERIC); - if ($destroy == 0) - continue; + foreach ($irak as $Element => $destroy) + { + $message .= $LNG['tech'][$Element].' (- '.$destroy.')
'; - if($this->_fleet['fleet_end_type'] == 3 && $Element == 502) - $SQL .= "UPDATE ".PLANETS." SET `".$resource[$Element]."` = `".$resource[$Element]."` - '".$destroy."' WHERE id_luna = ".$TargetInfo['id'].";"; - elseif(in_array($Element, $reslist['one'])) - $SQL .= "UPDATE ".PLANETS." SET `".$resource[$Element]."` = '0' WHERE id = ".$TargetInfo['id'].";"; - else - $SQL .= "UPDATE ".PLANETS." SET `".$resource[$Element]."` = `".$resource[$Element]."` - '".$destroy."' WHERE id = ".$TargetInfo['id'].";"; + if(in_array($Element, $reslist['one'])) + $SQL .= "UPDATE ".PLANETS." SET ".$resource[$Element]." = '0' WHERE id = ".$targetData['id'].";"; + else + $SQL .= "UPDATE ".PLANETS." SET ".$resource[$Element]." = ".$resource[$Element]." - ".$destroy." WHERE id = ".$targetData['id'].";"; + } + } + else + { + $message = $LNG['sys_irak_no_def']; } } - $UserPlanet = $db->uniquequery("SELECT name FROM ".PLANETS." WHERE id = '" . $this->_fleet['fleet_owner'] . "';"); - $OwnerLink = $UserPlanet['name']."[".$this->_fleet['fleet_start_galaxy'].":".$this->_fleet['fleet_start_system'].":".$this->_fleet['fleet_start_planet']."]"; - $TargetLink = $TargetInfo['name']."[".$this->_fleet['fleet_end_galaxy'].":".$this->_fleet['fleet_end_system'].":".$this->_fleet['fleet_end_planet']."]";; - $Message = sprintf($LNG['sys_irak_mess'], $this->_fleet['fleet_amount'], $OwnerLink, $TargetLink).(empty($message) ? $LNG['sys_irak_no_def'] : $message); + $UserPlanet = $GLOBALS['DATABASE']->getFirstRow("SELECT name FROM ".PLANETS." WHERE id = ".$this->_fleet['fleet_start_id'].";"); + $OwnerLink = $UserPlanet['name']." [".$this->_fleet['fleet_start_galaxy'].":".$this->_fleet['fleet_start_system'].":".$this->_fleet['fleet_start_planet']."]"; + $TargetLink = $targetData['name']." [".$this->_fleet['fleet_end_galaxy'].":".$this->_fleet['fleet_end_system'].":".$this->_fleet['fleet_end_planet']."]"; + $Message = sprintf($LNG['sys_irak_mess'], $this->_fleet['fleet_amount'], $OwnerLink, $TargetLink).$message; - SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_start_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_irak_subject'] , $Message); - SendSimpleMessage($this->_fleet['fleet_target_owner'], 0, $this->_fleet['fleet_start_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_irak_subject'] , $Message); - $SQL .= "DELETE FROM ".FLEETS." WHERE fleet_id = '" . $this->_fleet['fleet_id'] . "';"; - $db->multi_query($SQL); + SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_start_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_irak_subject'], $Message); + SendSimpleMessage($this->_fleet['fleet_target_owner'], 0, $this->_fleet['fleet_start_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_irak_subject'], $Message); + $SQL .= "DELETE FROM ".FLEETS." WHERE fleet_id = '".$this->_fleet['fleet_id']."';"; + $GLOBALS['DATABASE']->multi_query($SQL); } function EndStayEvent() @@ -129,5 +134,3 @@ function ReturnEvent() return; } } - -?> \ No newline at end of file diff --git a/includes/classes/missions/MissionCaseRecycling.php b/includes/classes/missions/MissionCaseRecycling.php index b685872..0e61407 100644 --- a/includes/classes/missions/MissionCaseRecycling.php +++ b/includes/classes/missions/MissionCaseRecycling.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,13 +18,12 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class MissionCaseRecycling extends MissionFunctions @@ -36,56 +35,84 @@ function __construct($Fleet) function TargetEvent() { - global $db, $pricelist, $LANG; - $Target = $db->uniquequery("SELECT der_metal, der_crystal, (der_metal + der_crystal) as der_total FROM ".PLANETS." WHERE `id` = '".$this->_fleet['fleet_end_id']."';"); - $FleetRecord = explode(";", $this->_fleet['fleet_array']); - $RecyclerCapacity = 0; - $OtherFleetCapacity = 0; - foreach ($FleetRecord as $Item => $Group) + global $pricelist, $reslist, $resource; + + $resourceIDs = array(901, 902, 903, 921); + $debrisIDs = array(901, 902); + $resQuery = array(); + $collectQuery = array(); + + $collectedGoods = array(); + + foreach($debrisIDs as $debrisID) { - if (empty($Group)) - continue; - - $Class = explode (",", $Group); - if ($Class[0] == 209 || $Class[0] == 219) - $RecyclerCapacity += $pricelist[$Class[0]]['capacity'] * $Class[1]; - else - $OtherFleetCapacity += $pricelist[$Class[0]]['capacity'] * $Class[1]; + $collectedGoods[$debrisID] = 0; + $resQuery[] = 'der_'.$resource[$debrisID]; } - $RecycledGoods = array('metal' => 0, 'crystal' => 0); - $IncomingFleetGoods = $FleetRow['fleet_resource_metal'] + $FleetRow['fleet_resource_crystal'] + $FleetRow['fleet_resource_deuterium']; - if ($IncomingFleetGoods > $OtherFleetCapacity) - $RecyclerCapacity -= ($IncomingFleetGoods - $OtherFleetCapacity); + + $targetData = $GLOBALS['DATABASE']->getFirstRow("SELECT ".implode(',', $resQuery).", (".implode(' + ', $resQuery).") as total FROM ".PLANETS." WHERE id = ".$this->_fleet['fleet_end_id'].";"); + if(!empty($targetData['total'])) + { + $targetUser = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".USERS." WHERE id = ".$this->_fleet['fleet_owner'].";"); + $targetUserFactors = getFactors($targetUser); + $shipStorageFactor = 1 + $targetUserFactors['ShipStorage']; + + // Get fleet capacity + $fleetData = explode(";", $this->_fleet['fleet_array']); - if ($Target['der_total'] <= $RecyclerCapacity) { - $RecycledGoods['metal'] = $Target['der_metal']; - $RecycledGoods['crystal'] = $Target['der_crystal']; - } elseif (($Target['der_metal'] > $RecyclerCapacity / 2) && ($Target['der_crystal'] > $RecyclerCapacity / 2)) { - $RecycledGoods['metal'] = $RecyclerCapacity / 2; - $RecycledGoods['crystal'] = $RecyclerCapacity / 2; - } elseif ($Target['der_metal'] > $Target['der_crystal']) { - $RecycledGoods['crystal'] = $Target['der_crystal']; - if ($Target['der_metal'] > ($RecyclerCapacity - $RecycledGoods['crystal'])) - $RecycledGoods['metal'] = $RecyclerCapacity - $RecycledGoods['crystal']; - else - $RecycledGoods['metal'] = $Target['der_metal']; - } else { - $RecycledGoods['metal'] = $Target['der_metal']; - if ($Target['der_crystal'] > ($RecyclerCapacity - $RecycledGoods['metal'])) - $RecycledGoods['crystal'] = $RecyclerCapacity - $RecycledGoods['metal']; - else - $RecycledGoods['crystal'] = $Target['der_crystal']; - } - - $db->query("UPDATE ".PLANETS." SET `der_metal` = `der_metal` - ".$RecycledGoods['metal'].", `der_crystal` = `der_crystal` - ".$RecycledGoods['crystal']." WHERE `id` = '".$this->_fleet['fleet_end_id']."';"); + $recyclerStorage = 0; + $otherFleetStorage = 0; + + foreach ($fleetData as $fleetRow) + { + if (empty($fleetRow)) continue; + + $temp = explode (",", $fleetRow); - $LNG = $LANG->GetUserLang($this->_fleet['fleet_owner']); - $Message = sprintf($LNG['sys_recy_gotten'], pretty_number($RecycledGoods['metal']), $LNG['Metal'], pretty_number($RecycledGoods['crystal']), $LNG['Crystal']); - SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_start_time'], 5, $LNG['sys_mess_tower'], $LNG['sys_recy_report'], $Message); + if ($temp[0] == 209 || $temp[0] == 219) + { + $recyclerStorage += $pricelist[$temp[0]]['capacity'] * $temp[1]; + } + else + { + $otherFleetStorage += $pricelist[$temp[0]]['capacity'] * $temp[1]; + } + } + + $recyclerStorage *= $shipStorageFactor; + $otherFleetStorage *= $shipStorageFactor; + + unset($temp); + + $incomingGoods = 0; + foreach($resourceIDs as $resourceID) + { + $incomingGoods += $this->_fleet['fleet_resource_'.$resource[$debrisID]]; + } + + $totalStorage = $recyclerStorage + min(0, $otherFleetStorage - $incomingGoods); + + // fast way + $collectFactor = min(1, $totalStorage / $targetData['total']); + foreach($debrisIDs as $debrisID) + { + $collectedGoods[$debrisID] = ceil($targetData['der_'.$resource[$debrisID]] * $collectFactor); + $collectQuery[] = 'der_'.$resource[$debrisID].' = GREATEST(0, der_'.$resource[$debrisID].' - '.$collectedGoods[$debrisID].')'; + $this->UpdateFleet('fleet_resource_'.$resource[$debrisID], $this->_fleet['fleet_resource_'.$resource[$debrisID]] + $collectedGoods[$debrisID]); + } + + $GLOBALS['DATABASE']->query("UPDATE ".PLANETS." SET ".implode(',', $collectQuery)." WHERE id = ".$this->_fleet['fleet_end_id'].";"); + } + + $LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']); - $this->UpdateFleet('fleet_resource_metal', $this->_fleet['fleet_resource_metal'] + $RecycledGoods['metal']); - $this->UpdateFleet('fleet_resource_crystal', $this->_fleet['fleet_resource_crystal'] + $RecycledGoods['crystal']); - $this->UpdateFleet('fleet_mess', 1); + $Message = sprintf($LNG['sys_recy_gotten'], + pretty_number($collectedGoods[901]), $LNG['tech'][901], + pretty_number($collectedGoods[902]), $LNG['tech'][902] + ); + + SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_start_time'], 5, $LNG['sys_mess_tower'], $LNG['sys_recy_report'], $Message); + $this->setState(FLEET_RETURN); $this->SaveFleet(); } @@ -96,13 +123,12 @@ function EndStayEvent() function ReturnEvent() { - global $LANG; - $LNG = $LANG->GetUserLang($this->_fleet['fleet_owner']); + $LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']); + $TargetName = $GLOBALS['DATABASE']->getFirstCell("SELECT name FROM ".PLANETS." WHERE id = ".$this->_fleet['fleet_start_id'].";"); - $Message = sprintf( $LNG['sys_tran_mess_owner'], $TargetName, GetStartAdressLink($this->_fleet, ''), pretty_number($this->_fleet['fleet_resource_metal']), $LNG['Metal'], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['Crystal'], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['Deuterium'] ); + $Message = sprintf($LNG['sys_tran_mess_owner'], $TargetName, GetStartAdressLink($this->_fleet, ''), pretty_number($this->_fleet['fleet_resource_metal']), $LNG['tech'][901], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['tech'][902], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['tech'][903] ); SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_end_time'], 5, $LNG['sys_mess_tower'], $LNG['sys_mess_fleetback'], $Message); $this->RestoreFleet(); } -} -?> \ No newline at end of file +} \ No newline at end of file diff --git a/includes/classes/missions/MissionCaseSpy.php b/includes/classes/missions/MissionCaseSpy.php index 50fdb78..c12a947 100644 --- a/includes/classes/missions/MissionCaseSpy.php +++ b/includes/classes/missions/MissionCaseSpy.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,13 +18,12 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class MissionCaseSpy extends MissionFunctions @@ -37,127 +36,151 @@ function __construct($Fleet) function TargetEvent() { - global $db, $pricelist, $LANG; - $CurrentUser = $db->uniquequery("SELECT `lang`, `spy_tech`, `rpg_espion` FROM ".USERS." WHERE `id` = '".$this->_fleet['fleet_owner']."';"); - $LNG = $LANG->GetUserLang($CurrentUser['lang'], array('L18N', 'FLEET', 'TECH')); - $CurrentUserID = $this->_fleet['fleet_owner']; - $TargetPlanet = $db->uniquequery("SELECT * FROM ".PLANETS." WHERE `id` = ".$this->_fleet['fleet_end_id'].";"); - $TargetUserID = $TargetPlanet['id_owner']; - $CurrentPlanet = $db->uniquequery("SELECT name,system,galaxy,planet FROM ".PLANETS." WHERE `galaxy` = '".$this->_fleet['fleet_start_galaxy']."' AND `system` = '".$this->_fleet['fleet_start_system']."' AND `planet` = '".$this->_fleet['fleet_start_planet']."';"); - $CurrentSpyLvl = max(($CurrentUser['spy_tech'] + ($CurrentUser['rpg_espion'] * $pricelist[610]['info'])), 1); - $TargetUser = $db->uniquequery("SELECT * FROM ".USERS." WHERE `id` = '".$TargetUserID."';"); - $TargetSpyLvl = max(($TargetUser['spy_tech'] + ($TargetUser['rpg_espion'] * $pricelist[610]['info'])), 1); - $fleet = explode(";", $this->_fleet['fleet_array']); - - require_once(ROOT_PATH.'includes/classes/class.PlanetRessUpdate.php'); - $PlanetRess = new ResourceUpdate(); + global $pricelist, $reslist, $resource; + $senderUser = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".USERS." WHERE id = ".$this->_fleet['fleet_owner'].";"); + $senderPlanet = $GLOBALS['DATABASE']->getFirstRow("SELECT galaxy, system, planet, name FROM ".PLANETS." WHERE id = ".$this->_fleet['fleet_start_id'].";"); + $senderUser['factor'] = getFactors($senderUser, 'basic', $this->_fleet['fleet_start_time']); + $ownSpyLvl = max($senderUser['spy_tech'], 1); + + $LNG = $this->getLanguage($senderUser['lang']); + + $targetUser = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".USERS." WHERE id = ".$this->_fleet['fleet_target_owner'].";"); + $targetPlanet = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".PLANETS." WHERE id = ".$this->_fleet['fleet_end_id'].";"); - $TargetUser['factor'] = getFactors($TargetUser, 'basic', $this->_fleet['fleet_start_time']); + $targetSpyLvl = max($targetUser['spy_tech'], 1); + + $targetUser['factor'] = getFactors($targetUser, 'basic', $this->_fleet['fleet_start_time']); $PlanetRess = new ResourceUpdate(); - list($TargetUser, $TargetPlanet) = $PlanetRess->CalcResource($TargetUser, $TargetPlanet, true, $this->_fleet['fleet_start_time']); + list($targetUser, $targetPlanet) = $PlanetRess->CalcResource($targetUser, $targetPlanet, true, $this->_fleet['fleet_start_time']); + + $targetStayFleets = $GLOBALS['DATABASE']->query("SELECT * FROM ".FLEETS." WHERE fleet_end_id = ".$this->_fleet['fleet_end_id']." AND fleet_mission = 5 AND fleet_end_stay > ".$this->_fleet['fleet_start_time'].";"); - foreach ($fleet as $a => $b) + while($fleetRow = $GLOBALS['DATABASE']->fetch_array($targetStayFleets)) { - if (empty($b)) - continue; - - $a = explode(",", $b); - if ($a[0] != 210) - continue; - - $LS = $a[1]; - break; + $temp = explode(';', $fleetRow['fleet_array']); + foreach ($temp as $temp2) + { + $temp2 = explode(',', $temp2); + if (!isset($targetPlanet[$resource[$temp2[0]]])) + { + $targetPlanet[$resource[$temp2[0]]] = 0; + } + + $targetPlanet[$resource[$temp2[0]]] += $temp2[1]; + } } - - - $Diffence = abs($CurrentSpyLvl - $TargetSpyLvl); - $MinAmount = ($CurrentSpyLvl > $TargetSpyLvl) ? -1 * pow($Diffence, 2) : pow($Diffence, 2); - $SpyFleet = ($LS >= $MinAmount) ? true : false; - $SpyDef = ($LS >= $MinAmount + 1) ? true : false; - $SpyBuild = ($LS >= $MinAmount + 3) ? true : false; - $SpyTechno = ($LS >= $MinAmount + 5) ? true : false; - $MaterialsInfo = $this->SpyTarget($TargetPlanet, 0, $LNG['sys_mess_head'], $LNG); - $GetSB = $MaterialsInfo['String']; - $Array = $MaterialsInfo['Array']; - $Count = array(); + $GLOBALS['DATABASE']->free_result($targetStayFleets); + + $fleetAmount = $this->_fleet['fleet_amount'] * (1 + $senderUser['factor']['SpyPower']); + + $Diffence = abs($ownSpyLvl - $targetSpyLvl); + $MinAmount = ($ownSpyLvl > $targetSpyLvl ? -1 : 1) * pow($Diffence * SPY_DIFFENCE_FACTOR, 2); + $SpyFleet = $fleetAmount >= $MinAmount; + $SpyDef = $fleetAmount >= $MinAmount + 1 * SPY_VIEW_FACTOR; + $SpyBuild = $fleetAmount >= $MinAmount + 3 * SPY_VIEW_FACTOR; + $SpyTechno = $fleetAmount >= $MinAmount + 5 * SPY_VIEW_FACTOR; - if($SpyFleet){ - $PlanetFleetInfo = $this->SpyTarget($TargetPlanet, 1, $LNG['sys_spy_fleet'], $LNG); - $GetSB .= $PlanetFleetInfo['String']; - $Count['Fleet'] = $PlanetFleetInfo['Count']; - $Array = $Array + $PlanetFleetInfo['Array']; - } - if($SpyDef){ - $PlanetDefenInfo = $this->SpyTarget($TargetPlanet, 2, $LNG['sys_spy_defenses'], $LNG); - $GetSB .= $PlanetDefenInfo['String']; - $Count['Def'] = $PlanetDefenInfo['Count']; - $Array = $Array + $PlanetDefenInfo['Array']; + + $classIDs[900] = array_merge($reslist['resstype'][1], $reslist['resstype'][2]); + + if($SpyFleet) + { + $classIDs[200] = $reslist['fleet']; } - if($SpyBuild){ - $PlanetBuildInfo = $this->SpyTarget($TargetPlanet, 3, $LNG['tech'][0], $LNG); - $GetSB .= $PlanetBuildInfo['String']; + + if($SpyDef) + { + $classIDs[400] = $reslist['defense']; } - if($SpyTechno){ - $TargetTechnInfo = $this->SpyTarget($TargetUser, 4, $LNG['tech'][100], $LNG); - $GetSB .= $TargetTechnInfo['String']; - $Array = $Array + $TargetTechnInfo['Array']; + + if($SpyBuild) + { + $classIDs[0] = $reslist['build']; } - foreach($Array as $ID => $Amount) + if($SpyTechno) { - $string .= "&im[".$ID."]=".$Amount; + $classIDs[100] = $reslist['tech']; } - - if(array_sum($Count) == 0){ - $TargetChances = 0; - $SpyerChances = 1; - } else { - $TargetChances = mt_rand(0, min(($LS/4) * ($TargetSpyLvl / $CurrentSpyLvl), 100)); - $SpyerChances = mt_rand(0, 100); + + $targetChance = mt_rand(0, min(($fleetAmount/4) * ($targetSpyLvl / $ownSpyLvl), 100)); + $spyChance = mt_rand(0, 100); + + foreach($classIDs as $classID => $elementIDs) + { + foreach($elementIDs as $elementID) + { + if($classID == 100) + { + $spyData[$classID][$elementID] = $targetUser[$resource[$elementID]]; + } + else + { + $spyData[$classID][$elementID] = $targetPlanet[$resource[$elementID]]; + } + } + + if($senderUser['spyMessagesMode'] == 1) + { + $spyData[$classID] = array_filter($spyData[$classID]); + } } - $DestProba = $TargetChances >= $SpyerChances ? $LNG['sys_mess_spy_destroyed'] : sprintf( $LNG['sys_mess_spy_lostproba'], $TargetChances); + // I'm use template class here, because i want to exclude HTML in PHP. + + require_once(ROOT_PATH.'includes/classes/class.template.php'); + + $template = new template; + + $template->caching = true; + $template->compile_id = $senderUser['lang']; + $template->loadFilter('output', 'trimwhitespace'); + list($tplDir) = $template->getTemplateDir(); + $template->setTemplateDir($tplDir.'game/'); + $template->assign_vars(array( + 'spyData' => $spyData, + 'targetPlanet' => $targetPlanet, + 'targetChance' => $targetChance, + 'spyChance' => $spyChance, + 'isBattleSim' => ENABLE_SIMULATOR_LINK == true && isModulAvalible(MODULE_SIMULATOR), + 'title' => sprintf($LNG['sys_mess_head'], $targetPlanet['name'], $targetPlanet['galaxy'], $targetPlanet['system'], $targetPlanet['planet'], _date($LNG['php_tdformat'], $this->_fleet['fleet_end_time'], $targetUser['timezone'], $LNG)), + )); + + $template->assign_vars(array( + 'LNG' => $LNG + ), false); + + $spyRaport = $template->fetch('shared.mission.spyraport.tpl'); - $AttackLink = "
"; - $AttackLink .= "_fleet['fleet_end_galaxy'] ."&system=". $this->_fleet['fleet_end_system'] .""; - $AttackLink .= "&planet=".$this->_fleet['fleet_end_planet']."&planettype=".$this->_fleet['fleet_end_type'].""; - $AttackLink .= "&target_mission=1"; - $AttackLink .= " \">". $LNG['type_mission'][1]; - $AttackLink .= "
"; - $MessageEnd = "
".$DestProba."
".((ENABLE_SIMULATOR_LINK == true && !CheckModule(39)) ? "".$LNG['fl_simulate']."":"")."
"; - - $SpyMessage = "
".$GetSB."
".$AttackLink.$MessageEnd; - SendSimpleMessage($CurrentUserID, 0, $this->_fleet['fleet_start_time'], 0, $LNG['sys_mess_qg'], $LNG['sys_mess_spy_report'], $SpyMessage); + SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_start_time'], 0, $LNG['sys_mess_qg'], $LNG['sys_mess_spy_report'], $spyRaport); - $LNG = $LANG->GetUserLang($TargetUser['lang']); - $TargetMessage = $LNG['sys_mess_spy_ennemyfleet'] ." ". $CurrentPlanet['name']; + $LNG = $this->getLanguage($targetUser['lang']); + $targetMessage = $LNG['sys_mess_spy_ennemyfleet'] ." ". $senderPlanet['name']; if($this->_fleet['fleet_start_type'] == 3) - $TargetMessage .= $LNG['sys_mess_spy_report_moon'].' '; + $targetMessage .= $LNG['sys_mess_spy_report_moon'].' '; - $TargetMessage .= ""; - $TargetMessage .= "[". $CurrentPlanet["galaxy"] .":". $CurrentPlanet["system"] .":". $CurrentPlanet["planet"] ."] "; - $TargetMessage .= $LNG['sys_mess_spy_seen_at'] ." ". $TargetPlanet['name']; - $TargetMessage .= " [". $TargetPlanet["galaxy"] .":". $TargetPlanet["system"] .":". $TargetPlanet["planet"] ."] ". $LNG['sys_mess_spy_seen_at2'] ."."; + $targetMessage .= ''. + '['.$senderPlanet['galaxy'].':'.$senderPlanet['system'].':'.$senderPlanet['planet'].'] '. + $LNG['sys_mess_spy_seen_at'].' '.$targetPlanet['name']. + ' ['. $targetPlanet['galaxy'].':'.$targetPlanet['system'].':'.$targetPlanet['planet'].'] '.$LNG['sys_mess_spy_seen_at2'].'.'; - SendSimpleMessage($TargetUserID, 0, $this->_fleet['fleet_start_time'], 0, $LNG['sys_mess_spy_control'], $LNG['sys_mess_spy_activity'], $TargetMessage); + SendSimpleMessage($this->_fleet['fleet_target_owner'], 0, $this->_fleet['fleet_start_time'], 0, $LNG['sys_mess_spy_control'], $LNG['sys_mess_spy_activity'], $targetMessage); - if ($TargetChances >= $SpyerChances) + if ($targetChance >= $spyChance) { - $Qry = "UPDATE ".PLANETS." SET "; - $Qry .= "`der_crystal` = `der_crystal` + '".($LS * 300)."' "; - $Qry .= "WHERE `galaxy` = '". $TargetPlanet['galaxy'] ."' AND "; - $Qry .= "`system` = '". $TargetPlanet['system'] ."' AND "; - $Qry .= "`planet` = '". $TargetPlanet['planet'] ."' AND "; - $Qry .= "`planet_type` = '1';"; - - $db->query($Qry); + $CONF = Config::getAll(NULL, $this->_fleet['fleet_universe']); + $WhereCol = $this->_fleet['fleet_end_type'] == 3 ? "id_luna" : "id"; + $GLOBALS['DATABASE']->query("UPDATE ".PLANETS." SET + der_metal = der_metal + ".($fleetAmount * $pricelist[210]['cost'][901] * (Config::get('Fleet_Cdr') / 100)).", + der_crystal = der_crystal + ".($fleetAmount * $pricelist[210]['cost'][902] * (Config::get('Fleet_Cdr') / 100))." + WHERE ".$WhereCol." = ".$this->_fleet['fleet_end_id'].";"); $this->KillFleet(); } else { - $this->UpdateFleet('fleet_mess', 1); + $this->setState(FLEET_RETURN); $this->SaveFleet(); } } @@ -171,131 +194,4 @@ function ReturnEvent() { $this->RestoreFleet(); } - - private function SpyTarget($TargetPlanet, $Mode, $TitleString, $LNG) - { - global $resource, $db; - - $LookAtLoop = true; - if ($Mode == 0) - { - $String = ' - - - - - - - - '; - - $Array[1] = $TargetPlanet['metal']; - $Array[2] = $TargetPlanet['crystal']; - $Array[3] = $TargetPlanet['deuterium']; - - $LookAtLoop = false; - } - elseif ($Mode == 1) - { - $ResFrom[0] = 200; - $ResTo[0] = 299; - $Loops = 1; - } - elseif ($Mode == 2) - { - $ResFrom[0] = 400; - $ResTo[0] = 499; - $ResFrom[1] = 500; - $ResTo[1] = 599; - $Loops = 2; - } - elseif ($Mode == 3) - { - $ResFrom[0] = 1; - $ResTo[0] = 99; - $Loops = 1; - } - elseif ($Mode == 4) - { - $ResFrom[0] = 100; - $ResTo[0] = 199; - $Loops = 1; - } - - if ($Mode == 1) - { - $def = $db->query('SELECT * FROM '.FLEETS.' WHERE `fleet_mission` = 5 AND `fleet_end_id` = '. $this->_fleet['fleet_end_id'].' AND fleet_start_time<'.TIMESTAMP.' AND fleet_end_stay>='.TIMESTAMP.';'); - while ($defRow = $db->fetch_array($def)) - { - $defRowDef = explode(';', $defRow['fleet_array']); - foreach ($defRowDef as $Element) - { - $Element = explode(',', $Element); - - if ($Element[0] < 100) continue; - - if (!isset($TargetPlanet[$resource[$Element[0]]])) - $TargetPlanet[$resource[$Element[0]]] = 0; - - $TargetPlanet[$resource[$Element[0]]] += $Element[1]; - } - } - } - - if ($LookAtLoop == true) - { - $String = '
- - '.sprintf($TitleString, $TargetPlanet['name'], $TargetPlanet['galaxy'], $TargetPlanet['system'], $TargetPlanet['planet'], tz_date($this->_fleet['fleet_end_time'], $LNG['php_tdformat'], $LNG)) .'
'. $LNG['Metal'] .''. pretty_number($TargetPlanet['metal']) .' '. $LNG['Crystal'] .''. pretty_number($TargetPlanet['crystal']) .'
'. $LNG['Deuterium'] .''. pretty_number($TargetPlanet['deuterium']) .' '. $LNG['Energy'] .''. pretty_number($TargetPlanet['energy_max']) .'
'; - $Count = 0; - $CurrentLook = 0; - while ($CurrentLook < $Loops) - { - $row = 0; - for ($Item = $ResFrom[$CurrentLook]; $Item <= $ResTo[$CurrentLook]; $Item++) - { - if ($TargetPlanet[$resource[$Item]] <= 0) - continue; - - if ($row == 0) - $String .= ""; - - $String .= ''; - - $Array[$Item] = $TargetPlanet[$resource[$Item]]; - $Count += $TargetPlanet[$resource[$Item]]; - $row++; - if ($row == SPY_REPORT_ROW) - { - $String .= ''; - $row = 0; - } else { - $String .= ''; - } - } - - while ($row != 0) - { - $String .= ''; - $row++; - if ($row == SPY_REPORT_ROW) - { - $String .= ''; - $row = 0; - } - } - $CurrentLook++; - } - } - - $String .= '
'. $TitleString .'
'.$LNG['tech'][$Item].''.pretty_number($TargetPlanet[$resource[$Item]]).'
   
'; - - $return['String'] = $String; - $return['Array'] = (is_array($Array) ? $Array : array()); - $return['Count'] = $Count; - - return $return; - } } - -?> \ No newline at end of file diff --git a/includes/classes/missions/MissionCaseStay.php b/includes/classes/missions/MissionCaseStay.php index c7256e1..835336b 100644 --- a/includes/classes/missions/MissionCaseStay.php +++ b/includes/classes/missions/MissionCaseStay.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,13 +18,12 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class MissionCaseStay extends MissionFunctions @@ -36,11 +35,28 @@ function __construct($Fleet) function TargetEvent() { - global $LANG; - $LNG = $LANG->GetUserLang($this->_fleet['fleet_owner']); + $senderUser = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".USERS." WHERE id = ".$this->_fleet['fleet_owner'].";"); + $senderUser['factor'] = getFactors($senderUser, 'basic', $this->_fleet['fleet_start_time']); + $fleetArray = fleetAmountToArray($this->_fleet['fleet_array']); + $duration = $this->_fleet['fleet_start_time'] - $this->_fleet['start_time']; + + require_once(ROOT_PATH . 'includes/classes/class.FleetFunctions.php'); + + $fleetMaxSpeed = FleetFunctions::GetFleetMaxSpeed($fleetArray, $senderUser); + $SpeedFactor = FleetFunctions::GetGameSpeedFactor(); + $distance = FleetFunctions::GetTargetDistance( + array($this->_fleet['fleet_start_galaxy'], $this->_fleet['fleet_start_system'], $this->_fleet['fleet_start_planet']), + array($this->_fleet['fleet_end_galaxy'], $this->_fleet['fleet_end_system'], $this->_fleet['fleet_end_planet']) + ); + + $consumption = FleetFunctions::GetFleetConsumption($fleetArray, $duration, $distance, $fleetMaxSpeed, $senderUser, $SpeedFactor); + + $this->UpdateFleet('fleet_resource_deuterium', $this->_fleet['fleet_resource_deuterium'] + $consumption / 2); + + $LNG = $this->getLanguage($senderUser['lang']); $TargetUserID = $this->_fleet['fleet_target_owner']; - $TargetMessage = sprintf($LNG['sys_stat_mess'], GetTargetAdressLink($this->_fleet, ''), pretty_number($this->_fleet['fleet_resource_metal']), $LNG['Metal'], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['Crystal'], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['Deuterium']); + $TargetMessage = sprintf($LNG['sys_stat_mess'], GetTargetAdressLink($this->_fleet, ''), pretty_number($this->_fleet['fleet_resource_metal']), $LNG['tech'][901], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['tech'][902], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['tech'][903]); SendSimpleMessage($TargetUserID, 0, $this->_fleet['fleet_start_time'], 5, $LNG['sys_mess_tower'], $LNG['sys_stat_mess_stay'], $TargetMessage); $this->RestoreFleet(false); @@ -53,14 +69,11 @@ function EndStayEvent() function ReturnEvent() { - global $LANG; - $LNG = $LANG->GetUserLang($this->_fleet['fleet_owner']); - + $LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']); $TargetUserID = $this->_fleet['fleet_target_owner']; - $TargetMessage = sprintf($LNG['sys_stat_mess'], GetStartAdressLink($this->_fleet, ''), pretty_number($this->_fleet['fleet_resource_metal']), $LNG['Metal'], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['Crystal'], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['Deuterium']); + $TargetMessage = sprintf($LNG['sys_stat_mess'], GetStartAdressLink($this->_fleet, ''), pretty_number($this->_fleet['fleet_resource_metal']), $LNG['tech'][901], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['tech'][902], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['tech'][903]); SendSimpleMessage($TargetUserID, 0, $this->_fleet['fleet_end_time'], 5, $LNG['sys_mess_tower'], $LNG['sys_stat_mess_stay'], $TargetMessage); $this->RestoreFleet(); } -} -?> \ No newline at end of file +} \ No newline at end of file diff --git a/includes/classes/missions/MissionCaseStayAlly.php b/includes/classes/missions/MissionCaseStayAlly.php index 6af89dc..15ea7ed 100644 --- a/includes/classes/missions/MissionCaseStayAlly.php +++ b/includes/classes/missions/MissionCaseStayAlly.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,13 +18,12 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class MissionCaseStayAlly extends MissionFunctions @@ -36,42 +35,42 @@ function __construct($Fleet) function TargetEvent() { - global $db, $LANG; - $StartPlanet = $db->uniquequery("SELECT name FROM ".PLANETS." WHERE `id` = '". $this->_fleet['fleet_start_id'] ."';"); - $StartName = $StartPlanet['name']; - $StartOwner = $this->_fleet['fleet_owner']; + $StartPlanet = $GLOBALS['DATABASE']->getFirstRow("SELECT name FROM ".PLANETS." WHERE `id` = '". $this->_fleet['fleet_start_id'] ."';"); + $StartName = $StartPlanet['name']; + $StartOwner = $this->_fleet['fleet_owner']; - $TargetPlanet = $db->uniquequery("SELECT name FROM ".PLANETS." WHERE `id` = '". $this->_fleet['fleet_end_id'] ."';"); - $TargetName = $TargetPlanet['name']; - $TargetOwner = $this->_fleet['fleet_target_owner']; + $TargetPlanet = $GLOBALS['DATABASE']->getFirstRow("SELECT name FROM ".PLANETS." WHERE `id` = '". $this->_fleet['fleet_end_id'] ."';"); + $TargetName = $TargetPlanet['name']; + $TargetOwner = $this->_fleet['fleet_target_owner']; - $LNG = $LANG->GetUserLang($this->_fleet['fleet_owner']); + $LNG = $this->getLanguage(NULL, $StartOwner); - $Message = sprintf($LNG['sys_tran_mess_owner'], $TargetName, GetTargetAdressLink($this->_fleet, ''), $this->_fleet['fleet_resource_metal'], $LNG['Metal'], $this->_fleet['fleet_resource_crystal'], $LNG['Crystal'], $this->_fleet['fleet_resource_deuterium'], $LNG['Deuterium'] ); + $Message = sprintf($LNG['sys_tran_mess_owner'], $TargetName, GetTargetAdressLink($this->_fleet, ''), $this->_fleet['fleet_resource_metal'], $LNG['tech'][901], $this->_fleet['fleet_resource_crystal'], $LNG['tech'][902], $this->_fleet['fleet_resource_deuterium'], $LNG['tech'][903] ); SendSimpleMessage ($StartOwner, 0, $this->_fleet['fleet_start_time'], 5, $LNG['sys_mess_tower'], $LNG['sys_mess_transport'], $Message); + + $LNG = $this->getLanguage(NULL, $TargetOwner); - $Message = sprintf($LNG['sys_tran_mess_user'], $StartName, GetStartAdressLink($this->_fleet, ''), $TargetName, GetTargetAdressLink($this->_fleet, ''), $this->_fleet['fleet_resource_metal'], $LNG['Metal'], $this->_fleet['fleet_resource_crystal'], $LNG['Crystal'], $this->_fleet['fleet_resource_deuterium'], $LNG['Deuterium']); + $Message = sprintf($LNG['sys_tran_mess_user'], $StartName, GetStartAdressLink($this->_fleet, ''), $TargetName, GetTargetAdressLink($this->_fleet, ''), $this->_fleet['fleet_resource_metal'], $LNG['tech'][901], $this->_fleet['fleet_resource_crystal'], $LNG['tech'][902], $this->_fleet['fleet_resource_deuterium'], $LNG['tech'][903]); SendSimpleMessage ($TargetOwner, 0, $this->_fleet['fleet_start_time'], 5, $LNG['sys_mess_tower'], $LNG['sys_mess_transport'], $Message); - $this->UpdateFleet('fleet_mess', 2); + $this->setState(FLEET_HOLD); $this->SaveFleet(); } function EndStayEvent() { - $this->UpdateFleet('fleet_mess', 1); + $this->setState(FLEET_RETURN); $this->SaveFleet(); } function ReturnEvent() { - global $LANG; - $LNG = $LANG->GetUserLang($this->_fleet['fleet_owner']); + $LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']); + $StartName = $GLOBALS['DATABASE']->getFirstCell("SELECT name FROM ".PLANETS." WHERE id = ".$this->_fleet['fleet_end_id'].";"); - $Message = sprintf ($LNG['sys_tran_mess_back'], $StartName, GetStartAdressLink($this->_fleet, '')); + $Message = sprintf ($LNG['sys_tran_mess_back'], $StartName, GetStartAdressLink($this->_fleet, '')); SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_end_time'], 5, $LNG['sys_mess_tower'], $LNG['sys_mess_fleetback'], $Message); $this->RestoreFleet(); } -} -?> \ No newline at end of file +} \ No newline at end of file diff --git a/includes/classes/missions/MissionCaseTransport.php b/includes/classes/missions/MissionCaseTransport.php index 5fc0ccb..e2d0af3 100644 --- a/includes/classes/missions/MissionCaseTransport.php +++ b/includes/classes/missions/MissionCaseTransport.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,13 +18,12 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ class MissionCaseTransport extends MissionFunctions { @@ -35,27 +34,26 @@ function __construct($Fleet) function TargetEvent() { - global $db, $LANG; - $StartPlanet = $db->uniquequery("SELECT name FROM ".PLANETS." WHERE `id` = '". $this->_fleet['fleet_start_id'] ."';"); - $StartName = $StartPlanet['name']; - $StartOwner = $this->_fleet['fleet_owner']; + $StartPlanet = $GLOBALS['DATABASE']->getFirstRow("SELECT name FROM ".PLANETS." WHERE `id` = '". $this->_fleet['fleet_start_id'] ."';"); + $StartName = $StartPlanet['name']; + $StartOwner = $this->_fleet['fleet_owner']; - $TargetPlanet = $db->uniquequery("SELECT name FROM ".PLANETS." WHERE `id` = '". $this->_fleet['fleet_end_id'] ."';"); - $TargetName = $TargetPlanet['name']; - $TargetOwner = $this->_fleet['fleet_target_owner']; + $TargetPlanet = $GLOBALS['DATABASE']->getFirstRow("SELECT name FROM ".PLANETS." WHERE `id` = '". $this->_fleet['fleet_end_id'] ."';"); + $TargetName = $TargetPlanet['name']; + $TargetOwner = $this->_fleet['fleet_target_owner']; - $LNG = $LANG->GetUserLang($StartOwner); - $Message = sprintf($LNG['sys_tran_mess_owner'], $TargetName, GetTargetAdressLink($this->_fleet, ''), pretty_number($this->_fleet['fleet_resource_metal']), $LNG['Metal'], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['Crystal'], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['Deuterium']); + $LNG = $this->getLanguage(NULL, $StartOwner); + $Message = sprintf($LNG['sys_tran_mess_owner'], $TargetName, GetTargetAdressLink($this->_fleet, ''), pretty_number($this->_fleet['fleet_resource_metal']), $LNG['tech'][901], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['tech'][902], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['tech'][903]); SendSimpleMessage($StartOwner, 0, $this->_fleet['fleet_start_time'], 5, $LNG['sys_mess_tower'], $LNG['sys_mess_transport'], $Message); if ($TargetOwner != $StartOwner) { - $LNG = $LANG->GetUserLang($TargetOwner); - $Message = sprintf($LNG['sys_tran_mess_user'], $StartName, GetStartAdressLink($this->_fleet, ''), $TargetName, GetTargetAdressLink($this->_fleet, ''), pretty_number($this->_fleet['fleet_resource_metal']), $LNG['Metal'], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['Crystal'], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['Deuterium'] ); + $LNG = $this->getLanguage(NULL, $TargetOwner); + $Message = sprintf($LNG['sys_tran_mess_user'], $StartName, GetStartAdressLink($this->_fleet, ''), $TargetName, GetTargetAdressLink($this->_fleet, ''), pretty_number($this->_fleet['fleet_resource_metal']), $LNG['tech'][901], pretty_number($this->_fleet['fleet_resource_crystal']), $LNG['tech'][902], pretty_number($this->_fleet['fleet_resource_deuterium']), $LNG['tech'][903] ); SendSimpleMessage($TargetOwner, 0, $this->_fleet['fleet_start_time'], 5, $LNG['sys_mess_tower'], $LNG['sys_mess_transport'], $Message); } $this->StoreGoodsToPlanet(); - $this->UpdateFleet('fleet_mess', 1); + $this->setState(FLEET_RETURN); $this->SaveFleet(); } @@ -66,12 +64,10 @@ function EndStayEvent() function ReturnEvent() { - global $LANG; - $LNG = $LANG->GetUserLang($this->_fleet['fleet_owner']); - - $Message = sprintf ($LNG['sys_tran_mess_back'], $StartName, GetStartAdressLink($this->_fleet, '')); + $LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']); + $StartName = $GLOBALS['DATABASE']->getFirstCell("SELECT name FROM ".PLANETS." WHERE id = ".$this->_fleet['fleet_start_id'].";"); + $Message = sprintf($LNG['sys_tran_mess_back'], $StartName, GetStartAdressLink($this->_fleet, '')); SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_end_time'], 5, $LNG['sys_mess_tower'], $LNG['sys_mess_fleetback'], $Message); $this->RestoreFleet(); } -} -?> \ No newline at end of file +} \ No newline at end of file diff --git a/includes/classes/missions/calculateAttack.php b/includes/classes/missions/calculateAttack.php index 1244f9c..f38678e 100644 --- a/includes/classes/missions/calculateAttack.php +++ b/includes/classes/missions/calculateAttack.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,13 +18,12 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ @@ -39,14 +38,16 @@ function calculateAttack(&$attackers, &$defenders, $FleetTF, $DefTF) foreach ($attackers as $fleetID => $attacker) { - foreach ($attacker['detail'] as $element => $amount) + foreach ($attacker['unit'] as $element => $amount) { - $ARES['metal'] += $pricelist[$element]['metal'] * $amount; - $ARES['crystal'] += $pricelist[$element]['crystal'] * $amount; + $ARES['metal'] += $pricelist[$element]['cost'][901] * $amount; + $ARES['crystal'] += $pricelist[$element]['cost'][902] * $amount; } } foreach($CombatCaps as $e => $arr) { + if(!isset($arr['sd'])) continue; + foreach($arr['sd'] as $t => $sd) { if($sd == 0) continue; $RF[$t][$e] = $sd; @@ -57,22 +58,22 @@ function calculateAttack(&$attackers, &$defenders, $FleetTF, $DefTF) foreach ($defenders as $fleetID => $defender) { - foreach ($defender['def'] as $element => $amount) + foreach ($defender['unit'] as $element => $amount) { if ($element < 300) { - $DRES['metal'] += $pricelist[$element]['metal'] * $amount; - $DRES['crystal'] += $pricelist[$element]['crystal'] * $amount ; + $DRES['metal'] += $pricelist[$element]['cost'][901] * $amount; + $DRES['crystal'] += $pricelist[$element]['cost'][902] * $amount ; - $TRES['defender'] += $pricelist[$element]['metal'] * $amount; - $TRES['defender'] += $pricelist[$element]['crystal'] * $amount; + $TRES['defender'] += $pricelist[$element]['cost'][901] * $amount; + $TRES['defender'] += $pricelist[$element]['cost'][902] * $amount; } else { if (!isset($STARTDEF[$element])) $STARTDEF[$element] = 0; $STARTDEF[$element] += $amount; - $TRES['defender'] += $pricelist[$element]['metal'] * $amount; - $TRES['defender'] += $pricelist[$element]['crystal'] * $amount; + $TRES['defender'] += $pricelist[$element]['cost'][901] * $amount; + $TRES['defender'] += $pricelist[$element]['cost'][902] * $amount; } } } @@ -93,15 +94,15 @@ function calculateAttack(&$attackers, &$defenders, $FleetTF, $DefTF) $attackShield[$fleetID] = 0; $attackAmount[$fleetID] = 0; - $attTech = (1 + (0.1 * $attacker['user']['military_tech']) + $attacker['user']['factor']['attack']); //attaque - $defTech = (1 + (0.1 * $attacker['user']['defence_tech']) + $attacker['user']['factor']['defensive']); //bouclier - $shieldTech = (1 + (0.1 * $attacker['user']['shield_tech']) + $attacker['user']['factor']['shield']); //coque + $attTech = (1 + (0.1 * $attacker['player']['military_tech']) + $attacker['player']['factor']['Attack']); //attaque + $defTech = (1 + (0.1 * $attacker['player']['defence_tech']) + $attacker['player']['factor']['Defensive']); //bouclier + $shieldTech = (1 + (0.1 * $attacker['player']['shield_tech']) + $attacker['player']['factor']['Shield']); //coque $attackers[$fleetID]['techs'] = array($attTech, $defTech, $shieldTech); - foreach ($attacker['detail'] as $element => $amount) { + foreach ($attacker['unit'] as $element => $amount) { $thisAtt = $amount * ($CombatCaps[$element]['attack']) * $attTech * (rand(80, 120) / 100); //attaque $thisDef = $amount * ($CombatCaps[$element]['shield']) * $defTech ; //bouclier - $thisShield = $amount * ($pricelist[$element]['metal'] + $pricelist[$element]['crystal']) / 10 * $shieldTech; //coque + $thisShield = $amount * ($pricelist[$element]['cost'][901] + $pricelist[$element]['cost'][902]) / 10 * $shieldTech; //coque $attArray[$fleetID][$element] = array('def' => $thisDef, 'shield' => $thisShield, 'att' => $thisAtt); @@ -112,7 +113,6 @@ function calculateAttack(&$attackers, &$defenders, $FleetTF, $DefTF) $attackAmount[$fleetID] += $amount; $attackAmount['total'] += $amount; } - $temp1 = $attacker['detail']; } foreach ($defenders as $fleetID => $defender) { @@ -120,15 +120,15 @@ function calculateAttack(&$attackers, &$defenders, $FleetTF, $DefTF) $defenseShield[$fleetID] = 0; $defenseAmount[$fleetID] = 0; - $attTech = (1 + (0.1 * $defender['user']['military_tech']) + $defender['user']['factor']['attack']); //attaquue - $defTech = (1 + (0.1 * $defender['user']['defence_tech']) + $defender['user']['factor']['defensive']); //bouclier - $shieldTech = (1 + (0.1 * $defender['user']['shield_tech']) + $defender['user']['factor']['shield']); //coque + $attTech = (1 + (0.1 * $defender['player']['military_tech']) + $defender['player']['factor']['Attack']); //attaquue + $defTech = (1 + (0.1 * $defender['player']['defence_tech']) + $defender['player']['factor']['Defensive']); //bouclier + $shieldTech = (1 + (0.1 * $defender['player']['shield_tech']) + $defender['player']['factor']['Shield']); //coque $defenders[$fleetID]['techs'] = array($attTech, $defTech, $shieldTech); - foreach ($defender['def'] as $element => $amount) { + foreach ($defender['unit'] as $element => $amount) { $thisAtt = $amount * ($CombatCaps[$element]['attack']) * $attTech * (rand(80, 120) / 100); //attaque $thisDef = $amount * ($CombatCaps[$element]['shield']) * $defTech ; //bouclier - $thisShield = $amount * ($pricelist[$element]['metal'] + $pricelist[$element]['crystal']) / 10 * $shieldTech; //coque + $thisShield = $amount * ($pricelist[$element]['cost'][901] + $pricelist[$element]['cost'][902]) / 10 * $shieldTech; //coque if ($element == 407 || $element == 408 || $element == 409) $thisAtt = 0; @@ -141,7 +141,6 @@ function calculateAttack(&$attackers, &$defenders, $FleetTF, $DefTF) $defenseAmount[$fleetID] += $amount; $defenseAmount['total'] += $amount; } - $temp2 = $defender['def']; } $ROUND[$ROUNDC] = array('attackers' => $attackers, 'defenders' => $defenders, 'attackA' => $attackAmount, 'defenseA' => $defenseAmount, 'infoA' => $attArray, 'infoD' => $defArray); @@ -170,7 +169,7 @@ function calculateAttack(&$attackers, &$defenders, $FleetTF, $DefTF) foreach ($attackers as $fleetID => $attacker) { $attacker_n[$fleetID] = array(); - foreach($attacker['detail'] as $element => $amount) { + foreach($attacker['unit'] as $element => $amount) { if ($amount <= 0) { $attacker_n[$fleetID][$element] = 0; continue; @@ -181,10 +180,10 @@ function calculateAttack(&$attackers, &$defenders, $FleetTF, $DefTF) if(isset($RF[$element])) { foreach($RF[$element] as $shooter => $shots) { foreach($defArray as $fID => $rfdef) { - if($rfdef[$shooter]['att'] <= 0 || $attackAmount[$fleetID] <= 0) continue; + if(empty($rfdef[$shooter]['att']) || $attackAmount[$fleetID] <= 0) continue; $defender_moc += $rfdef[$shooter]['att'] * $shots / ($amount / $attackAmount[$fleetID] * $attackPct[$fleetID]); - $defenseAmount['total'] += $defenders[$fID]['def'][$shooter] * $shots; + $defenseAmount['total'] += $defenders[$fID]['unit'][$shooter] * $shots; } } } @@ -214,7 +213,7 @@ function calculateAttack(&$attackers, &$defenders, $FleetTF, $DefTF) foreach ($defenders as $fleetID => $defender) { $defender_n[$fleetID] = array(); - foreach($defender['def'] as $element => $amount) { + foreach($defender['unit'] as $element => $amount) { if ($amount <= 0) { $defender_n[$fleetID][$element] = 0; continue; @@ -224,10 +223,10 @@ function calculateAttack(&$attackers, &$defenders, $FleetTF, $DefTF) if (isset($RF[$element])) { foreach($RF[$element] as $shooter => $shots) { foreach($attArray as $fID => $rfatt) { - if ($rfatt[$shooter]['att'] <= 0 || $defenseAmount[$fleetID] <= 0 ) continue; + if (empty($rfatt[$shooter]['att']) || $defenseAmount[$fleetID] <= 0 ) continue; $attacker_moc += $rfatt[$shooter]['att'] * $shots / ($amount / $defenseAmount[$fleetID] * $defensePct[$fleetID]); - $attackAmount['total'] += $attackers[$fID]['detail'][$shooter] * $shots; + $attackAmount['total'] += $attackers[$fID]['unit'][$shooter] * $shots; } } } @@ -255,11 +254,11 @@ function calculateAttack(&$attackers, &$defenders, $FleetTF, $DefTF) $ROUND[$ROUNDC]['attackShield'] = $attacker_shield; $ROUND[$ROUNDC]['defShield'] = $defender_shield; foreach ($attackers as $fleetID => $attacker) { - $attackers[$fleetID]['detail'] = array_map('round', $attacker_n[$fleetID]); + $attackers[$fleetID]['unit'] = array_map('round', $attacker_n[$fleetID]); } foreach ($defenders as $fleetID => $defender) { - $defenders[$fleetID]['def'] = array_map('round', $defender_n[$fleetID]); + $defenders[$fleetID]['unit'] = array_map('round', $defender_n[$fleetID]); } } @@ -273,34 +272,34 @@ function calculateAttack(&$attackers, &$defenders, $FleetTF, $DefTF) // CDR foreach ($attackers as $fleetID => $attacker) { // flotte attaquant en CDR - foreach ($attacker['detail'] as $element => $amount) { - $TRES['attacker'] -= $pricelist[$element]['metal'] * $amount ; - $TRES['attacker'] -= $pricelist[$element]['crystal'] * $amount ; + foreach ($attacker['unit'] as $element => $amount) { + $TRES['attacker'] -= $pricelist[$element]['cost'][901] * $amount ; + $TRES['attacker'] -= $pricelist[$element]['cost'][902] * $amount ; - $ARES['metal'] -= $pricelist[$element]['metal'] * $amount ; - $ARES['crystal'] -= $pricelist[$element]['crystal'] * $amount ; + $ARES['metal'] -= $pricelist[$element]['cost'][901] * $amount ; + $ARES['crystal'] -= $pricelist[$element]['cost'][902] * $amount ; } } $DRESDefs = array('metal' => 0, 'crystal' => 0); foreach ($defenders as $fleetID => $defender) { - foreach ($defender['def'] as $element => $amount) { + foreach ($defender['unit'] as $element => $amount) { if ($element < 300) { // flotte defenseur en CDR - $DRES['metal'] -= $pricelist[$element]['metal'] * $amount ; - $DRES['crystal'] -= $pricelist[$element]['crystal'] * $amount ; + $DRES['metal'] -= $pricelist[$element]['cost'][901] * $amount ; + $DRES['crystal'] -= $pricelist[$element]['cost'][902] * $amount ; - $TRES['defender'] -= $pricelist[$element]['metal'] * $amount ; - $TRES['defender'] -= $pricelist[$element]['crystal'] * $amount ; + $TRES['defender'] -= $pricelist[$element]['cost'][901] * $amount ; + $TRES['defender'] -= $pricelist[$element]['cost'][902] * $amount ; } else { // defs defenseur en CDR + reconstruction - $TRES['defender'] -= $pricelist[$element]['metal'] * $amount ; - $TRES['defender'] -= $pricelist[$element]['crystal'] * $amount ; + $TRES['defender'] -= $pricelist[$element]['cost'][901] * $amount ; + $TRES['defender'] -= $pricelist[$element]['cost'][902] * $amount ; $lost = $STARTDEF[$element] - $amount; $giveback = round($lost * (rand(56, 84) / 100)); - $defenders[$fleetID]['def'][$element] += $giveback; - $DRESDefs['metal'] += $pricelist[$element]['metal'] * ($lost - $giveback) ; - $DRESDefs['crystal'] += $pricelist[$element]['crystal'] * ($lost - $giveback) ; + $defenders[$fleetID]['unit'][$element] += $giveback; + $DRESDefs['metal'] += $pricelist[$element]['cost'][901] * ($lost - $giveback) ; + $DRESDefs['crystal'] += $pricelist[$element]['cost'][902] * ($lost - $giveback) ; } } } @@ -312,12 +311,11 @@ function calculateAttack(&$attackers, &$defenders, $FleetTF, $DefTF) $TRES['attacker'] = max($TRES['attacker'], 0); $TRES['defender'] = max($TRES['defender'], 0); - $totalLost = array('att' => $TRES['attacker'], 'def' => $TRES['defender']); + $totalLost = array('attacker' => $TRES['attacker'], 'defender' => $TRES['defender']); $debAttMet = ($ARES['metal'] * ($FleetTF / 100)); $debAttCry = ($ARES['crystal'] * ($FleetTF / 100)); $debDefMet = ($DRES['metal'] * ($FleetTF / 100)) + ($DRESDefs['metal'] * ($DefTF / 100)); $debDefCry = ($DRES['crystal'] * ($FleetTF / 100)) + ($DRESDefs['crystal'] * ($DefTF / 100)); - return array('won' => $won, 'debree' => array('att' => array($debAttMet, $debAttCry), 'def' => array($debDefMet, $debDefCry)), 'rw' => $ROUND, 'lost' => $totalLost); -} -?> \ No newline at end of file + return array('won' => $won, 'debris' => array('attacker' => array(901 => $debAttMet, 902 => $debAttCry), 'defender' => array(901 => $debDefMet, 902 => $debDefCry)), 'rw' => $ROUND, 'unitLost' => $totalLost); +} \ No newline at end of file diff --git a/includes/classes/missions/calculateMIPAttack.php b/includes/classes/missions/calculateMIPAttack.php index 18e650f..430712d 100644 --- a/includes/classes/missions/calculateMIPAttack.php +++ b/includes/classes/missions/calculateMIPAttack.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,59 +18,49 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ -function calculateMIPAttack($TargetDefTech, $OwnerAttTech, $ipm, $TargetDefensive, $pri_target, $adm) +function calculateMIPAttack($TargetDefTech, $OwnerAttTech, $missiles, $targetDefensive, $firstTarget, $defenseMissles) { - global $pricelist, $reslist, $CombatCaps; - // Based on http://websim.speedsim.net/ JS-IRak Simulation - unset($TargetDefensive[503]); - $GetTargetKeys = array_keys($TargetDefensive); + global $pricelist, $CombatCaps; - $life_fac = $TargetDefTech / 10 + 1; - $life_fac_a = $CombatCaps[503]['attack'] * ($OwnerAttTech / 10 + 1); + $destroyShips = array(); + $countMissles = $missiles - $defenseMissles; - $ipm -= $adm; - $adm = 0; - $max_dam = $ipm * $life_fac_a; - $i = 0; + if($countMissles == 0) + { + return $destroyShips; + } - $ship_res = array(); - foreach($TargetDefensive as $Element => $Count) + $totalAttack = $countMissles * $CombatCaps[503]['attack'] * (1 + 0.1 * $OwnerAttTech); + + // Select primary target, if exists + if(isset($targetDefensive[$firstTarget])) { - if($i == 0) - $target = $pri_target; - elseif($Element <= $pri_target) - $target = $Element - 1; - else - $target = $Element; - + $firstTargetData = array($firstTarget => $targetDefensive[$firstTarget]); + unset($targetDefensive[$firstTarget]); + $targetDefensive = array_merge($firstTargetData, $targetDefensive); + } + + foreach($targetDefensive as $element => $count) + { + $elementStructurePoints = ($pricelist[$element]['cost'][901] + $pricelist[$element]['cost'][902]) * (1 + 0.1 * $TargetDefTech) / 10; + $destroyCount = floor($totalAttack / $elementStructurePoints); + $destroyCount = min($destroyCount, $count); + $totalAttack -= $destroyCount * $elementStructurePoints; - $Dam = $max_dam - ($pricelist[$target]['metal'] + $pricelist[$target]['crystal']) / 10 * $TargetDefensive[$target] * $life_fac; - - if($Dam > 0) + $destroyShips[$element] = $destroyCount; + if($totalAttack <= 0) { - $dest = $TargetDefensive[$target]; - $ship_res[$target] = $dest; + return $destroyShips; } - else - { - // not enough damage for all items - $dest = floor($max_dam / (($pricelist[$target]['metal'] + $pricelist[$target]['crystal']) / 10 * $life_fac)); - $ship_res[$target] = $dest; - } - $max_dam -= $dest * round(($pricelist[$target]['metal'] + $pricelist[$target]['crystal']) / 10 * $life_fac); - $i++; } - return $ship_res; -} - -?> \ No newline at end of file + return $destroyShips; +} \ No newline at end of file diff --git a/includes/classes/missions/calculateSteal.php b/includes/classes/missions/calculateSteal.php index b9f3614..143a159 100644 --- a/includes/classes/missions/calculateSteal.php +++ b/includes/classes/missions/calculateSteal.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,79 +18,94 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ -function calculateSteal($attackFleets, $defenderPlanet, $ForSim = false) +function calculateSteal($attackFleets, $defenderPlanet, $simMode = false) { //Steal-Math by Slaver for 2Moons(http://www.2moons.cc) based on http://www.owiki.de/Beute - global $pricelist, $db; + global $pricelist, $resource; + + $firstResource = 901; + $secondResource = 902; + $thirdResource = 903; $SortFleets = array(); - $Sumcapacity = 0; - $booty = array('metal' => 0, 'crystal' => 0, 'deuterium' => 0); + $capacity = 0; + + $stealResource = array( + $firstResource => 0, + $secondResource => 0, + $thirdResource => 0 + ); + foreach($attackFleets as $FleetID => $Attacker) { $SortFleets[$FleetID] = 0; - foreach($Attacker['detail'] as $Element => $amount) + + foreach($Attacker['unit'] as $Element => $amount) { $SortFleets[$FleetID] += $pricelist[$Element]['capacity'] * $amount; } - $SortFleets[$FleetID] -= $Attacker['fleet']['fleet_resource_metal']; - $SortFleets[$FleetID] -= $Attacker['fleet']['fleet_resource_crystal']; - $SortFleets[$FleetID] -= $Attacker['fleet']['fleet_resource_deuterium']; - $Sumcapacity += $SortFleets[$FleetID]; + $SortFleets[$FleetID] *= (1 + $Attacker['player']['factor']['ShipStorage']); + + $SortFleets[$FleetID] -= $Attacker['fleetDetail']['fleet_resource_metal']; + $SortFleets[$FleetID] -= $Attacker['fleetDetail']['fleet_resource_crystal']; + $SortFleets[$FleetID] -= $Attacker['fleetDetail']['fleet_resource_deuterium']; + $capacity += $SortFleets[$FleetID]; } - $AllCapacity = $Sumcapacity; + $AllCapacity = $capacity; if($AllCapacity <= 0) - return $booty; - + { + return $stealResource; + } + // Step 1 - $booty['metal'] = min($Sumcapacity / 3, $defenderPlanet['metal'] / 2); - $Sumcapacity -= $booty['metal']; + $stealResource[$firstResource] = min($capacity / 3, $defenderPlanet[$resource[$firstResource]] / 2); + $capacity -= $stealResource[$firstResource]; // Step 2 - $booty['crystal'] = min($Sumcapacity / 2, $defenderPlanet['crystal'] / 2); - $Sumcapacity -= $booty['crystal']; + $stealResource[$secondResource] = min($capacity / 2, $defenderPlanet[$resource[$secondResource]] / 2); + $capacity -= $stealResource[$secondResource]; // Step 3 - $booty['deuterium'] = min($Sumcapacity, $defenderPlanet['deuterium'] / 2); - $Sumcapacity -= $booty['deuterium']; + $stealResource[$thirdResource] = min($capacity, $defenderPlanet[$resource[$thirdResource]] / 2); + $capacity -= $stealResource[$thirdResource]; // Step 4 - $oldMetalBooty = $booty['metal']; - $booty['metal'] += min($Sumcapacity / 2, $defenderPlanet['metal'] / 2 - $booty['metal']); - $Sumcapacity -= $booty['metal'] - $oldMetalBooty; + $oldMetalBooty = $stealResource[$firstResource]; + $stealResource[$firstResource] += min($capacity / 2, $defenderPlanet[$resource[$firstResource]] / 2 - $stealResource[$firstResource]); + $capacity -= $stealResource[$firstResource] - $oldMetalBooty; // Step 5 - $booty['crystal'] += min($Sumcapacity, $defenderPlanet['crystal'] / 2 - $booty['crystal']); + $stealResource[$secondResource] += min($capacity, $defenderPlanet[$resource[$secondResource]] / 2 - $stealResource[$secondResource]); - if($ForSim) - return $booty; - - $Qry = ""; - + if($simMode) + { + return $stealResource; + } + $sqlQuery = ""; foreach($SortFleets as $FleetID => $Capacity) { - $Factor = $Capacity / $AllCapacity; - $Qry .= "UPDATE ".FLEETS." SET "; - $Qry .= "`fleet_resource_metal` = `fleet_resource_metal` + '".$booty['metal'] * $Factor."', "; - $Qry .= "`fleet_resource_crystal` = `fleet_resource_crystal` + '".$booty['crystal'] * $Factor."', "; - $Qry .= "`fleet_resource_deuterium` = `fleet_resource_deuterium` + '".$booty['deuterium'] * $Factor."' "; - $Qry .= "WHERE fleet_id = '".$FleetID."';"; + $slotFactor = $Capacity / $AllCapacity; + + $sqlQuery .= "UPDATE ".FLEETS." SET "; + $sqlQuery .= "`fleet_resource_metal` = `fleet_resource_metal` + '".($stealResource[$firstResource] * $slotFactor)."', "; + $sqlQuery .= "`fleet_resource_crystal` = `fleet_resource_crystal` + '".($stealResource[$secondResource] * $slotFactor)."', "; + $sqlQuery .= "`fleet_resource_deuterium` = `fleet_resource_deuterium` + '".($stealResource[$thirdResource] * $slotFactor)."' "; + $sqlQuery .= "WHERE fleet_id = '".$FleetID."';"; } - $db->multi_query($Qry); - return $booty; -} + $GLOBALS['DATABASE']->multi_query($sqlQuery); -?> \ No newline at end of file + return $stealResource; +} + \ No newline at end of file diff --git a/includes/common.php b/includes/common.php index 9513f0d..e06c4ea 100644 --- a/includes/common.php +++ b/includes/common.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,165 +18,172 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ -if(!defined('IN_ADMIN') || !defined('IN_CRON')) - define("STARTTIME", microtime(true)); +define("BETA", 0); - -define("BETA", file_exists(ROOT_PATH.'BETA_GAME')); +if (isset($_POST['GLOBALS']) || isset($_GET['GLOBALS'])) { + exit('You cannot set the GLOBALS-array from outside the script.'); +} + +// Magic Quotes work around. +// http://www.php.net/manual/de/security.magicquotes.disabling.php#91585 +if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() == 1) { + function stripslashes_gpc(&$value) + { + $value = stripslashes($value); + } + array_walk_recursive($_GET, 'stripslashes_gpc'); + array_walk_recursive($_POST, 'stripslashes_gpc'); + array_walk_recursive($_COOKIE, 'stripslashes_gpc'); + array_walk_recursive($_REQUEST, 'stripslashes_gpc'); +} + +if (function_exists('mb_internal_encoding')) { + mb_internal_encoding("UTF-8"); +} ignore_user_abort(true); -error_reporting(E_ALL ^ E_NOTICE); +error_reporting(E_ALL & ~E_STRICT); + +// If the guy forgot to set date.timezone on php.ini +date_default_timezone_set(@date_default_timezone_get()); + ini_set('display_errors', 1); header('Content-Type: text/html; charset=UTF-8'); -define('TIMESTAMP', $_SERVER['REQUEST_TIME']); - -require_once(ROOT_PATH . 'includes/config.php'); -require_once(ROOT_PATH . 'includes/constants.php'); - -ini_set('session.save_path', ROOT_PATH.'cache/sessions'); -ini_set('upload_tmp_dir', ROOT_PATH.'cache/sessions'); -ini_set('session.use_cookies', '1'); -ini_set('session.use_only_cookies', '1'); -session_set_cookie_params(SESSION_LIFETIME, '/'); -session_cache_limiter('nocache'); -session_name('2Moons'); -ini_set('session.use_trans_sid', 0); -ini_set('session.auto_start', '0'); -ini_set('session.serialize_handler', 'php'); -ini_set('session.gc_maxlifetime', SESSION_LIFETIME); -ini_set('session.gc_probability', '1'); -ini_set('session.gc_divisor', '1000'); -ini_set('session.bug_compat_warn', '0'); -ini_set('session.bug_compat_42', '0'); -ini_set('session.cookie_httponly', true); -ini_set('error_log', ROOT_PATH.'includes/error.log'); - -if(!defined('LOGIN')) - session_start(); +define('TIMESTAMP', time()); -if(!function_exists('bcadd')) - require_once(ROOT_PATH . 'includes/bcmath.php'); - -require_once(ROOT_PATH . 'includes/GeneralFunctions.php'); -set_exception_handler('exception_handler'); +require(ROOT_PATH . 'includes/constants.php'); -require_once(ROOT_PATH . 'includes/classes/class.MySQLi.php'); -require_once(ROOT_PATH . 'includes/classes/class.Lang.php'); -require_once(ROOT_PATH . 'includes/classes/class.theme.php'); -require_once(ROOT_PATH . 'includes/classes/class.Session.php'); - -$db = new DB_MySQLi(); -$THEME = new Theme(); -$LANG = new Language(); -$CONFIG = array(); +ini_set('log_errors', 'On'); +ini_set('error_log', ROOT_PATH.'includes/error.log'); -$UNI = getUniverse(); -unset($database); +require(ROOT_PATH . 'includes/GeneralFunctions.php'); +set_exception_handler('exceptionHandler'); +set_error_handler('errorHandler'); + +require(ROOT_PATH . 'includes/classes/class.Cache.php'); +require(ROOT_PATH . 'includes/classes/class.Database.php'); +require(ROOT_PATH . 'includes/classes/class.theme.php'); +require(ROOT_PATH . 'includes/classes/class.Session.php'); +require(ROOT_PATH . 'includes/classes/class.template.php'); +require(ROOT_PATH . 'includes/classes/Config.class.php'); +require(ROOT_PATH . 'includes/classes/ArrayUtil.class.php'); +require(ROOT_PATH . 'includes/classes/Language.class.php'); +require(ROOT_PATH . 'includes/classes/HTTP.class.php'); +require(ROOT_PATH . 'includes/classes/PlayerUtil.class.php'); // Say Browsers to Allow ThirdParty Cookies (Thanks to morktadela) -header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'); +HTTP::sendHeader('P3P', 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'); +define('AJAX_REQUEST', HTTP::_GP('ajax', 0)); -if(UNIS_MULTIVARS) - require_once(ROOT_PATH.'includes/vars_uni'.$UNI.'.php'); -else - require_once(ROOT_PATH.'includes/vars.php'); - -$CONF = getConfig($UNI); -$LANG->setDefault($CONF['lang']); -require(ROOT_PATH.'includes/libs/FirePHP/FirePHP.class.php'); -require(ROOT_PATH.'includes/libs/FirePHP/fb.php'); -$FirePHP = FirePHP::getInstance(true); -$FirePHP->setEnabled((bool) $GLOBALS['CONF']['debug']); -if($GLOBALS['CONF']['debug']) { - ob_start(); - $FirePHP->registerErrorHandler(true); -} +$THEME = new Theme(); +$CACHE = new Cache(); -if (!defined('CLI') && !defined('LOGIN') && !defined('IN_CRON') && !defined('AJAX') && !defined('ROOT')) +if (MODE === 'INSTALL') { - $SESSION = new Session(); - - if(!$SESSION->IsUserLogin()) redirectTo('index.php?code=3'); + return; +} + +if(!file_exists(ROOT_PATH.'includes/config.php')) { + HTTP::redirectTo("install/index.php"); +} + +require(ROOT_PATH . 'includes/config.php'); +require(ROOT_PATH . 'includes/dbtables.php'); + +$SESSION = new Session(); +$DATABASE = new Database(); +unset($database); + +Config::init(); +$UNI = getUniverse(); +Config::setGlobals(); + +date_default_timezone_set(Config::get('timezone')); + +require(ROOT_PATH.'includes/vars.php'); + +if (MODE === 'INGAME' || MODE === 'ADMIN' || MODE === 'CHAT') +{ + if(!$SESSION->isActiveSession()) + { + HTTP::redirectTo('index.php?code=3'); + } $SESSION->UpdateSession(); - - if($CONF['game_disable'] == 0 && $_SESSION['authlevel'] == AUTH_USR) { - message($CONF['close_reason']); - } - if(!CheckModule(10) && !defined('IN_ADMIN') && request_var('ajax', 0) == 0) + require(ROOT_PATH.'includes/classes/class.BuildFunctions.php'); + require(ROOT_PATH.'includes/classes/class.PlanetRessUpdate.php'); + + if(!AJAX_REQUEST && MODE === 'INGAME' && isModulAvalible(MODULE_FLEET_EVENTS)) { require(ROOT_PATH.'includes/FleetHandler.php'); + } - $USER = $db->uniquequery("SELECT u.*, s.`total_points`, s.`total_rank` FROM ".USERS." as u LEFT JOIN ".STATPOINTS." as s ON s.`id_owner` = u.`id` AND s.`stat_type` = '1' WHERE u.`id` = '".$_SESSION['id']."';"); - $FirePHP->log("Load User: ".$USER['id']); + $USER = $GLOBALS['DATABASE']->getFirstRow("SELECT + user.*, + stat.total_points, + stat.total_rank, + COUNT(message.message_id) as messages + FROM ".USERS." as user + LEFT JOIN ".STATPOINTS." as stat ON stat.id_owner = user.id AND stat.stat_type = '1' + LEFT JOIN ".MESSAGES." as message ON message.message_owner = user.id AND message.message_unread = '1' + WHERE user.id = ".$_SESSION['id']." + GROUP BY message.message_owner;"); + if(empty($USER)) { exit(header('Location: index.php')); - } elseif(empty($USER['lang'])) { - $USER['lang'] = $CONF['lang']; - $db->query("UPDATE ".USERS." SET `lang` = '".$USER['lang']."' WHERE `id` = '".$USER['id']."';"); - $FirePHP->log("Load User: ".$USER['id']); } - $LANG->setUser($USER['lang']); - $LANG->includeLang(array('L18N', 'INGAME', 'TECH')); + $LNG = new Language($USER['lang']); + $LNG->includeData(array('L18N', 'INGAME', 'TECH', 'CUSTOM')); $THEME->setUserTheme($USER['dpath']); - if($USER['bana'] == 1) - { - message("".$LNG['css_account_banned_message']."

".sprintf($LNG['css_account_banned_expire'],date("d. M y H:i", $USER['banaday']))."

".$LNG['css_goto_homeside']); - exit; + + if(Config::get('game_disable') == 0 && $USER['authlevel'] == AUTH_USR) { + ShowErrorPage::printError($LNG['sys_closed_game'].'

'.Config::get('close_reason'), false); + } + + if($USER['bana'] == 1) { + ShowErrorPage::printError("".$LNG['css_account_banned_message']."

".sprintf($LNG['css_account_banned_expire'], _date($LNG['php_tdformat'], $USER['banaday'], $USER['timezone']))."

".$LNG['css_goto_homeside'], false); } - if (!defined('IN_ADMIN')) + if (MODE === 'INGAME') { - require_once(ROOT_PATH . 'includes/classes/class.PlanetRessUpdate.php'); - $PLANET = $db->uniquequery("SELECT * FROM `".PLANETS."` WHERE `id` = '".$_SESSION['planet']."';"); + if($UNI != $USER['universe'] && count($CONFIG) > 1) + { + HTTP::redirectTo(PROTOCOL.HTTP_HOST.HTTP_BASE."uni".$USER['universe']."/".HTTP_FILE, true); + } + + $PLANET = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".PLANETS." WHERE id = ".$_SESSION['planet'].";"); - if(empty($PLANET)){ - $PLANET = $db->uniquequery("SELECT * FROM `".PLANETS."` WHERE `id` = '".$USER['id_planet']."';"); + if(empty($PLANET)) + { + $PLANET = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM ".PLANETS." WHERE id = ".$USER['id_planet'].";"); - if(empty($PLANET)){ + if(empty($PLANET)) + { throw new Exception("Main Planet does not exist!"); } } + $USER['factor'] = getFactors($USER); $USER['PLANETS'] = getPlanets($USER); - $FirePHP->log("Load Planet: ".$PLANET['id']); - + } elseif (MODE === 'ADMIN') { + error_reporting(E_ERROR | E_WARNING | E_PARSE); - if(empty($PLANET['b_hanger_id']) && !empty($PLANET['b_hanger'])) - { - $_SESSION['messtoken'] = md5($USER['id'].'|1'); - $db->query("UPDATE ".PLANETS." SET `b_hanger` = 0 WHERE `id` = '".$_SESSION['planet']."';"); - message("

Bug ahead!

Please give Informations about your last steps!

"); - exit; - } - if(empty($PLANET['b_building_id']) && !empty($PLANET['b_building'])) - { - $_SESSION['messtoken'] = md5($USER['id'].'|1'); - $db->query("UPDATE ".PLANETS." SET `b_building` = 0 WHERE `id` = '".$_SESSION['planet']."';"); - message("

Bug ahead!

Please give Informations about your last steps!

"); - exit; - } - } else { - $USER['rights'] = unserialize($USER['rights']); - $LANG->includeLang(array('ADMIN')); + $USER['rights'] = unserialize($USER['rights']); + $LNG->includeData(array('ADMIN', 'CUSTOM')); } -} elseif(defined('LOGIN')) { - //Login - $LANG->GetLangFromBrowser(); - $LANG->includeLang(array('INGAME', 'PUBLIC')); } - -if (!defined('AJAX') && !defined('CLI')) - require_once(ROOT_PATH.'includes/classes/class.template.php'); - -?> \ No newline at end of file +elseif(MODE === 'LOGIN') +{ + $LNG = new Language(); + $LNG->getUserAgentLanguage(); + $LNG->includeData(array('L18N', 'INGAME', 'PUBLIC', 'CUSTOM')); +} \ No newline at end of file diff --git a/includes/config.sample.php b/includes/config.sample.php index be2e7b1..f9591d3 100644 --- a/includes/config.sample.php +++ b/includes/config.sample.php @@ -1,13 +1,14 @@ \ No newline at end of file diff --git a/includes/constants.php b/includes/constants.php index 0a2b3bd..bf67a4b 100644 --- a/includes/constants.php +++ b/includes/constants.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,139 +18,212 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ //SET TIMEZONE (if Server Timezone are not correct) //date_default_timezone_set('America/Chicago'); + //TEMPLATES DEFAULT SETTINGS -define('DEFAULT_THEME' , 'gow'); +define('DEFAULT_THEME' , 'gow'); +define('HTTPS' , isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on'); +define('PROTOCOL' , HTTPS ? 'https://' : 'http://'); -define('PROTOCOL' , (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https://' : 'http://'); -define('HTTP_ROOT' , str_replace(basename($_SERVER["PHP_SELF"]), '', $_SERVER["PHP_SELF"])); +define('HTTP_BASE' , str_replace(array('\\', '//'), '/', dirname($_SERVER['SCRIPT_NAME']).'/')); +define('HTTP_ROOT' , str_replace(basename($_SERVER['SCRIPT_FILENAME']), '', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))); -define('AJAX_CHAT_PATH' , ROOT_PATH.'/chat/'); +define('HTTP_FILE' , basename($_SERVER['SCRIPT_NAME'])); +define('HTTP_HOST' , $_SERVER['HTTP_HOST']); +define('HTTP_PATH' , PROTOCOL.HTTP_HOST.HTTP_ROOT); -define('DEFAULT_LANG' , "de"); // For Fatal Errors! -define('PHPEXT' , "php"); +if(!defined('AJAX_CHAT_PATH')) { + define('AJAX_CHAT_PATH', ROOT_PATH.'/chat/'); +} -// SUPPORT WILDCAST DOMAINS -define('UNIS_WILDCAST' , false); +if(!defined('CACHE_PATH')) { + define('CACHE_PATH', ROOT_PATH.'/cache/'); +} -// SUPPORT OWN vars.php / UNIVERSE | NOTE: make a COPY of vars.php and rename it to vars_uni1.php, vars_uni2.php, etc... -define('UNIS_MULTIVARS' , false); +// For Fatal Errors! +define('DEFAULT_LANG' , 'de'); -// NUMBER OF COLUMNS FOR SPY REPORTS -define('SPY_REPORT_ROW' , 2); +// SUPPORT WILDCAST DOMAINS +define('UNIS_WILDCAST' , false); // FIELDS FOR EACH LEVEL OF THE LUNAR BASE -define('FIELDS_BY_MOONBASIS_LEVEL', 3); +define('FIELDS_BY_MOONBASIS_LEVEL' , 3); // FIELDS FOR EACH LEVEL OF THE TERRAFORMER -define('FIELDS_BY_TERRAFORMER' , 5); +define('FIELDS_BY_TERRAFORMER' , 5); + +// TIME IN SECONDS, TO (i) APPEAR ON GALAXY +define('INACTIVE' , 604800); -// ADDED PLANET PRO 2 TECH LEVELS -define('PLANETS_PER_TECH' , 1); +// TIME IN SECONDS, TO (i I) APPEAR ON GALAXY +define('INACTIVE_LONG' , 2419200); + +// FEE FOR CANCEL QUEUE IN SHIPYARD +define('FACTOR_CANCEL_SHIPYARD' , 0.6); + +// MINIMUM FLEET TIME +define('MIN_FLEET_TIME' , 5); + +// PHALANX COST'S +define('PHALANX_DEUTERIUM' , 5000); // Time of changable nick after changing nick. -define('USERNAME_CHANGETIME' , 604800); +define('USERNAME_CHANGETIME' , 604800); // Factor for Metal/Crystal and Deuterium Storages -define('STORAGE_FACTOR' , 1.0); +define('STORAGE_FACTOR' , 1.0); // Max Results in Searchpage (-1 = disable) -define('SEARCH_LIMIT' , 25); +define('SEARCH_LIMIT' , 25); + +// Messages per page at message list +define('MESSAGES_PER_PAGE' , 10); + +// banned users per page at ban list +define('BANNED_USERS_PER_PAGE' , 25); // How much IP Block ll be checked // 1 = (AAA); 2 = (AAA.BBB); 3 = (AAA.BBB.CCC) -define('COMPARE_IP_BLOCKS' , 2); +define('COMPARE_IP_BLOCKS' , 2); // Max Round on Combats -define('MAX_ATTACK_ROUNDS' , 6); +define('MAX_ATTACK_ROUNDS' , 6); // Enable the one-Click SImulation on Spy-Raports -define('ENABLE_SIMULATOR_LINK' , true); - -// Planetrows on overview -define('PLANET_ROWS_ON_OVERVIEW' , 2); +define('ENABLE_SIMULATOR_LINK' , true); // Max. User Session in Seconds -define('SESSION_LIFETIME' , 43200); +define('SESSION_LIFETIME' , 43200); + +// ENABLE Mutlialert on sending fleets +define('ENABLE_MULTIALERT' , true); + +// UTF-8 support for names (required for non-english chars!) +define('UTF8_SUPPORT' , true); -// DISCLAMER INFOS -define('DICLAMER_NAME' , "Edit constans.php!"); -define('DICLAMER_ADRESS1' , "Edit constans.php!"); -define('DICLAMER_ADRESS2' , "Edit constans.php!"); -define('DICLAMER_TEL' , "Edit constans.php!"); -define('DICLAMER_EMAIL' , "Edit constans.php!"); +// Define, how its more hard to spy all inforation +/* + if [Spy tech level of sender] > [Spy tech level of target] + min amount of spies = -1 * (abs([Spy tech level of sender] - [Spy tech level of target]) * SPY_DIFFENCE_FACTOR) ^ 2; + else + min amount of spies = -1 * (abs([Spy tech level of sender] - [Spy tech level of target]) * SPY_DIFFENCE_FACTOR) ^ 2; + +*/ +define('SPY_DIFFENCE_FACTOR' , 1); -// UTF-8 Support for Names (Requried for non-english Chars!) -define('UTF8_SUPPORT' , true); +// Define, how its more hard to spy all inforation +/* + min amount of spies = see MissionCaseSpy.php#78 -// EventHandler Settings. Not in use! -define('EH_ACTIVE_ECO' , BETA); -define('EH_ACTIVE_FLEETS' , BETA); + To see Fleet = {min amount of spies} + To see Defense = {min amount of spies} + 1 * SPY_VIEW_FACTOR + To see Buildings = {min amount of spies} + 3 * SPY_VIEW_FACTOR + To see Technology = {min amount of spies} + 5 * SPY_VIEW_FACTOR +*/ +define('SPY_VIEW_FACTOR' , 1); // Bash Settings -define('BASH_ON' , false); -define('BASH_COUNT' , 6); -define('BASH_TIME' , 86400); +define('BASH_ON' , false); +define('BASH_COUNT' , 6); +define('BASH_TIME' , 86400); + +// Bash rule on wars: +// 0 = NORMAL +// 1 = ON WAR, BASH RULE IS DEACTIVE +define('BASH_WAR' , 0); -// Invisible Missions for Phalanx -// Exsample: '1','4','7','10' -define('INV_PHALANX_MISSIONS' , ''); +// MINIMUM FLEET TIME MUST HIGHER THEN BASH_TIME +define('FLEETLOG_AGE' , 86400); // Root IDs -define('ROOT_UNI' , 1); -define('ROOT_USER' , 1); - -// AdminAuthlevels -define('AUTH_ADM' , 3); -define('AUTH_OPS' , 2); -define('AUTH_MOD' , 1); -define('AUTH_USR' , 0); - -// Data Tabells -define('DB_NAME' , $database['databasename']); -define('DB_PREFIX' , $database['tableprefix']); - -define('AKS' , $database['tableprefix'].'aks'); -define('ALLIANCE' , $database['tableprefix'].'alliance'); -define('ALLIANCE_REQUEST' , $database['tableprefix'].'alliance_request'); -define('BANNED' , $database['tableprefix'].'banned'); -define('BUDDY' , $database['tableprefix'].'buddy'); -define('BUDDY_REQUEST' , $database['tableprefix'].'buddy_request'); -define('CHAT_ON' , $database['tableprefix'].'chat_online'); -define('CHAT_MES' , $database['tableprefix'].'chat_messages'); -define('CHAT_BAN' , $database['tableprefix'].'chat_bans'); -define('CHAT_INV' , $database['tableprefix'].'chat_invitations'); -define('CONFIG' , $database['tableprefix'].'config'); -define('DIPLO' , $database['tableprefix'].'diplo'); -define('FLEETS' , $database['tableprefix'].'fleets'); -define('LOG' , $database['tableprefix'].'log'); -define('LOG_FLEETS' , $database['tableprefix'].'log_fleets'); -define('NEWS' , $database['tableprefix'].'news'); -define('NOTES' , $database['tableprefix'].'notes'); -define('MESSAGES' , $database['tableprefix'].'messages'); -define('PLANETS' , $database['tableprefix'].'planets'); -define('RW' , $database['tableprefix'].'raports'); -define('SESSION' , $database['tableprefix'].'session'); -define('STATPOINTS' , $database['tableprefix'].'statpoints'); -define('SUPP' , $database['tableprefix'].'supp'); -define('TOPKB' , $database['tableprefix'].'topkb'); -define('TOPKB_USERS' , $database['tableprefix'].'users_to_topkb'); -define('USERS' , $database['tableprefix'].'users'); -define('USERS_VALID' , $database['tableprefix'].'users_valid'); - - - -// MOD-TABLES - - -?> \ No newline at end of file +define('ROOT_UNI' , 1); +define('ROOT_USER' , 1); + +// AUTHLEVEL +define('AUTH_ADM' , 3); +define('AUTH_OPS' , 2); +define('AUTH_MOD' , 1); +define('AUTH_USR' , 0); + +// Modules +define('MODULE_AMOUNT' , 43); +define('MODULE_ALLIANCE' , 0); +define('MODULE_BANLIST' , 21); +define('MODULE_BANNER' , 37); +define('MODULE_BATTLEHALL' , 12); +define('MODULE_BUDDYLIST' , 6); +define('MODULE_BUILDING' , 2); +define('MODULE_CHAT' , 7); +define('MODULE_DMEXTRAS' , 8); +define('MODULE_FLEET_EVENTS' , 10); +define('MODULE_FLEET_TABLE' , 9); +define('MODULE_FLEET_TRADER' , 38); +define('MODULE_GALAXY' , 11); +define('MODULE_IMPERIUM' , 15); +define('MODULE_INFORMATION' , 14); +define('MODULE_MESSAGES' , 16); +define('MODULE_MISSILEATTACK' , 40); +define('MODULE_MISSION_ATTACK' , 1); +define('MODULE_MISSION_ACS' , 42); +define('MODULE_MISSION_COLONY' , 35); +define('MODULE_MISSION_DARKMATTER' , 31); +define('MODULE_MISSION_DESTROY' , 29); +define('MODULE_MISSION_EXPEDITION' , 30); +define('MODULE_MISSION_HOLD' , 33); +define('MODULE_MISSION_RECYCLE' , 32); +define('MODULE_MISSION_SPY' , 24); +define('MODULE_MISSION_STATION' , 36); +define('MODULE_MISSION_TRANSPORT' , 34); +define('MODULE_NOTICE' , 17); +define('MODULE_OFFICIER' , 18); +define('MODULE_PHALANX' , 19); +define('MODULE_PLAYERCARD' , 20); +define('MODULE_RECORDS' , 22); +define('MODULE_RESEARCH' , 3); +define('MODULE_RESSOURCE_LIST' , 23); +define('MODULE_SEARCH' , 26); +define('MODULE_SHIPYARD_FLEET' , 4); +define('MODULE_SHIPYARD_DEFENSIVE' , 5); +define('MODULE_SHORTCUTS' , 41); +define('MODULE_SIMULATOR' , 39); +define('MODULE_STATISTICS' , 25); +define('MODULE_SUPPORT' , 27); +define('MODULE_TECHTREE' , 28); +define('MODULE_TRADER' , 13); + +// FLEET STATE +define('FLEET_OUTWARD' , 0); +define('FLEET_RETURN' , 1); +define('FLEET_HOLD' , 2); + +// ELEMENT FLAGS +define('ELEMENT_BUILD' , 1); # ID 0 - 99 +define('ELEMENT_TECH' , 2); # ID 101 - 199 +define('ELEMENT_FLEET' , 4); # ID 201 - 399 +define('ELEMENT_DEFENSIVE' , 8); # ID 401 - 599 +define('ELEMENT_OFFICIER' , 16); # ID 601 - 699 +define('ELEMENT_BONUS' , 32); # ID 701 - 799 +define('ELEMENT_RACE' , 64); # ID 801 - 899 +define('ELEMENT_PLANET_RESOURCE' , 128); # ID 901 - 949 +define('ELEMENT_USER_RESOURCE' , 256); # ID 951 - 999 + +// .. 512, 1024, 2048, 4096, 8192, 16384, 32768 + +define('ELEMENT_PRODUCTION' , 65536); +define('ELEMENT_STORAGE' , 131072); +define('ELEMENT_ONEPERPLANET' , 262144); +define('ELEMENT_BOUNS' , 524288); +define('ELEMENT_BUILD_ON_PLANET' , 1048576); +define('ELEMENT_BUILD_ON_MOONS' , 2097152); +define('ELEMENT_RESOURCE_ON_TF' , 4194304); +define('ELEMENT_RESOURCE_ON_FLEET' , 8388608); +define('ELEMENT_RESOURCE_ON_STEAL' , 16777216); diff --git a/includes/dbtables.php b/includes/dbtables.php new file mode 100644 index 0000000..7e2ece0 --- /dev/null +++ b/includes/dbtables.php @@ -0,0 +1,79 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2009 Lucky + * @copyright 2011 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.5 (2011-07-31) + * @info $Id$ + * @link http://2moons.cc/ + */ + +// Global configkeys +$BASICCONFIG = array('VERSION', 'game_name', 'stat', 'stat_level', 'stat_last_update', 'stat_settings', 'stat_update_time', 'stat_last_db_update', 'stats_fly_lock', 'cron_lock', 'ts_modon', 'ts_server', 'ts_tcpport', 'ts_udpport', 'ts_timeout', 'ts_version', 'ts_cron_last', 'ts_cron_interval', 'ts_login', 'ts_password', 'capaktiv', 'cappublic', 'capprivate', 'mail_active', 'mail_use', 'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_ssl', 'smtp_sendmail', 'smail_path', 'fb_on', 'fb_apikey', 'fb_skey', 'ga_active', 'ga_key', 'chat_closed', 'chat_allowchan', 'chat_allowmes', 'chat_allowdelmes', 'chat_logmessage', 'chat_nickchange', 'chat_botname', 'chat_channelname', 'chat_socket_active', 'chat_socket_host', 'chat_socket_ip', 'chat_socket_port', 'chat_socket_chatid', 'ttf_file', 'sendmail_inactive', 'del_user_sendmail', 'del_user_automatic', 'del_oldstuff', 'del_user_manually', 'ref_max_referals', 'disclamerAddress','disclamerPhone','disclamerMail','disclamerNotice'); + +// Data Tabells +define('DB_NAME' , $database['databasename']); +define('DB_PREFIX' , $database['tableprefix']); + +define('AKS' , DB_PREFIX.'aks'); +define('ALLIANCE' , DB_PREFIX.'alliance'); +define('ALLIANCE_RANK' , DB_PREFIX.'alliance_ranks'); +define('ALLIANCE_REQUEST' , DB_PREFIX.'alliance_request'); +define('BANNED' , DB_PREFIX.'banned'); +define('BUDDY' , DB_PREFIX.'buddy'); +define('BUDDY_REQUEST' , DB_PREFIX.'buddy_request'); +define('CHAT_BAN' , DB_PREFIX.'chat_bans'); +define('CHAT_INV' , DB_PREFIX.'chat_invitations'); +define('CHAT_MES' , DB_PREFIX.'chat_messages'); +define('CHAT_ON' , DB_PREFIX.'chat_online'); +define('CONFIG' , DB_PREFIX.'config'); +define('CRONJOBS' , DB_PREFIX.'cronjobs'); +define('DIPLO' , DB_PREFIX.'diplo'); +define('FLEETS' , DB_PREFIX.'fleets'); +define('FLEETS_EVENT' , DB_PREFIX.'fleet_event'); +define('LOG' , DB_PREFIX.'log'); +define('LOG_FLEETS' , DB_PREFIX.'log_fleets'); +define('LOSTPASSWORD' , DB_PREFIX.'lostpassword'); +define('NEWS' , DB_PREFIX.'news'); +define('NOTES' , DB_PREFIX.'notes'); +define('MESSAGES' , DB_PREFIX.'messages'); +define('MULTI' , DB_PREFIX.'multi'); +define('PLANETS' , DB_PREFIX.'planets'); +define('RW' , DB_PREFIX.'raports'); +define('RECORDS' , DB_PREFIX.'records'); +define('SESSION' , DB_PREFIX.'session'); +define('SHORTCUTS' , DB_PREFIX.'shortcuts'); +define('STATPOINTS' , DB_PREFIX.'statpoints'); +define('TICKETS' , DB_PREFIX.'ticket'); +define('TICKETS_ANSWER' , DB_PREFIX.'ticket_answer'); +define('TICKETS_CATEGORY' , DB_PREFIX.'ticket_category'); +define('TOPKB' , DB_PREFIX.'topkb'); +define('TOPKB_USERS' , DB_PREFIX.'users_to_topkb'); +define('USERS' , DB_PREFIX.'users'); +define('USERS_ACS' , DB_PREFIX.'users_to_acs'); +define('USERS_AUTH' , DB_PREFIX.'users_to_extauth'); +define('USERS_VALID' , DB_PREFIX.'users_valid'); +define('VARS' , DB_PREFIX.'vars'); +define('VARS_RAPIDFIRE' , DB_PREFIX.'vars_rapidfire'); +define('VARS_REQUIRE' , DB_PREFIX.'vars_requriements'); + +// MOD-TABLES \ No newline at end of file diff --git a/includes/extauth/facebook.class.php b/includes/extauth/facebook.class.php new file mode 100644 index 0000000..9e4416c --- /dev/null +++ b/includes/extauth/facebook.class.php @@ -0,0 +1,103 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + +require(ROOT_PATH.'/includes/libs/facebook/facebook.php'); +class FacebookAuth extends Facebook { + function __construct() + { + if($this->isActiveMode()) + { + parent::__construct(array( + 'appId' => $GLOBALS['CONF']['fb_apikey'], + 'secret' => $GLOBALS['CONF']['fb_skey'], + 'cookie' => true, + )); + } + } + + function isActiveMode() { + return $GLOBALS['CONF']['fb_on'] == 1; + } + + function isVaild() { + if($this->getUser() != 0) + { + return $this->getUser(); + } + + HTTP::sendHeader('Location', $this->getLoginUrl(array( + 'scope' => 'publish_stream,publish_actions,user_games_activity', + 'redirect_uri' => HTTP_PATH.'index.php?page=externalAuth&method=facebook' + ))); + exit; + } + + function getAccount() + { + return $this->getUser(); + } + + function register() + { + $uid = $this->getAccount(); + + $me = $this->api('/me'); + $ValidReg = $GLOBALS['DATABASE']->getFirstCell("SELECT cle FROM ".USERS_VALID." WHERE universe = ".$UNI." AND email = '".$GLOBALS['DATABASE']->sql_escape($me['email'])."';"); + if(!empty($ValidReg)) + HTTP::redirectTo("index.php?uni=".$UNI."&page=reg&action=valid&clef=".$ValidReg); + + $GLOBALS['DATABASE']->query("INSERT INTO ".USERS_AUTH." SET + id = (SELECT id FROM ".USERS." WHERE email = '".$GLOBALS['DATABASE']->sql_escape($me['email'])."' OR email_2 = '".$GLOBALS['DATABASE']->sql_escape($me['email'])."'), + account = ".$uid.", + mode = 'facebook';"); + } + + function getLoginData() + { + global $UNI; + + $uid = $this->getAccount(); + + return $GLOBALS['DATABASE']->getFirstRow("SELECT + user.id, id_planet + FROM ".USERS_AUTH." auth + INNER JOIN ".USERS." user ON auth.id = user.id AND user.universe = ".$UNI." + WHERE auth.account = ".$uid." AND mode = 'facebook';"); + } + + function getAccountData() + { + $data = $this->api('/me', array('access_token' => $this->getAccessToken())); + + return array( + 'id' => $data['id'], + 'name' => $data['name'], + 'locale' => $data['locale'] + ); + } +} \ No newline at end of file diff --git a/includes/extauth/openid.class.php b/includes/extauth/openid.class.php new file mode 100644 index 0000000..fb2d3e6 --- /dev/null +++ b/includes/extauth/openid.class.php @@ -0,0 +1,114 @@ +. + * + * @package 2Moons + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke + * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License + * @version 1.7.0 (2013-01-17) + * @info $Id$ + * @link http://2moons.cc/ + */ + +require(ROOT_PATH.'/includes/libs/OpenID/openid.php'); + +class OpenIDAuth extends LightOpenID { + + function __construct() + { + parent::__construct(PROTOCOL.HTTP_HOST); + if(!$this->mode) { + if(isset($_REQUEST['openid_identifier'])) { + $this->identity = $_REQUEST['openid_identifier']; + + $this->required = array('contact/email'); + $this->optional = array('namePerson', 'namePerson/friendly'); + header('Location: ' . $this->authUrl()); + exit; + } else { + HTTP::redirectTo('index.php?code=4'); + } + } + } + + function isVaild() { + return $this->mode && $this->mode != 'cancel'; + } + + function getAccount() { + $user = $this->getAttributes(); + + if(!empty($user['contact/email'])) { + return $user['contact/email']; + } + + if(!empty($user['namePerson/friendly'])) { + return $user['namePerson/friendly']; + } + + if(!empty($user['namePerson'])) { + return $user['namePerson']; + } + + HTTP::redirectTo('index.php?code=4'); + } + + function register() + { + + $uid = getAccount(); + $user = $this->getAttributes(); + + if(empty($user['contact/email'])) { + $user['contact/email'] = ""; + } + + if(!empty($user['namePerson/friendly'])) { + $username = $user['namePerson/friendly']; + } elseif(!empty($user['namePerson'])) { + $username = $user['namePerson']; + } + + $ValidReg = $GLOBALS['DATABASE']->getFirstCell("SELECT cle FROM ".USERS_VALID." WHERE universe = ".$UNI." AND email = '".$GLOBALS['DATABASE']->sql_escape($user['contact/email'])."';"); + if(!empty($ValidReg)) + HTTP::redirectTo("index.php?uni=".$UNI."&page=reg&action=valid&clef=".$ValidReg); + + $GLOBALS['DATABASE']->query("INSERT INTO ".USERS_AUTH." SET + id = (SELECT id FROM ".USERS." WHERE email = '".$GLOBALS['DATABASE']->sql_escape($me['email'])."' OR email_2 = '".$GLOBALS['DATABASE']->sql_escape($user['contact/email'])."'), + account = '".$uid."', + mode = '".$GLOBALS['DATABASE']->sql_escape($_REQUEST['openid_identifier'])."';"); + } + + function getLoginData() + { + global $UNI; + + try { + $user = $this->getAttributes(); + } catch (FacebookApiException $e) { + HTTP::redirectTo('index.php?code=4'); + } + + return $GLOBALS['DATABASE']->getFirstRow("SELECT + user.id, user.username, user.dpath, user.authlevel, user.id_planet + FROM ".USERS_AUTH." auth + INNER JOIN ".USERS." user ON auth.id = user.id AND user.universe = ".$UNI." + WHERE auth.account = '".$user['contact/email']."' AND mode = '".$GLOBALS['DATABASE']->sql_escape($_REQUEST['openid_identifier'])."';"); + } +} \ No newline at end of file diff --git a/includes/functions/BBCode.php b/includes/functions/BBCode.php index 41c2f61..1d30a6f 100644 --- a/includes/functions/BBCode.php +++ b/includes/functions/BBCode.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,13 +18,12 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kröpke + * @copyright 2012 Jan Kröpke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ function bbcode($text) { @@ -83,7 +82,7 @@ function bbcode($text) { } - return makebr($bbcode->parse($text)); + return str_replace('&amp;', '&', makebr($bbcode->parse($text))); } function convertlinebreaks ($text) { @@ -209,5 +208,4 @@ function bbcode_color($action, $attributes, $content, $params, $node_object) { function bbcode_bgcolor($action, $attributes, $content, $params, $node_object) { if ($action == 'validate') return true; return ''.$content.''; -} -?> \ No newline at end of file +} \ No newline at end of file diff --git a/includes/functions/CreateOneMoonRecord.php b/includes/functions/CreateOneMoonRecord.php index 5c5c503..709c79c 100644 --- a/includes/functions/CreateOneMoonRecord.php +++ b/includes/functions/CreateOneMoonRecord.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kr�pke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,78 +18,64 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kr�pke + * @copyright 2012 Jan Kr�pke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ -if(!defined('INSIDE')) die('Hacking attempt!'); +function CreateOneMoonRecord($Galaxy, $System, $Planet, $Universe, $Owner, $MoonName, $Chance, $time = 0, $Size = 0) +{ + global $USER; - function CreateOneMoonRecord($Galaxy, $System, $Planet, $Universe, $Owner, $MoonID, $MoonName, $Chance, $Size = 0) - { - global $LNG, $USER, $db; + $SQL = "SELECT id_luna,planet_type,id,name,temp_max,temp_min FROM ".PLANETS." "; + $SQL .= "WHERE "; + $SQL .= "universe = '".$Universe."' AND "; + $SQL .= "galaxy = '".$Galaxy."' AND "; + $SQL .= "system = '".$System."' AND "; + $SQL .= "planet = '".$Planet."' AND "; + $SQL .= "planet_type = '1';"; + $MoonPlanet = $GLOBALS['DATABASE']->getFirstRow($SQL); - $SQL = "SELECT id_luna,planet_type,id,name,temp_max,temp_min FROM ".PLANETS." "; - $SQL .= "WHERE "; - $SQL .= "`universe` = '".$Universe."' AND "; - $SQL .= "`galaxy` = '".$Galaxy."' AND "; - $SQL .= "`system` = '".$System."' AND "; - $SQL .= "`planet` = '".$Planet."' AND "; - $SQL .= "`planet_type` = '1';"; - $MoonPlanet = $db->uniquequery($SQL); + if ($MoonPlanet['id_luna'] != 0) + return false; - if ($MoonPlanet['id_luna'] != 0) - return false; - - if($Size == 0) { - $size = floor(pow(mt_rand(10, 20) + 3 * $Chance, 0.5) * 1000); # New Calculation - 23.04.2011 - } else { - $size = $Size; - } - - $maxtemp = $MoonPlanet['temp_max'] - mt_rand(10, 45); - $mintemp = $MoonPlanet['temp_min'] - mt_rand(10, 45); - - $SQL = "INSERT INTO ".PLANETS." SET "; - $SQL .= "`name` = '".$MoonName."', "; - $SQL .= "`id_owner` = '".$Owner."', "; - $SQL .= "`universe` = '".$Universe."', "; - $SQL .= "`galaxy` = '".$Galaxy."', "; - $SQL .= "`system` = '".$System."', "; - $SQL .= "`planet` = '".$Planet."', "; - $SQL .= "`last_update` = '".TIMESTAMP."', "; - $SQL .= "`planet_type` = '3', "; - $SQL .= "`image` = 'mond', "; - $SQL .= "`diameter` = '".$size."', "; - $SQL .= "`field_max` = '1', "; - $SQL .= "`temp_min` = '".$mintemp."', "; - $SQL .= "`temp_max` = '".$maxtemp."', "; - $SQL .= "`metal` = '0', "; - $SQL .= "`metal_perhour` = '0', "; - $SQL .= "`metal_max` = '".BASE_STORAGE_SIZE."', "; - $SQL .= "`crystal` = '0', "; - $SQL .= "`crystal_perhour` = '0', "; - $SQL .= "`crystal_max` = '".BASE_STORAGE_SIZE."', "; - $SQL .= "`deuterium` = '0', "; - $SQL .= "`deuterium_perhour` = '0', "; - $SQL .= "`deuterium_max` = '".BASE_STORAGE_SIZE."';"; - $db->query($SQL); - - $SQL = "UPDATE ".PLANETS." SET "; - $SQL .= "`id_luna` = '".$db->GetInsertID()."' "; - $SQL .= "WHERE "; - $SQL .= "`universe` = '".$Universe."' AND "; - $SQL .= "`galaxy` = '".$Galaxy."' AND "; - $SQL .= "`system` = '".$System."' AND "; - $SQL .= "`planet` = '".$Planet."' AND "; - $SQL .= "`planet_type` = '1';"; - $db->query($SQL); - - return $MoonPlanet['name']; + if($Size == 0) { + $size = floor(pow(mt_rand(10, 20) + 3 * $Chance, 0.5) * 1000); # New Calculation - 23.04.2011 + } else { + $size = $Size; } + + $maxtemp = $MoonPlanet['temp_max'] - mt_rand(10, 45); + $mintemp = $MoonPlanet['temp_min'] - mt_rand(10, 45); + + $GLOBALS['DATABASE']->multi_query("INSERT INTO ".PLANETS." SET + name = '".$MoonName."', + id_owner = ".$Owner.", + universe = ".$Universe.", + galaxy = ".$Galaxy.", + system = ".$System.", + planet = ".$Planet.", + last_update = ".TIMESTAMP.", + planet_type = '3', + image = 'mond', + diameter = ".$size.", + field_max = '1', + temp_min = ".$mintemp.", + temp_max = ".$maxtemp.", + metal = 0, + metal_perhour = 0, + crystal = 0, + crystal_perhour = 0, + deuterium = 0, + deuterium_perhour = 0; + SET @moonID = LAST_INSERT_ID(); + UPDATE ".PLANETS." SET + id_luna = @moonID + WHERE + id = ".$MoonPlanet['id'].";"); -?> \ No newline at end of file + return true; +} diff --git a/includes/functions/CreateOnePlanetRecord.php b/includes/functions/CreateOnePlanetRecord.php index df79d6d..8eb02fc 100644 --- a/includes/functions/CreateOnePlanetRecord.php +++ b/includes/functions/CreateOnePlanetRecord.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kr�pke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,30 +18,28 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kr�pke + * @copyright 2012 Jan Kr�pke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ function CreateOnePlanetRecord($Galaxy, $System, $Position, $Universe, $PlanetOwnerID, $PlanetName = '', $HomeWorld = false, $AuthLevel = 0) { - global $LNG, $db; + global $LNG; - $CONF = getConfig($Universe); - - if ($CONF['max_galaxy'] < $Galaxy || 1 > $Galaxy) { + $CONF = Config::getAll(NULL, $Universe); + if (Config::get('max_galaxy') < $Galaxy || 1 > $Galaxy) { throw new Exception("Access denied for CreateOnePlanetRecord.php.
Try to create a planet at position:".$Galaxy.":".$System.":".$Position); } - if ($CONF['max_system'] < $System || 1 > $System) { + if (Config::get('max_system') < $System || 1 > $System) { throw new Exception("Access denied for CreateOnePlanetRecord.php.
Try to create a planet at position:".$Galaxy.":".$System.":".$Position); } - if ($CONF['max_planets'] < $Position || 1 > $Position) { + if (Config::get('max_planets') < $Position || 1 > $Position) { throw new Exception("Access denied for CreateOnePlanetRecord.php.
Try to create a planet at position:".$Galaxy.":".$System.":".$Position); } @@ -49,41 +47,37 @@ function CreateOnePlanetRecord($Galaxy, $System, $Position, $Universe, $PlanetOw return false; } - $FieldFactor = $CONF['planet_factor']; + $FieldFactor = Config::get('planet_factor'); require(ROOT_PATH.'includes/PlanetData.php'); - $Pos = ceil($Position / ($CONF['max_planets'] / count($PlanetData))); + $Pos = ceil($Position / (Config::get('max_planets') / count($PlanetData))); $TMax = $PlanetData[$Pos]['temp']; $TMin = $TMax - 40; - $Fields = $PlanetData[$Pos]['fields'] * $CONF['planet_factor']; + $Fields = $PlanetData[$Pos]['fields'] * Config::get('planet_factor'); $Types = array_keys($PlanetData[$Pos]['image']); $Type = $Types[array_rand($Types)]; $Class = $Type.'planet'.($PlanetData[$Pos]['image'][$Type] < 10 ? '0' : '').$PlanetData[$Pos]['image'][$Type]; + $Name = !empty($PlanetName) ? $GLOBALS['DATABASE']->sql_escape($PlanetName) : $LNG['type_planet'][1]; - $SQL = "INSERT INTO ".PLANETS." SET "; + $GLOBALS['DATABASE']->query("INSERT INTO ".PLANETS." SET + name = '".$Name."', + universe = ".$Universe.", + id_owner = ".$PlanetOwnerID.", + galaxy = ".$Galaxy.", + system = ".$System.", + planet = ".$Position.", + last_update = ".TIMESTAMP.", + planet_type = '1', + image = '".$Class."', + diameter = ".floor(1000 * sqrt($Fields)).", + field_max = ".(($HomeWorld) ? Config::get('initial_fields') : floor($Fields)).", + temp_min = ".$TMin.", + temp_max = ".$TMax.", + metal = ".Config::get('metal_start').", + metal_perhour = ".Config::get('metal_basic_income').", + crystal = ".Config::get('crystal_start').", + crystal_perhour = ".Config::get('crystal_basic_income').", + deuterium = ".Config::get('deuterium_start').", + deuterium_perhour = ".Config::get('deuterium_basic_income').";"); - if(!empty($PlanetName)) - $SQL .= "`name` = '".$db->sql_escape($PlanetName)."', "; - - $SQL .= "`universe` = '".$Universe."', "; - $SQL .= "`id_owner` = '".$PlanetOwnerID."', "; - $SQL .= "`galaxy` = '".$Galaxy."', "; - $SQL .= "`system` = '".$System."', "; - $SQL .= "`planet` = '".$Position."', "; - $SQL .= "`last_update` = '".TIMESTAMP."', "; - $SQL .= "`planet_type` = '1', "; - $SQL .= "`image` = '".$Class."', "; - $SQL .= "`diameter` = '".floor(1000 * sqrt($Fields))."', "; - $SQL .= "`field_max` = '".(($HomeWorld) ? $CONF['initial_fields'] : floor($Fields))."', "; - $SQL .= "`temp_min` = '".$TMin."', "; - $SQL .= "`temp_max` = '".$TMax."', "; - $SQL .= "`metal` = '".$CONF['metal_start']."', "; - $SQL .= "`metal_perhour` = '".$CONF['metal_basic_income']."', "; - $SQL .= "`crystal` = '".$CONF['crystal_start']."', "; - $SQL .= "`crystal_perhour` = '".$CONF['crystal_basic_income']."', "; - $SQL .= "`deuterium` = '".$CONF['deuterium_start']."', "; - $SQL .= "`deuterium_perhour` = '".$CONF['deuterium_basic_income']."';"; - - $db->query($SQL); - return $db->GetInsertID(); -} -?> \ No newline at end of file + return $GLOBALS['DATABASE']->GetInsertID(); +} \ No newline at end of file diff --git a/includes/functions/DeleteSelectedUser.php b/includes/functions/DeleteSelectedUser.php index 29f526e..36273cc 100644 --- a/includes/functions/DeleteSelectedUser.php +++ b/includes/functions/DeleteSelectedUser.php @@ -2,7 +2,7 @@ /** * 2Moons - * Copyright (C) 2011 Slaver + * Copyright (C) 2012 Jan Kr�pke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,92 +18,83 @@ * along with this program. If not, see . * * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) + * @author Jan Kr�pke + * @copyright 2012 Jan Kr�pke * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) + * @version 1.7.0 (2013-01-17) * @info $Id$ - * @link http://code.google.com/p/2moons/ + * @link http://2moons.cc/ */ -function DeleteSelectedUser($UserID) +require_once(ROOT_PATH.'includes/classes/class.FleetFunctions.php'); + +function DeleteSelectedUser($userID) { global $db ,$CONF; - if(ROOT_USER == $UserId) + if(ROOT_USER == $userID) { return false; - - $TheUser = $db->uniquequery("SELECT universe, ally_id FROM ".USERS." WHERE `id` = '".$UserID."';"); + } + + $userData = $GLOBALS['DATABASE']->getFirstRow("SELECT universe, ally_id FROM ".USERS." WHERE id = '".$userID."';"); $SQL = ""; - if ($TheUser['ally_id'] != 0 ) + if ($userData['ally_id'] != 0) { - $TheAlly = $db->uniquequery("SELECT ally_members FROM ".ALLIANCE." WHERE `id` = '".$TheUser['ally_id']."';"); - $TheAlly['ally_members'] -= 1; + $memberCount = $GLOBALS['DATABASE']->getFirstCell("SELECT ally_members FROM ".ALLIANCE." WHERE id = ".$userData['ally_id'].";"); - if ($TheAlly['ally_members'] > 0) + if ($memberCount >= 2) { - $SQL .= "UPDATE ".ALLIANCE." SET `ally_members` = '".$TheAlly['ally_members']."' WHERE `id` = '".$TheUser['ally_id']."';"; + $SQL .= "UPDATE ".ALLIANCE." SET ally_members = ally_members - 1 WHERE id = ".$userData['ally_id'].";"; } else { - $SQL .= "DELETE FROM ".ALLIANCE." WHERE `id` = '" . $TheUser['ally_id'] . "';"; - $SQL .= "DELETE FROM ".STATPOINTS." WHERE `stat_type` = '2' AND `id_owner` = '".$TheUser['ally_id']."';"; + $SQL .= "DELETE FROM ".ALLIANCE." WHERE id = ".$userData['ally_id'].";"; + $SQL .= "DELETE FROM ".STATPOINTS." WHERE stat_type = '2' AND id_owner = ".$userID.";"; + $SQL .= "UPDATE ".STATPOINTS." SET id_ally = 0 WHERE id_ally = ".$userData['ally_id'].";"; } } - - $SQL .= "DELETE FROM ".BUDDY." WHERE `owner` = ".$UserID." OR `sender` = ".$UserID.";"; - $SQL .= "DELETE FROM ".FLEETS." WHERE `fleet_owner` = ".$UserID.";"; - $SQL .= "DELETE FROM ".MESSAGES." WHERE `message_owner` = ".$UserID.";"; - $SQL .= "DELETE FROM ".NOTES." WHERE `owner` = ".$UserID.";"; - $SQL .= "DELETE FROM ".PLANETS." WHERE `id_owner` = ".$UserID.";"; - $SQL .= "DELETE FROM ".USERS." WHERE `id` = ".$UserID.";"; - $SQL .= "DELETE FROM ".STATPOINTS." WHERE `stat_type` = '1' AND `id_owner` = ".$UserID.";"; - $db->multi_query($SQL); - $SQL = $db->query("SELECT fleet_id FROM ".FLEETS." WHERE `fleet_target_owner` = '".$UserID."';"); - while($FleetID = $db->fetch_array($SQL)) { - SendFleetBack($UserID, $FleetID); + $SQL .= "DELETE FROM ".ALLIANCE_REQUEST." WHERE userID = ".$userID.";"; + $SQL .= "DELETE FROM ".BUDDY." WHERE owner = ".$userID." OR sender = ".$userID.";"; + $SQL .= "DELETE FROM ".FLEETS." WHERE fleet_owner = ".$userID.";"; + $SQL .= "DELETE FROM ".MESSAGES." WHERE message_owner = ".$userID.";"; + $SQL .= "DELETE FROM ".NOTES." WHERE owner = ".$userID.";"; + $SQL .= "DELETE FROM ".PLANETS." WHERE id_owner = ".$userID.";"; + $SQL .= "DELETE FROM ".USERS." WHERE id = ".$userID.";"; + $SQL .= "DELETE FROM ".STATPOINTS." WHERE stat_type = '1' AND id_owner = ".$userID.";"; + $GLOBALS['DATABASE']->multi_query($SQL); + + $fleetData = $GLOBALS['DATABASE']->query("SELECT fleet_id FROM ".FLEETS." WHERE fleet_target_owner = ".$userID.";"); + + while($FleetID = $GLOBALS['DATABASE']->fetch_array($fleetData)) { + FleetFunctions::SendFleetBack($userID, $FleetID['fleet_id']); } - update_config(array('users_amount' => $CONF['users_amount'] - 1), $TheUser['universe']); + + $GLOBALS['DATABASE']->free_result($fleetData); + + Config::update(array('users_amount' => Config::get('users_amount') - 1), $userData['universe']); } -function SendFleetBack($CurrentUser, $FleetID) +function DeleteSelectedPlanet($planetID) { - global $db; - - $FleetRow = $db->uniquequery("SELECT `start_time`, `fleet_mission`, `fleet_group`, `fleet_owner`, `fleet_mess` FROM ".FLEETS." WHERE `fleet_id` = '". $FleetID ."';"); - if ($FleetRow['fleet_owner'] != $CurrentUser || $FleetRow['fleet_mess'] == 1) - return; - - $where = 'fleet_id'; - - if($FleetRow['fleet_mission'] == 1 && $FleetRow['fleet_group'] > 0) - { - $Aks = $db->uniquequery("SELECT teilnehmer FROM ".AKS." WHERE id = '". $FleetRow['fleet_group'] ."';"); - - if($Aks['teilnehmer'] == $FleetRow['fleet_owner']) - { - $db->query("DELETE FROM ".AKS." WHERE id ='". $FleetRow['fleet_group'] ."';"); - $FleetID = $FleetRow['fleet_group']; - $where = 'fleet_group'; - } + $planetData = $GLOBALS['DATABASE']->getFirstRow("SELECT planet_type FROM ".PLANETS." WHERE id = ".$planetID." AND id NOT IN (SELECT id_planet FROM ".USERS.");"); + + if(empty($planetData)) { + return false; } - $db->query("UPDATE ".FLEETS." SET `fleet_group` = '0', `start_time` = '".TIMESTAMP."', `fleet_end_stay` = '".TIMESTAMP."', `fleet_end_time` = '".((TIMESTAMP - $FleetRow['start_time']) + TIMESTAMP)."', `fleet_mess` = '1' WHERE `".$where."` = '".$FleetID."';"); -} - -function DeleteSelectedPlanet ($ID) -{ - global $db; - - $QueryPlanet = $db->uniquequery("SELECT universe,galaxy,planet,system,planet_type FROM ".PLANETS." WHERE id = '".$ID."';"); - - if ($QueryPlanet['planet_type'] == '3') - $db->multi_query("DELETE FROM ".PLANETS." WHERE id = '".$ID."';UPDATE ".PLANETS." SET id_luna = '0' WHERE id_luna = '".$ID."';"); - else - $db->query("DELETE FROM ".PLANETS." WHERE universe = '".$QueryPlanet['universe']."' AND galaxy = '".$QueryPlanet['galaxy']."' AND system = '".$QueryPlanet['system']."' AND planet = '".$QueryPlanet['planet']."';"); + $fleetData = $GLOBALS['DATABASE']->query("SELECT fleet_id FROM ".FLEETS." WHERE fleet_end_id = ".$planetID.";"); + + while($FleetID = $GLOBALS['DATABASE']->fetch_array($fleetData)) { + FleetFunctions::SendFleetBack($$planetID, $FleetID['fleet_id']); + } + + $GLOBALS['DATABASE']->free_result($fleetData); + + if ($planetData['planet_type'] == 3) { + $GLOBALS['DATABASE']->multi_query("DELETE FROM ".PLANETS." WHERE id = ".$planetID.";UPDATE ".PLANETS." SET id_luna = 0 WHERE id_luna = ".$planetID.";"); + } else { + $GLOBALS['DATABASE']->query("DELETE FROM ".PLANETS." WHERE id = ".$planetID." OR id_luna = ".$planetID.";"); + } } - -?> \ No newline at end of file diff --git a/includes/functions/GetBuildingPrice.php b/includes/functions/GetBuildingPrice.php deleted file mode 100644 index 7b0a395..0000000 --- a/includes/functions/GetBuildingPrice.php +++ /dev/null @@ -1,50 +0,0 @@ -. - * - * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) - * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) - * @info $Id$ - * @link http://code.google.com/p/2moons/ - */ - -if(!defined('INSIDE')) die('Hacking attempt!'); - - function GetBuildingPrice ($CurrentUser, $CurrentPlanet, $Element, $Incremental = true, $ForDestroy = false) - { - global $pricelist, $resource; - - if ($Incremental) - $level = (isset($CurrentPlanet[$resource[$Element]])) ? $CurrentPlanet[$resource[$Element]] : $CurrentUser[$resource[$Element]]; - - $array = array('metal', 'crystal', 'deuterium', 'darkmatter', 'energy_max'); - foreach ($array as $ResType) - { - $cost[$ResType] = $Incremental ? floor($pricelist[$Element][$ResType] * pow($pricelist[$Element]['factor'], $level)) : floor($pricelist[$Element][$ResType]); - - if ($ForDestroy == true) - $cost[$ResType] /= 2; - } - - return $cost; - } -?> \ No newline at end of file diff --git a/includes/functions/GetBuildingTime.php b/includes/functions/GetBuildingTime.php deleted file mode 100644 index 3afd725..0000000 --- a/includes/functions/GetBuildingTime.php +++ /dev/null @@ -1,71 +0,0 @@ -. - * - * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) - * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) - * @info $Id$ - * @link http://code.google.com/p/2moons/ - */ - -if(!defined('INSIDE')) die('Hacking attempt!'); - - function GetBuildingTime ($USER, $PLANET, $Element, $Destroy = false) - { - global $pricelist, $resource, $reslist, $requeriments; - $CONF = getConfig($USER['universe']); - $level = isset($PLANET[$resource[$Element]]) ? $PLANET[$resource[$Element]] : $USER[$resource[$Element]]; - - $Cost = floor($pricelist[$Element]['metal'] * pow($pricelist[$Element]['factor'], $level)) + floor($pricelist[$Element]['crystal'] * pow($pricelist[$Element]['factor'], $level)); - - if (in_array($Element, $reslist['build'])) - $time = $Cost / ($CONF['game_speed'] * (1 + $PLANET[$resource[14]])) * pow(0.5, $PLANET[$resource[15]]) * $USER['factor']['bulidspeed']; - elseif (in_array($Element, $reslist['fleet'])) - $time = $Cost / ($CONF['game_speed'] * (1 + $PLANET[$resource[21]])) * pow(0.5, $PLANET[$resource[15]]) * $USER['factor']['fleetspeed']; - elseif (in_array($Element, $reslist['defense'])) - $time = $Cost / ($CONF['game_speed'] * (1 + $PLANET[$resource[21]])) * pow(0.5, $PLANET[$resource[15]]) * $USER['factor']['defspeed']; - elseif (in_array($Element, $reslist['tech'])) - { - if(is_array($PLANET[$resource[31].'_inter'])) - { - $Level = 0; - foreach($PLANET[$resource[31].'_inter'] as $Levels) - { - if($Levels >= $requeriments[$Element][31]) - $Level += $Levels; - } - } - else - $Level = $PLANET[$resource[31]]; - - $time = $Cost / (1000 * (1 + $Level)) / ($CONF['game_speed'] / 2500) * pow(1 - $CONF['factor_university'] / 100, $PLANET[$resource[6]]) * $USER['factor']['techspeed']; - } - - if(!$Destroy) - $time = floor($time * 3600); - else - $time = floor($time * 1300); - - return max($time, $CONF['min_build_time']); - } - -?> \ No newline at end of file diff --git a/includes/functions/GetElementPrice.php b/includes/functions/GetElementPrice.php deleted file mode 100644 index 14ef7f6..0000000 --- a/includes/functions/GetElementPrice.php +++ /dev/null @@ -1,54 +0,0 @@ -. - * - * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) - * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) - * @info $Id$ - * @link http://code.google.com/p/2moons/ - */ - -function GetElementPrice ($USER, $PLANET, $Element, $USERfactor = true) { - global $pricelist, $resource, $LNG; - if ($USERfactor) - $level = (isset($PLANET[$resource[$Element]])) ? $PLANET[$resource[$Element]] : $USER[$resource[$Element]]; - - $array = array( - 'metal' => $LNG['Metal'], - 'crystal' => $LNG['Crystal'], - 'deuterium' => $LNG['Deuterium'], - 'energy_max' => $LNG['Energy'], - 'darkmatter' => $LNG['Darkmatter'], - ); - $text = ""; - foreach ($array as $ResType => $ResTitle) - { - if ($pricelist[$Element][$ResType] != 0) - { - $text .= $ResTitle . ": "; - $cost = $USERfactor ? floor($pricelist[$Element][$ResType] * pow($pricelist[$Element]['factor'], $level)) : floor($pricelist[$Element][$ResType]); - $text .= (isset($PLANET[$ResType]) && $cost > $PLANET[$ResType]) || (isset($USER[$ResType]) && $cost > $USER[$ResType]) ? "" . pretty_number($cost) . " " : "" . pretty_number($cost) . " "; - } - } - return $text; -} -?> \ No newline at end of file diff --git a/includes/functions/IsElementBuyable.php b/includes/functions/IsElementBuyable.php deleted file mode 100644 index b54ad66..0000000 --- a/includes/functions/IsElementBuyable.php +++ /dev/null @@ -1,62 +0,0 @@ -. - * - * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) - * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) - * @info $Id$ - * @link http://code.google.com/p/2moons/ - */ - -if(!defined('INSIDE')) die('Hacking attempt!'); - - function IsElementBuyable ($USER, $PLANET, $Element, $Incremental = true, $ForDestroy = false) - { - global $pricelist, $resource; - - include_once(ROOT_PATH . 'includes/functions/IsVacationMode.php'); - - if (IsVacationMode($USER)) - return false; - - if ($Incremental) - $level = isset($PLANET[$resource[$Element]]) ? $PLANET[$resource[$Element]] : $USER[$resource[$Element]]; - - $array = array('metal', 'crystal', 'deuterium', 'energy_max', 'darkmatter'); - - foreach ($array as $ResType) - { - if (empty($pricelist[$Element][$ResType])) - continue; - - $cost[$ResType] = $Incremental ? floor($pricelist[$Element][$ResType] * pow($pricelist[$Element]['factor'], $level)) : floor($pricelist[$Element][$ResType]); - - if ($ForDestroy) - $cost[$ResType] = floor($cost[$ResType] / 2); - - if ((isset($PLANET[$ResType]) && $cost[$ResType] > $PLANET[$ResType]) || (isset($USER[$ResType]) && $cost[$ResType] > $USER[$ResType])) - return false; - } - return true; - } - -?> \ No newline at end of file diff --git a/includes/functions/IsTechnologieAccessible.php b/includes/functions/IsTechnologieAccessible.php deleted file mode 100644 index 7e3976c..0000000 --- a/includes/functions/IsTechnologieAccessible.php +++ /dev/null @@ -1,46 +0,0 @@ -. - * - * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) - * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.6.1 (2011-11-19) - * @info $Id$ - * @link http://code.google.com/p/2moons/ - */ - -if(!defined('INSIDE')) die('Hacking attempt!'); - - function IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $Element) - { - global $requeriments, $resource, $reslist; - - if(!isset($requeriments[$Element])) - return true; - - foreach($requeriments[$Element] as $ReqElement => $EleLevel) - { - if ((isset($CurrentPlanet[$resource[$ReqElement]]) && $CurrentPlanet[$resource[$ReqElement]] < $EleLevel) || (isset($CurrentUser[$resource[$ReqElement]]) && $CurrentUser[$resource[$ReqElement]] < $EleLevel)) - return false; - } - return true; - } -?> \ No newline at end of file diff --git a/includes/functions/mvc/mvc_2Moons.php b/includes/functions/mvc/mvc_2Moons.php deleted file mode 100644 index 2940e63..0000000 --- a/includes/functions/mvc/mvc_2Moons.php +++ /dev/null @@ -1,13 +0,0 @@ - 'Slaver', - 'title' => '2Moons', - 'tag' => 'moons_update', - 'version' => '1.3', - 'link' => 'http://2moons.cc/', - 'update' => 'http://2moons.cc/update.xml', - 'description' => array('de' => 'Basis', 'en' => 'Basic', 'ru' => 'Основной', 'pt' => 'Básico'), -); - -?> \ No newline at end of file diff --git a/includes/libs/FirePHP/FirePHP.class.php b/includes/libs/FirePHP/FirePHP.class.php deleted file mode 100644 index 67ef84f..0000000 --- a/includes/libs/FirePHP/FirePHP.class.php +++ /dev/null @@ -1,1784 +0,0 @@ - - * @license http://www.opensource.org/licenses/bsd-license.php - * @package FirePHPCore - */ - -/** - * @see http://code.google.com/p/firephp/issues/detail?id=112 - */ -if (!defined('E_STRICT')) { - define('E_STRICT', 2048); -} -if (!defined('E_RECOVERABLE_ERROR')) { - define('E_RECOVERABLE_ERROR', 4096); -} -if (!defined('E_DEPRECATED')) { - define('E_DEPRECATED', 8192); -} -if (!defined('E_USER_DEPRECATED')) { - define('E_USER_DEPRECATED', 16384); -} - -/** - * Sends the given data to the FirePHP Firefox Extension. - * The data can be displayed in the Firebug Console or in the - * "Server" request tab. - * - * For more information see: http://www.firephp.org/ - * - * @copyright Copyright (C) 2007-2009 Christoph Dorn - * @author Christoph Dorn - * @license http://www.opensource.org/licenses/bsd-license.php - * @package FirePHPCore - */ -class FirePHP { - - /** - * FirePHP version - * - * @var string - */ - const VERSION = '0.3'; // @pinf replace '0.3' with '%%package.version%%' - - /** - * Firebug LOG level - * - * Logs a message to firebug console. - * - * @var string - */ - const LOG = 'LOG'; - - /** - * Firebug INFO level - * - * Logs a message to firebug console and displays an info icon before the message. - * - * @var string - */ - const INFO = 'INFO'; - - /** - * Firebug WARN level - * - * Logs a message to firebug console, displays an warning icon before the message and colors the line turquoise. - * - * @var string - */ - const WARN = 'WARN'; - - /** - * Firebug ERROR level - * - * Logs a message to firebug console, displays an error icon before the message and colors the line yellow. Also increments the firebug error count. - * - * @var string - */ - const ERROR = 'ERROR'; - - /** - * Dumps a variable to firebug's server panel - * - * @var string - */ - const DUMP = 'DUMP'; - - /** - * Displays a stack trace in firebug console - * - * @var string - */ - const TRACE = 'TRACE'; - - /** - * Displays an exception in firebug console - * - * Increments the firebug error count. - * - * @var string - */ - const EXCEPTION = 'EXCEPTION'; - - /** - * Displays an table in firebug console - * - * @var string - */ - const TABLE = 'TABLE'; - - /** - * Starts a group in firebug console - * - * @var string - */ - const GROUP_START = 'GROUP_START'; - - /** - * Ends a group in firebug console - * - * @var string - */ - const GROUP_END = 'GROUP_END'; - - /** - * Singleton instance of FirePHP - * - * @var FirePHP - */ - protected static $instance = null; - - /** - * Flag whether we are logging from within the exception handler - * - * @var boolean - */ - protected $inExceptionHandler = false; - - /** - * Flag whether to throw PHP errors that have been converted to ErrorExceptions - * - * @var boolean - */ - protected $throwErrorExceptions = true; - - /** - * Flag whether to convert PHP assertion errors to Exceptions - * - * @var boolean - */ - protected $convertAssertionErrorsToExceptions = true; - - /** - * Flag whether to throw PHP assertion errors that have been converted to Exceptions - * - * @var boolean - */ - protected $throwAssertionExceptions = false; - - /** - * Wildfire protocol message index - * - * @var int - */ - protected $messageIndex = 1; - - /** - * Options for the library - * - * @var array - */ - protected $options = array('maxDepth' => 10, - 'maxObjectDepth' => 5, - 'maxArrayDepth' => 5, - 'useNativeJsonEncode' => true, - 'includeLineNumbers' => true); - - /** - * Filters used to exclude object members when encoding - * - * @var array - */ - protected $objectFilters = array( - 'firephp' => array('objectStack', 'instance', 'json_objectStack'), - 'firephp_test_class' => array('objectStack', 'instance', 'json_objectStack') - ); - - /** - * A stack of objects used to detect recursion during object encoding - * - * @var object - */ - protected $objectStack = array(); - - /** - * Flag to enable/disable logging - * - * @var boolean - */ - protected $enabled = true; - - /** - * The insight console to log to if applicable - * - * @var object - */ - protected $logToInsightConsole = null; - - /** - * When the object gets serialized only include specific object members. - * - * @return array - */ - public function __sleep() - { - return array('options','objectFilters','enabled'); - } - - /** - * Gets singleton instance of FirePHP - * - * @param boolean $AutoCreate - * @return FirePHP - */ - public static function getInstance($AutoCreate = false) - { - if ($AutoCreate===true && !self::$instance) { - self::init(); - } - return self::$instance; - } - - /** - * Creates FirePHP object and stores it for singleton access - * - * @return FirePHP - */ - public static function init() - { - return self::setInstance(new self()); - } - - /** - * Set the instance of the FirePHP singleton - * - * @param FirePHP $instance The FirePHP object instance - * @return FirePHP - */ - public static function setInstance($instance) - { - return self::$instance = $instance; - } - - /** - * Set an Insight console to direct all logging calls to - * - * @param object $console The console object to log to - * @return void - */ - public function setLogToInsightConsole($console) - { - if(is_string($console)) { - if(get_class($this)!='FirePHP_Insight' && !is_subclass_of($this, 'FirePHP_Insight')) { - throw new Exception('FirePHP instance not an instance or subclass of FirePHP_Insight!'); - } - $this->logToInsightConsole = $this->to('request')->console($console); - } else { - $this->logToInsightConsole = $console; - } - } - - /** - * Enable and disable logging to Firebug - * - * @param boolean $Enabled TRUE to enable, FALSE to disable - * @return void - */ - public function setEnabled($Enabled) - { - $this->enabled = $Enabled; - } - - /** - * Check if logging is enabled - * - * @return boolean TRUE if enabled - */ - public function getEnabled() - { - return $this->enabled; - } - - /** - * Specify a filter to be used when encoding an object - * - * Filters are used to exclude object members. - * - * @param string $Class The class name of the object - * @param array $Filter An array of members to exclude - * @return void - */ - public function setObjectFilter($Class, $Filter) - { - $this->objectFilters[strtolower($Class)] = $Filter; - } - - /** - * Set some options for the library - * - * Options: - * - maxDepth: The maximum depth to traverse (default: 10) - * - maxObjectDepth: The maximum depth to traverse objects (default: 5) - * - maxArrayDepth: The maximum depth to traverse arrays (default: 5) - * - useNativeJsonEncode: If true will use json_encode() (default: true) - * - includeLineNumbers: If true will include line numbers and filenames (default: true) - * - * @param array $Options The options to be set - * @return void - */ - public function setOptions($Options) - { - $this->options = array_merge($this->options,$Options); - } - - /** - * Get options from the library - * - * @return array The currently set options - */ - public function getOptions() - { - return $this->options; - } - - /** - * Set an option for the library - * - * @param string $Name - * @param mixed $Value - * @throws Exception - * @return void - */ - public function setOption($Name, $Value) - { - if (!isset($this->options[$Name])) { - throw $this->newException('Unknown option: ' . $Name); - } - $this->options[$Name] = $Value; - } - - /** - * Get an option from the library - * - * @param string $Name - * @throws Exception - * @return mixed - */ - public function getOption($Name) - { - if (!isset($this->options[$Name])) { - throw $this->newException('Unknown option: ' . $Name); - } - return $this->options[$Name]; - } - - /** - * Register FirePHP as your error handler - * - * Will throw exceptions for each php error. - * - * @return mixed Returns a string containing the previously defined error handler (if any) - */ - public function registerErrorHandler($throwErrorExceptions = false) - { - //NOTE: The following errors will not be caught by this error handler: - // E_ERROR, E_PARSE, E_CORE_ERROR, - // E_CORE_WARNING, E_COMPILE_ERROR, - // E_COMPILE_WARNING, E_STRICT - - $this->throwErrorExceptions = $throwErrorExceptions; - - return set_error_handler(array($this,'errorHandler')); - } - - /** - * FirePHP's error handler - * - * Throws exception for each php error that will occur. - * - * @param int $errno - * @param string $errstr - * @param string $errfile - * @param int $errline - * @param array $errcontext - */ - public function errorHandler($errno, $errstr, $errfile, $errline, $errcontext) - { - // Don't throw exception if error reporting is switched off - if (error_reporting() == 0) { - return; - } - // Only throw exceptions for errors we are asking for - if (error_reporting() & $errno) { - - $exception = new ErrorException($errstr, 0, $errno, $errfile, $errline); - if ($this->throwErrorExceptions) { - throw $exception; - } else { - $this->fb($exception); - } - } - } - - /** - * Register FirePHP as your exception handler - * - * @return mixed Returns the name of the previously defined exception handler, - * or NULL on error. - * If no previous handler was defined, NULL is also returned. - */ - public function registerExceptionHandler() - { - return set_exception_handler(array($this,'exceptionHandler')); - } - - /** - * FirePHP's exception handler - * - * Logs all exceptions to your firebug console and then stops the script. - * - * @param Exception $Exception - * @throws Exception - */ - function exceptionHandler($Exception) - { - - $this->inExceptionHandler = true; - - header('HTTP/1.1 500 Internal Server Error'); - - try { - $this->fb($Exception); - } catch (Exception $e) { - echo 'We had an exception: ' . $e; - } - $this->inExceptionHandler = false; - } - - /** - * Register FirePHP driver as your assert callback - * - * @param boolean $convertAssertionErrorsToExceptions - * @param boolean $throwAssertionExceptions - * @return mixed Returns the original setting or FALSE on errors - */ - public function registerAssertionHandler($convertAssertionErrorsToExceptions = true, $throwAssertionExceptions = false) - { - $this->convertAssertionErrorsToExceptions = $convertAssertionErrorsToExceptions; - $this->throwAssertionExceptions = $throwAssertionExceptions; - - if ($throwAssertionExceptions && !$convertAssertionErrorsToExceptions) { - throw $this->newException('Cannot throw assertion exceptions as assertion errors are not being converted to exceptions!'); - } - - return assert_options(ASSERT_CALLBACK, array($this, 'assertionHandler')); - } - - /** - * FirePHP's assertion handler - * - * Logs all assertions to your firebug console and then stops the script. - * - * @param string $file File source of assertion - * @param int $line Line source of assertion - * @param mixed $code Assertion code - */ - public function assertionHandler($file, $line, $code) - { - if ($this->convertAssertionErrorsToExceptions) { - - $exception = new ErrorException('Assertion Failed - Code[ '.$code.' ]', 0, null, $file, $line); - - if ($this->throwAssertionExceptions) { - throw $exception; - } else { - $this->fb($exception); - } - - } else { - $this->fb($code, 'Assertion Failed', FirePHP::ERROR, array('File'=>$file,'Line'=>$line)); - } - } - - /** - * Start a group for following messages. - * - * Options: - * Collapsed: [true|false] - * Color: [#RRGGBB|ColorName] - * - * @param string $Name - * @param array $Options OPTIONAL Instructions on how to log the group - * @return true - * @throws Exception - */ - public function group($Name, $Options = null) - { - - if (!$Name) { - throw $this->newException('You must specify a label for the group!'); - } - - if ($Options) { - if (!is_array($Options)) { - throw $this->newException('Options must be defined as an array!'); - } - if (array_key_exists('Collapsed', $Options)) { - $Options['Collapsed'] = ($Options['Collapsed'])?'true':'false'; - } - } - - return $this->fb(null, $Name, FirePHP::GROUP_START, $Options); - } - - /** - * Ends a group you have started before - * - * @return true - * @throws Exception - */ - public function groupEnd() - { - return $this->fb(null, null, FirePHP::GROUP_END); - } - - /** - * Log object with label to firebug console - * - * @see FirePHP::LOG - * @param mixes $Object - * @param string $Label - * @return true - * @throws Exception - */ - public function log($Object, $Label = null, $Options = array()) - { - return $this->fb($Object, $Label, FirePHP::LOG, $Options); - } - - /** - * Log object with label to firebug console - * - * @see FirePHP::INFO - * @param mixes $Object - * @param string $Label - * @return true - * @throws Exception - */ - public function info($Object, $Label = null, $Options = array()) - { - return $this->fb($Object, $Label, FirePHP::INFO, $Options); - } - - /** - * Log object with label to firebug console - * - * @see FirePHP::WARN - * @param mixes $Object - * @param string $Label - * @return true - * @throws Exception - */ - public function warn($Object, $Label = null, $Options = array()) - { - return $this->fb($Object, $Label, FirePHP::WARN, $Options); - } - - /** - * Log object with label to firebug console - * - * @see FirePHP::ERROR - * @param mixes $Object - * @param string $Label - * @return true - * @throws Exception - */ - public function error($Object, $Label = null, $Options = array()) - { - return $this->fb($Object, $Label, FirePHP::ERROR, $Options); - } - - /** - * Dumps key and variable to firebug server panel - * - * @see FirePHP::DUMP - * @param string $Key - * @param mixed $Variable - * @return true - * @throws Exception - */ - public function dump($Key, $Variable, $Options = array()) - { - if (!is_string($Key)) { - throw $this->newException('Key passed to dump() is not a string'); - } - if (strlen($Key)>100) { - throw $this->newException('Key passed to dump() is longer than 100 characters'); - } - if (!preg_match_all('/^[a-zA-Z0-9-_\.:]*$/', $Key, $m)) { - throw $this->newException('Key passed to dump() contains invalid characters [a-zA-Z0-9-_\.:]'); - } - return $this->fb($Variable, $Key, FirePHP::DUMP, $Options); - } - - /** - * Log a trace in the firebug console - * - * @see FirePHP::TRACE - * @param string $Label - * @return true - * @throws Exception - */ - public function trace($Label) - { - return $this->fb($Label, FirePHP::TRACE); - } - - /** - * Log a table in the firebug console - * - * @see FirePHP::TABLE - * @param string $Label - * @param string $Table - * @return true - * @throws Exception - */ - public function table($Label, $Table, $Options = array()) - { - return $this->fb($Table, $Label, FirePHP::TABLE, $Options); - } - - /** - * Insight API wrapper - * - * @see Insight_Helper::to() - */ - public static function to() - { - $instance = self::getInstance(); - if (!method_exists($instance, "_to")) { - throw new Exception("FirePHP::to() implementation not loaded"); - } - $args = func_get_args(); - return call_user_func_array(array($instance, '_to'), $args); - } - - /** - * Insight API wrapper - * - * @see Insight_Helper::plugin() - */ - public static function plugin() - { - $instance = self::getInstance(); - if (!method_exists($instance, "_plugin")) { - throw new Exception("FirePHP::plugin() implementation not loaded"); - } - $args = func_get_args(); - return call_user_func_array(array($instance, '_plugin'), $args); - } - - /** - * Check if FirePHP is installed on client - * - * @return boolean - */ - public function detectClientExtension() - { - // Check if FirePHP is installed on client via User-Agent header - if (@preg_match_all('/\sFirePHP\/([\.\d]*)\s?/si',$this->getUserAgent(),$m) && - version_compare($m[1][0],'0.0.6','>=')) { - return true; - } else - // Check if FirePHP is installed on client via X-FirePHP-Version header - if (@preg_match_all('/^([\.\d]*)$/si',$this->getRequestHeader("X-FirePHP-Version"),$m) && - version_compare($m[1][0],'0.0.6','>=')) { - return true; - } - return false; - } - - /** - * Log varible to Firebug - * - * @see http://www.firephp.org/Wiki/Reference/Fb - * @param mixed $Object The variable to be logged - * @return true Return TRUE if message was added to headers, FALSE otherwise - * @throws Exception - */ - public function fb($Object) - { - if($this instanceof FirePHP_Insight && method_exists($this, '_logUpgradeClientMessage')) { - if(!FirePHP_Insight::$upgradeClientMessageLogged) { // avoid infinite recursion as _logUpgradeClientMessage() logs a message - $this->_logUpgradeClientMessage(); - } - } - - static $insightGroupStack = array(); - - if (!$this->getEnabled()) { - return false; - } - - if ($this->headersSent($filename, $linenum)) { - // If we are logging from within the exception handler we cannot throw another exception - if ($this->inExceptionHandler) { - // Simply echo the error out to the page - echo '
FirePHP ERROR: Headers already sent in '.$filename.' on line '.$linenum.'. Cannot send log data to FirePHP. You must have Output Buffering enabled via ob_start() or output_buffering ini directive.
'; - } else { - throw $this->newException('Headers already sent in '.$filename.' on line '.$linenum.'. Cannot send log data to FirePHP. You must have Output Buffering enabled via ob_start() or output_buffering ini directive.'); - } - } - - $Type = null; - $Label = null; - $Options = array(); - - if (func_num_args()==1) { - } else - if (func_num_args()==2) { - switch(func_get_arg(1)) { - case self::LOG: - case self::INFO: - case self::WARN: - case self::ERROR: - case self::DUMP: - case self::TRACE: - case self::EXCEPTION: - case self::TABLE: - case self::GROUP_START: - case self::GROUP_END: - $Type = func_get_arg(1); - break; - default: - $Label = func_get_arg(1); - break; - } - } else - if (func_num_args()==3) { - $Type = func_get_arg(2); - $Label = func_get_arg(1); - } else - if (func_num_args()==4) { - $Type = func_get_arg(2); - $Label = func_get_arg(1); - $Options = func_get_arg(3); - } else { - throw $this->newException('Wrong number of arguments to fb() function!'); - } - - if($this->logToInsightConsole!==null && (get_class($this)=='FirePHP_Insight' || is_subclass_of($this, 'FirePHP_Insight'))) { - $msg = $this->logToInsightConsole; - if ($Object instanceof Exception) { - $Type = self::EXCEPTION; - } - if($Label && $Type!=self::TABLE && $Type!=self::GROUP_START) { - $msg = $msg->label($Label); - } - switch($Type) { - case self::DUMP: - case self::LOG: - return $msg->log($Object); - case self::INFO: - return $msg->info($Object); - case self::WARN: - return $msg->warn($Object); - case self::ERROR: - return $msg->error($Object); - case self::TRACE: - return $msg->trace($Object); - case self::EXCEPTION: - return $this->plugin('engine')->handleException($Object, $msg); - case self::TABLE: - if (isset($Object[0]) && !is_string($Object[0]) && $Label) { - $Object = array($Label, $Object); - } - return $msg->table($Object[0], array_slice($Object[1],1), $Object[1][0]); - case self::GROUP_START: - $insightGroupStack[] = $msg->group(md5($Label))->open(); - return $msg->log($Label); - case self::GROUP_END: - if(count($insightGroupStack)==0) { - throw new Error('Too many groupEnd() as opposed to group() calls!'); - } - $group = array_pop($insightGroupStack); - return $group->close(); - default: - return $msg->log($Object); - } - } - - if (!$this->detectClientExtension()) { - return false; - } - - $meta = array(); - $skipFinalObjectEncode = false; - - if ($Object instanceof Exception) { - - $meta['file'] = $this->_escapeTraceFile($Object->getFile()); - $meta['line'] = $Object->getLine(); - - $trace = $Object->getTrace(); - if ($Object instanceof ErrorException - && isset($trace[0]['function']) - && $trace[0]['function']=='errorHandler' - && isset($trace[0]['class']) - && $trace[0]['class']=='FirePHP') { - - $severity = false; - switch($Object->getSeverity()) { - case E_WARNING: $severity = 'E_WARNING'; break; - case E_NOTICE: $severity = 'E_NOTICE'; break; - case E_USER_ERROR: $severity = 'E_USER_ERROR'; break; - case E_USER_WARNING: $severity = 'E_USER_WARNING'; break; - case E_USER_NOTICE: $severity = 'E_USER_NOTICE'; break; - case E_STRICT: $severity = 'E_STRICT'; break; - case E_RECOVERABLE_ERROR: $severity = 'E_RECOVERABLE_ERROR'; break; - case E_DEPRECATED: $severity = 'E_DEPRECATED'; break; - case E_USER_DEPRECATED: $severity = 'E_USER_DEPRECATED'; break; - } - - $Object = array('Class'=>get_class($Object), - 'Message'=>$severity.': '.$Object->getMessage(), - 'File'=>$this->_escapeTraceFile($Object->getFile()), - 'Line'=>$Object->getLine(), - 'Type'=>'trigger', - 'Trace'=>$this->_escapeTrace(array_splice($trace,2))); - $skipFinalObjectEncode = true; - } else { - $Object = array('Class'=>get_class($Object), - 'Message'=>$Object->getMessage(), - 'File'=>$this->_escapeTraceFile($Object->getFile()), - 'Line'=>$Object->getLine(), - 'Type'=>'throw', - 'Trace'=>$this->_escapeTrace($trace)); - $skipFinalObjectEncode = true; - } - $Type = self::EXCEPTION; - - } else - if ($Type==self::TRACE) { - - $trace = debug_backtrace(); - if (!$trace) return false; - for( $i=0 ; $i_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php' - || substr($this->_standardizePath($trace[$i]['file']),-29,29)=='FirePHPCore/FirePHP.class.php')) { - /* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */ - } else - if (isset($trace[$i]['class']) - && isset($trace[$i+1]['file']) - && $trace[$i]['class']=='FirePHP' - && substr($this->_standardizePath($trace[$i+1]['file']),-18,18)=='FirePHPCore/fb.php') { - /* Skip fb() */ - } else - if ($trace[$i]['function']=='fb' - || $trace[$i]['function']=='trace' - || $trace[$i]['function']=='send') { - - $Object = array('Class'=>isset($trace[$i]['class'])?$trace[$i]['class']:'', - 'Type'=>isset($trace[$i]['type'])?$trace[$i]['type']:'', - 'Function'=>isset($trace[$i]['function'])?$trace[$i]['function']:'', - 'Message'=>$trace[$i]['args'][0], - 'File'=>isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'', - 'Line'=>isset($trace[$i]['line'])?$trace[$i]['line']:'', - 'Args'=>isset($trace[$i]['args'])?$this->encodeObject($trace[$i]['args']):'', - 'Trace'=>$this->_escapeTrace(array_splice($trace,$i+1))); - - $skipFinalObjectEncode = true; - $meta['file'] = isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):''; - $meta['line'] = isset($trace[$i]['line'])?$trace[$i]['line']:''; - break; - } - } - - } else - if ($Type==self::TABLE) { - - if (isset($Object[0]) && is_string($Object[0])) { - $Object[1] = $this->encodeTable($Object[1]); - } else { - $Object = $this->encodeTable($Object); - } - - $skipFinalObjectEncode = true; - - } else - if ($Type==self::GROUP_START) { - - if (!$Label) { - throw $this->newException('You must specify a label for the group!'); - } - - } else { - if ($Type===null) { - $Type = self::LOG; - } - } - - if ($this->options['includeLineNumbers']) { - if (!isset($meta['file']) || !isset($meta['line'])) { - - $trace = debug_backtrace(); - for( $i=0 ; $trace && $i_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php' - || substr($this->_standardizePath($trace[$i]['file']),-29,29)=='FirePHPCore/FirePHP.class.php')) { - /* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */ - } else - if (isset($trace[$i]['class']) - && isset($trace[$i+1]['file']) - && $trace[$i]['class']=='FirePHP' - && substr($this->_standardizePath($trace[$i+1]['file']),-18,18)=='FirePHPCore/fb.php') { - /* Skip fb() */ - } else - if (isset($trace[$i]['file']) - && substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php') { - /* Skip FB::fb() */ - } else { - $meta['file'] = isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):''; - $meta['line'] = isset($trace[$i]['line'])?$trace[$i]['line']:''; - break; - } - } - } - } else { - unset($meta['file']); - unset($meta['line']); - } - - $this->setHeader('X-Wf-Protocol-1','http://meta.wildfirehq.org/Protocol/JsonStream/0.2'); - $this->setHeader('X-Wf-1-Plugin-1','http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/'.self::VERSION); - - $structure_index = 1; - if ($Type==self::DUMP) { - $structure_index = 2; - $this->setHeader('X-Wf-1-Structure-2','http://meta.firephp.org/Wildfire/Structure/FirePHP/Dump/0.1'); - } else { - $this->setHeader('X-Wf-1-Structure-1','http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1'); - } - - if ($Type==self::DUMP) { - $msg = '{"'.$Label.'":'.$this->jsonEncode($Object, $skipFinalObjectEncode).'}'; - } else { - $msg_meta = $Options; - $msg_meta['Type'] = $Type; - if ($Label!==null) { - $msg_meta['Label'] = $Label; - } - if (isset($meta['file']) && !isset($msg_meta['File'])) { - $msg_meta['File'] = $meta['file']; - } - if (isset($meta['line']) && !isset($msg_meta['Line'])) { - $msg_meta['Line'] = $meta['line']; - } - $msg = '['.$this->jsonEncode($msg_meta).','.$this->jsonEncode($Object, $skipFinalObjectEncode).']'; - } - - $parts = explode("\n",chunk_split($msg, 5000, "\n")); - - for( $i=0 ; $i2) { - // Message needs to be split into multiple parts - $this->setHeader('X-Wf-1-'.$structure_index.'-'.'1-'.$this->messageIndex, - (($i==0)?strlen($msg):'') - . '|' . $part . '|' - . (($isetHeader('X-Wf-1-'.$structure_index.'-'.'1-'.$this->messageIndex, - strlen($part) . '|' . $part . '|'); - } - - $this->messageIndex++; - - if ($this->messageIndex > 99999) { - throw $this->newException('Maximum number (99,999) of messages reached!'); - } - } - } - - $this->setHeader('X-Wf-1-Index',$this->messageIndex-1); - - return true; - } - - /** - * Standardizes path for windows systems. - * - * @param string $Path - * @return string - */ - protected function _standardizePath($Path) - { - return preg_replace('/\\\\+/','/',$Path); - } - - /** - * Escape trace path for windows systems - * - * @param array $Trace - * @return array - */ - protected function _escapeTrace($Trace) - { - if (!$Trace) return $Trace; - for( $i=0 ; $i_escapeTraceFile($Trace[$i]['file']); - } - if (isset($Trace[$i]['args'])) { - $Trace[$i]['args'] = $this->encodeObject($Trace[$i]['args']); - } - } - return $Trace; - } - - /** - * Escape file information of trace for windows systems - * - * @param string $File - * @return string - */ - protected function _escapeTraceFile($File) - { - /* Check if we have a windows filepath */ - if (strpos($File,'\\')) { - /* First strip down to single \ */ - - $file = preg_replace('/\\\\+/','\\',$File); - - return $file; - } - return $File; - } - - /** - * Check if headers have already been sent - * - * @param string $Filename - * @param integer $Linenum - */ - protected function headersSent(&$Filename, &$Linenum) - { - return headers_sent($Filename, $Linenum); - } - - /** - * Send header - * - * @param string $Name - * @param string $Value - */ - protected function setHeader($Name, $Value) - { - return header($Name.': '.$Value); - } - - /** - * Get user agent - * - * @return string|false - */ - protected function getUserAgent() - { - if (!isset($_SERVER['HTTP_USER_AGENT'])) return false; - return $_SERVER['HTTP_USER_AGENT']; - } - - /** - * Get all request headers - * - * @return array - */ - public static function getAllRequestHeaders() { - static $_cached_headers = false; - if($_cached_headers!==false) { - return $_cached_headers; - } - $headers = array(); - if(function_exists('getallheaders')) { - foreach( getallheaders() as $name => $value ) { - $headers[strtolower($name)] = $value; - } - } else { - foreach($_SERVER as $name => $value) { - if(substr($name, 0, 5) == 'HTTP_') { - $headers[strtolower(str_replace(' ', '-', str_replace('_', ' ', substr($name, 5))))] = $value; - } - } - } - return $_cached_headers = $headers; - } - - /** - * Get a request header - * - * @return string|false - */ - protected function getRequestHeader($Name) - { - $headers = self::getAllRequestHeaders(); - if (isset($headers[strtolower($Name)])) { - return $headers[strtolower($Name)]; - } - return false; - } - - /** - * Returns a new exception - * - * @param string $Message - * @return Exception - */ - protected function newException($Message) - { - return new Exception($Message); - } - - /** - * Encode an object into a JSON string - * - * Uses PHP's jeson_encode() if available - * - * @param object $Object The object to be encoded - * @return string The JSON string - */ - public function jsonEncode($Object, $skipObjectEncode = false) - { - if (!$skipObjectEncode) { - $Object = $this->encodeObject($Object); - } - - if (function_exists('json_encode') - && $this->options['useNativeJsonEncode']!=false) { - - return json_encode($Object); - } else { - return $this->json_encode($Object); - } - } - - /** - * Encodes a table by encoding each row and column with encodeObject() - * - * @param array $Table The table to be encoded - * @return array - */ - protected function encodeTable($Table) - { - - if (!$Table) return $Table; - - $new_table = array(); - foreach($Table as $row) { - - if (is_array($row)) { - $new_row = array(); - - foreach($row as $item) { - $new_row[] = $this->encodeObject($item); - } - - $new_table[] = $new_row; - } - } - - return $new_table; - } - - /** - * Encodes an object including members with - * protected and private visibility - * - * @param Object $Object The object to be encoded - * @param int $Depth The current traversal depth - * @return array All members of the object - */ - protected function encodeObject($Object, $ObjectDepth = 1, $ArrayDepth = 1, $MaxDepth = 1) - { - if ($MaxDepth > $this->options['maxDepth']) { - return '** Max Depth ('.$this->options['maxDepth'].') **'; - } - - $return = array(); - - if (is_resource($Object)) { - - return '** '.(string)$Object.' **'; - - } else - if (is_object($Object)) { - - if ($ObjectDepth > $this->options['maxObjectDepth']) { - return '** Max Object Depth ('.$this->options['maxObjectDepth'].') **'; - } - - foreach ($this->objectStack as $refVal) { - if ($refVal === $Object) { - return '** Recursion ('.get_class($Object).') **'; - } - } - array_push($this->objectStack, $Object); - - $return['__className'] = $class = get_class($Object); - $class_lower = strtolower($class); - - $reflectionClass = new ReflectionClass($class); - $properties = array(); - foreach( $reflectionClass->getProperties() as $property) { - $properties[$property->getName()] = $property; - } - - $members = (array)$Object; - - foreach( $properties as $plain_name => $property ) { - - $name = $raw_name = $plain_name; - if ($property->isStatic()) { - $name = 'static:'.$name; - } - if ($property->isPublic()) { - $name = 'public:'.$name; - } else - if ($property->isPrivate()) { - $name = 'private:'.$name; - $raw_name = "\0".$class."\0".$raw_name; - } else - if ($property->isProtected()) { - $name = 'protected:'.$name; - $raw_name = "\0".'*'."\0".$raw_name; - } - - if (!(isset($this->objectFilters[$class_lower]) - && is_array($this->objectFilters[$class_lower]) - && in_array($plain_name,$this->objectFilters[$class_lower]))) { - - if (array_key_exists($raw_name,$members) - && !$property->isStatic()) { - - $return[$name] = $this->encodeObject($members[$raw_name], $ObjectDepth + 1, 1, $MaxDepth + 1); - - } else { - if (method_exists($property,'setAccessible')) { - $property->setAccessible(true); - $return[$name] = $this->encodeObject($property->getValue($Object), $ObjectDepth + 1, 1, $MaxDepth + 1); - } else - if ($property->isPublic()) { - $return[$name] = $this->encodeObject($property->getValue($Object), $ObjectDepth + 1, 1, $MaxDepth + 1); - } else { - $return[$name] = '** Need PHP 5.3 to get value **'; - } - } - } else { - $return[$name] = '** Excluded by Filter **'; - } - } - - // Include all members that are not defined in the class - // but exist in the object - foreach( $members as $raw_name => $value ) { - - $name = $raw_name; - - if ($name{0} == "\0") { - $parts = explode("\0", $name); - $name = $parts[2]; - } - - $plain_name = $name; - - if (!isset($properties[$name])) { - $name = 'undeclared:'.$name; - - if (!(isset($this->objectFilters[$class_lower]) - && is_array($this->objectFilters[$class_lower]) - && in_array($plain_name,$this->objectFilters[$class_lower]))) { - - $return[$name] = $this->encodeObject($value, $ObjectDepth + 1, 1, $MaxDepth + 1); - } else { - $return[$name] = '** Excluded by Filter **'; - } - } - } - - array_pop($this->objectStack); - - } elseif (is_array($Object)) { - - if ($ArrayDepth > $this->options['maxArrayDepth']) { - return '** Max Array Depth ('.$this->options['maxArrayDepth'].') **'; - } - - foreach ($Object as $key => $val) { - - // Encoding the $GLOBALS PHP array causes an infinite loop - // if the recursion is not reset here as it contains - // a reference to itself. This is the only way I have come up - // with to stop infinite recursion in this case. - if ($key=='GLOBALS' - && is_array($val) - && array_key_exists('GLOBALS',$val)) { - $val['GLOBALS'] = '** Recursion (GLOBALS) **'; - } - - $return[$key] = $this->encodeObject($val, 1, $ArrayDepth + 1, $MaxDepth + 1); - } - } else { - if (self::is_utf8($Object)) { - return $Object; - } else { - return utf8_encode($Object); - } - } - return $return; - } - - /** - * Returns true if $string is valid UTF-8 and false otherwise. - * - * @param mixed $str String to be tested - * @return boolean - */ - protected static function is_utf8($str) - { - if(function_exists('mb_detect_encoding')) { - return (mb_detect_encoding($str) == 'UTF-8'); - } - $c=0; $b=0; - $bits=0; - $len=strlen($str); - for($i=0; $i<$len; $i++){ - $c=ord($str[$i]); - if ($c > 128){ - if (($c >= 254)) return false; - elseif ($c >= 252) $bits=6; - elseif ($c >= 248) $bits=5; - elseif ($c >= 240) $bits=4; - elseif ($c >= 224) $bits=3; - elseif ($c >= 192) $bits=2; - else return false; - if (($i+$bits) > $len) return false; - while($bits > 1){ - $i++; - $b=ord($str[$i]); - if ($b < 128 || $b > 191) return false; - $bits--; - } - } - } - return true; - } - - /** - * Converts to and from JSON format. - * - * JSON (JavaScript Object Notation) is a lightweight data-interchange - * format. It is easy for humans to read and write. It is easy for machines - * to parse and generate. It is based on a subset of the JavaScript - * Programming Language, Standard ECMA-262 3rd Edition - December 1999. - * This feature can also be found in Python. JSON is a text format that is - * completely language independent but uses conventions that are familiar - * to programmers of the C-family of languages, including C, C++, C#, Java, - * JavaScript, Perl, TCL, and many others. These properties make JSON an - * ideal data-interchange language. - * - * This package provides a simple encoder and decoder for JSON notation. It - * is intended for use with client-side Javascript applications that make - * use of HTTPRequest to perform server communication functions - data can - * be encoded into JSON notation for use in a client-side javascript, or - * decoded from incoming Javascript requests. JSON format is native to - * Javascript, and can be directly eval()'ed with no further parsing - * overhead - * - * All strings should be in ASCII or UTF-8 format! - * - * LICENSE: Redistribution and use in source and binary forms, with or - * without modification, are permitted provided that the following - * conditions are met: Redistributions of source code must retain the - * above copyright notice, this list of conditions and the following - * disclaimer. Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN - * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE - * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH - * DAMAGE. - * - * @category - * @package Services_JSON - * @author Michal Migurski - * @author Matt Knapp - * @author Brett Stimmerman - * @author Christoph Dorn - * @copyright 2005 Michal Migurski - * @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $ - * @license http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 - */ - - - /** - * Keep a list of objects as we descend into the array so we can detect recursion. - */ - private $json_objectStack = array(); - - - /** - * convert a string from one UTF-8 char to one UTF-16 char - * - * Normally should be handled by mb_convert_encoding, but - * provides a slower PHP-only method for installations - * that lack the multibye string extension. - * - * @param string $utf8 UTF-8 character - * @return string UTF-16 character - * @access private - */ - private function json_utf82utf16($utf8) - { - // oh please oh please oh please oh please oh please - if (function_exists('mb_convert_encoding')) { - return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8'); - } - - switch(strlen($utf8)) { - case 1: - // this case should never be reached, because we are in ASCII range - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return $utf8; - - case 2: - // return a UTF-16 character from a 2-byte UTF-8 char - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0x07 & (ord($utf8{0}) >> 2)) - . chr((0xC0 & (ord($utf8{0}) << 6)) - | (0x3F & ord($utf8{1}))); - - case 3: - // return a UTF-16 character from a 3-byte UTF-8 char - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr((0xF0 & (ord($utf8{0}) << 4)) - | (0x0F & (ord($utf8{1}) >> 2))) - . chr((0xC0 & (ord($utf8{1}) << 6)) - | (0x7F & ord($utf8{2}))); - } - - // ignoring UTF-32 for now, sorry - return ''; - } - - /** - * encodes an arbitrary variable into JSON format - * - * @param mixed $var any number, boolean, string, array, or object to be encoded. - * see argument 1 to Services_JSON() above for array-parsing behavior. - * if var is a strng, note that encode() always expects it - * to be in ASCII or UTF-8 format! - * - * @return mixed JSON string representation of input var or an error if a problem occurs - * @access public - */ - private function json_encode($var) - { - - if (is_object($var)) { - if (in_array($var,$this->json_objectStack)) { - return '"** Recursion **"'; - } - } - - switch (gettype($var)) { - case 'boolean': - return $var ? 'true' : 'false'; - - case 'NULL': - return 'null'; - - case 'integer': - return (int) $var; - - case 'double': - case 'float': - return (float) $var; - - case 'string': - // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT - $ascii = ''; - $strlen_var = strlen($var); - - /* - * Iterate over every character in the string, - * escaping with a slash or encoding to UTF-8 where necessary - */ - for ($c = 0; $c < $strlen_var; ++$c) { - - $ord_var_c = ord($var{$c}); - - switch (true) { - case $ord_var_c == 0x08: - $ascii .= '\b'; - break; - case $ord_var_c == 0x09: - $ascii .= '\t'; - break; - case $ord_var_c == 0x0A: - $ascii .= '\n'; - break; - case $ord_var_c == 0x0C: - $ascii .= '\f'; - break; - case $ord_var_c == 0x0D: - $ascii .= '\r'; - break; - - case $ord_var_c == 0x22: - case $ord_var_c == 0x2F: - case $ord_var_c == 0x5C: - // double quote, slash, slosh - $ascii .= '\\'.$var{$c}; - break; - - case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): - // characters U-00000000 - U-0000007F (same as ASCII) - $ascii .= $var{$c}; - break; - - case (($ord_var_c & 0xE0) == 0xC0): - // characters U-00000080 - U-000007FF, mask 110XXXXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, ord($var{$c + 1})); - $c += 1; - $utf16 = $this->json_utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xF0) == 0xE0): - // characters U-00000800 - U-0000FFFF, mask 1110XXXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2})); - $c += 2; - $utf16 = $this->json_utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xF8) == 0xF0): - // characters U-00010000 - U-001FFFFF, mask 11110XXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2}), - ord($var{$c + 3})); - $c += 3; - $utf16 = $this->json_utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xFC) == 0xF8): - // characters U-00200000 - U-03FFFFFF, mask 111110XX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2}), - ord($var{$c + 3}), - ord($var{$c + 4})); - $c += 4; - $utf16 = $this->json_utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xFE) == 0xFC): - // characters U-04000000 - U-7FFFFFFF, mask 1111110X - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2}), - ord($var{$c + 3}), - ord($var{$c + 4}), - ord($var{$c + 5})); - $c += 5; - $utf16 = $this->json_utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - } - } - - return '"'.$ascii.'"'; - - case 'array': - /* - * As per JSON spec if any array key is not an integer - * we must treat the the whole array as an object. We - * also try to catch a sparsely populated associative - * array with numeric keys here because some JS engines - * will create an array with empty indexes up to - * max_index which can cause memory issues and because - * the keys, which may be relevant, will be remapped - * otherwise. - * - * As per the ECMA and JSON specification an object may - * have any string as a property. Unfortunately due to - * a hole in the ECMA specification if the key is a - * ECMA reserved word or starts with a digit the - * parameter is only accessible using ECMAScript's - * bracket notation. - */ - - // treat as a JSON object - if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) { - - $this->json_objectStack[] = $var; - - $properties = array_map(array($this, 'json_name_value'), - array_keys($var), - array_values($var)); - - array_pop($this->json_objectStack); - - foreach($properties as $property) { - if ($property instanceof Exception) { - return $property; - } - } - - return '{' . join(',', $properties) . '}'; - } - - $this->json_objectStack[] = $var; - - // treat it like a regular array - $elements = array_map(array($this, 'json_encode'), $var); - - array_pop($this->json_objectStack); - - foreach($elements as $element) { - if ($element instanceof Exception) { - return $element; - } - } - - return '[' . join(',', $elements) . ']'; - - case 'object': - $vars = self::encodeObject($var); - - $this->json_objectStack[] = $var; - - $properties = array_map(array($this, 'json_name_value'), - array_keys($vars), - array_values($vars)); - - array_pop($this->json_objectStack); - - foreach($properties as $property) { - if ($property instanceof Exception) { - return $property; - } - } - - return '{' . join(',', $properties) . '}'; - - default: - return null; - } - } - - /** - * array-walking function for use in generating JSON-formatted name-value pairs - * - * @param string $name name of key to use - * @param mixed $value reference to an array element to be encoded - * - * @return string JSON-formatted name-value pair, like '"name":value' - * @access private - */ - private function json_name_value($name, $value) - { - // Encoding the $GLOBALS PHP array causes an infinite loop - // if the recursion is not reset here as it contains - // a reference to itself. This is the only way I have come up - // with to stop infinite recursion in this case. - if ($name=='GLOBALS' - && is_array($value) - && array_key_exists('GLOBALS',$value)) { - $value['GLOBALS'] = '** Recursion **'; - } - - $encoded_value = $this->json_encode($value); - - if ($encoded_value instanceof Exception) { - return $encoded_value; - } - - return $this->json_encode(strval($name)) . ':' . $encoded_value; - } - - /** - * @deprecated - */ - public function setProcessorUrl($URL) - { - trigger_error("The FirePHP::setProcessorUrl() method is no longer supported", E_USER_DEPRECATED); - } - - /** - * @deprecated - */ - public function setRendererUrl($URL) - { - trigger_error("The FirePHP::setRendererUrl() method is no longer supported", E_USER_DEPRECATED); - } -} diff --git a/includes/libs/FirePHP/fb.php b/includes/libs/FirePHP/fb.php deleted file mode 100644 index 9ed9c42..0000000 --- a/includes/libs/FirePHP/fb.php +++ /dev/null @@ -1,276 +0,0 @@ - - * @license http://www.opensource.org/licenses/bsd-license.php - * @package FirePHPCore - */ - -if(!class_exists('FirePHP')) { - require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'FirePHP.class.php'; -} - -/** - * Sends the given data to the FirePHP Firefox Extension. - * The data can be displayed in the Firebug Console or in the - * "Server" request tab. - * - * @see http://www.firephp.org/Wiki/Reference/Fb - * @param mixed $Object - * @return true - * @throws Exception - */ -function fb() -{ - $instance = FirePHP::getInstance(true); - - $args = func_get_args(); - return call_user_func_array(array($instance,'fb'),$args); -} - - -class FB -{ - /** - * Enable and disable logging to Firebug - * - * @see FirePHP->setEnabled() - * @param boolean $Enabled TRUE to enable, FALSE to disable - * @return void - */ - public static function setEnabled($Enabled) - { - $instance = FirePHP::getInstance(true); - $instance->setEnabled($Enabled); - } - - /** - * Check if logging is enabled - * - * @see FirePHP->getEnabled() - * @return boolean TRUE if enabled - */ - public static function getEnabled() - { - $instance = FirePHP::getInstance(true); - return $instance->getEnabled(); - } - - /** - * Specify a filter to be used when encoding an object - * - * Filters are used to exclude object members. - * - * @see FirePHP->setObjectFilter() - * @param string $Class The class name of the object - * @param array $Filter An array or members to exclude - * @return void - */ - public static function setObjectFilter($Class, $Filter) - { - $instance = FirePHP::getInstance(true); - $instance->setObjectFilter($Class, $Filter); - } - - /** - * Set some options for the library - * - * @see FirePHP->setOptions() - * @param array $Options The options to be set - * @return void - */ - public static function setOptions($Options) - { - $instance = FirePHP::getInstance(true); - $instance->setOptions($Options); - } - - /** - * Get options for the library - * - * @see FirePHP->getOptions() - * @return array The options - */ - public static function getOptions() - { - $instance = FirePHP::getInstance(true); - return $instance->getOptions(); - } - - /** - * Log object to firebug - * - * @see http://www.firephp.org/Wiki/Reference/Fb - * @param mixed $Object - * @return true - * @throws Exception - */ - public static function send() - { - $instance = FirePHP::getInstance(true); - $args = func_get_args(); - return call_user_func_array(array($instance,'fb'),$args); - } - - /** - * Start a group for following messages - * - * Options: - * Collapsed: [true|false] - * Color: [#RRGGBB|ColorName] - * - * @param string $Name - * @param array $Options OPTIONAL Instructions on how to log the group - * @return true - */ - public static function group($Name, $Options=null) - { - $instance = FirePHP::getInstance(true); - return $instance->group($Name, $Options); - } - - /** - * Ends a group you have started before - * - * @return true - * @throws Exception - */ - public static function groupEnd() - { - return self::send(null, null, FirePHP::GROUP_END); - } - - /** - * Log object with label to firebug console - * - * @see FirePHP::LOG - * @param mixes $Object - * @param string $Label - * @return true - * @throws Exception - */ - public static function log($Object, $Label=null) - { - return self::send($Object, $Label, FirePHP::LOG); - } - - /** - * Log object with label to firebug console - * - * @see FirePHP::INFO - * @param mixes $Object - * @param string $Label - * @return true - * @throws Exception - */ - public static function info($Object, $Label=null) - { - return self::send($Object, $Label, FirePHP::INFO); - } - - /** - * Log object with label to firebug console - * - * @see FirePHP::WARN - * @param mixes $Object - * @param string $Label - * @return true - * @throws Exception - */ - public static function warn($Object, $Label=null) - { - return self::send($Object, $Label, FirePHP::WARN); - } - - /** - * Log object with label to firebug console - * - * @see FirePHP::ERROR - * @param mixes $Object - * @param string $Label - * @return true - * @throws Exception - */ - public static function error($Object, $Label=null) - { - return self::send($Object, $Label, FirePHP::ERROR); - } - - /** - * Dumps key and variable to firebug server panel - * - * @see FirePHP::DUMP - * @param string $Key - * @param mixed $Variable - * @return true - * @throws Exception - */ - public static function dump($Key, $Variable) - { - return self::send($Variable, $Key, FirePHP::DUMP); - } - - /** - * Log a trace in the firebug console - * - * @see FirePHP::TRACE - * @param string $Label - * @return true - * @throws Exception - */ - public static function trace($Label) - { - return self::send($Label, FirePHP::TRACE); - } - - /** - * Log a table in the firebug console - * - * @see FirePHP::TABLE - * @param string $Label - * @param string $Table - * @return true - * @throws Exception - */ - public static function table($Label, $Table) - { - return self::send($Table, $Label, FirePHP::TABLE); - } - -} diff --git a/includes/libs/OpenID/openid.php b/includes/libs/OpenID/openid.php new file mode 100644 index 0000000..1556887 --- /dev/null +++ b/includes/libs/OpenID/openid.php @@ -0,0 +1,831 @@ + + * $openid = new LightOpenID('my-host.example.org'); + * $openid->identity = 'ID supplied by user'; + * header('Location: ' . $openid->authUrl()); + * + * The provider then sends various parameters via GET, one of them is openid_mode. + * Step two is verification: + * + * $openid = new LightOpenID('my-host.example.org'); + * if ($openid->mode) { + * echo $openid->validate() ? 'Logged in.' : 'Failed'; + * } + * + * + * Change the 'my-host.example.org' to your domain name. Do NOT use $_SERVER['HTTP_HOST'] + * for that, unless you know what you are doing. + * + * Optionally, you can set $returnUrl and $realm (or $trustRoot, which is an alias). + * The default values for those are: + * $openid->realm = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST']; + * $openid->returnUrl = $openid->realm . $_SERVER['REQUEST_URI']; + * If you don't know their meaning, refer to any openid tutorial, or specification. Or just guess. + * + * AX and SREG extensions are supported. + * To use them, specify $openid->required and/or $openid->optional before calling $openid->authUrl(). + * These are arrays, with values being AX schema paths (the 'path' part of the URL). + * For example: + * $openid->required = array('namePerson/friendly', 'contact/email'); + * $openid->optional = array('namePerson/first'); + * If the server supports only SREG or OpenID 1.1, these are automaticaly + * mapped to SREG names, so that user doesn't have to know anything about the server. + * + * To get the values, use $openid->getAttributes(). + * + * + * The library requires PHP >= 5.1.2 with curl or http/https stream wrappers enabled. + * @author Mewp + * @copyright Copyright (c) 2010, Mewp + * @license http://www.opensource.org/licenses/mit-license.php MIT + */ +class LightOpenID +{ + public $returnUrl + , $required = array() + , $optional = array() + , $verify_peer = null + , $capath = null + , $cainfo = null + , $data; + private $identity, $claimed_id; + protected $server, $version, $trustRoot, $aliases, $identifier_select = false + , $ax = false, $sreg = false, $setup_url = null, $headers = array(); + static protected $ax_to_sreg = array( + 'namePerson/friendly' => 'nickname', + 'contact/email' => 'email', + 'namePerson' => 'fullname', + 'birthDate' => 'dob', + 'person/gender' => 'gender', + 'contact/postalCode/home' => 'postcode', + 'contact/country/home' => 'country', + 'pref/language' => 'language', + 'pref/timezone' => 'timezone', + ); + + function __construct($host) + { + $this->trustRoot = (strpos($host, '://') ? $host : 'http://' . $host); + if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') + || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) + && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') + ) { + $this->trustRoot = (strpos($host, '://') ? $host : 'https://' . $host); + } + + if(($host_end = strpos($this->trustRoot, '/', 8)) !== false) { + $this->trustRoot = substr($this->trustRoot, 0, $host_end); + } + + $uri = rtrim(preg_replace('#((?<=\?)|&)openid\.[^&]+#', '', $_SERVER['REQUEST_URI']), '?'); + $this->returnUrl = $this->trustRoot . $uri; + + $this->data = ($_SERVER['REQUEST_METHOD'] === 'POST') ? $_POST : $_GET; + + if(!function_exists('curl_init') && !in_array('https', stream_get_wrappers())) { + throw new ErrorException('You must have either https wrappers or curl enabled.'); + } + } + + function __set($name, $value) + { + switch ($name) { + case 'identity': + if (strlen($value = trim((String) $value))) { + if (preg_match('#^xri:/*#i', $value, $m)) { + $value = substr($value, strlen($m[0])); + } elseif (!preg_match('/^(?:[=@+\$!\(]|https?:)/i', $value)) { + $value = "http://$value"; + } + if (preg_match('#^https?://[^/]+$#i', $value, $m)) { + $value .= '/'; + } + } + $this->$name = $this->claimed_id = $value; + break; + case 'trustRoot': + case 'realm': + $this->trustRoot = trim($value); + } + } + + function __get($name) + { + switch ($name) { + case 'identity': + # We return claimed_id instead of identity, + # because the developer should see the claimed identifier, + # i.e. what he set as identity, not the op-local identifier (which is what we verify) + return $this->claimed_id; + case 'trustRoot': + case 'realm': + return $this->trustRoot; + case 'mode': + return empty($this->data['openid_mode']) ? null : $this->data['openid_mode']; + } + } + + /** + * Checks if the server specified in the url exists. + * + * @param $url url to check + * @return true, if the server exists; false otherwise + */ + function hostExists($url) + { + if (strpos($url, '/') === false) { + $server = $url; + } else { + $server = @parse_url($url, PHP_URL_HOST); + } + + if (!$server) { + return false; + } + + return !!gethostbynamel($server); + } + + protected function request_curl($url, $method='GET', $params=array(), $update_claimed_id) + { + $params = http_build_query($params, '', '&'); + $curl = curl_init($url . ($method == 'GET' && $params ? '?' . $params : '')); + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($curl, CURLOPT_HEADER, false); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/xrds+xml, */*')); + + if($this->verify_peer !== null) { + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verify_peer); + if($this->capath) { + curl_setopt($curl, CURLOPT_CAPATH, $this->capath); + } + + if($this->cainfo) { + curl_setopt($curl, CURLOPT_CAINFO, $this->cainfo); + } + } + + if ($method == 'POST') { + curl_setopt($curl, CURLOPT_POST, true); + curl_setopt($curl, CURLOPT_POSTFIELDS, $params); + } elseif ($method == 'HEAD') { + curl_setopt($curl, CURLOPT_HEADER, true); + curl_setopt($curl, CURLOPT_NOBODY, true); + } else { + curl_setopt($curl, CURLOPT_HEADER, true); + curl_setopt($curl, CURLOPT_HTTPGET, true); + } + $response = curl_exec($curl); + + if($method == 'HEAD' && curl_getinfo($curl, CURLINFO_HTTP_CODE) == 405) { + curl_setopt($curl, CURLOPT_HTTPGET, true); + $response = curl_exec($curl); + $response = substr($response, 0, strpos($response, "\r\n\r\n")); + } + + if($method == 'HEAD' || $method == 'GET') { + $header_response = $response; + + # If it's a GET request, we want to only parse the header part. + if($method == 'GET') { + $header_response = substr($response, 0, strpos($response, "\r\n\r\n")); + } + + $headers = array(); + foreach(explode("\n", $header_response) as $header) { + $pos = strpos($header,':'); + if ($pos !== false) { + $name = strtolower(trim(substr($header, 0, $pos))); + $headers[$name] = trim(substr($header, $pos+1)); + } + } + + if($update_claimed_id) { + # Updating claimed_id in case of redirections. + $effective_url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL); + if($effective_url != $url) { + $this->identity = $this->claimed_id = $effective_url; + } + } + + if($method == 'HEAD') { + return $headers; + } else { + $this->headers = $headers; + } + } + + if (curl_errno($curl)) { + throw new ErrorException(curl_error($curl), curl_errno($curl)); + } + + return $response; + } + + protected function parse_header_array($array, $update_claimed_id) + { + $headers = array(); + foreach($array as $header) { + $pos = strpos($header,':'); + if ($pos !== false) { + $name = strtolower(trim(substr($header, 0, $pos))); + $headers[$name] = trim(substr($header, $pos+1)); + + # Following possible redirections. The point is just to have + # claimed_id change with them, because the redirections + # are followed automatically. + # We ignore redirections with relative paths. + # If any known provider uses them, file a bug report. + if($name == 'location' && $update_claimed_id) { + if(strpos($headers[$name], 'http') === 0) { + $this->identity = $this->claimed_id = $headers[$name]; + } elseif($headers[$name][0] == '/') { + $parsed_url = parse_url($this->claimed_id); + $this->identity = + $this->claimed_id = $parsed_url['scheme'] . '://' + . $parsed_url['host'] + . $headers[$name]; + } + } + } + } + return $headers; + } + + protected function request_streams($url, $method='GET', $params=array(), $update_claimed_id) + { + if(!$this->hostExists($url)) { + throw new ErrorException("Could not connect to $url.", 404); + } + + $params = http_build_query($params, '', '&'); + switch($method) { + case 'GET': + $opts = array( + 'http' => array( + 'method' => 'GET', + 'header' => 'Accept: application/xrds+xml, */*', + 'ignore_errors' => true, + ), 'ssl' => array( + 'CN_match' => parse_url($url, PHP_URL_HOST), + ), + ); + $url = $url . ($params ? '?' . $params : ''); + break; + case 'POST': + $opts = array( + 'http' => array( + 'method' => 'POST', + 'header' => 'Content-type: application/x-www-form-urlencoded', + 'content' => $params, + 'ignore_errors' => true, + ), 'ssl' => array( + 'CN_match' => parse_url($url, PHP_URL_HOST), + ), + ); + break; + case 'HEAD': + # We want to send a HEAD request, + # but since get_headers doesn't accept $context parameter, + # we have to change the defaults. + $default = stream_context_get_options(stream_context_get_default()); + stream_context_get_default( + array( + 'http' => array( + 'method' => 'HEAD', + 'header' => 'Accept: application/xrds+xml, */*', + 'ignore_errors' => true, + ), 'ssl' => array( + 'CN_match' => parse_url($url, PHP_URL_HOST), + ), + ) + ); + + $url = $url . ($params ? '?' . $params : ''); + $headers = get_headers ($url); + if(!$headers) { + return array(); + } + + if(intval(substr($headers[0], strlen('HTTP/1.1 '))) == 405) { + # The server doesn't support HEAD, so let's emulate it with + # a GET. + $args = func_get_args(); + $args[1] = 'GET'; + call_user_func_array(array($this, 'request_streams'), $args); + return $this->headers; + } + + $headers = $this->parse_header_array($headers, $update_claimed_id); + + # And restore them. + stream_context_get_default($default); + return $headers; + } + + if($this->verify_peer) { + $opts['ssl'] += array( + 'verify_peer' => true, + 'capath' => $this->capath, + 'cafile' => $this->cainfo, + ); + } + + $context = stream_context_create ($opts); + $data = file_get_contents($url, false, $context); + # This is a hack for providers who don't support HEAD requests. + # It just creates the headers array for the last request in $this->headers. + if(isset($http_response_header)) { + $this->headers = $this->parse_header_array($http_response_header, $update_claimed_id); + } + + return file_get_contents($url, false, $context); + } + + protected function request($url, $method='GET', $params=array(), $update_claimed_id=false) + { + if (function_exists('curl_init') + && (!in_array('https', stream_get_wrappers()) || !ini_get('safe_mode') && !ini_get('open_basedir')) + ) { + return $this->request_curl($url, $method, $params, $update_claimed_id); + } + return $this->request_streams($url, $method, $params, $update_claimed_id); + } + + protected function build_url($url, $parts) + { + if (isset($url['query'], $parts['query'])) { + $parts['query'] = $url['query'] . '&' . $parts['query']; + } + + $url = $parts + $url; + $url = $url['scheme'] . '://' + . (empty($url['username'])?'' + :(empty($url['password'])? "{$url['username']}@" + :"{$url['username']}:{$url['password']}@")) + . $url['host'] + . (empty($url['port'])?'':":{$url['port']}") + . (empty($url['path'])?'':$url['path']) + . (empty($url['query'])?'':"?{$url['query']}") + . (empty($url['fragment'])?'':"#{$url['fragment']}"); + return $url; + } + + /** + * Helper function used to scan for / tags and extract information + * from them + */ + protected function htmlTag($content, $tag, $attrName, $attrValue, $valueName) + { + preg_match_all("#<{$tag}[^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*$valueName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1); + preg_match_all("#<{$tag}[^>]*$valueName=['\"](.+?)['\"][^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*/?>#i", $content, $matches2); + + $result = array_merge($matches1[1], $matches2[1]); + return empty($result)?false:$result[0]; + } + + /** + * Performs Yadis and HTML discovery. Normally not used. + * @param $url Identity URL. + * @return String OP Endpoint (i.e. OpenID provider address). + * @throws ErrorException + */ + function discover($url) + { + if (!$url) throw new ErrorException('No identity supplied.'); + # Use xri.net proxy to resolve i-name identities + if (!preg_match('#^https?:#', $url)) { + $url = "https://xri.net/$url"; + } + + # We save the original url in case of Yadis discovery failure. + # It can happen when we'll be lead to an XRDS document + # which does not have any OpenID2 services. + $originalUrl = $url; + + # A flag to disable yadis discovery in case of failure in headers. + $yadis = true; + + # We'll jump a maximum of 5 times, to avoid endless redirections. + for ($i = 0; $i < 5; $i ++) { + if ($yadis) { + $headers = $this->request($url, 'HEAD', array(), true); + + $next = false; + if (isset($headers['x-xrds-location'])) { + $url = $this->build_url(parse_url($url), parse_url(trim($headers['x-xrds-location']))); + $next = true; + } + + if (isset($headers['content-type']) + && (strpos($headers['content-type'], 'application/xrds+xml') !== false + || strpos($headers['content-type'], 'text/xml') !== false) + ) { + # Apparently, some providers return XRDS documents as text/html. + # While it is against the spec, allowing this here shouldn't break + # compatibility with anything. + # --- + # Found an XRDS document, now let's find the server, and optionally delegate. + $content = $this->request($url, 'GET'); + + preg_match_all('#(.*?)#s', $content, $m); + foreach($m[1] as $content) { + $content = ' ' . $content; # The space is added, so that strpos doesn't return 0. + + # OpenID 2 + $ns = preg_quote('http://specs.openid.net/auth/2.0/', '#'); + if(preg_match('#\s*'.$ns.'(server|signon)\s*#s', $content, $type)) { + if ($type[1] == 'server') $this->identifier_select = true; + + preg_match('#(.*)#', $content, $server); + preg_match('#<(Local|Canonical)ID>(.*)#', $content, $delegate); + if (empty($server)) { + return false; + } + # Does the server advertise support for either AX or SREG? + $this->ax = (bool) strpos($content, 'http://openid.net/srv/ax/1.0'); + $this->sreg = strpos($content, 'http://openid.net/sreg/1.0') + || strpos($content, 'http://openid.net/extensions/sreg/1.1'); + + $server = $server[1]; + if (isset($delegate[2])) $this->identity = trim($delegate[2]); + $this->version = 2; + + $this->server = $server; + return $server; + } + + # OpenID 1.1 + $ns = preg_quote('http://openid.net/signon/1.1', '#'); + if (preg_match('#\s*'.$ns.'\s*#s', $content)) { + + preg_match('#(.*)#', $content, $server); + preg_match('#<.*?Delegate>(.*)#', $content, $delegate); + if (empty($server)) { + return false; + } + # AX can be used only with OpenID 2.0, so checking only SREG + $this->sreg = strpos($content, 'http://openid.net/sreg/1.0') + || strpos($content, 'http://openid.net/extensions/sreg/1.1'); + + $server = $server[1]; + if (isset($delegate[1])) $this->identity = $delegate[1]; + $this->version = 1; + + $this->server = $server; + return $server; + } + } + + $next = true; + $yadis = false; + $url = $originalUrl; + $content = null; + break; + } + if ($next) continue; + + # There are no relevant information in headers, so we search the body. + $content = $this->request($url, 'GET', array(), true); + + if (isset($this->headers['x-xrds-location'])) { + $url = $this->build_url(parse_url($url), parse_url(trim($this->headers['x-xrds-location']))); + continue; + } + + $location = $this->htmlTag($content, 'meta', 'http-equiv', 'X-XRDS-Location', 'content'); + if ($location) { + $url = $this->build_url(parse_url($url), parse_url($location)); + continue; + } + } + + if (!$content) $content = $this->request($url, 'GET'); + + # At this point, the YADIS Discovery has failed, so we'll switch + # to openid2 HTML discovery, then fallback to openid 1.1 discovery. + $server = $this->htmlTag($content, 'link', 'rel', 'openid2.provider', 'href'); + $delegate = $this->htmlTag($content, 'link', 'rel', 'openid2.local_id', 'href'); + $this->version = 2; + + if (!$server) { + # The same with openid 1.1 + $server = $this->htmlTag($content, 'link', 'rel', 'openid.server', 'href'); + $delegate = $this->htmlTag($content, 'link', 'rel', 'openid.delegate', 'href'); + $this->version = 1; + } + + if ($server) { + # We found an OpenID2 OP Endpoint + if ($delegate) { + # We have also found an OP-Local ID. + $this->identity = $delegate; + } + $this->server = $server; + return $server; + } + + throw new ErrorException("No OpenID Server found at $url", 404); + } + throw new ErrorException('Endless redirection!', 500); + } + + protected function sregParams() + { + $params = array(); + # We always use SREG 1.1, even if the server is advertising only support for 1.0. + # That's because it's fully backwards compatibile with 1.0, and some providers + # advertise 1.0 even if they accept only 1.1. One such provider is myopenid.com + $params['openid.ns.sreg'] = 'http://openid.net/extensions/sreg/1.1'; + if ($this->required) { + $params['openid.sreg.required'] = array(); + foreach ($this->required as $required) { + if (!isset(self::$ax_to_sreg[$required])) continue; + $params['openid.sreg.required'][] = self::$ax_to_sreg[$required]; + } + $params['openid.sreg.required'] = implode(',', $params['openid.sreg.required']); + } + + if ($this->optional) { + $params['openid.sreg.optional'] = array(); + foreach ($this->optional as $optional) { + if (!isset(self::$ax_to_sreg[$optional])) continue; + $params['openid.sreg.optional'][] = self::$ax_to_sreg[$optional]; + } + $params['openid.sreg.optional'] = implode(',', $params['openid.sreg.optional']); + } + return $params; + } + + protected function axParams() + { + $params = array(); + if ($this->required || $this->optional) { + $params['openid.ns.ax'] = 'http://openid.net/srv/ax/1.0'; + $params['openid.ax.mode'] = 'fetch_request'; + $this->aliases = array(); + $counts = array(); + $required = array(); + $optional = array(); + foreach (array('required','optional') as $type) { + foreach ($this->$type as $alias => $field) { + if (is_int($alias)) $alias = strtr($field, '/', '_'); + $this->aliases[$alias] = 'http://axschema.org/' . $field; + if (empty($counts[$alias])) $counts[$alias] = 0; + $counts[$alias] += 1; + ${$type}[] = $alias; + } + } + foreach ($this->aliases as $alias => $ns) { + $params['openid.ax.type.' . $alias] = $ns; + } + foreach ($counts as $alias => $count) { + if ($count == 1) continue; + $params['openid.ax.count.' . $alias] = $count; + } + + # Don't send empty ax.requied and ax.if_available. + # Google and possibly other providers refuse to support ax when one of these is empty. + if($required) { + $params['openid.ax.required'] = implode(',', $required); + } + if($optional) { + $params['openid.ax.if_available'] = implode(',', $optional); + } + } + return $params; + } + + protected function authUrl_v1($immediate) + { + $returnUrl = $this->returnUrl; + # If we have an openid.delegate that is different from our claimed id, + # we need to somehow preserve the claimed id between requests. + # The simplest way is to just send it along with the return_to url. + if($this->identity != $this->claimed_id) { + $returnUrl .= (strpos($returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $this->claimed_id; + } + + $params = array( + 'openid.return_to' => $returnUrl, + 'openid.mode' => $immediate ? 'checkid_immediate' : 'checkid_setup', + 'openid.identity' => $this->identity, + 'openid.trust_root' => $this->trustRoot, + ) + $this->sregParams(); + + return $this->build_url(parse_url($this->server) + , array('query' => http_build_query($params, '', '&'))); + } + + protected function authUrl_v2($immediate) + { + $params = array( + 'openid.ns' => 'http://specs.openid.net/auth/2.0', + 'openid.mode' => $immediate ? 'checkid_immediate' : 'checkid_setup', + 'openid.return_to' => $this->returnUrl, + 'openid.realm' => $this->trustRoot, + ); + if ($this->ax) { + $params += $this->axParams(); + } + if ($this->sreg) { + $params += $this->sregParams(); + } + if (!$this->ax && !$this->sreg) { + # If OP doesn't advertise either SREG, nor AX, let's send them both + # in worst case we don't get anything in return. + $params += $this->axParams() + $this->sregParams(); + } + + if ($this->identifier_select) { + $params['openid.identity'] = $params['openid.claimed_id'] + = 'http://specs.openid.net/auth/2.0/identifier_select'; + } else { + $params['openid.identity'] = $this->identity; + $params['openid.claimed_id'] = $this->claimed_id; + } + + return $this->build_url(parse_url($this->server) + , array('query' => http_build_query($params, '', '&'))); + } + + /** + * Returns authentication url. Usually, you want to redirect your user to it. + * @return String The authentication url. + * @param String $select_identifier Whether to request OP to select identity for an user in OpenID 2. Does not affect OpenID 1. + * @throws ErrorException + */ + function authUrl($immediate = false) + { + if ($this->setup_url && !$immediate) return $this->setup_url; + if (!$this->server) $this->discover($this->identity); + + if ($this->version == 2) { + return $this->authUrl_v2($immediate); + } + return $this->authUrl_v1($immediate); + } + + /** + * Performs OpenID verification with the OP. + * @return Bool Whether the verification was successful. + * @throws ErrorException + */ + function validate() + { + # If the request was using immediate mode, a failure may be reported + # by presenting user_setup_url (for 1.1) or reporting + # mode 'setup_needed' (for 2.0). Also catching all modes other than + # id_res, in order to avoid throwing errors. + if(isset($this->data['openid_user_setup_url'])) { + $this->setup_url = $this->data['openid_user_setup_url']; + return false; + } + if($this->mode != 'id_res') { + return false; + } + + $this->claimed_id = isset($this->data['openid_claimed_id'])?$this->data['openid_claimed_id']:$this->data['openid_identity']; + $params = array( + 'openid.assoc_handle' => $this->data['openid_assoc_handle'], + 'openid.signed' => $this->data['openid_signed'], + 'openid.sig' => $this->data['openid_sig'], + ); + + if (isset($this->data['openid_ns'])) { + # We're dealing with an OpenID 2.0 server, so let's set an ns + # Even though we should know location of the endpoint, + # we still need to verify it by discovery, so $server is not set here + $params['openid.ns'] = 'http://specs.openid.net/auth/2.0'; + } elseif (isset($this->data['openid_claimed_id']) + && $this->data['openid_claimed_id'] != $this->data['openid_identity'] + ) { + # If it's an OpenID 1 provider, and we've got claimed_id, + # we have to append it to the returnUrl, like authUrl_v1 does. + $this->returnUrl .= (strpos($this->returnUrl, '?') ? '&' : '?') + . 'openid.claimed_id=' . $this->claimed_id; + } + + if ($this->data['openid_return_to'] != $this->returnUrl) { + # The return_to url must match the url of current request. + # I'm assuing that noone will set the returnUrl to something that doesn't make sense. + return false; + } + + $server = $this->discover($this->claimed_id); + + foreach (explode(',', $this->data['openid_signed']) as $item) { + # Checking whether magic_quotes_gpc is turned on, because + # the function may fail if it is. For example, when fetching + # AX namePerson, it might containg an apostrophe, which will be escaped. + # In such case, validation would fail, since we'd send different data than OP + # wants to verify. stripslashes() should solve that problem, but we can't + # use it when magic_quotes is off. + $value = $this->data['openid_' . str_replace('.','_',$item)]; + $params['openid.' . $item] = function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() ? stripslashes($value) : $value; + + } + + $params['openid.mode'] = 'check_authentication'; + + $response = $this->request($server, 'POST', $params); + + return preg_match('/is_valid\s*:\s*true/i', $response); + } + + protected function getAxAttributes() + { + $alias = null; + if (isset($this->data['openid_ns_ax']) + && $this->data['openid_ns_ax'] != 'http://openid.net/srv/ax/1.0' + ) { # It's the most likely case, so we'll check it before + $alias = 'ax'; + } else { + # 'ax' prefix is either undefined, or points to another extension, + # so we search for another prefix + foreach ($this->data as $key => $val) { + if (substr($key, 0, strlen('openid_ns_')) == 'openid_ns_' + && $val == 'http://openid.net/srv/ax/1.0' + ) { + $alias = substr($key, strlen('openid_ns_')); + break; + } + } + } + if (!$alias) { + # An alias for AX schema has not been found, + # so there is no AX data in the OP's response + return array(); + } + + $attributes = array(); + foreach (explode(',', $this->data['openid_signed']) as $key) { + $keyMatch = $alias . '.value.'; + if (substr($key, 0, strlen($keyMatch)) != $keyMatch) { + continue; + } + $key = substr($key, strlen($keyMatch)); + if (!isset($this->data['openid_' . $alias . '_type_' . $key])) { + # OP is breaking the spec by returning a field without + # associated ns. This shouldn't happen, but it's better + # to check, than cause an E_NOTICE. + continue; + } + $value = $this->data['openid_' . $alias . '_value_' . $key]; + $key = substr($this->data['openid_' . $alias . '_type_' . $key], + strlen('http://axschema.org/')); + + $attributes[$key] = $value; + } + return $attributes; + } + + protected function getSregAttributes() + { + $attributes = array(); + $sreg_to_ax = array_flip(self::$ax_to_sreg); + foreach (explode(',', $this->data['openid_signed']) as $key) { + $keyMatch = 'sreg.'; + if (substr($key, 0, strlen($keyMatch)) != $keyMatch) { + continue; + } + $key = substr($key, strlen($keyMatch)); + if (!isset($sreg_to_ax[$key])) { + # The field name isn't part of the SREG spec, so we ignore it. + continue; + } + $attributes[$sreg_to_ax[$key]] = $this->data['openid_sreg_' . $key]; + } + return $attributes; + } + + /** + * Gets AX/SREG attributes provided by OP. should be used only after successful validaton. + * Note that it does not guarantee that any of the required/optional parameters will be present, + * or that there will be no other attributes besides those specified. + * In other words. OP may provide whatever information it wants to. + * * SREG names will be mapped to AX names. + * * @return Array Array of attributes with keys being the AX schema names, e.g. 'contact/email' + * @see http://www.axschema.org/types/ + */ + function getAttributes() + { + if (isset($this->data['openid_ns']) + && $this->data['openid_ns'] == 'http://specs.openid.net/auth/2.0' + ) { # OpenID 2.0 + # We search for both AX and SREG attributes, with AX taking precedence. + return $this->getAxAttributes() + $this->getSregAttributes(); + } + return $this->getSregAttributes(); + } +} diff --git a/includes/libs/Smarty/Smarty.class.php b/includes/libs/Smarty/Smarty.class.php index e48bf94..4e3cacd 100644 --- a/includes/libs/Smarty/Smarty.class.php +++ b/includes/libs/Smarty/Smarty.class.php @@ -1,55 +1,55 @@ -* @author Uwe Tews -* @author Rodney Rehm -* @package Smarty -* @version 3.1-DEV -*/ + * Project: Smarty: the PHP compiling template engine + * File: Smarty.class.php + * SVN: $Id$ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * For questions, help, comments, discussion, etc., please join the + * Smarty mailing list. Send a blank e-mail to + * smarty-discussion-subscribe@googlegroups.com + * + * @link http://www.smarty.net/ + * @copyright 2008 New Digital Group, Inc. + * @author Monte Ohrt + * @author Uwe Tews + * @author Rodney Rehm + * @package Smarty + * @version 3.1.12 + */ /** -* define shorthand directory separator constant -*/ + * define shorthand directory separator constant + */ if (!defined('DS')) { define('DS', DIRECTORY_SEPARATOR); } /** -* set SMARTY_DIR to absolute path to Smarty library files. -* Sets SMARTY_DIR only if user application has not already defined it. -*/ + * set SMARTY_DIR to absolute path to Smarty library files. + * Sets SMARTY_DIR only if user application has not already defined it. + */ if (!defined('SMARTY_DIR')) { define('SMARTY_DIR', dirname(__FILE__) . DS); } /** -* set SMARTY_SYSPLUGINS_DIR to absolute path to Smarty internal plugins. -* Sets SMARTY_SYSPLUGINS_DIR only if user application has not already defined it. -*/ + * set SMARTY_SYSPLUGINS_DIR to absolute path to Smarty internal plugins. + * Sets SMARTY_SYSPLUGINS_DIR only if user application has not already defined it. + */ if (!defined('SMARTY_SYSPLUGINS_DIR')) { define('SMARTY_SYSPLUGINS_DIR', SMARTY_DIR . 'sysplugins' . DS); } @@ -57,19 +57,25 @@ define('SMARTY_PLUGINS_DIR', SMARTY_DIR . 'plugins' . DS); } if (!defined('SMARTY_MBSTRING')) { - define('SMARTY_MBSTRING', function_exists('mb_strlen')); + define('SMARTY_MBSTRING', function_exists('mb_split')); } if (!defined('SMARTY_RESOURCE_CHAR_SET')) { // UTF-8 can only be done properly when mbstring is available! + /** + * @deprecated in favor of Smarty::$_CHARSET + */ define('SMARTY_RESOURCE_CHAR_SET', SMARTY_MBSTRING ? 'UTF-8' : 'ISO-8859-1'); } if (!defined('SMARTY_RESOURCE_DATE_FORMAT')) { + /** + * @deprecated in favor of Smarty::$_DATE_FORMAT + */ define('SMARTY_RESOURCE_DATE_FORMAT', '%b %e, %Y'); } /** -* register the class autoloader -*/ + * register the class autoloader + */ if (!defined('SMARTY_SPL_AUTOLOAD')) { define('SMARTY_SPL_AUTOLOAD', 0); } @@ -84,8 +90,8 @@ } /** -* Load always needed external class files -*/ + * Load always needed external class files + */ include_once SMARTY_SYSPLUGINS_DIR.'smarty_internal_data.php'; include_once SMARTY_SYSPLUGINS_DIR.'smarty_internal_templatebase.php'; include_once SMARTY_SYSPLUGINS_DIR.'smarty_internal_template.php'; @@ -95,56 +101,56 @@ include_once SMARTY_SYSPLUGINS_DIR.'smarty_internal_cacheresource_file.php'; /** -* This is the main Smarty class -* @package Smarty -*/ + * This is the main Smarty class + * @package Smarty + */ class Smarty extends Smarty_Internal_TemplateBase { /**#@+ - * constant definitions - */ + * constant definitions + */ /** - * smarty version - */ - const SMARTY_VERSION = 'Smarty 3.1-DEV'; + * smarty version + */ + const SMARTY_VERSION = 'Smarty-3.1.12'; /** - * define variable scopes - */ + * define variable scopes + */ const SCOPE_LOCAL = 0; const SCOPE_PARENT = 1; const SCOPE_ROOT = 2; const SCOPE_GLOBAL = 3; /** - * define caching modes - */ + * define caching modes + */ const CACHING_OFF = 0; const CACHING_LIFETIME_CURRENT = 1; const CACHING_LIFETIME_SAVED = 2; /** - * define compile check modes - */ + * define compile check modes + */ const COMPILECHECK_OFF = 0; const COMPILECHECK_ON = 1; const COMPILECHECK_CACHEMISS = 2; /** - * modes for handling of "" tags in templates. - */ + * modes for handling of "" tags in templates. + */ const PHP_PASSTHRU = 0; //-> print tags as plain text const PHP_QUOTE = 1; //-> escape tags as entities const PHP_REMOVE = 2; //-> escape tags as entities const PHP_ALLOW = 3; //-> escape tags as entities /** - * filter types - */ + * filter types + */ const FILTER_POST = 'post'; const FILTER_PRE = 'pre'; const FILTER_OUTPUT = 'output'; const FILTER_VARIABLE = 'variable'; /** - * plugin types - */ + * plugin types + */ const PLUGIN_FUNCTION = 'function'; const PLUGIN_BLOCK = 'block'; const PLUGIN_COMPILER = 'compiler'; @@ -154,10 +160,10 @@ class Smarty extends Smarty_Internal_TemplateBase { /**#@-*/ /** - * assigned global tpl vars - */ + * assigned global tpl vars + */ public static $global_tpl_vars = array(); - + /** * error handler returned by set_error_hanlder() in Smarty::muteExpectedErrors() */ @@ -166,90 +172,112 @@ class Smarty extends Smarty_Internal_TemplateBase { * contains directories outside of SMARTY_DIR that are to be muted by muteExpectedErrors() */ public static $_muted_directories = array(); + /** + * Flag denoting if Multibyte String functions are available + */ + public static $_MBSTRING = SMARTY_MBSTRING; + /** + * The character set to adhere to (e.g. "UTF-8") + */ + public static $_CHARSET = SMARTY_RESOURCE_CHAR_SET; + /** + * The date format to be used internally + * (accepts date() and strftime()) + */ + public static $_DATE_FORMAT = SMARTY_RESOURCE_DATE_FORMAT; + /** + * Flag denoting if PCRE should run in UTF-8 mode + */ + public static $_UTF8_MODIFIER = 'u'; + + /** + * Flag denoting if operating system is windows + */ + public static $_IS_WINDOWS = false; /**#@+ - * variables - */ + * variables + */ /** - * auto literal on delimiters with whitspace - * @var boolean - */ + * auto literal on delimiters with whitspace + * @var boolean + */ public $auto_literal = true; /** - * display error on not assigned variables - * @var boolean - */ + * display error on not assigned variables + * @var boolean + */ public $error_unassigned = false; /** - * look up relative filepaths in include_path - * @var boolean - */ + * look up relative filepaths in include_path + * @var boolean + */ public $use_include_path = false; /** - * template directory - * @var array - */ - protected $template_dir = array(); + * template directory + * @var array + */ + private $template_dir = array(); /** - * joined template directory string used in cache keys - * @var string - */ + * joined template directory string used in cache keys + * @var string + */ public $joined_template_dir = null; /** - * joined config directory string used in cache keys - * @var string - */ + * joined config directory string used in cache keys + * @var string + */ public $joined_config_dir = null; /** - * default template handler - * @var callable - */ + * default template handler + * @var callable + */ public $default_template_handler_func = null; /** - * default config handler - * @var callable - */ + * default config handler + * @var callable + */ public $default_config_handler_func = null; /** - * default plugin handler - * @var callable - */ + * default plugin handler + * @var callable + */ public $default_plugin_handler_func = null; /** - * compile directory - * @var string - */ - protected $compile_dir = null; - /** - * plugins directory - * @var array - */ - protected $plugins_dir = array(); - /** - * cache directory - * @var string - */ - protected $cache_dir = null; - /** - * config directory - * @var array - */ - protected $config_dir = array(); - /** - * force template compiling? - * @var boolean - */ + * compile directory + * @var string + */ + private $compile_dir = null; + /** + * plugins directory + * @var array + */ + private $plugins_dir = array(); + /** + * cache directory + * @var string + */ + private $cache_dir = null; + /** + * config directory + * @var array + */ + private $config_dir = array(); + /** + * force template compiling? + * @var boolean + */ public $force_compile = false; /** - * check template for modifications? - * @var boolean - */ + * check template for modifications? + * @var boolean + */ public $compile_check = true; /** - * use sub dirs for compiled/cached files? - * @var boolean - */ + * use sub dirs for compiled/cached files? + * @var boolean + */ public $use_sub_dirs = false; /** * allow ambiguous resources (that are made unique by the resource handler) @@ -257,24 +285,24 @@ class Smarty extends Smarty_Internal_TemplateBase { */ public $allow_ambiguous_resources = false; /** - * caching enabled - * @var boolean - */ + * caching enabled + * @var boolean + */ public $caching = false; /** - * merge compiled includes - * @var boolean - */ + * merge compiled includes + * @var boolean + */ public $merge_compiled_includes = false; /** - * cache lifetime in seconds - * @var integer - */ + * cache lifetime in seconds + * @var integer + */ public $cache_lifetime = 3600; /** - * force cache file creation - * @var boolean - */ + * force cache file creation + * @var boolean + */ public $force_cache = false; /** * Set this if you want different sets of cache files for the same @@ -291,63 +319,63 @@ class Smarty extends Smarty_Internal_TemplateBase { */ public $compile_id = null; /** - * template left-delimiter - * @var string - */ + * template left-delimiter + * @var string + */ public $left_delimiter = "{"; /** - * template right-delimiter - * @var string - */ + * template right-delimiter + * @var string + */ public $right_delimiter = "}"; /**#@+ - * security - */ - /** - * class name - * - * This should be instance of Smarty_Security. - * - * @var string - * @see Smarty_Security - */ + * security + */ + /** + * class name + * + * This should be instance of Smarty_Security. + * + * @var string + * @see Smarty_Security + */ public $security_class = 'Smarty_Security'; /** - * implementation of security class - * - * @var Smarty_Security - */ + * implementation of security class + * + * @var Smarty_Security + */ public $security_policy = null; /** - * controls handling of PHP-blocks - * - * @var integer - */ + * controls handling of PHP-blocks + * + * @var integer + */ public $php_handling = self::PHP_PASSTHRU; /** - * controls if the php template file resource is allowed - * - * @var bool - */ + * controls if the php template file resource is allowed + * + * @var bool + */ public $allow_php_templates = false; /** - * Should compiled-templates be prevented from being called directly? - * - * {@internal - * Currently used by Smarty_Internal_Template only. - * }} - * - * @var boolean - */ + * Should compiled-templates be prevented from being called directly? + * + * {@internal + * Currently used by Smarty_Internal_Template only. + * }} + * + * @var boolean + */ public $direct_access_security = true; /**#@-*/ /** - * debug mode - * - * Setting this to true enables the debug-console. - * - * @var boolean - */ + * debug mode + * + * Setting this to true enables the debug-console. + * + * @var boolean + */ public $debugging = false; /** * This determines if debugging is enable-able from the browser. @@ -355,64 +383,64 @@ class Smarty extends Smarty_Internal_TemplateBase { *
  • NONE => no debugging control allowed
  • *
  • URL => enable debugging when SMARTY_DEBUG is found in the URL.
  • * - * @var string - */ + * @var string + */ public $debugging_ctrl = 'NONE'; /** - * Name of debugging URL-param. - * - * Only used when $debugging_ctrl is set to 'URL'. - * The name of the URL-parameter that activates debugging. - * - * @var type - */ + * Name of debugging URL-param. + * + * Only used when $debugging_ctrl is set to 'URL'. + * The name of the URL-parameter that activates debugging. + * + * @var type + */ public $smarty_debug_id = 'SMARTY_DEBUG'; /** - * Path of debug template. - * @var string - */ + * Path of debug template. + * @var string + */ public $debug_tpl = null; /** - * When set, smarty uses this value as error_reporting-level. - * @var int - */ + * When set, smarty uses this value as error_reporting-level. + * @var int + */ public $error_reporting = null; /** - * Internal flag for getTags() - * @var boolean - */ + * Internal flag for getTags() + * @var boolean + */ public $get_used_tags = false; /**#@+ - * config var settings - */ + * config var settings + */ /** - * Controls whether variables with the same name overwrite each other. - * @var boolean - */ + * Controls whether variables with the same name overwrite each other. + * @var boolean + */ public $config_overwrite = true; /** - * Controls whether config values of on/true/yes and off/false/no get converted to boolean. - * @var boolean - */ + * Controls whether config values of on/true/yes and off/false/no get converted to boolean. + * @var boolean + */ public $config_booleanize = true; /** - * Controls whether hidden config sections/vars are read from the file. - * @var boolean - */ + * Controls whether hidden config sections/vars are read from the file. + * @var boolean + */ public $config_read_hidden = false; /**#@-*/ /**#@+ - * resource locking - */ + * resource locking + */ /** - * locking concurrent compiles - * @var boolean - */ + * locking concurrent compiles + * @var boolean + */ public $compile_locking = true; /** * Controls whether cache resources should emply locking mechanism @@ -428,163 +456,163 @@ class Smarty extends Smarty_Internal_TemplateBase { /**#@-*/ /** - * global template functions - * @var array - */ + * global template functions + * @var array + */ public $template_functions = array(); /** - * resource type used if none given - * - * Must be an valid key of $registered_resources. - * @var string - */ + * resource type used if none given + * + * Must be an valid key of $registered_resources. + * @var string + */ public $default_resource_type = 'file'; /** - * caching type - * - * Must be an element of $cache_resource_types. - * - * @var string - */ + * caching type + * + * Must be an element of $cache_resource_types. + * + * @var string + */ public $caching_type = 'file'; /** - * internal config properties - * @var array - */ + * internal config properties + * @var array + */ public $properties = array(); /** - * config type - * @var string - */ + * config type + * @var string + */ public $default_config_type = 'file'; /** - * cached template objects - * @var array - */ + * cached template objects + * @var array + */ public $template_objects = array(); /** - * check If-Modified-Since headers - * @var boolean - */ + * check If-Modified-Since headers + * @var boolean + */ public $cache_modified_check = false; /** - * registered plugins - * @var array - */ + * registered plugins + * @var array + */ public $registered_plugins = array(); /** - * plugin search order - * @var array - */ + * plugin search order + * @var array + */ public $plugin_search_order = array('function', 'block', 'compiler', 'class'); /** - * registered objects - * @var array - */ + * registered objects + * @var array + */ public $registered_objects = array(); /** - * registered classes - * @var array - */ + * registered classes + * @var array + */ public $registered_classes = array(); /** - * registered filters - * @var array - */ + * registered filters + * @var array + */ public $registered_filters = array(); /** - * registered resources - * @var array - */ + * registered resources + * @var array + */ public $registered_resources = array(); /** - * resource handler cache - * @var array - */ + * resource handler cache + * @var array + */ public $_resource_handlers = array(); /** - * registered cache resources - * @var array - */ + * registered cache resources + * @var array + */ public $registered_cache_resources = array(); /** - * cache resource handler cache - * @var array - */ + * cache resource handler cache + * @var array + */ public $_cacheresource_handlers = array(); /** - * autoload filter - * @var array - */ + * autoload filter + * @var array + */ public $autoload_filters = array(); /** - * default modifier - * @var array - */ + * default modifier + * @var array + */ public $default_modifiers = array(); /** - * autoescape variable output - * @var boolean - */ + * autoescape variable output + * @var boolean + */ public $escape_html = false; /** - * global internal smarty vars - * @var array - */ + * global internal smarty vars + * @var array + */ public static $_smarty_vars = array(); /** - * start time for execution time calculation - * @var int - */ + * start time for execution time calculation + * @var int + */ public $start_time = 0; /** - * default file permissions - * @var int - */ + * default file permissions + * @var int + */ public $_file_perms = 0644; /** - * default dir permissions - * @var int - */ + * default dir permissions + * @var int + */ public $_dir_perms = 0771; /** - * block tag hierarchy - * @var array - */ + * block tag hierarchy + * @var array + */ public $_tag_stack = array(); /** - * self pointer to Smarty object - * @var Smarty - */ + * self pointer to Smarty object + * @var Smarty + */ public $smarty; /** - * required by the compiler for BC - * @var string - */ + * required by the compiler for BC + * @var string + */ public $_current_file = null; /** - * internal flag to enable parser debugging - * @var bool - */ + * internal flag to enable parser debugging + * @var bool + */ public $_parserdebug = false; /** - * Saved parameter of merged templates during compilation - * - * @var array - */ + * Saved parameter of merged templates during compilation + * + * @var array + */ public $merged_templates_func = array(); /**#@-*/ /** - * Initialize new Smarty object - * - */ + * Initialize new Smarty object + * + */ public function __construct() { // selfpointer needed by some other class methods $this->smarty = $this; if (is_callable('mb_internal_encoding')) { - mb_internal_encoding(SMARTY_RESOURCE_CHAR_SET); + mb_internal_encoding(Smarty::$_CHARSET); } $this->start_time = microtime(true); // set default dirs @@ -593,25 +621,25 @@ public function __construct() ->setPluginsDir(SMARTY_PLUGINS_DIR) ->setCacheDir('.' . DS . 'cache' . DS) ->setConfigDir('.' . DS . 'configs' . DS); - + $this->debug_tpl = 'file:' . dirname(__FILE__) . '/debug.tpl'; if (isset($_SERVER['SCRIPT_NAME'])) { $this->assignGlobal('SCRIPT_NAME', $_SERVER['SCRIPT_NAME']); } } - + /** - * Class destructor - */ + * Class destructor + */ public function __destruct() { // intentionally left blank } /** - * <> set selfpointer on cloned object - */ + * <> set selfpointer on cloned object + */ public function __clone() { $this->smarty = $this; @@ -619,14 +647,14 @@ public function __clone() /** - * <> Generic getter. - * - * Calls the appropriate getter function. - * Issues an E_USER_NOTICE if no valid getter is found. - * - * @param string $name property name - * @return mixed - */ + * <> Generic getter. + * + * Calls the appropriate getter function. + * Issues an E_USER_NOTICE if no valid getter is found. + * + * @param string $name property name + * @return mixed + */ public function __get($name) { $allowed = array( @@ -645,14 +673,14 @@ public function __get($name) } /** - * <> Generic setter. - * - * Calls the appropriate setter function. - * Issues an E_USER_NOTICE if no valid setter is found. - * - * @param string $name property name - * @param mixed $value parameter passed to setter - */ + * <> Generic setter. + * + * Calls the appropriate setter function. + * Issues an E_USER_NOTICE if no valid setter is found. + * + * @param string $name property name + * @param mixed $value parameter passed to setter + */ public function __set($name, $value) { $allowed = array( @@ -671,11 +699,11 @@ public function __set($name, $value) } /** - * Check if a template resource exists - * - * @param string $resource_name template name - * @return boolean status - */ + * Check if a template resource exists + * + * @param string $resource_name template name + * @return boolean status + */ public function templateExists($resource_name) { // create template object @@ -688,12 +716,12 @@ public function templateExists($resource_name) } /** - * Returns a single or all global variables - * - * @param object $smarty - * @param string $varname variable name or null - * @return string variable value or or array of variables - */ + * Returns a single or all global variables + * + * @param object $smarty + * @param string $varname variable name or null + * @return string variable value or or array of variables + */ public function getGlobal($varname = null) { if (isset($varname)) { @@ -712,12 +740,12 @@ public function getGlobal($varname = null) } /** - * Empty cache folder - * - * @param integer $exp_time expiration time - * @param string $type resource type - * @return integer number of cache files deleted - */ + * Empty cache folder + * + * @param integer $exp_time expiration time + * @param string $type resource type + * @return integer number of cache files deleted + */ function clearAllCache($exp_time = null, $type = null) { // load cache resource and call clearAll @@ -727,15 +755,15 @@ function clearAllCache($exp_time = null, $type = null) } /** - * Empty cache for a specific template - * - * @param string $template_name template name - * @param string $cache_id cache id - * @param string $compile_id compile id - * @param integer $exp_time expiration time - * @param string $type resource type - * @return integer number of cache files deleted - */ + * Empty cache for a specific template + * + * @param string $template_name template name + * @param string $cache_id cache id + * @param string $compile_id compile id + * @param integer $exp_time expiration time + * @param string $type resource type + * @return integer number of cache files deleted + */ public function clearCache($template_name, $cache_id = null, $compile_id = null, $exp_time = null, $type = null) { // load cache resource and call clear @@ -745,12 +773,12 @@ public function clearCache($template_name, $cache_id = null, $compile_id = null, } /** - * Loads security class and enables security - * - * @param string|Smarty_Security $security_class if a string is used, it must be class-name - * @return Smarty current Smarty instance for chaining - * @throws SmartyException when an invalid class name is provided - */ + * Loads security class and enables security + * + * @param string|Smarty_Security $security_class if a string is used, it must be class-name + * @return Smarty current Smarty instance for chaining + * @throws SmartyException when an invalid class name is provided + */ public function enableSecurity($security_class = null) { if ($security_class instanceof Smarty_Security) { @@ -774,9 +802,9 @@ public function enableSecurity($security_class = null) } /** - * Disable security - * @return Smarty current Smarty instance for chaining - */ + * Disable security + * @return Smarty current Smarty instance for chaining + */ public function disableSecurity() { $this->security_policy = null; @@ -785,11 +813,11 @@ public function disableSecurity() } /** - * Set template directory - * - * @param string|array $template_dir directory(s) of template sources - * @return Smarty current Smarty instance for chaining - */ + * Set template directory + * + * @param string|array $template_dir directory(s) of template sources + * @return Smarty current Smarty instance for chaining + */ public function setTemplateDir($template_dir) { $this->template_dir = array(); @@ -802,13 +830,13 @@ public function setTemplateDir($template_dir) } /** - * Add template directory(s) - * - * @param string|array $template_dir directory(s) of template sources - * @param string $key of the array element to assign the template dir to - * @return Smarty current Smarty instance for chaining - * @throws SmartyException when the given template directory is not valid - */ + * Add template directory(s) + * + * @param string|array $template_dir directory(s) of template sources + * @param string $key of the array element to assign the template dir to + * @return Smarty current Smarty instance for chaining + * @throws SmartyException when the given template directory is not valid + */ public function addTemplateDir($template_dir, $key=null) { // make sure we're dealing with an array @@ -836,11 +864,11 @@ public function addTemplateDir($template_dir, $key=null) } /** - * Get template directories - * - * @param mixed index of directory to get, null to get all - * @return array|string list of template directories, or directory of $index - */ + * Get template directories + * + * @param mixed index of directory to get, null to get all + * @return array|string list of template directories, or directory of $index + */ public function getTemplateDir($index=null) { if ($index !== null) { @@ -851,29 +879,29 @@ public function getTemplateDir($index=null) } /** - * Set config directory - * - * @param string|array $template_dir directory(s) of configuration sources - * @return Smarty current Smarty instance for chaining - */ + * Set config directory + * + * @param string|array $template_dir directory(s) of configuration sources + * @return Smarty current Smarty instance for chaining + */ public function setConfigDir($config_dir) { $this->config_dir = array(); foreach ((array) $config_dir as $k => $v) { $this->config_dir[$k] = rtrim($v, '/\\') . DS; } - + $this->joined_config_dir = join(DIRECTORY_SEPARATOR, $this->config_dir); return $this; } /** - * Add config directory(s) - * - * @param string|array $config_dir directory(s) of config sources - * @param string key of the array element to assign the config dir to - * @return Smarty current Smarty instance for chaining - */ + * Add config directory(s) + * + * @param string|array $config_dir directory(s) of config sources + * @param string key of the array element to assign the config dir to + * @return Smarty current Smarty instance for chaining + */ public function addConfigDir($config_dir, $key=null) { // make sure we're dealing with an array @@ -896,17 +924,17 @@ public function addConfigDir($config_dir, $key=null) // append new directory $this->config_dir[] = rtrim($config_dir, '/\\') . DS; } - + $this->joined_config_dir = join(DIRECTORY_SEPARATOR, $this->config_dir); return $this; } /** - * Get config directory - * - * @param mixed index of directory to get, null to get all - * @return array|string configuration directory - */ + * Get config directory + * + * @param mixed index of directory to get, null to get all + * @return array|string configuration directory + */ public function getConfigDir($index=null) { if ($index !== null) { @@ -917,11 +945,11 @@ public function getConfigDir($index=null) } /** - * Set plugins directory - * - * @param string|array $plugins_dir directory(s) of plugins - * @return Smarty current Smarty instance for chaining - */ + * Set plugins directory + * + * @param string|array $plugins_dir directory(s) of plugins + * @return Smarty current Smarty instance for chaining + */ public function setPluginsDir($plugins_dir) { $this->plugins_dir = array(); @@ -933,12 +961,12 @@ public function setPluginsDir($plugins_dir) } /** - * Adds directory of plugin files - * - * @param object $smarty - * @param string $ |array $ plugins folder - * @return Smarty current Smarty instance for chaining - */ + * Adds directory of plugin files + * + * @param object $smarty + * @param string $ |array $ plugins folder + * @return Smarty current Smarty instance for chaining + */ public function addPluginsDir($plugins_dir) { // make sure we're dealing with an array @@ -964,21 +992,21 @@ public function addPluginsDir($plugins_dir) } /** - * Get plugin directories - * - * @return array list of plugin directories - */ + * Get plugin directories + * + * @return array list of plugin directories + */ public function getPluginsDir() { return (array)$this->plugins_dir; } /** - * Set compile directory - * - * @param string $compile_dir directory to store compiled templates in - * @return Smarty current Smarty instance for chaining - */ + * Set compile directory + * + * @param string $compile_dir directory to store compiled templates in + * @return Smarty current Smarty instance for chaining + */ public function setCompileDir($compile_dir) { $this->compile_dir = rtrim($compile_dir, '/\\') . DS; @@ -989,21 +1017,21 @@ public function setCompileDir($compile_dir) } /** - * Get compiled directory - * - * @return string path to compiled templates - */ + * Get compiled directory + * + * @return string path to compiled templates + */ public function getCompileDir() { return $this->compile_dir; } /** - * Set cache directory - * - * @param string $cache_dir directory to store cached templates in - * @return Smarty current Smarty instance for chaining - */ + * Set cache directory + * + * @param string $cache_dir directory to store cached templates in + * @return Smarty current Smarty instance for chaining + */ public function setCacheDir($cache_dir) { $this->cache_dir = rtrim($cache_dir, '/\\') . DS; @@ -1014,21 +1042,21 @@ public function setCacheDir($cache_dir) } /** - * Get cache directory - * - * @return string path of cache directory - */ + * Get cache directory + * + * @return string path of cache directory + */ public function getCacheDir() { return $this->cache_dir; } /** - * Set default modifiers - * - * @param array|string $modifiers modifier or list of modifiers to set - * @return Smarty current Smarty instance for chaining - */ + * Set default modifiers + * + * @param array|string $modifiers modifier or list of modifiers to set + * @return Smarty current Smarty instance for chaining + */ public function setDefaultModifiers($modifiers) { $this->default_modifiers = (array) $modifiers; @@ -1036,11 +1064,11 @@ public function setDefaultModifiers($modifiers) } /** - * Add default modifiers - * - * @param array|string $modifiers modifier or list of modifiers to add - * @return Smarty current Smarty instance for chaining - */ + * Add default modifiers + * + * @param array|string $modifiers modifier or list of modifiers to add + * @return Smarty current Smarty instance for chaining + */ public function addDefaultModifiers($modifiers) { if (is_array($modifiers)) { @@ -1053,10 +1081,10 @@ public function addDefaultModifiers($modifiers) } /** - * Get default modifiers - * - * @return array list of default modifiers - */ + * Get default modifiers + * + * @return array list of default modifiers + */ public function getDefaultModifiers() { return $this->default_modifiers; @@ -1064,12 +1092,12 @@ public function getDefaultModifiers() /** - * Set autoload filters - * - * @param array $filters filters to load automatically - * @param string $type "pre", "output", … specify the filter type to set. Defaults to none treating $filters' keys as the appropriate types - * @return Smarty current Smarty instance for chaining - */ + * Set autoload filters + * + * @param array $filters filters to load automatically + * @param string $type "pre", "output", … specify the filter type to set. Defaults to none treating $filters' keys as the appropriate types + * @return Smarty current Smarty instance for chaining + */ public function setAutoloadFilters($filters, $type=null) { if ($type !== null) { @@ -1082,12 +1110,12 @@ public function setAutoloadFilters($filters, $type=null) } /** - * Add autoload filters - * - * @param array $filters filters to load automatically - * @param string $type "pre", "output", … specify the filter type to set. Defaults to none treating $filters' keys as the appropriate types - * @return Smarty current Smarty instance for chaining - */ + * Add autoload filters + * + * @param array $filters filters to load automatically + * @param string $type "pre", "output", … specify the filter type to set. Defaults to none treating $filters' keys as the appropriate types + * @return Smarty current Smarty instance for chaining + */ public function addAutoloadFilters($filters, $type=null) { if ($type !== null) { @@ -1110,11 +1138,11 @@ public function addAutoloadFilters($filters, $type=null) } /** - * Get autoload filters - * - * @param string $type type of filter to get autoloads for. Defaults to all autoload filters - * @return array array( 'type1' => array( 'filter1', 'filter2', … ) ) or array( 'filter1', 'filter2', …) if $type was specified - */ + * Get autoload filters + * + * @param string $type type of filter to get autoloads for. Defaults to all autoload filters + * @return array array( 'type1' => array( 'filter1', 'filter2', … ) ) or array( 'filter1', 'filter2', …) if $type was specified + */ public function getAutoloadFilters($type=null) { if ($type !== null) { @@ -1125,22 +1153,22 @@ public function getAutoloadFilters($type=null) } /** - * return name of debugging template - * - * @return string - */ + * return name of debugging template + * + * @return string + */ public function getDebugTemplate() { return $this->debug_tpl; } /** - * set the debug template - * - * @param string $tpl_name - * @return Smarty current Smarty instance for chaining - * @throws SmartyException if file is not readable - */ + * set the debug template + * + * @param string $tpl_name + * @return Smarty current Smarty instance for chaining + * @throws SmartyException if file is not readable + */ public function setDebugTemplate($tpl_name) { if (!is_readable($tpl_name)) { @@ -1152,15 +1180,15 @@ public function setDebugTemplate($tpl_name) } /** - * creates a template object - * - * @param string $template the resource handle of the template file - * @param mixed $cache_id cache id to be used with this template - * @param mixed $compile_id compile id to be used with this template - * @param object $parent next higher level of Smarty variables - * @param boolean $do_clone flag is Smarty object shall be cloned - * @return object template object - */ + * creates a template object + * + * @param string $template the resource handle of the template file + * @param mixed $cache_id cache id to be used with this template + * @param mixed $compile_id compile id to be used with this template + * @param object $parent next higher level of Smarty variables + * @param boolean $do_clone flag is Smarty object shall be cloned + * @return object template object + */ public function createTemplate($template, $cache_id = null, $compile_id = null, $parent = null, $do_clone = true) { if (!empty($cache_id) && (is_object($cache_id) || is_array($cache_id))) { @@ -1191,6 +1219,8 @@ public function createTemplate($template, $cache_id = null, $compile_id = null, $tpl = clone $this->template_objects[$_templateId]; $tpl->smarty = clone $tpl->smarty; $tpl->parent = $parent; + $tpl->tpl_vars = array(); + $tpl->config_vars = array(); } else { $tpl = new $this->template_class($template, clone $this, $parent, $cache_id, $compile_id); } @@ -1198,6 +1228,9 @@ public function createTemplate($template, $cache_id = null, $compile_id = null, if (isset($this->template_objects[$_templateId])) { // return cached template object $tpl = $this->template_objects[$_templateId]; + $tpl->parent = $parent; + $tpl->tpl_vars = array(); + $tpl->config_vars = array(); } else { $tpl = new $this->template_class($template, $this, $parent, $cache_id, $compile_id); } @@ -1214,14 +1247,14 @@ public function createTemplate($template, $cache_id = null, $compile_id = null, /** - * Takes unknown classes and loads plugin files for them - * class name format: Smarty_PluginType_PluginName - * plugin filename format: plugintype.pluginname.php - * - * @param string $plugin_name class plugin name to load - * @param bool $check check if already loaded - * @return string |boolean filepath of loaded file or false - */ + * Takes unknown classes and loads plugin files for them + * class name format: Smarty_PluginType_PluginName + * plugin filename format: plugintype.pluginname.php + * + * @param string $plugin_name class plugin name to load + * @param bool $check check if already loaded + * @return string |boolean filepath of loaded file or false + */ public function loadPlugin($plugin_name, $check = true) { // if function or class exists, exit silently (already loaded) @@ -1249,6 +1282,8 @@ public function loadPlugin($plugin_name, $check = true) // plugin filename is expected to be: [type].[name].php $_plugin_filename = "{$_name_parts[1]}.{$_name_parts[2]}.php"; + $_stream_resolve_include_path = function_exists('stream_resolve_include_path'); + // loop through plugin dirs and find the plugin foreach($this->getPluginsDir() as $_plugin_dir) { $names = array( @@ -1262,7 +1297,13 @@ public function loadPlugin($plugin_name, $check = true) } if ($this->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_plugin_dir)) { // try PHP include_path - if (($file = Smarty_Internal_Get_Include_Path::getIncludePath($file)) !== false) { + if ($_stream_resolve_include_path) { + $file = stream_resolve_include_path($file); + } else { + $file = Smarty_Internal_Get_Include_Path::getIncludePath($file); + } + + if ($file !== false) { require_once($file); return $file; } @@ -1274,41 +1315,41 @@ public function loadPlugin($plugin_name, $check = true) } /** - * Compile all template files - * - * @param string $extension file extension - * @param bool $force_compile force all to recompile - * @param int $time_limit - * @param int $max_errors - * @return integer number of template files recompiled - */ + * Compile all template files + * + * @param string $extension file extension + * @param bool $force_compile force all to recompile + * @param int $time_limit + * @param int $max_errors + * @return integer number of template files recompiled + */ public function compileAllTemplates($extention = '.tpl', $force_compile = false, $time_limit = 0, $max_errors = null) { return Smarty_Internal_Utility::compileAllTemplates($extention, $force_compile, $time_limit, $max_errors, $this); } /** - * Compile all config files - * - * @param string $extension file extension - * @param bool $force_compile force all to recompile - * @param int $time_limit - * @param int $max_errors - * @return integer number of template files recompiled - */ + * Compile all config files + * + * @param string $extension file extension + * @param bool $force_compile force all to recompile + * @param int $time_limit + * @param int $max_errors + * @return integer number of template files recompiled + */ public function compileAllConfig($extention = '.conf', $force_compile = false, $time_limit = 0, $max_errors = null) { return Smarty_Internal_Utility::compileAllConfig($extention, $force_compile, $time_limit, $max_errors, $this); } /** - * Delete compiled template file - * - * @param string $resource_name template name - * @param string $compile_id compile id - * @param integer $exp_time expiration time - * @return integer number of template files deleted - */ + * Delete compiled template file + * + * @param string $resource_name template name + * @param string $compile_id compile id + * @param integer $exp_time expiration time + * @return integer number of template files deleted + */ public function clearCompiledTemplate($resource_name = null, $compile_id = null, $exp_time = null) { return Smarty_Internal_Utility::clearCompiledTemplate($resource_name, $compile_id, $exp_time, $this); @@ -1316,11 +1357,11 @@ public function clearCompiledTemplate($resource_name = null, $compile_id = null, /** - * Return array of tag/attributes of all tags used by an template - * - * @param object $templae template object - * @return array of tag/attributes - */ + * Return array of tag/attributes of all tags used by an template + * + * @param object $templae template object + * @return array of tag/attributes + */ public function getTags(Smarty_Internal_Template $template) { return Smarty_Internal_Utility::getTags($template); @@ -1347,7 +1388,7 @@ public function testInstall(&$errors=null) public static function mutingErrorHandler($errno, $errstr, $errfile, $errline, $errcontext) { $_is_muted_directory = false; - + // add the SMARTY_DIR to the list of muted directories if (!isset(Smarty::$_muted_directories[SMARTY_DIR])) { $smarty_dir = realpath(SMARTY_DIR); @@ -1356,7 +1397,7 @@ public static function mutingErrorHandler($errno, $errstr, $errfile, $errline, $ 'length' => strlen($smarty_dir), ); } - + // walk the muted directories and test against $errfile foreach (Smarty::$_muted_directories as $key => &$dir) { if (!$dir) { @@ -1427,23 +1468,34 @@ public static function unmuteExpectedErrors() } } +// Check if we're running on windows +Smarty::$_IS_WINDOWS = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'; + +// let PCRE (preg_*) treat strings as ISO-8859-1 if we're not dealing with UTF-8 +if (Smarty::$_CHARSET !== 'UTF-8') { + Smarty::$_UTF8_MODIFIER = ''; +} + /** -* Smarty exception class -* @package Smarty -*/ + * Smarty exception class + * @package Smarty + */ class SmartyException extends Exception { + public function __construct($message) { + $this->message = htmlentities($message); + } } /** -* Smarty compiler exception class -* @package Smarty -*/ + * Smarty compiler exception class + * @package Smarty + */ class SmartyCompilerException extends SmartyException { } /** -* Autoloader -*/ + * Autoloader + */ function smartyAutoload($class) { $_class = strtolower($class); diff --git a/includes/libs/Smarty/debug.tpl b/includes/libs/Smarty/debug.tpl deleted file mode 100644 index 058c5b2..0000000 --- a/includes/libs/Smarty/debug.tpl +++ /dev/null @@ -1,133 +0,0 @@ -{capture name='_smarty_debug' assign=debug_output} - - - - Smarty Debug Console - - - - -

    Smarty Debug Console - {if isset($template_name)}{$template_name|debug_print_var}{else}Total Time {$execution_time|string_format:"%.5f"}{/if}

    - -{if !empty($template_data)} -

    included templates & config files (load time in seconds)

    - -
    -{foreach $template_data as $template} - {$template.name} - - (compile {$template['compile_time']|string_format:"%.5f"}) (render {$template['render_time']|string_format:"%.5f"}) (cache {$template['cache_time']|string_format:"%.5f"}) - -
    -{/foreach} -
    -{/if} - -

    assigned template variables

    - - - {foreach $assigned_vars as $vars} - - - - {/foreach} -
    ${$vars@key|escape:'html'}{$vars|debug_print_var}
    - -

    assigned config file variables (outer template scope)

    - - - {foreach $config_vars as $vars} - - - - {/foreach} - -
    {$vars@key|escape:'html'}{$vars|debug_print_var}
    - - -{/capture} - diff --git a/includes/libs/Smarty/plugins/block.lang.php b/includes/libs/Smarty/plugins/block.lang.php deleted file mode 100644 index 8696028..0000000 --- a/includes/libs/Smarty/plugins/block.lang.php +++ /dev/null @@ -1,45 +0,0 @@ -. - * - * @package 2Moons - * @author Slaver - * @copyright 2009 Lucky (XGProyecto) - * @copyright 2011 Slaver (Fork/2Moons) - * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License - * @version 1.5 (2011-05-04) - * @info $Id$ - * @link http://code.google.com/p/2moons/ - */ - -function smarty_block_lang($params, $content, $template, &$repeat) -{ - if(empty($content)) - return ''; - - if(strpos($content, '.') === false) - return isset($GLOBALS['LNG'][$content]) ? $GLOBALS['LNG'][$content] : $content; - - $_TMP = explode('.', $content); - if(count($_TMP) == 2) - return isset($GLOBALS['LNG'][$_TMP[0]][$_TMP[1]]) ? $GLOBALS['LNG'][$_TMP[0]][$_TMP[1]] : $content; - else - return isset($GLOBALS['LNG'][$_TMP[0]][$_TMP[1]][$_TMP[2]]) ? $GLOBALS['LNG'][$_TMP[0]][$_TMP[1]][$_TMP[2]] : $content; -} - -?> \ No newline at end of file diff --git a/includes/libs/Smarty/plugins/block.textformat.php b/includes/libs/Smarty/plugins/block.textformat.php index bdd8067..b22b104 100644 --- a/includes/libs/Smarty/plugins/block.textformat.php +++ b/includes/libs/Smarty/plugins/block.textformat.php @@ -84,13 +84,13 @@ function smarty_block_textformat($params, $content, $template, &$repeat) continue; } // convert mult. spaces & special chars to single space - $_paragraph = preg_replace(array('!\s+!u', '!(^\s+)|(\s+$)!u'), array(' ', ''), $_paragraph); + $_paragraph = preg_replace(array('!\s+!' . Smarty::$_UTF8_MODIFIER, '!(^\s+)|(\s+$)!' . Smarty::$_UTF8_MODIFIER), array(' ', ''), $_paragraph); // indent first line if ($indent_first > 0) { $_paragraph = str_repeat($indent_char, $indent_first) . $_paragraph; } // wordwrap sentences - if (SMARTY_MBSTRING /* ^phpunit */&&empty($_SERVER['SMARTY_PHPUNIT_DISABLE_MBSTRING'])/* phpunit$ */) { + if (Smarty::$_MBSTRING) { require_once(SMARTY_PLUGINS_DIR . 'shared.mb_wordwrap.php'); $_paragraph = smarty_mb_wordwrap($_paragraph, $wrap - $indent, $wrap_char, $wrap_cut); } else { diff --git a/includes/libs/Smarty/plugins/function.fetch.php b/includes/libs/Smarty/plugins/function.fetch.php index cde98d2..eca1182 100644 --- a/includes/libs/Smarty/plugins/function.fetch.php +++ b/includes/libs/Smarty/plugins/function.fetch.php @@ -26,188 +26,186 @@ function smarty_function_fetch($params, $template) trigger_error("[plugin] fetch parameter 'file' cannot be empty",E_USER_NOTICE); return; } - - $content = ''; - if (isset($template->smarty->security_policy) && !preg_match('!^(http|ftp)://!i', $params['file'])) { - if(!$template->smarty->security_policy->isTrustedResourceDir($params['file'])) { - return; - } - - // fetch the file - if($fp = @fopen($params['file'],'r')) { - while(!feof($fp)) { - $content .= fgets ($fp,4096); + + // strip file protocol + if (stripos($params['file'], 'file://') === 0) { + $params['file'] = substr($params['file'], 7); + } + + $protocol = strpos($params['file'], '://'); + if ($protocol !== false) { + $protocol = strtolower(substr($params['file'], 0, $protocol)); + } + + if (isset($template->smarty->security_policy)) { + if ($protocol) { + // remote resource (or php stream, …) + if(!$template->smarty->security_policy->isTrustedUri($params['file'])) { + return; } - fclose($fp); } else { - trigger_error('[plugin] fetch cannot read file \'' . $params['file'] . '\'',E_USER_NOTICE); - return; + // local file + if(!$template->smarty->security_policy->isTrustedResourceDir($params['file'])) { + return; + } } - } else { - // not a local file - if(preg_match('!^http://!i',$params['file'])) { - // http fetch - if($uri_parts = parse_url($params['file'])) { - // set defaults - $host = $server_name = $uri_parts['host']; - $timeout = 30; - $accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*"; - $agent = "Smarty Template Engine ". Smarty::SMARTY_VERSION; - $referer = ""; - $uri = !empty($uri_parts['path']) ? $uri_parts['path'] : '/'; - $uri .= !empty($uri_parts['query']) ? '?' . $uri_parts['query'] : ''; - $_is_proxy = false; - if(empty($uri_parts['port'])) { - $port = 80; - } else { - $port = $uri_parts['port']; - } - if(!empty($uri_parts['user'])) { - $user = $uri_parts['user']; - } - if(!empty($uri_parts['pass'])) { - $pass = $uri_parts['pass']; - } - // loop through parameters, setup headers - foreach($params as $param_key => $param_value) { - switch($param_key) { - case "file": - case "assign": - case "assign_headers": - break; - case "user": - if(!empty($param_value)) { - $user = $param_value; - } - break; - case "pass": - if(!empty($param_value)) { - $pass = $param_value; - } - break; - case "accept": - if(!empty($param_value)) { - $accept = $param_value; - } - break; - case "header": - if(!empty($param_value)) { - if(!preg_match('![\w\d-]+: .+!',$param_value)) { - trigger_error("[plugin] invalid header format '".$param_value."'",E_USER_NOTICE); - return; - } else { - $extra_headers[] = $param_value; - } - } - break; - case "proxy_host": - if(!empty($param_value)) { - $proxy_host = $param_value; - } - break; - case "proxy_port": - if(!preg_match('!\D!', $param_value)) { - $proxy_port = (int) $param_value; - } else { - trigger_error("[plugin] invalid value for attribute '".$param_key."'",E_USER_NOTICE); + } + + $content = ''; + if ($protocol == 'http') { + // http fetch + if($uri_parts = parse_url($params['file'])) { + // set defaults + $host = $server_name = $uri_parts['host']; + $timeout = 30; + $accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*"; + $agent = "Smarty Template Engine ". Smarty::SMARTY_VERSION; + $referer = ""; + $uri = !empty($uri_parts['path']) ? $uri_parts['path'] : '/'; + $uri .= !empty($uri_parts['query']) ? '?' . $uri_parts['query'] : ''; + $_is_proxy = false; + if(empty($uri_parts['port'])) { + $port = 80; + } else { + $port = $uri_parts['port']; + } + if(!empty($uri_parts['user'])) { + $user = $uri_parts['user']; + } + if(!empty($uri_parts['pass'])) { + $pass = $uri_parts['pass']; + } + // loop through parameters, setup headers + foreach($params as $param_key => $param_value) { + switch($param_key) { + case "file": + case "assign": + case "assign_headers": + break; + case "user": + if(!empty($param_value)) { + $user = $param_value; + } + break; + case "pass": + if(!empty($param_value)) { + $pass = $param_value; + } + break; + case "accept": + if(!empty($param_value)) { + $accept = $param_value; + } + break; + case "header": + if(!empty($param_value)) { + if(!preg_match('![\w\d-]+: .+!',$param_value)) { + trigger_error("[plugin] invalid header format '".$param_value."'",E_USER_NOTICE); return; - } - break; - case "agent": - if(!empty($param_value)) { - $agent = $param_value; - } - break; - case "referer": - if(!empty($param_value)) { - $referer = $param_value; - } - break; - case "timeout": - if(!preg_match('!\D!', $param_value)) { - $timeout = (int) $param_value; } else { - trigger_error("[plugin] invalid value for attribute '".$param_key."'",E_USER_NOTICE); - return; + $extra_headers[] = $param_value; } - break; - default: - trigger_error("[plugin] unrecognized attribute '".$param_key."'",E_USER_NOTICE); + } + break; + case "proxy_host": + if(!empty($param_value)) { + $proxy_host = $param_value; + } + break; + case "proxy_port": + if(!preg_match('!\D!', $param_value)) { + $proxy_port = (int) $param_value; + } else { + trigger_error("[plugin] invalid value for attribute '".$param_key."'",E_USER_NOTICE); return; - } - } - if(!empty($proxy_host) && !empty($proxy_port)) { - $_is_proxy = true; - $fp = fsockopen($proxy_host,$proxy_port,$errno,$errstr,$timeout); - } else { - $fp = fsockopen($server_name,$port,$errno,$errstr,$timeout); + } + break; + case "agent": + if(!empty($param_value)) { + $agent = $param_value; + } + break; + case "referer": + if(!empty($param_value)) { + $referer = $param_value; + } + break; + case "timeout": + if(!preg_match('!\D!', $param_value)) { + $timeout = (int) $param_value; + } else { + trigger_error("[plugin] invalid value for attribute '".$param_key."'",E_USER_NOTICE); + return; + } + break; + default: + trigger_error("[plugin] unrecognized attribute '".$param_key."'",E_USER_NOTICE); + return; } + } + if(!empty($proxy_host) && !empty($proxy_port)) { + $_is_proxy = true; + $fp = fsockopen($proxy_host,$proxy_port,$errno,$errstr,$timeout); + } else { + $fp = fsockopen($server_name,$port,$errno,$errstr,$timeout); + } - if(!$fp) { - trigger_error("[plugin] unable to fetch: $errstr ($errno)",E_USER_NOTICE); - return; + if(!$fp) { + trigger_error("[plugin] unable to fetch: $errstr ($errno)",E_USER_NOTICE); + return; + } else { + if($_is_proxy) { + fputs($fp, 'GET ' . $params['file'] . " HTTP/1.0\r\n"); } else { - if($_is_proxy) { - fputs($fp, 'GET ' . $params['file'] . " HTTP/1.0\r\n"); - } else { - fputs($fp, "GET $uri HTTP/1.0\r\n"); - } - if(!empty($host)) { - fputs($fp, "Host: $host\r\n"); - } - if(!empty($accept)) { - fputs($fp, "Accept: $accept\r\n"); - } - if(!empty($agent)) { - fputs($fp, "User-Agent: $agent\r\n"); - } - if(!empty($referer)) { - fputs($fp, "Referer: $referer\r\n"); - } - if(isset($extra_headers) && is_array($extra_headers)) { - foreach($extra_headers as $curr_header) { - fputs($fp, $curr_header."\r\n"); - } - } - if(!empty($user) && !empty($pass)) { - fputs($fp, "Authorization: BASIC ".base64_encode("$user:$pass")."\r\n"); + fputs($fp, "GET $uri HTTP/1.0\r\n"); + } + if(!empty($host)) { + fputs($fp, "Host: $host\r\n"); + } + if(!empty($accept)) { + fputs($fp, "Accept: $accept\r\n"); + } + if(!empty($agent)) { + fputs($fp, "User-Agent: $agent\r\n"); + } + if(!empty($referer)) { + fputs($fp, "Referer: $referer\r\n"); + } + if(isset($extra_headers) && is_array($extra_headers)) { + foreach($extra_headers as $curr_header) { + fputs($fp, $curr_header."\r\n"); } + } + if(!empty($user) && !empty($pass)) { + fputs($fp, "Authorization: BASIC ".base64_encode("$user:$pass")."\r\n"); + } - fputs($fp, "\r\n"); - while(!feof($fp)) { - $content .= fgets($fp,4096); - } - fclose($fp); - $csplit = preg_split("!\r\n\r\n!",$content,2); + fputs($fp, "\r\n"); + while(!feof($fp)) { + $content .= fgets($fp,4096); + } + fclose($fp); + $csplit = preg_split("!\r\n\r\n!",$content,2); - $content = $csplit[1]; + $content = $csplit[1]; - if(!empty($params['assign_headers'])) { - $template->assign($params['assign_headers'],preg_split("!\r\n!",$csplit[0])); - } + if(!empty($params['assign_headers'])) { + $template->assign($params['assign_headers'],preg_split("!\r\n!",$csplit[0])); } - } else { - trigger_error("[plugin fetch] unable to parse URL, check syntax",E_USER_NOTICE); - return; } } else { - // ftp fetch - if($fp = @fopen($params['file'],'r')) { - while(!feof($fp)) { - $content .= fgets ($fp,4096); - } - fclose($fp); - } else { - trigger_error('[plugin] fetch cannot read file \'' . $params['file'] .'\'',E_USER_NOTICE); - return; - } + trigger_error("[plugin fetch] unable to parse URL, check syntax",E_USER_NOTICE); + return; + } + } else { + $content = @file_get_contents($params['file']); + if ($content === false) { + throw new SmartyException("{fetch} cannot read resource '" . $params['file'] ."'"); } - } - if (!empty($params['assign'])) { - $template->assign($params['assign'],$content); + $template->assign($params['assign'], $content); } else { return $content; } diff --git a/includes/libs/Smarty/plugins/function.html_checkboxes.php b/includes/libs/Smarty/plugins/function.html_checkboxes.php index 1e8beb4..fb9584b 100644 --- a/includes/libs/Smarty/plugins/function.html_checkboxes.php +++ b/includes/libs/Smarty/plugins/function.html_checkboxes.php @@ -29,6 +29,7 @@ * - separator (optional) - ie
    or   * - output (optional) - the output next to each checkbox * - assign (optional) - assign the output as an array to this variable + * - escape (optional) - escape the content (not value), defaults to true * * * @link http://www.smarty.net/manual/en/language.function.html.checkboxes.php {html_checkboxes} @@ -50,6 +51,7 @@ function smarty_function_html_checkboxes($params, $template) $options = null; $selected = array(); $separator = ''; + $escape = true; $labels = true; $label_ids = false; $output = null; @@ -63,6 +65,7 @@ function smarty_function_html_checkboxes($params, $template) $$_key = (string) $_val; break; + case 'escape': case 'labels': case 'label_ids': $$_key = (bool) $_val; @@ -130,12 +133,12 @@ function smarty_function_html_checkboxes($params, $template) if (isset($options)) { foreach ($options as $_key=>$_val) { - $_html_result[] = smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids); + $_html_result[] = smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids, $escape); } } else { foreach ($values as $_i=>$_key) { $_val = isset($output[$_i]) ? $output[$_i] : ''; - $_html_result[] = smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids); + $_html_result[] = smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids, $escape); } } @@ -147,7 +150,7 @@ function smarty_function_html_checkboxes($params, $template) } -function smarty_function_html_checkboxes_output($name, $value, $output, $selected, $extra, $separator, $labels, $label_ids) { +function smarty_function_html_checkboxes_output($name, $value, $output, $selected, $extra, $separator, $labels, $label_ids, $escape=true) { $_output = ''; if (is_object($value)) { @@ -174,7 +177,7 @@ function smarty_function_html_checkboxes_output($name, $value, $output, $selecte if ($labels) { if ($label_ids) { - $_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!u', '_', $name . '_' . $value)); + $_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!' . Smarty::$_UTF8_MODIFIER, '_', $name . '_' . $value)); $_output .= '