diff options
103 files changed, 8233 insertions, 636 deletions
diff --git a/.gitignore b/.gitignore index 6eb5419a0..a25819b26 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,8 @@ Server/CONTRIBUTORS Server/LICENSE Server/Licenses Server/itemblacklist +Tools/MCADefrag/MCADefrag +Tools/ProtoProxy/ProtoProxy Testing/ ChunkWorxSave.ini doxy/ diff --git a/CMakeLists.txt b/CMakeLists.txt index e15f9084f..3234e93d7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9,14 +9,13 @@ if (MSVC) endif() # These env variables are used for configuring Travis CI builds. -# See https://github.com/mc-server/MCServer/pull/767 if(DEFINED ENV{TRAVIS_CUBERITE_BUILD_TYPE}) message("Setting build type to $ENV{TRAVIS_CUBERITE_BUILD_TYPE}") set(CMAKE_BUILD_TYPE $ENV{TRAVIS_CUBERITE_BUILD_TYPE}) endif() -if(DEFINED ENV{TRAVIS_MCSERVER_FORCE32}) - set(FORCE32 $ENV{TRAVIS_MCSERVER_FORCE32}) +if(DEFINED ENV{TRAVIS_CUBERITE_FORCE32}) + set(FORCE32 $ENV{TRAVIS_CUBERITE_FORCE32}) endif() if(DEFINED ENV{TRAVIS_BUILD_WITH_COVERAGE}) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 87e5e9492..005d0855e 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -16,6 +16,7 @@ keyboard Lapayo linnemannr (Reid Linnemann) lkolbly +LogicParrot Luksor M10360 marmot21 @@ -29,7 +30,6 @@ nesco NiLSPACE (formerly STR_Warrior) p-mcgowan rs2k -SafwatHalaby (Safwat Halaby) SamJBarney Schwertspize Seadragon91 (Lukas Pioch) @@ -26,7 +26,7 @@ DOXYFILE_ENCODING = UTF-8 # identify the project. Note that if you do not use Doxywizard you need # to put quotes around the project name if it contains spaces. -PROJECT_NAME = MCServer +PROJECT_NAME = Cuberite # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or diff --git a/GETTING-STARTED.md b/GETTING-STARTED.md index fc777aed0..5a36652ee 100644 --- a/GETTING-STARTED.md +++ b/GETTING-STARTED.md @@ -88,8 +88,8 @@ Basically, the process is: **Windows:** You need to first generate a solution file by executing `cmake .` on the commandline at the top-level folder of the repository, then just open the solution file in MSVC and build. Note that the first time after generating the solution, you will need to do extra setup in order to be able to fully debug in MSVC: -- Set the startup project to Cuberite: right-click the MCServer project in the Solution Explorer and choose "Set as Startup Project". -- Set the debugging folder: right-click the MCServer project in the Solution Explorer, choose "Properties". In the dialog, browse to "Configuration Properties" -> "Debugging" and set "Working Directory" to "../MCServer". +- Set the startup project to Cuberite: right-click the Cuberite project in the Solution Explorer and choose "Set as Startup Project". +- Set the debugging folder: right-click the Cuberite project in the Solution Explorer, choose "Properties". In the dialog, browse to "Configuration Properties" -> "Debugging" and set "Working Directory" to "../Server". How to Run ---------- diff --git a/Install/.gitignore b/Install/.gitignore index 3b0a53050..52c5ca5a9 100644 --- a/Install/.gitignore +++ b/Install/.gitignore @@ -1,4 +1,2 @@ -MCServer.exe -*.7z *.tag *.example.ini
\ No newline at end of file diff --git a/Install/Cuberite_high_detail_debug.cmd b/Install/Cuberite_high_detail_debug.cmd new file mode 100644 index 000000000..0880495e3 --- /dev/null +++ b/Install/Cuberite_high_detail_debug.cmd @@ -0,0 +1 @@ +Cuberite --crash-dump-full diff --git a/Install/Cuberite_medium_detail_debug.cmd b/Install/Cuberite_medium_detail_debug.cmd new file mode 100644 index 000000000..1dcb291a0 --- /dev/null +++ b/Install/Cuberite_medium_detail_debug.cmd @@ -0,0 +1 @@ +Cuberite --crash-dump-globals diff --git a/Install/MCServer_high_detail_debug.cmd b/Install/MCServer_high_detail_debug.cmd deleted file mode 100644 index d94af8150..000000000 --- a/Install/MCServer_high_detail_debug.cmd +++ /dev/null @@ -1 +0,0 @@ -MCServer --crash-dump-full diff --git a/Install/MCServer_medium_detail_debug.cmd b/Install/MCServer_medium_detail_debug.cmd deleted file mode 100644 index 0a33c27fd..000000000 --- a/Install/MCServer_medium_detail_debug.cmd +++ /dev/null @@ -1 +0,0 @@ -MCServer --crash-dump-globals diff --git a/Server/.gitignore b/Server/.gitignore index 1df22b079..768adbb2c 100644 --- a/Server/.gitignore +++ b/Server/.gitignore @@ -31,6 +31,7 @@ motd.txt *.dmp *.xml mcserver_api.lua +cuberite_api.lua # Ignore the webadmin certs / privkey, so that no-one commits theirs by accident: webadmin/httpscert.crt diff --git a/Server/Plugins/APIDump/APIDesc.lua b/Server/Plugins/APIDump/APIDesc.lua index 6be3795a8..6f3736bef 100644 --- a/Server/Plugins/APIDump/APIDesc.lua +++ b/Server/Plugins/APIDump/APIDesc.lua @@ -1928,6 +1928,7 @@ a_Player:OpenWindow(Window); Feed = { Params = "AddFood, AddSaturation", Return = "bool", Notes = "Tries to add the specified amounts to food level and food saturation level (only positive amounts expected). Returns true if player was hungry and the food was consumed, false if too satiated." }, FoodPoison = { Params = "NumTicks", Return = "", Notes = "Starts the food poisoning for the specified amount of ticks; if already foodpoisoned, sets FoodPoisonedTicksRemaining to the larger of the two" }, ForceSetSpeed = { Params = "{{Vector3d|Direction}}", Notes = "Forces the player to move to the given direction." }, + Freeze = { Params = "{{Vector3d|Location}}", Return = "", Notes = "Teleports the player to \"Location\" and prevents them from moving, locking them in place until unfreeze() is called" }, GetClientHandle = { Params = "", Return = "{{cClientHandle}}", Notes = "Returns the client handle representing the player's connection. May be nil (AI players)." }, GetColor = { Return = "string", Notes = "Returns the full color code to be used for this player's messages (based on their rank). Prefix player messages with this code." }, GetCurrentXp = { Params = "", Return = "number", Notes = "Returns the current amount of XP" }, @@ -1943,6 +1944,7 @@ a_Player:OpenWindow(Window); GetFoodPoisonedTicksRemaining = { Params = "", Return = "", Notes = "Returns the number of ticks left for the food posoning effect" }, GetFoodSaturationLevel = { Params = "", Return = "number", Notes = "Returns the food saturation (overcharge of the food level, is depleted before food level)" }, GetFoodTickTimer = { Params = "", Return = "", Notes = "Returns the number of ticks past the last food-based heal or damage action; when this timer reaches 80, a new heal / damage is applied." }, + GetFrozenDuration = { Params = "", Return = "number", Notes = "Returns the number of ticks since the player was frozen" }, GetGameMode = { Return = "{{Globals#GameMode|GameMode}}", Notes = "Returns the player's gamemode. The player may have their gamemode unassigned, in which case they inherit the gamemode from the current {{cWorld|world}}.<br /> <b>NOTE:</b> Instead of comparing the value returned by this function to the gmXXX constants, use the IsGameModeXXX() functions. These functions handle the gamemode inheritance automatically."}, GetIP = { Return = "string", Notes = "Returns the IP address of the player, if available. Returns an empty string if there's no IP to report."}, GetInventory = { Return = "{{cInventory|Inventory}}", Notes = "Returns the player's inventory"}, @@ -1975,6 +1977,7 @@ a_Player:OpenWindow(Window); IsGameModeSurvival = { Params = "", Return = "bool", Notes = "Returns true if the player is in the gmSurvival gamemode, or has their gamemode unset and the world is a gmSurvival world." }, IsInBed = { Params = "", Return = "bool", Notes = "Returns true if the player is currently lying in a bed." }, IsSatiated = { Params = "", Return = "bool", Notes = "Returns true if the player is satiated (cannot eat)." }, + IsFrozen = { Params = "", Return = "bool", Notes = "Returns true if the player is frozen. See Freeze()" }, IsVisible = { Params = "", Return = "bool", Notes = "Returns true if the player is visible to other players" }, LoadRank = { Params = "", Return = "", Notes = "Reloads the player's rank, message visuals and permissions from the {{cRankManager}}, based on the player's current rank." }, MoveTo = { Params = "{{Vector3d|NewPosition}}", Return = "Tries to move the player into the specified position." }, @@ -2017,6 +2020,7 @@ a_Player:OpenWindow(Window); TossEquippedItem = { Params = "[Amount]", Return = "", Notes = "Tosses the item that the player has selected in their hotbar. Amount defaults to 1." }, TossHeldItem = { Params = "[Amount]", Return = "", Notes = "Tosses the item held by the cursor, then the player is in a UI window. Amount defaults to 1." }, TossPickup = { Params = "{{cItem|Item}}", Return = "", Notes = "Tosses a pickup newly created from the specified item." }, + Unfreeze = { Params = "", Return = "", Notes = "Allows the player to move again, canceling the effects of Freeze()" }, XpForLevel = { Params = "XPLevel", Return = "number", Notes = "(STATIC) Returns the total amount of XP needed for the specified XP level. Inverse of CalcLevelFromXp()." }, }, Constants = @@ -2286,7 +2290,50 @@ local CompressedString = cStringCompression.CompressStringGZIP("DataToCompress") SetFuseTicks = { Return = "number", Notes = "Set the fuse ticks until the tnt will explode." }, }, Inherits = "cEntity", - }, + }, -- cTNTEntity + + cUrlParser = + { + Desc = [[ + Provides a parser for generic URLs that returns the individual components of the URL.</p> + <p> + Note that all functions are static. Call them by using "cUrlParser:Parse(...)" etc. + ]], + Functions = + { + GetDefaultPort = { Params = "Scheme", Return = "number", Notes = "(STATIC) Returns the default port that should be used for the given scheme (protocol). Returns zero if the scheme is not known." }, + IsKnownScheme = { Params = "Scheme", Return = "bool", Notes = "(STATIC) Returns true if the scheme (protocol) is recognized by the parser." }, + Parse = { Params = "URL", Return = "Scheme, Username, Password, Host, Port, Path, Query, Fragment", Notes = "(STATIC) Returns the individual parts of the URL. Parts that are not explicitly specified in the URL are empty, the default port for the scheme is used. If parsing fails, the function returns nil and an error message." }, + ParseAuthorityPart = { Params = "AuthPart", Return = "Username, Password, Host, Port", Notes = "(STATIC) Parses the Authority part of the URL. Parts that are not explicitly specified in the AuthPart are returned empty, the port is returned zero. If parsing fails, the function returns nil and an error message." }, + }, + AdditionalInfo = + { + { + Header = "Code example", + Contents = [==[ + The following code fragment uses the cUrlParser to parse an URL string into its components, and + prints those components out: +<pre class="prettyprint lang-lua"> +local Scheme, Username, Password, Host, Port, Path, Query, Fragment = cUrlParser:Parse( + "http://anonymous:user@example.com@ftp.cuberite.org:9921/releases/2015/?sort=date#files" +) +if not(Scheme) then + LOG(" Error: " .. (username or "<nil>")) +else + LOG(" Scheme = " .. Scheme) -- "http" + LOG(" Username = " .. Username) -- "anonymous" + LOG(" Password = " .. Password) -- "user@example.com" + LOG(" Host = " .. Host) -- "ftp.cuberite.org" + LOG(" Port = " .. Port) -- 9921 + LOG(" Path = " .. Path) -- "releases/2015/" + LOG(" Query = " .. Query) -- "sort=date" + LOG(" Fragment = " .. Fragment) -- "files" +end +</pre> + ]==], + }, + }, + }, -- cUrlParser cWebPlugin = { @@ -2385,7 +2432,7 @@ local CompressedString = cStringCompression.CompressStringGZIP("DataToCompress") BroadcastChatSuccess = { Params = "Message, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Prepends Green [INFO] / colours entire text (depending on ShouldUseChatPrefixes()) and broadcasts message. For success messages." }, BroadcastChatWarning = { Params = "Message, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Prepends Rose [WARN] / colours entire text (depending on ShouldUseChatPrefixes()) and broadcasts message. For concerning events, such as plugin reload etc." }, BroadcastEntityAnimation = { Params = "{{cEntity|TargetEntity}}, Animation, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Sends an animation of an entity to all clienthandles (except ExcludeClient if given)" }, - BroadcastParticleEffect = { Params = "ParticleName, X, Y, Z, OffSetX, OffSetY, OffSetZ, ParticleData, ParticleAmmount, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Spawns the specified particles to all players in the world exept the optional ExeptClient. A list of available particles by thinkofdeath can be found {{https://gist.github.com/thinkofdeath/5110835|Here}}" }, + BroadcastParticleEffect = { Params = "ParticleName, X, Y, Z, OffSetX, OffSetY, OffSetZ, ParticleData, ParticleAmount, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Spawns the specified particles to all players in the world exept the optional ExeptClient. A list of available particles by thinkofdeath can be found {{https://gist.github.com/thinkofdeath/5110835|Here}}" }, BroadcastSoundEffect = { Params = "SoundName, X, Y, Z, Volume, Pitch, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Sends the specified sound effect to all players in this world, except the optional ExceptClient" }, BroadcastSoundParticleEffect = { Params = "EffectID, X, Y, Z, EffectData, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Sends the specified effect to all players in this world, except the optional ExceptClient" }, CastThunderbolt = { Params = "X, Y, Z", Return = "", Notes = "Creates a thunderbolt at the specified coords" }, diff --git a/Server/Plugins/APIDump/Classes/BlockEntities.lua b/Server/Plugins/APIDump/Classes/BlockEntities.lua index 019e702eb..f3e53351b 100644 --- a/Server/Plugins/APIDump/Classes/BlockEntities.lua +++ b/Server/Plugins/APIDump/Classes/BlockEntities.lua @@ -282,10 +282,13 @@ World:ForEachChestInChunk(Player:GetChunkX(), Player:GetChunkZ(), { SetType = { Params = "eMobHeadType", Return = "", Notes = "Set the type of the mob head" }, SetRotation = { Params = "eMobHeadRotation", Return = "", Notes = "Sets the rotation of the mob head" }, - SetOwner = { Params = "string", Return = "", Notes = "Set the player name for mob heads with player type" }, + SetOwner = { Params = "cPlayer", Return = "", Notes = "Set the {{cPlayer|player}} for mob heads with player type" }, GetType = { Params = "", Return = "eMobHeadType", Notes = "Returns the type of the mob head" }, GetRotation = { Params = "", Return = "eMobHeadRotation", Notes = "Returns the rotation of the mob head" }, - GetOwner = { Params = "", Return = "string", Notes = "Returns the player name of the mob head" }, + GetOwnerName = { Params = "", Return = "string", Notes = "Returns the player name of the mob head" }, + GetOwnerUUID = { Params = "", Return = "string", Notes = "Returns the player UUID of the mob head" }, + GetOwnerTexture = { Params = "", Return = "string", Notes = "Returns the player texture of the mob head" }, + GetOwnerTextureSignature = { Params = "", Return = "string", Notes = "Returns the signature of the player texture of the mob head" }, }, }, -- cMobHeadEntity diff --git a/Server/Plugins/APIDump/InfoFile.html b/Server/Plugins/APIDump/InfoFile.html index 99910f5ae..baba2d27c 100644 --- a/Server/Plugins/APIDump/InfoFile.html +++ b/Server/Plugins/APIDump/InfoFile.html @@ -22,25 +22,25 @@ <li><a href="#Using">Using the file in code</a></li> <li><a href="#Examples">Examples</a></li> </ul> - - + + <hr /> <a name="Introduction"><h2>Introduction</h2></a> - + <p>For a long time Cuberite plugins were plagued by poor documentation. The plugins worked, people who wrote them knew how to use them, but for anyone new to the plugin it was a terrible ordeal learning how to use it. Most of the times, the plugin authors only wrote what commands the plugin supported, sometimes not even that. Then, there was a call to action to put an end to this, to make documenting the plugins easy and at the same time centralized. Thus, the Info.lua file was born.</p> - + <p>Most plugins have some parts that are the same across all the plugins. These are commands, console commands and their permissions. If a plugin implemented a command, it would practically copy & paste the same code over and over again. So it makes sense to extract only unique information, centralize it and automate all the parts around it. This was another reason for the Info.lua file - it is a central hub of commands, console commands and their permissions.</p> - + <p>Last, but not least, we want to make a plugin repository on the web in the future, a repository that would store plugins, their descriptions, comments. It makes sense that the centralized information can be parsed by the repository automatically, so that advanced things, such as searching for a plugin based on a command, or determining whether two plugins collide command-wise, are possible.</p> - + <p>After this file format has been devised, a tool has been written that allows for an easy generation of the documentation for the plugin in various formats. It outputs the documentation in a format that is perfect for pasting into the forum. It generates documentation in a Markup format to use in README.md on GitHub and similar sites. The clever thing is that you don't need to keep all those formats in sync manually - you edit the Info.lua file and this tool will re-generate the documentation for you.</p> - + <p>So to sum up, the Info.lua file contains the plugins' commands, console commands, their permissions and possibly the overall plugin documentation, in a structured manner that can be parsed by a program, yet is human readable and editable.</p> - - + + <hr /> <a name="Overall"><h2>The overall structure</h2></a> - + <p>The file consist of a declaration of a single Lua table, g_PluginInfo. This table contains all the information, structured, as its members. Each member can be a structure by itself. The entire file is a valid Lua source file, so any tool that syntax-checks Lua source can syntax-check this file. The file is somewhat forward- and backward- compatible, in the sense that it can be extended in any way without breaking.</p> <p>Here's a skeleton of the file:</p> <pre class="prettyprint lang-lua"> @@ -49,7 +49,7 @@ g_PluginInfo = Name = "Example Plugin", Date = "2014-06-12", Description = "This is an example plugin that shows how to use the Info.lua file", - + -- The following members will be documented in greater detail later: AdditionalInfo = {}, Commands = {}, @@ -58,15 +58,15 @@ g_PluginInfo = } </pre> <p>As you can see, the structure is pretty straightforward. Note that the order of the elements inside the table is not important (Lua property).</p> - + <p>The first few elements are for book-keeping. They declare the plugin's name, the date in ISO-format, representing the version of the plugin, and the description. The idea is that the description sums up what the plugin is all about, within some two or three sentences.</p> - - + + <hr /> <a name="AdditionalInfo"><h2>AdditionalInfo table</h2></a> - + <p>This table is used for more detailed description of the plugin. If there is any non-trivial setup process, dependencies, describe them here. This is where the description should get detailed. Don't worry about using several paragraphs of text here, if it makes the plugin easier to understand.</p> - + <p>The table should have the following layout:</p> <pre class="prettyprint lang-lua"> AdditionalInfo = @@ -82,13 +82,13 @@ AdditionalInfo = } </pre> <p>The idea here is that the tool that is used to generate the documentation from the Info.lua file will create a linkified table of contents and then each of the information elements' contents. This information should be all that is needed to successfully configure, run and manage the plugin.</p> - - + + <hr /> <a name="Commands"><h2>Commands table</h2></a> - + <p>The commands table lists all the commands that the plugin implements, together with their handler functions, required permissions, help strings and further information. The table supports recursion, which allows plugins to create multi-word commands easily (such as "//schematic load" and "//schematic save"), each having its own separate handler.</p> - + <p>The table uses structure similar to the following:</p> <pre class="prettyprint lang-lua"> Commands = @@ -144,21 +144,21 @@ Commands = }, } </pre> - + <p>Although it may seem overwhelming at first, there is a "method to this madness". Each element of the Commands table defines one command. Most commands start with a slash, so the special Lua syntax for table elements with non-standard names needs to be applied (<code>["/cmd1"] =</code>). The command can either specify subcommands, or a handler function (specifying both is UndefinedBehavior). Subcommands uses the same structure as the entire Commands table, recursively.</p> - + <p>The permission element specifies that the command is only available with the specified permission. Note that the permission for subcommand's parent isn't checked when the subcommand is called. This means that specifying the permission for a command that has subcommands has no effect whatsoever, but is discouraged because we may add processing for that in the future.</p> - + <p>The ParameterCombinations table is used only for generating the documentation, it lists the various combinations of parameters that the command supports. It's worth specifying even if the command supports only one combination, because that combination will get documented this way.</p> - + <p>The Alias member specifies any possible aliases for the command. Each alias is registered separately and if there is a subcommand table, it is applied to all aliases, just as one would expect. You can specify either a single string as the value (if there's only one alias), or a table of strings for multiple aliases. Commands with no aliases do not need to specify this member at all.</p> - - + + <hr /> <a name="ConsoleCommands"><h2>ConsoleCommands table</h2> - + <p>This table serves a purpose similar to that of the Commands table, only these commands are provided for the server console. Therefore, there are no permissions specified for these commands. Since most console commands don't use a leading slash, the command names don't need the special syntax. Also, the handler function doesn't receive the Player parameter.</p> - + <p>Here's an example of a ConsoleCommands table:</p> <pre class="prettyprint lang-lua"> ConsoleCommands = @@ -193,9 +193,9 @@ ConsoleCommands = <hr /> <a name="Permissions"><h2>Permissions table</h2></a> - + <p>The purpose of this table is to document permissions that the plugin uses. The documentation generator automatically collects the permissions specified in the Command table; the Permissions table adds a description for these permissions and may declare other permissions that aren't specifically included in the Command table.</p> - + <pre class="prettyprint lang-lua"> Permissions = { @@ -217,7 +217,7 @@ Permissions = <hr /> <a name="Using"><h2>Using the file in code</h2></a> - + <p>Just writing the Info.lua file and saving it to the plugin folder is not enough for it to actually be used. Your plugin needs to include the following boilerplate code, preferably in its Initialize() function:</p> <pre class="prettyprint lang-lua"> -- Use the InfoReg shared library to process the Info.lua file: @@ -227,11 +227,11 @@ RegisterPluginInfoConsoleCommands() </pre> <p>Of course, if your plugin doesn't have any console commands, it doesn't need to call the RegisterPluginInfoConsoleCommands() function, and similarly if it doesn't have any in-game commands, it doesn't need to call the RegisterPluginInfoCommands() function.</p> - - + + <hr /> <a name="Examples"><h2>Examples</h2></a> - + <p>There are several plugins that already implement this approach. You can visit them for inspiration and to see what the generated documentation looks like:</p> <ul> <li>Gallery plugin: <a href="https://github.com/mc-server/Gallery/blob/master/Info.lua">Info.lua</a>, <a href="http://forum.mc-server.org/showthread.php?tid=1306">Forum</a> documentation</li> @@ -242,5 +242,22 @@ RegisterPluginInfoConsoleCommands() prettyPrint(); </script> </div> + + <!-- Piwik --> + <script type="text/javascript"> + var _paq = _paq || []; + _paq.push(['trackPageView']); + _paq.push(['enableLinkTracking']); + (function() { + var u="https://analytics.cuberite.org/"; + _paq.push(['setTrackerUrl', u+'piwik.php']); + _paq.push(['setSiteId', 5]); + var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; + g.type='text/javascript'; g.async=true; g.defer=true; g.src='piwik.js'; s.parentNode.insertBefore(g,s); + })(); + </script> + <noscript><p><img src="https://analytics.cuberite.org/piwik.php?idsite=5" style="border:0;" alt="" /></p></noscript> + <!-- End Piwik Code --> + </body> </html> diff --git a/Server/Plugins/APIDump/SettingUpDecoda.html b/Server/Plugins/APIDump/SettingUpDecoda.html index 8a74f0240..fcb23a572 100644 --- a/Server/Plugins/APIDump/SettingUpDecoda.html +++ b/Server/Plugins/APIDump/SettingUpDecoda.html @@ -16,7 +16,7 @@ This article will explain how to set up Decoda, an IDE for writing Lua code, so that you can develop Cuberite plugins with the comfort of an IDE.</p> <h2><img src="Static/decoda_logo.png" /> About Decoda</h2> - + <p>To quickly introduce Decoda, it is an IDE for writing Lua code. It has the basic features expected of an IDE - you can group files into project, you can edit multiple files in a tabbed editor, the code is syntax-highlighted. Code completion, symbol browsing, and more. It also features a Lua debugger that allows you to debug your Lua code within any application that embeds the Lua runtime or uses Lua as a dynamic-link library (DLL). Although it is written using the multiplatform WxWidgets toolkit, it hasn't yet been ported to any platform other than 32-bit Windows. This unfortunately means that Linux users will not be able to use it. It can be used on 64-bit Windows, but the debugger only works for 32-bit programs.</p> <p>Here's a screenshot of a default Decoda window with the debugger stepping through the code (scaled down):<br /> <img src="Static/decoda_workspace.png" /></p> @@ -45,5 +45,22 @@ <li>Unfortunately for us Windows users, the Decoda project file uses Unix-lineends (CR only). This makes it problematic when checking the file into a version control system, since those usually expect windows (CRLF) lineends; I personally convert the lineends each time I edit the project file using <a href="http://jsimlo.sk/notepad/">TED Notepad</a>.</li> </ul> </div> + + <!-- Piwik --> + <script type="text/javascript"> + var _paq = _paq || []; + _paq.push(['trackPageView']); + _paq.push(['enableLinkTracking']); + (function() { + var u="https://analytics.cuberite.org/"; + _paq.push(['setTrackerUrl', u+'piwik.php']); + _paq.push(['setSiteId', 5]); + var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; + g.type='text/javascript'; g.async=true; g.defer=true; g.src='piwik.js'; s.parentNode.insertBefore(g,s); + })(); + </script> + <noscript><p><img src="https://analytics.cuberite.org/piwik.php?idsite=5" style="border:0;" alt="" /></p></noscript> + <!-- End Piwik Code --> + </body> </html> diff --git a/Server/Plugins/APIDump/SettingUpZeroBrane.html b/Server/Plugins/APIDump/SettingUpZeroBrane.html index 26a557140..8bef69626 100644 --- a/Server/Plugins/APIDump/SettingUpZeroBrane.html +++ b/Server/Plugins/APIDump/SettingUpZeroBrane.html @@ -16,20 +16,20 @@ This article will explain how to set up ZeroBrane Studio, an IDE for writing Lua code, so that you can develop Cuberite plugins with the comfort of an IDE.</p> <h2><img src="Static/zbs_logo.png" /> About ZeroBrane Studio</h2> - + <p>To quickly introduce ZeroBrane Studio, it is an IDE for writing Lua code. It has the basic features expected of an IDE - it allows you to manage groups of files as a project, you can edit multiple files in a tabbed editor, the code is syntax-highlighted. Code completion, symbol browsing, and more. It also features a Lua debugger that allows you to debug your Lua code within any application that uses Lua and can load Lua packages. It is written using the multiplatform WxWidgets toolkit, and runs on multiple platforms, including Windows, Linux and MacOS.</p> <p>Here's a screenshot of a default ZBS window with the debugger stepping through the code (scaled down):<br /> <img src="Static/zbs_workspace.png" /></p> <p>As you can see, you can set breakpoints in the code, inspect variables' values, view the Lua call-stacks.</p> <p>ZBS is open-source, the sources are on GitHub: <a href="https://github.com/pkulchenko/ZeroBraneStudio">https://github.com/pkulchenko/ZeroBraneStudio</a>. The project's homepage is at <a href="http://studio.zerobrane.com/">http://studio.zerobrane.com/</a>. - + <h2><img src="Static/zbs_logo.png" /> First-time setup</h2> <p>Since ZBS is a universal Lua IDE, you need to first set it up so that it is ready for Cuberite plugin development. For that, you need to download one file, <a href="https://raw.githubusercontent.com/pkulchenko/ZeroBranePackage/master/cuberite.lua">cuberite.lua</a> from the <a href="https://github.com/pkulchenko/ZeroBranePackage">ZBS's plugin repository</a>. Place that file in the "packages" folder inside your ZBS's folder. Note that there are other useful plugins in the repository and you may want to have a look there later on to further customize your ZBS. To install them, simply save them into the same folder.</p> <p>Next you should install the code-completion support specific for Cuberite. You should repeat this step from time to time, because the API evolves in time so new functions and classes are added to it quite often. You should have an APIDump plugin in your Cuberite installation. Enable the APIDump plugin in the server settings, it's very cheap to keep it enabled and it doesn't cost any performance during normal gameplay. To generate the code-completion support file, enter the <code style="background: #ddd; border: 1px solid #aaa">api</code> command into the server console. This will create a new file, "cuberite_api.lua", next to the Cuberite executable. Move that file into the "api/lua" subfolder inside your ZBS's folder. (Note that if you had the "mcserver_api.lua" file from previous versions, you should remove it)</p> <p>After you download the cuberite.lua file and install the completion support, you need to restart ZBS in order for the plugin to load. If there are no errors, you should see two new items in the Project -> Lua Interpreter submenu: "Cuberite - debug mode" and "Cuberite - release mode". The only difference between the two is which filename they use to launch Cuberite - cuberite_debug(.exe) for the debug option and "cuberite(.exe)" for the release option. If you built your own Cuberite executable and you built it in debug mode, you should select the debug mode option. In all other cases, including if you downloaded the already-compiled Cuberite executable from the internet, you should select the release mode option.</p> <p>For a first time user, it might be a bit overwhelming that there are no GUI settings in the ZBS, yet the IDE is very configurable. There are two files that you edit in order to change settings, either system-wide (all users of the computer share those settings) or user-wide (the settings are only for a specific user of the computer). Those files are regular Lua sources and you can quickly locate them and edit them from within the IDE itself, select Edit -> Preferences -> Settings: XYZ from the menu, with XYZ being either System or User.</p> <p>There is a documentation on most of the settings on ZBS's webpage, have a look at <a href="http://studio.zerobrane.com/documentation.html">http://studio.zerobrane.com/documentation.html</a>, especially the Preferences section. Personally I recommend setting editor.usetabs to true and possibly adjusting the editor.tabwidth, turn off the editor.smartindent feature and for debugging the option debugger.alloweditting should be set to true unless you feel like punishing yourself.</p> - + <h2><img src="Static/zbs_logo.png" /> Project management</h2> <p>ZBS works with projects, it considers all files and subfolder in a specific folder to be a project. There's no need for a special project file nor for adding individual files to the workspace, all files are added automatically. To open a Cuberite plugin as the project, click the triple-dot button in the Project pane, or select Project -> Project directory -> Choose... from the menu. Browse and select the Cuberite plugin's folder. ZBS will load all the files in the plugin's folder and you can start editting code.</p> <p>Note that although ZBS allows you to work with subfolders in your plugins (and you should, especially with larger plugins), the current Cuberite ZBS plugin will not be able to start debugging unless you have a file open in the editor that is at the root level of the Cuberite plugin's folder.</p> @@ -42,5 +42,22 @@ <p>Once running, if the execution hits a breakpoint, the ZBS window will come up and a green arrow is displayed next to the breakpoint line. You can step through the code using F10 (Step Into) and Shift+F10 (Step Over). You can also use the Watch window to inspect variable values, or simply hover your mouse over a variable to display its value in the tooltip. Use the Remote console pane to execute commands directly *inside* the Cuberite's plugin context.</p> <p>You can also use the Project -> Break menu item to break into the debugger as soon as possible. You can also set breakpoints while the Cuberite plugin is running. Note that due to the way in which the debugger is implemented, Cuberite may execute some more Lua code before the break / breakpoint comes into effect. If Cuberite is not executing any Lua code in your plugin, it will not break until the plugin code kicks in again. This may result in missed breakpoints and delays before the Break command becomes effective. Therefore it's best to set breakpoints before running the program, or while the program is waiting in another breakpoint.</p> </div> + + <!-- Piwik --> + <script type="text/javascript"> + var _paq = _paq || []; + _paq.push(['trackPageView']); + _paq.push(['enableLinkTracking']); + (function() { + var u="https://analytics.cuberite.org/"; + _paq.push(['setTrackerUrl', u+'piwik.php']); + _paq.push(['setSiteId', 5]); + var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; + g.type='text/javascript'; g.async=true; g.defer=true; g.src='piwik.js'; s.parentNode.insertBefore(g,s); + })(); + </script> + <noscript><p><img src="https://analytics.cuberite.org/piwik.php?idsite=5" style="border:0;" alt="" /></p></noscript> + <!-- End Piwik Code --> + </body> </html> diff --git a/Server/Plugins/APIDump/UsingChunkStays.html b/Server/Plugins/APIDump/UsingChunkStays.html index a7cb5302a..faedfdfaa 100644 --- a/Server/Plugins/APIDump/UsingChunkStays.html +++ b/Server/Plugins/APIDump/UsingChunkStays.html @@ -14,7 +14,7 @@ <p> A plugin may need to manipulate data in arbitrary chunks, and it needs a way to make the server guarantee that the chunks are available in memory.</p> - + <h2>The problem</h2> <p> Usually when plugins want to manipulate larger areas of world data, they need to make sure that the @@ -27,7 +27,7 @@ either the block area has incomplete data (Read() failed) or incomplete data has been written to the world (Write() failed). Recovery from this is near impossible - you can't simply read or write again later, because the world may have changed in the meantime.</p> - + <h2>The solution</h2> <p> The naive solution would be to monitor chunk loads and unloads, and postpone the operations until all @@ -47,7 +47,7 @@ despawned. So the callback must use the longer way to access such objects, such as calling <a href="cWorld.html">cWorld:DoWithEntityByID()</a> or <a href="cWorld.html">cWorld:DoWithPlayer()</a>.</p> - + <h2>The example</h2> <p> As a simple example, consider a theoretical plugin that allows a player to save the immediate @@ -66,13 +66,13 @@ function HandleCommandSaveSpawn(a_Split, a_Player) local SpawnZ = a_Player:GetWorld():GetSpawnZ() local Bounds = cCuboid(SpawnX - 25, SpawnY - 25, SpawnZ - 25, SpawnX + 25, SpawnY + 25, SpawnZ + 25) Bounds:ClampY(0, 255) - + -- Read the area around spawn into a cBlockArea, save to file: local Area = cBlockArea() local FileName = a_Player:GetName() .. "_spawn.schematic" Area:Read(a_Player:GetWorld(), Bounds, cBlockArea.baTypes + cBlockArea.baMetas) Area:SaveToSchematicFile(FileName) - + -- Notify the player: a_Player:SendMessage(cCompositeChat("The spawn has been saved", mtInfo)) return true @@ -96,7 +96,7 @@ function HandleCommandSaveSpawn(a_Split, a_Player) local SpawnZ = a_Player:GetWorld():GetSpawnZ() local Bounds = cCuboid(SpawnX - 25, SpawnY - 25, SpawnZ - 25, SpawnX + 25, SpawnY + 25, SpawnZ + 25) Bounds:ClampY(0, 255) - + -- Get a list of chunks that we need loaded: local MinChunkX = math.floor((SpawnX - 25) / 16) local MaxChunkX = math.ceil ((SpawnX + 25) / 16) @@ -108,11 +108,11 @@ function HandleCommandSaveSpawn(a_Split, a_Player) table.insert(Chunks, {x, z}) end end -- for x - + -- Store the player's name and world to use in the callback, because the a_Player object may no longer be valid: local PlayerName = a_Player:GetName() local World = a_Player:GetWorld() - + -- This is the callback that is executed once all the chunks are loaded: local OnAllChunksAvailable = function() -- Read the area around spawn into a cBlockArea, save to file: @@ -124,7 +124,7 @@ function HandleCommandSaveSpawn(a_Split, a_Player) else Msg = cCompositeChat("Cannot save the spawn", mtFailure) end - + -- Notify the player: -- Note that we cannot use a_Player here, because it may no longer be valid (if the player disconnected before the command completes) World:DoWithPlayer(PlayerName, @@ -133,14 +133,14 @@ function HandleCommandSaveSpawn(a_Split, a_Player) end ) end - + -- Ask the server to load our chunks and notify us once it's done: World:ChunkStay(Chunks, nil, OnAllChunksAvailable) - + -- Note that code here may get executed before the callback is called! -- The ChunkStay says "once you have the chunks", not "wait until you have the chunks" -- So you can't notify the player here, because the saving needn't have occurred yet. - + return true end </pre> @@ -150,7 +150,7 @@ end when we've got the chunks loaded, there's still the issue of free RAM - if the memory for the area cannot be allocated, it cannot be read even with all the chunks present. So we still do need that check.</p> - + <h2>The conclusion</h2> <p> Although it makes the code a little bit longer and is a bit more difficult to grasp at first, the @@ -163,5 +163,22 @@ end prettyPrint(); </script> </div> + + <!-- Piwik --> + <script type="text/javascript"> + var _paq = _paq || []; + _paq.push(['trackPageView']); + _paq.push(['enableLinkTracking']); + (function() { + var u="https://analytics.cuberite.org/"; + _paq.push(['setTrackerUrl', u+'piwik.php']); + _paq.push(['setSiteId', 5]); + var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; + g.type='text/javascript'; g.async=true; g.defer=true; g.src='piwik.js'; s.parentNode.insertBefore(g,s); + })(); + </script> + <noscript><p><img src="https://analytics.cuberite.org/piwik.php?idsite=5" style="border:0;" alt="" /></p></noscript> + <!-- End Piwik Code --> + </body> </html> diff --git a/Server/Plugins/APIDump/WebWorldThreads.html b/Server/Plugins/APIDump/WebWorldThreads.html index b6c5c34ca..a9e22b694 100644 --- a/Server/Plugins/APIDump/WebWorldThreads.html +++ b/Server/Plugins/APIDump/WebWorldThreads.html @@ -68,5 +68,22 @@ cRoot:Get():ForEachWorld( -- For each world... prettyPrint(); </script> </div> + + <!-- Piwik --> + <script type="text/javascript"> + var _paq = _paq || []; + _paq.push(['trackPageView']); + _paq.push(['enableLinkTracking']); + (function() { + var u="https://analytics.cuberite.org/"; + _paq.push(['setTrackerUrl', u+'piwik.php']); + _paq.push(['setSiteId', 5]); + var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; + g.type='text/javascript'; g.async=true; g.defer=true; g.src='piwik.js'; s.parentNode.insertBefore(g,s); + })(); + </script> + <noscript><p><img src="https://analytics.cuberite.org/piwik.php?idsite=5" style="border:0;" alt="" /></p></noscript> + <!-- End Piwik Code --> + </body> -</html>
\ No newline at end of file +</html> diff --git a/Server/Plugins/APIDump/Writing-a-Cuberite-plugin.html b/Server/Plugins/APIDump/Writing-a-Cuberite-plugin.html index a75a925b3..af46ad433 100644 --- a/Server/Plugins/APIDump/Writing-a-Cuberite-plugin.html +++ b/Server/Plugins/APIDump/Writing-a-Cuberite-plugin.html @@ -252,5 +252,22 @@ end prettyPrint(); </script> </div> + + <!-- Piwik --> + <script type="text/javascript"> + var _paq = _paq || []; + _paq.push(['trackPageView']); + _paq.push(['enableLinkTracking']); + (function() { + var u="https://analytics.cuberite.org/"; + _paq.push(['setTrackerUrl', u+'piwik.php']); + _paq.push(['setSiteId', 5]); + var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; + g.type='text/javascript'; g.async=true; g.defer=true; g.src='piwik.js'; s.parentNode.insertBefore(g,s); + })(); + </script> + <noscript><p><img src="https://analytics.cuberite.org/piwik.php?idsite=5" style="border:0;" alt="" /></p></noscript> + <!-- End Piwik Code --> + </body> </html> diff --git a/Server/Plugins/APIDump/main_APIDump.lua b/Server/Plugins/APIDump/main_APIDump.lua index 872fa60f4..4d8f58483 100644 --- a/Server/Plugins/APIDump/main_APIDump.lua +++ b/Server/Plugins/APIDump/main_APIDump.lua @@ -309,6 +309,22 @@ local function WriteHtmlHook(a_Hook, a_HookNav) end f:write([[</td></tr></table></div><script>prettyPrint();</script>]]) f:write(GetHtmlTimestamp()) + f:write([[<!-- Piwik --> + <script type="text/javascript"> + var _paq = _paq || []; + _paq.push(['trackPageView']); + _paq.push(['enableLinkTracking']); + (function() { + var u="https://analytics.cuberite.org/"; + _paq.push(['setTrackerUrl', u+'piwik.php']); + _paq.push(['setSiteId', 5]); + var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; + g.type='text/javascript'; g.async=true; g.defer=true; g.src='piwik.js'; s.parentNode.insertBefore(g,s); + })(); + </script> + <noscript><p><img src="https://analytics.cuberite.org/piwik.php?idsite=5" style="border:0;" alt="" /></p></noscript> + <!-- End Piwik Code --> + ]]) f:write([[</body></html>]]) f:close(); end @@ -956,6 +972,22 @@ local function WriteHtmlClass(a_ClassAPI, a_ClassMenu) cf:write([[</td></tr></table></div><script>prettyPrint();</script>]]) cf:write(GetHtmlTimestamp()) + cf:write([[<!-- Piwik --> + <script type="text/javascript"> + var _paq = _paq || []; + _paq.push(['trackPageView']); + _paq.push(['enableLinkTracking']); + (function() { + var u="https://analytics.cuberite.org/"; + _paq.push(['setTrackerUrl', u+'piwik.php']); + _paq.push(['setSiteId', 5]); + var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; + g.type='text/javascript'; g.async=true; g.defer=true; g.src='piwik.js'; s.parentNode.insertBefore(g,s); + })(); + </script> + <noscript><p><img src="https://analytics.cuberite.org/piwik.php?idsite=5" style="border:0;" alt="" /></p></noscript> + <!-- End Piwik Code --> + ]]) cf:write([[</body></html>]]) cf:close() end @@ -1318,6 +1350,7 @@ local function DumpAPIHtml(a_API) local StaticFiles = { "main.css", + "piwik.js", "prettify.js", "prettify.css", "lang-lua.js", @@ -1337,6 +1370,22 @@ local function DumpAPIHtml(a_API) f:write([[</ul></div>]]) f:write(GetHtmlTimestamp()) + f:write([[<!-- Piwik --> + <script type="text/javascript"> + var _paq = _paq || []; + _paq.push(['trackPageView']); + _paq.push(['enableLinkTracking']); + (function() { + var u="https://analytics.cuberite.org/"; + _paq.push(['setTrackerUrl', u+'piwik.php']); + _paq.push(['setSiteId', 5]); + var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; + g.type='text/javascript'; g.async=true; g.defer=true; g.src='piwik.js'; s.parentNode.insertBefore(g,s); + })(); + </script> + <noscript><p><img src="https://analytics.cuberite.org/piwik.php?idsite=5" style="border:0;" alt="" /></p></noscript> + <!-- End Piwik Code --> + ]]) f:write([[</body></html>]]) f:close() @@ -1686,7 +1735,7 @@ local function HandleCmdApiCheck(a_Split, a_EntireCmd) if (OfficialStats == "") then return true, "Cannot load official stats" end - + -- Load the API stats as a Lua file, process into usable dictionary: local Loaded, Msg = loadstring(OfficialStats) if not(Loaded) then @@ -1714,10 +1763,10 @@ local function HandleCmdApiCheck(a_Split, a_EntireCmd) end Parsed[clsK] = cls end - + -- Get the current API's undocumented stats: local API = PrepareApi() - + -- Compare the two sets of undocumented stats, list anything extra in current: local res = {} local ins = table.insert @@ -1740,7 +1789,7 @@ local function HandleCmdApiCheck(a_Split, a_EntireCmd) end end table.sort(res) - + -- Bail out if no items found: if not(res[1]) then return true, "No new undocumented functions" @@ -1751,7 +1800,7 @@ local function HandleCmdApiCheck(a_Split, a_EntireCmd) f:write(table.concat(res, "\n")) f:write("\n") f:close() - + return true, "Newly undocumented items: " .. #res .. "\n" .. table.concat(res, "\n") end diff --git a/Server/Plugins/APIDump/piwik.js b/Server/Plugins/APIDump/piwik.js new file mode 100644 index 000000000..4cc288e87 --- /dev/null +++ b/Server/Plugins/APIDump/piwik.js @@ -0,0 +1,6572 @@ +/*! + * Piwik - free/libre analytics platform + * + * JavaScript tracking client + * + * @link http://piwik.org + * @source https://github.com/piwik/piwik/blob/master/js/piwik.js + * @license http://piwik.org/free-software/bsd/ BSD-3 Clause (also in js/LICENSE.txt) + * @license magnet:?xt=urn:btih:c80d50af7d3db9be66a4d0a86db0286e4fd33292&dn=bsd-3-clause.txt BSD-3-Clause + */ +// NOTE: if you change this above Piwik comment block, you must also change `$byteStart` in js/tracker.php + +// Refer to README.md for build instructions when minifying this file for distribution. + +/* + * Browser [In]Compatibility + * - minimum required ECMAScript: ECMA-262, edition 3 + * + * Incompatible with these (and earlier) versions of: + * - IE4 - try..catch and for..in introduced in IE5 + * - IE5 - named anonymous functions, array.push, encodeURIComponent, decodeURIComponent, and getElementsByTagName introduced in IE5.5 + * - Firefox 1.0 and Netscape 8.x - FF1.5 adds array.indexOf, among other things + * - Mozilla 1.7 and Netscape 6.x-7.x + * - Netscape 4.8 + * - Opera 6 - Error object (and Presto) introduced in Opera 7 + * - Opera 7 + */ + +/*global JSON2:true */ + +if (typeof JSON2 !== 'object' && typeof window.JSON === 'object' && window.JSON.stringify && window.JSON.parse) { + JSON2 = window.JSON; +} else { + (function () { + // we make sure to not break any site that uses JSON3 as well as we do not know if they run it in conflict mode + // or not. + var exports = {}; + + // Create a JSON object only if one does not already exist. We create the + // methods in a closure to avoid creating global variables. + + /*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */ + (function () { + // Detect the `define` function exposed by asynchronous module loaders. The + // strict `define` check is necessary for compatibility with `r.js`. + var isLoader = typeof define === "function" && define.amd; + + // A set of types used to distinguish objects from primitives. + var objectTypes = { + "function": true, + "object": true + }; + + // Detect the `exports` object exposed by CommonJS implementations. + var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; + + // Use the `global` object exposed by Node (including Browserify via + // `insert-module-globals`), Narwhal, and Ringo as the default context, + // and the `window` object in browsers. Rhino exports a `global` function + // instead. + var root = objectTypes[typeof window] && window || this, + freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global; + + if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) { + root = freeGlobal; + } + + // Public: Initializes JSON 3 using the given `context` object, attaching the + // `stringify` and `parse` functions to the specified `exports` object. + function runInContext(context, exports) { + context || (context = root["Object"]()); + exports || (exports = root["Object"]()); + + // Native constructor aliases. + var Number = context["Number"] || root["Number"], + String = context["String"] || root["String"], + Object = context["Object"] || root["Object"], + Date = context["Date"] || root["Date"], + SyntaxError = context["SyntaxError"] || root["SyntaxError"], + TypeError = context["TypeError"] || root["TypeError"], + Math = context["Math"] || root["Math"], + nativeJSON = context["JSON"] || root["JSON"]; + + // Delegate to the native `stringify` and `parse` implementations. + if (typeof nativeJSON == "object" && nativeJSON) { + exports.stringify = nativeJSON.stringify; + exports.parse = nativeJSON.parse; + } + + // Convenience aliases. + var objectProto = Object.prototype, + getClass = objectProto.toString, + isProperty, forEach, undef; + + // Test the `Date#getUTC*` methods. Based on work by @Yaffle. + var isExtended = new Date(-3509827334573292); + try { + // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical + // results for certain dates in Opera >= 10.53. + isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 && + // Safari < 2.0.2 stores the internal millisecond time value correctly, + // but clips the values returned by the date methods to the range of + // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]). + isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708; + } catch (exception) {} + + // Internal: Determines whether the native `JSON.stringify` and `parse` + // implementations are spec-compliant. Based on work by Ken Snyder. + function has(name) { + if (has[name] !== undef) { + // Return cached feature test result. + return has[name]; + } + var isSupported; + if (name == "bug-string-char-index") { + // IE <= 7 doesn't support accessing string characters using square + // bracket notation. IE 8 only supports this for primitives. + isSupported = "a"[0] != "a"; + } else if (name == "json") { + // Indicates whether both `JSON.stringify` and `JSON.parse` are + // supported. + isSupported = has("json-stringify") && has("json-parse"); + } else { + var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}'; + // Test `JSON.stringify`. + if (name == "json-stringify") { + var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended; + if (stringifySupported) { + // A test function object with a custom `toJSON` method. + (value = function () { + return 1; + }).toJSON = value; + try { + stringifySupported = + // Firefox 3.1b1 and b2 serialize string, number, and boolean + // primitives as object literals. + stringify(0) === "0" && + // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object + // literals. + stringify(new Number()) === "0" && + stringify(new String()) == '""' && + // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or + // does not define a canonical JSON representation (this applies to + // objects with `toJSON` properties as well, *unless* they are nested + // within an object or array). + stringify(getClass) === undef && + // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and + // FF 3.1b3 pass this test. + stringify(undef) === undef && + // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s, + // respectively, if the value is omitted entirely. + stringify() === undef && + // FF 3.1b1, 2 throw an error if the given value is not a number, + // string, array, object, Boolean, or `null` literal. This applies to + // objects with custom `toJSON` methods as well, unless they are nested + // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON` + // methods entirely. + stringify(value) === "1" && + stringify([value]) == "[1]" && + // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of + // `"[null]"`. + stringify([undef]) == "[null]" && + // YUI 3.0.0b1 fails to serialize `null` literals. + stringify(null) == "null" && + // FF 3.1b1, 2 halts serialization if an array contains a function: + // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3 + // elides non-JSON values from objects and arrays, unless they + // define custom `toJSON` methods. + stringify([undef, getClass, null]) == "[null,null,null]" && + // Simple serialization test. FF 3.1b1 uses Unicode escape sequences + // where character escape codes are expected (e.g., `\b` => `\u0008`). + stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized && + // FF 3.1b1 and b2 ignore the `filter` and `width` arguments. + stringify(null, value) === "1" && + stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" && + // JSON 2, Prototype <= 1.7, and older SpiderwebKit builds incorrectly + // serialize extended years. + stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' && + // The milliseconds are optional in ES 5, but required in 5.1. + stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' && + // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative + // four-digit years instead of six-digit years. Credits: @Yaffle. + stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' && + // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond + // values less than 1000. Credits: @Yaffle. + stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"'; + } catch (exception) { + stringifySupported = false; + } + } + isSupported = stringifySupported; + } + // Test `JSON.parse`. + if (name == "json-parse") { + var parse = exports.parse; + if (typeof parse == "function") { + try { + // FF 3.1b1, b2 will throw an exception if a bare literal is provided. + // Conforming implementations should also coerce the initial argument to + // a string prior to parsing. + if (parse("0") === 0 && !parse(false)) { + // Simple parsing test. + value = parse(serialized); + var parseSupported = value["a"].length == 5 && value["a"][0] === 1; + if (parseSupported) { + try { + // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings. + parseSupported = !parse('"\t"'); + } catch (exception) {} + if (parseSupported) { + try { + // FF 4.0 and 4.0.1 allow leading `+` signs and leading + // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow + // certain octal literals. + parseSupported = parse("01") !== 1; + } catch (exception) {} + } + if (parseSupported) { + try { + // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal + // points. These environments, along with FF 3.1b1 and 2, + // also allow trailing commas in JSON objects and arrays. + parseSupported = parse("1.") !== 1; + } catch (exception) {} + } + } + } + } catch (exception) { + parseSupported = false; + } + } + isSupported = parseSupported; + } + } + return has[name] = !!isSupported; + } + + if (!has("json")) { + // Common `[[Class]]` name aliases. + var functionClass = "[object Function]", + dateClass = "[object Date]", + numberClass = "[object Number]", + stringClass = "[object String]", + arrayClass = "[object Array]", + booleanClass = "[object Boolean]"; + + // Detect incomplete support for accessing string characters by index. + var charIndexBuggy = has("bug-string-char-index"); + + // Define additional utility methods if the `Date` methods are buggy. + if (!isExtended) { + var floor = Math.floor; + // A mapping between the months of the year and the number of days between + // January 1st and the first of the respective month. + var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; + // Internal: Calculates the number of days between the Unix epoch and the + // first day of the given month. + var getDay = function (year, month) { + return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400); + }; + } + + // Internal: Determines if a property is a direct property of the given + // object. Delegates to the native `Object#hasOwnProperty` method. + if (!(isProperty = objectProto.hasOwnProperty)) { + isProperty = function (property) { + var members = {}, constructor; + if ((members.__proto__ = null, members.__proto__ = { + // The *proto* property cannot be set multiple times in recent + // versions of Firefox and SeaMonkey. + "toString": 1 + }, members).toString != getClass) { + // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but + // supports the mutable *proto* property. + isProperty = function (property) { + // Capture and break the object's prototype chain (see section 8.6.2 + // of the ES 5.1 spec). The parenthesized expression prevents an + // unsafe transformation by the Closure Compiler. + var original = this.__proto__, result = property in (this.__proto__ = null, this); + // Restore the original prototype chain. + this.__proto__ = original; + return result; + }; + } else { + // Capture a reference to the top-level `Object` constructor. + constructor = members.constructor; + // Use the `constructor` property to simulate `Object#hasOwnProperty` in + // other environments. + isProperty = function (property) { + var parent = (this.constructor || constructor).prototype; + return property in this && !(property in parent && this[property] === parent[property]); + }; + } + members = null; + return isProperty.call(this, property); + }; + } + + // Internal: Normalizes the `for...in` iteration algorithm across + // environments. Each enumerated key is yielded to a `callback` function. + forEach = function (object, callback) { + var size = 0, Properties, members, property; + + // Tests for bugs in the current environment's `for...in` algorithm. The + // `valueOf` property inherits the non-enumerable flag from + // `Object.prototype` in older versions of IE, Netscape, and Mozilla. + (Properties = function () { + this.valueOf = 0; + }).prototype.valueOf = 0; + + // Iterate over a new instance of the `Properties` class. + members = new Properties(); + for (property in members) { + // Ignore all properties inherited from `Object.prototype`. + if (isProperty.call(members, property)) { + size++; + } + } + Properties = members = null; + + // Normalize the iteration algorithm. + if (!size) { + // A list of non-enumerable properties inherited from `Object.prototype`. + members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"]; + // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable + // properties. + forEach = function (object, callback) { + var isFunction = getClass.call(object) == functionClass, property, length; + var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty; + for (property in object) { + // Gecko <= 1.0 enumerates the `prototype` property of functions under + // certain conditions; IE does not. + if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) { + callback(property); + } + } + // Manually invoke the callback for each non-enumerable property. + for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property)); + }; + } else if (size == 2) { + // Safari <= 2.0.4 enumerates shadowed properties twice. + forEach = function (object, callback) { + // Create a set of iterated properties. + var members = {}, isFunction = getClass.call(object) == functionClass, property; + for (property in object) { + // Store each property name to prevent double enumeration. The + // `prototype` property of functions is not enumerated due to cross- + // environment inconsistencies. + if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) { + callback(property); + } + } + }; + } else { + // No bugs detected; use the standard `for...in` algorithm. + forEach = function (object, callback) { + var isFunction = getClass.call(object) == functionClass, property, isConstructor; + for (property in object) { + if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) { + callback(property); + } + } + // Manually invoke the callback for the `constructor` property due to + // cross-environment inconsistencies. + if (isConstructor || isProperty.call(object, (property = "constructor"))) { + callback(property); + } + }; + } + return forEach(object, callback); + }; + + // Public: Serializes a JavaScript `value` as a JSON string. The optional + // `filter` argument may specify either a function that alters how object and + // array members are serialized, or an array of strings and numbers that + // indicates which properties should be serialized. The optional `width` + // argument may be either a string or number that specifies the indentation + // level of the output. + if (!has("json-stringify")) { + // Internal: A map of control characters and their escaped equivalents. + var Escapes = { + 92: "\\\\", + 34: '\\"', + 8: "\\b", + 12: "\\f", + 10: "\\n", + 13: "\\r", + 9: "\\t" + }; + + // Internal: Converts `value` into a zero-padded string such that its + // length is at least equal to `width`. The `width` must be <= 6. + var leadingZeroes = "000000"; + var toPaddedString = function (width, value) { + // The `|| 0` expression is necessary to work around a bug in + // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`. + return (leadingZeroes + (value || 0)).slice(-width); + }; + + // Internal: Double-quotes a string `value`, replacing all ASCII control + // characters (characters with code unit values between 0 and 31) with + // their escaped equivalents. This is an implementation of the + // `Quote(value)` operation defined in ES 5.1 section 15.12.3. + var unicodePrefix = "\\u00"; + var quote = function (value) { + var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10; + var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value); + for (; index < length; index++) { + var charCode = value.charCodeAt(index); + // If the character is a control character, append its Unicode or + // shorthand escape sequence; otherwise, append the character as-is. + switch (charCode) { + case 8: case 9: case 10: case 12: case 13: case 34: case 92: + result += Escapes[charCode]; + break; + default: + if (charCode < 32) { + result += unicodePrefix + toPaddedString(2, charCode.toString(16)); + break; + } + result += useCharIndex ? symbols[index] : value.charAt(index); + } + } + return result + '"'; + }; + + // Internal: Recursively serializes an object. Implements the + // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations. + var serialize = function (property, object, callback, properties, whitespace, indentation, stack) { + var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result; + try { + // Necessary for host object support. + value = object[property]; + } catch (exception) {} + if (typeof value == "object" && value) { + className = getClass.call(value); + if (className == dateClass && !isProperty.call(value, "toJSON")) { + if (value > -1 / 0 && value < 1 / 0) { + // Dates are serialized according to the `Date#toJSON` method + // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15 + // for the ISO 8601 date time string format. + if (getDay) { + // Manually compute the year, month, date, hours, minutes, + // seconds, and milliseconds if the `getUTC*` methods are + // buggy. Adapted from @Yaffle's `date-shim` project. + date = floor(value / 864e5); + for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++); + for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++); + date = 1 + date - getDay(year, month); + // The `time` value specifies the time within the day (see ES + // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used + // to compute `A modulo B`, as the `%` operator does not + // correspond to the `modulo` operation for negative numbers. + time = (value % 864e5 + 864e5) % 864e5; + // The hours, minutes, seconds, and milliseconds are obtained by + // decomposing the time within the day. See section 15.9.1.10. + hours = floor(time / 36e5) % 24; + minutes = floor(time / 6e4) % 60; + seconds = floor(time / 1e3) % 60; + milliseconds = time % 1e3; + } else { + year = value.getUTCFullYear(); + month = value.getUTCMonth(); + date = value.getUTCDate(); + hours = value.getUTCHours(); + minutes = value.getUTCMinutes(); + seconds = value.getUTCSeconds(); + milliseconds = value.getUTCMilliseconds(); + } + // Serialize extended years correctly. + value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + + "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) + + // Months, dates, hours, minutes, and seconds should have two + // digits; milliseconds should have three. + "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) + + // Milliseconds are optional in ES 5.0, but required in 5.1. + "." + toPaddedString(3, milliseconds) + "Z"; + } else { + value = null; + } + } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) { + // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the + // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3 + // ignores all `toJSON` methods on these objects unless they are + // defined directly on an instance. + value = value.toJSON(property); + } + } + if (callback) { + // If a replacement function was provided, call it to obtain the value + // for serialization. + value = callback.call(object, property, value); + } + if (value === null) { + return "null"; + } + className = getClass.call(value); + if (className == booleanClass) { + // Booleans are represented literally. + return "" + value; + } else if (className == numberClass) { + // JSON numbers must be finite. `Infinity` and `NaN` are serialized as + // `"null"`. + return value > -1 / 0 && value < 1 / 0 ? "" + value : "null"; + } else if (className == stringClass) { + // Strings are double-quoted and escaped. + return quote("" + value); + } + // Recursively serialize objects and arrays. + if (typeof value == "object") { + // Check for cyclic structures. This is a linear search; performance + // is inversely proportional to the number of unique nested objects. + for (length = stack.length; length--;) { + if (stack[length] === value) { + // Cyclic structures cannot be serialized by `JSON.stringify`. + throw TypeError(); + } + } + // Add the object to the stack of traversed objects. + stack.push(value); + results = []; + // Save the current indentation level and indent one additional level. + prefix = indentation; + indentation += whitespace; + if (className == arrayClass) { + // Recursively serialize array elements. + for (index = 0, length = value.length; index < length; index++) { + element = serialize(index, value, callback, properties, whitespace, indentation, stack); + results.push(element === undef ? "null" : element); + } + result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]"; + } else { + // Recursively serialize object members. Members are selected from + // either a user-specified list of property names, or the object + // itself. + forEach(properties || value, function (property) { + var element = serialize(property, value, callback, properties, whitespace, indentation, stack); + if (element !== undef) { + // According to ES 5.1 section 15.12.3: "If `gap` {whitespace} + // is not the empty string, let `member` {quote(property) + ":"} + // be the concatenation of `member` and the `space` character." + // The "`space` character" refers to the literal space + // character, not the `space` {width} argument provided to + // `JSON.stringify`. + results.push(quote(property) + ":" + (whitespace ? " " : "") + element); + } + }); + result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}"; + } + // Remove the object from the traversed object stack. + stack.pop(); + return result; + } + }; + + // Public: `JSON.stringify`. See ES 5.1 section 15.12.3. + exports.stringify = function (source, filter, width) { + var whitespace, callback, properties, className; + if (objectTypes[typeof filter] && filter) { + if ((className = getClass.call(filter)) == functionClass) { + callback = filter; + } else if (className == arrayClass) { + // Convert the property names array into a makeshift set. + properties = {}; + for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1)); + } + } + if (width) { + if ((className = getClass.call(width)) == numberClass) { + // Convert the `width` to an integer and create a string containing + // `width` number of space characters. + if ((width -= width % 1) > 0) { + for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " "); + } + } else if (className == stringClass) { + whitespace = width.length <= 10 ? width : width.slice(0, 10); + } + } + // Opera <= 7.54u2 discards the values associated with empty string keys + // (`""`) only if they are used directly within an object member list + // (e.g., `!("" in { "": 1})`). + return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []); + }; + } + + // Public: Parses a JSON source string. + if (!has("json-parse")) { + var fromCharCode = String.fromCharCode; + + // Internal: A map of escaped control characters and their unescaped + // equivalents. + var Unescapes = { + 92: "\\", + 34: '"', + 47: "/", + 98: "\b", + 116: "\t", + 110: "\n", + 102: "\f", + 114: "\r" + }; + + // Internal: Stores the parser state. + var Index, Source; + + // Internal: Resets the parser state and throws a `SyntaxError`. + var abort = function () { + Index = Source = null; + throw SyntaxError(); + }; + + // Internal: Returns the next token, or `"$"` if the parser has reached + // the end of the source string. A token may be a string, number, `null` + // literal, or Boolean literal. + var lex = function () { + var source = Source, length = source.length, value, begin, position, isSigned, charCode; + while (Index < length) { + charCode = source.charCodeAt(Index); + switch (charCode) { + case 9: case 10: case 13: case 32: + // Skip whitespace tokens, including tabs, carriage returns, line + // feeds, and space characters. + Index++; + break; + case 123: case 125: case 91: case 93: case 58: case 44: + // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at + // the current position. + value = charIndexBuggy ? source.charAt(Index) : source[Index]; + Index++; + return value; + case 34: + // `"` delimits a JSON string; advance to the next character and + // begin parsing the string. String tokens are prefixed with the + // sentinel `@` character to distinguish them from punctuators and + // end-of-string tokens. + for (value = "@", Index++; Index < length;) { + charCode = source.charCodeAt(Index); + if (charCode < 32) { + // Unescaped ASCII control characters (those with a code unit + // less than the space character) are not permitted. + abort(); + } else if (charCode == 92) { + // A reverse solidus (`\`) marks the beginning of an escaped + // control character (including `"`, `\`, and `/`) or Unicode + // escape sequence. + charCode = source.charCodeAt(++Index); + switch (charCode) { + case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114: + // Revive escaped control characters. + value += Unescapes[charCode]; + Index++; + break; + case 117: + // `\u` marks the beginning of a Unicode escape sequence. + // Advance to the first character and validate the + // four-digit code point. + begin = ++Index; + for (position = Index + 4; Index < position; Index++) { + charCode = source.charCodeAt(Index); + // A valid sequence comprises four hexdigits (case- + // insensitive) that form a single hexadecimal value. + if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) { + // Invalid Unicode escape sequence. + abort(); + } + } + // Revive the escaped character. + value += fromCharCode("0x" + source.slice(begin, Index)); + break; + default: + // Invalid escape sequence. + abort(); + } + } else { + if (charCode == 34) { + // An unescaped double-quote character marks the end of the + // string. + break; + } + charCode = source.charCodeAt(Index); + begin = Index; + // Optimize for the common case where a string is valid. + while (charCode >= 32 && charCode != 92 && charCode != 34) { + charCode = source.charCodeAt(++Index); + } + // Append the string as-is. + value += source.slice(begin, Index); + } + } + if (source.charCodeAt(Index) == 34) { + // Advance to the next character and return the revived string. + Index++; + return value; + } + // Unterminated string. + abort(); + default: + // Parse numbers and literals. + begin = Index; + // Advance past the negative sign, if one is specified. + if (charCode == 45) { + isSigned = true; + charCode = source.charCodeAt(++Index); + } + // Parse an integer or floating-point value. + if (charCode >= 48 && charCode <= 57) { + // Leading zeroes are interpreted as octal literals. + if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) { + // Illegal octal literal. + abort(); + } + isSigned = false; + // Parse the integer component. + for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++); + // Floats cannot contain a leading decimal point; however, this + // case is already accounted for by the parser. + if (source.charCodeAt(Index) == 46) { + position = ++Index; + // Parse the decimal component. + for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); + if (position == Index) { + // Illegal trailing decimal. + abort(); + } + Index = position; + } + // Parse exponents. The `e` denoting the exponent is + // case-insensitive. + charCode = source.charCodeAt(Index); + if (charCode == 101 || charCode == 69) { + charCode = source.charCodeAt(++Index); + // Skip past the sign following the exponent, if one is + // specified. + if (charCode == 43 || charCode == 45) { + Index++; + } + // Parse the exponential component. + for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); + if (position == Index) { + // Illegal empty exponent. + abort(); + } + Index = position; + } + // Coerce the parsed value to a JavaScript number. + return +source.slice(begin, Index); + } + // A negative sign may only precede numbers. + if (isSigned) { + abort(); + } + // `true`, `false`, and `null` literals. + if (source.slice(Index, Index + 4) == "true") { + Index += 4; + return true; + } else if (source.slice(Index, Index + 5) == "false") { + Index += 5; + return false; + } else if (source.slice(Index, Index + 4) == "null") { + Index += 4; + return null; + } + // Unrecognized token. + abort(); + } + } + // Return the sentinel `$` character if the parser has reached the end + // of the source string. + return "$"; + }; + + // Internal: Parses a JSON `value` token. + var get = function (value) { + var results, hasMembers; + if (value == "$") { + // Unexpected end of input. + abort(); + } + if (typeof value == "string") { + if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") { + // Remove the sentinel `@` character. + return value.slice(1); + } + // Parse object and array literals. + if (value == "[") { + // Parses a JSON array, returning a new JavaScript array. + results = []; + for (;; hasMembers || (hasMembers = true)) { + value = lex(); + // A closing square bracket marks the end of the array literal. + if (value == "]") { + break; + } + // If the array literal contains elements, the current token + // should be a comma separating the previous element from the + // next. + if (hasMembers) { + if (value == ",") { + value = lex(); + if (value == "]") { + // Unexpected trailing `,` in array literal. + abort(); + } + } else { + // A `,` must separate each array element. + abort(); + } + } + // Elisions and leading commas are not permitted. + if (value == ",") { + abort(); + } + results.push(get(value)); + } + return results; + } else if (value == "{") { + // Parses a JSON object, returning a new JavaScript object. + results = {}; + for (;; hasMembers || (hasMembers = true)) { + value = lex(); + // A closing curly brace marks the end of the object literal. + if (value == "}") { + break; + } + // If the object literal contains members, the current token + // should be a comma separator. + if (hasMembers) { + if (value == ",") { + value = lex(); + if (value == "}") { + // Unexpected trailing `,` in object literal. + abort(); + } + } else { + // A `,` must separate each object member. + abort(); + } + } + // Leading commas are not permitted, object property names must be + // double-quoted strings, and a `:` must separate each property + // name and value. + if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") { + abort(); + } + results[value.slice(1)] = get(lex()); + } + return results; + } + // Unexpected token encountered. + abort(); + } + return value; + }; + + // Internal: Updates a traversed object member. + var update = function (source, property, callback) { + var element = walk(source, property, callback); + if (element === undef) { + delete source[property]; + } else { + source[property] = element; + } + }; + + // Internal: Recursively traverses a parsed JSON object, invoking the + // `callback` function for each value. This is an implementation of the + // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2. + var walk = function (source, property, callback) { + var value = source[property], length; + if (typeof value == "object" && value) { + // `forEach` can't be used to traverse an array in Opera <= 8.54 + // because its `Object#hasOwnProperty` implementation returns `false` + // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`). + if (getClass.call(value) == arrayClass) { + for (length = value.length; length--;) { + update(value, length, callback); + } + } else { + forEach(value, function (property) { + update(value, property, callback); + }); + } + } + return callback.call(source, property, value); + }; + + // Public: `JSON.parse`. See ES 5.1 section 15.12.2. + exports.parse = function (source, callback) { + var result, value; + Index = 0; + Source = "" + source; + result = get(lex()); + // If a JSON string contains multiple tokens, it is invalid. + if (lex() != "$") { + abort(); + } + // Reset the parser state. + Index = Source = null; + return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result; + }; + } + } + + exports["runInContext"] = runInContext; + return exports; + } + + if (freeExports && !isLoader) { + // Export for CommonJS environments. + runInContext(root, freeExports); + } else { + // Export for spiderweb browsers and JavaScript engines. + var nativeJSON = root.JSON, + previousJSON = root["JSON3"], + isRestored = false; + + var JSON3 = runInContext(root, (root["JSON3"] = { + // Public: Restores the original value of the global `JSON` object and + // returns a reference to the `JSON3` object. + "noConflict": function () { + if (!isRestored) { + isRestored = true; + root.JSON = nativeJSON; + root["JSON3"] = previousJSON; + nativeJSON = previousJSON = null; + } + return JSON3; + } + })); + + root.JSON = { + "parse": JSON3.parse, + "stringify": JSON3.stringify + }; + } + + // Export for asynchronous module loaders. + if (isLoader) { + define(function () { + return JSON3; + }); + } + }).call(this); + /************************************************************ + * end JSON + ************************************************************/ + + JSON2 = exports; + + })(); +} + +/* startjslint */ +/*jslint browser:true, plusplus:true, vars:true, nomen:true, evil:true, regexp: false, bitwise: true, white: true */ +/*global JSON2 */ +/*global window */ +/*global unescape */ +/*global ActiveXObject */ +/*members encodeURIComponent, decodeURIComponent, getElementsByTagName, + shift, unshift, piwikAsyncInit, + createElement, appendChild, characterSet, charset, all, + addEventListener, attachEvent, removeEventListener, detachEvent, disableCookies, + cookie, domain, readyState, documentElement, doScroll, title, text, + location, top, onerror, document, referrer, parent, links, href, protocol, name, GearsFactory, + performance, mozPerformance, msPerformance, spiderwebkitPerformance, timing, requestStart, + responseEnd, event, which, button, srcElement, type, target, + parentNode, tagName, hostname, className, + userAgent, cookieEnabled, platform, mimeTypes, enabledPlugin, javaEnabled, + XMLHttpRequest, ActiveXObject, open, setRequestHeader, onreadystatechange, send, readyState, status, + getTime, getTimeAlias, setTime, toGMTString, getHours, getMinutes, getSeconds, + toLowerCase, toUpperCase, charAt, indexOf, lastIndexOf, split, slice, + onload, src, + min, round, random, + exec, + res, width, height, devicePixelRatio, + pdf, qt, realp, wma, dir, fla, java, gears, ag, + hook, getHook, getVisitorId, getVisitorInfo, setUserId, getUserId, setSiteId, getSiteId, setTrackerUrl, getTrackerUrl, appendToTrackingUrl, getRequest, addPlugin, + getAttributionInfo, getAttributionCampaignName, getAttributionCampaignKeyword, + getAttributionReferrerTimestamp, getAttributionReferrerUrl, + setCustomData, getCustomData, + setCustomRequestProcessing, + setCustomVariable, getCustomVariable, deleteCustomVariable, storeCustomVariablesInCookie, setCustomDimension, getCustomDimension, + deleteCustomDimension, setDownloadExtensions, addDownloadExtensions, removeDownloadExtensions, + setDomains, setIgnoreClasses, setRequestMethod, setRequestContentType, + setReferrerUrl, setCustomUrl, setAPIUrl, setDocumentTitle, + setDownloadClasses, setLinkClasses, + setCampaignNameKey, setCampaignKeywordKey, + discardHashTag, + setCookieNamePrefix, setCookieDomain, setCookiePath, setVisitorIdCookie, + setVisitorCookieTimeout, setSessionCookieTimeout, setReferralCookieTimeout, + setConversionAttributionFirstReferrer, + disablePerformanceTracking, setGenerationTimeMs, + doNotTrack, setDoNotTrack, msDoNotTrack, getValuesFromVisitorIdCookie, + addListener, enableLinkTracking, enableJSErrorTracking, setLinkTrackingTimer, + enableHeartBeatTimer, disableHeartBeatTimer, killFrame, redirectFile, setCountPreRendered, + trackGoal, trackLink, trackPageView, trackSiteSearch, trackEvent, + setEcommerceView, addEcommerceItem, trackEcommerceOrder, trackEcommerceCartUpdate, + deleteCookie, deleteCookies, offsetTop, offsetLeft, offsetHeight, offsetWidth, nodeType, defaultView, + innerHTML, scrollLeft, scrollTop, currentStyle, getComputedStyle, querySelectorAll, splice, + getAttribute, hasAttribute, attributes, nodeName, findContentNodes, findContentNodes, findContentNodesWithinNode, + findPieceNode, findTargetNodeNoDefault, findTargetNode, findContentPiece, children, hasNodeCssClass, + getAttributeValueFromNode, hasNodeAttributeWithValue, hasNodeAttribute, findNodesByTagName, findMultiple, + makeNodesUnique, concat, find, htmlCollectionToArray, offsetParent, value, nodeValue, findNodesHavingAttribute, + findFirstNodeHavingAttribute, findFirstNodeHavingAttributeWithValue, getElementsByClassName, + findNodesHavingCssClass, findFirstNodeHavingClass, isLinkElement, findParentContentNode, removeDomainIfIsInLink, + findContentName, findMediaUrlInNode, toAbsoluteUrl, findContentTarget, getLocation, origin, host, isSameDomain, + search, trim, getBoundingClientRect, bottom, right, left, innerWidth, innerHeight, clientWidth, clientHeight, + isOrWasNodeInViewport, isNodeVisible, buildInteractionRequestParams, buildImpressionRequestParams, + shouldIgnoreInteraction, setHrefAttribute, setAttribute, buildContentBlock, collectContent, setLocation, + CONTENT_ATTR, CONTENT_CLASS, CONTENT_NAME_ATTR, CONTENT_PIECE_ATTR, CONTENT_PIECE_CLASS, + CONTENT_TARGET_ATTR, CONTENT_TARGET_CLASS, CONTENT_IGNOREINTERACTION_ATTR, CONTENT_IGNOREINTERACTION_CLASS, + trackCallbackOnLoad, trackCallbackOnReady, buildContentImpressionsRequests, wasContentImpressionAlreadyTracked, + getQuery, getContent, getContentImpressionsRequestsFromNodes, buildContentInteractionTrackingRedirectUrl, + buildContentInteractionRequestNode, buildContentInteractionRequest, buildContentImpressionRequest, + appendContentInteractionToRequestIfPossible, setupInteractionsTracking, trackContentImpressionClickInteraction, + internalIsNodeVisible, clearTrackedContentImpressions, getTrackerUrl, trackAllContentImpressions, + getTrackedContentImpressions, getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet, + contentInteractionTrackingSetupDone, contains, match, pathname, piece, trackContentInteractionNode, + trackContentInteractionNode, trackContentImpressionsWithinNode, trackContentImpression, + enableTrackOnlyVisibleContent, trackContentInteraction, clearEnableTrackOnlyVisibleContent, logAllContentBlocksOnPage, + trackVisibleContentImpressions, isTrackOnlyVisibleContentEnabled, port, isUrlToCurrentDomain, + isNodeAuthorizedToTriggerInteraction, replaceHrefIfInternalLink, getConfigDownloadExtensions, disableLinkTracking, + substr, setAnyAttribute, wasContentTargetAttrReplaced, max, abs, childNodes, compareDocumentPosition, body, + getConfigVisitorCookieTimeout, getRemainingVisitorCookieTimeout, getDomains, getConfigCookiePath, + newVisitor, uuid, createTs, visitCount, currentVisitTs, lastVisitTs, lastEcommerceOrderTs, + "", "\b", "\t", "\n", "\f", "\r", "\"", "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, + getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, + sort, slice, stringify, test, toJSON, toString, valueOf, objectToJSON + */ +/*global _paq:true */ +/*members push */ +/*global Piwik:true */ +/*members addPlugin, getTracker, getAsyncTracker */ +/*global Piwik_Overlay_Client */ +/*global AnalyticsTracker:true */ +/*members initialize */ +/*global define */ +/*members amd */ +/*global console:true */ +/*members error */ +/*members log */ + +// asynchronous tracker (or proxy) +if (typeof _paq !== 'object') { + _paq = []; +} + +// Piwik singleton and namespace +if (typeof Piwik !== 'object') { + Piwik = (function () { + 'use strict'; + + /************************************************************ + * Private data + ************************************************************/ + + var expireDateTime, + + /* plugins */ + plugins = {}, + + /* alias frequently used globals for added minification */ + documentAlias = document, + navigatorAlias = navigator, + screenAlias = screen, + windowAlias = window, + + /* performance timing */ + performanceAlias = windowAlias.performance || windowAlias.mozPerformance || windowAlias.msPerformance || windowAlias.spiderwebkitPerformance, + + /* DOM Ready */ + hasLoaded = false, + registeredOnLoadHandlers = [], + + /* encode */ + encodeWrapper = windowAlias.encodeURIComponent, + + /* decode */ + decodeWrapper = windowAlias.decodeURIComponent, + + /* urldecode */ + urldecode = unescape, + + /* asynchronous tracker */ + asyncTracker, + + /* iterator */ + iterator, + + /* local Piwik */ + Piwik; + + /************************************************************ + * Private methods + ************************************************************/ + + /** + * See https://github.com/piwik/piwik/issues/8413 + * To prevent Javascript Error: Uncaught URIError: URI malformed when encoding is not UTF-8. Use this method + * instead of decodeWrapper if a text could contain any non UTF-8 encoded characters eg + * a URL like http://apache.piwik/test.html?%F6%E4%FC or a link like + * <a href="test-with-%F6%E4%FC/story/0">(encoded iso-8859-1 URL)</a> + */ + function safeDecodeWrapper(url) + { + try { + return decodeWrapper(url); + } catch (e) { + return unescape(url); + } + } + + /* + * Is property defined? + */ + function isDefined(property) { + // workaround https://github.com/douglascrockford/JSLint/commit/24f63ada2f9d7ad65afc90e6d949f631935c2480 + var propertyType = typeof property; + + return propertyType !== 'undefined'; + } + + /* + * Is property a function? + */ + function isFunction(property) { + return typeof property === 'function'; + } + + /* + * Is property an object? + * + * @return bool Returns true if property is null, an Object, or subclass of Object (i.e., an instanceof String, Date, etc.) + */ + function isObject(property) { + return typeof property === 'object'; + } + + /* + * Is property a string? + */ + function isString(property) { + return typeof property === 'string' || property instanceof String; + } + + function isObjectEmpty(property) + { + if (!property) { + return true; + } + + var i; + var isEmpty = true; + for (i in property) { + if (Object.prototype.hasOwnProperty.call(property, i)) { + isEmpty = false; + } + } + + return isEmpty; + } + + /* + * apply wrapper + * + * @param array parameterArray An array comprising either: + * [ 'methodName', optional_parameters ] + * or: + * [ functionObject, optional_parameters ] + */ + function apply() { + var i, f, parameterArray; + + for (i = 0; i < arguments.length; i += 1) { + parameterArray = arguments[i]; + f = parameterArray.shift(); + + if (isString(f)) { + asyncTracker[f].apply(asyncTracker, parameterArray); + } else { + f.apply(asyncTracker, parameterArray); + } + } + } + + /* + * Cross-browser helper function to add event handler + */ + function addEventListener(element, eventType, eventHandler, useCapture) { + if (element.addEventListener) { + element.addEventListener(eventType, eventHandler, useCapture); + + return true; + } + + if (element.attachEvent) { + return element.attachEvent('on' + eventType, eventHandler); + } + + element['on' + eventType] = eventHandler; + } + + /* + * Call plugin hook methods + */ + function executePluginMethod(methodName, callback) { + var result = '', + i, + pluginMethod; + + for (i in plugins) { + if (Object.prototype.hasOwnProperty.call(plugins, i)) { + pluginMethod = plugins[i][methodName]; + + if (isFunction(pluginMethod)) { + result += pluginMethod(callback); + } + } + } + + return result; + } + + /* + * Handle beforeunload event + * + * Subject to Safari's "Runaway JavaScript Timer" and + * Chrome V8 extension that terminates JS that exhibits + * "slow unload", i.e., calling getTime() > 1000 times + */ + function beforeUnloadHandler() { + var now; + + executePluginMethod('unload'); + + /* + * Delay/pause (blocks UI) + */ + if (expireDateTime) { + // the things we do for backwards compatibility... + // in ECMA-262 5th ed., we could simply use: + // while (Date.now() < expireDateTime) { } + do { + now = new Date(); + } while (now.getTimeAlias() < expireDateTime); + } + } + + /* + * Handler for onload event + */ + function loadHandler() { + var i; + + if (!hasLoaded) { + hasLoaded = true; + executePluginMethod('load'); + for (i = 0; i < registeredOnLoadHandlers.length; i++) { + registeredOnLoadHandlers[i](); + } + } + + return true; + } + + /* + * Add onload or DOM ready handler + */ + function addReadyListener() { + var _timer; + + if (documentAlias.addEventListener) { + addEventListener(documentAlias, 'DOMContentLoaded', function ready() { + documentAlias.removeEventListener('DOMContentLoaded', ready, false); + loadHandler(); + }); + } else if (documentAlias.attachEvent) { + documentAlias.attachEvent('onreadystatechange', function ready() { + if (documentAlias.readyState === 'complete') { + documentAlias.detachEvent('onreadystatechange', ready); + loadHandler(); + } + }); + + if (documentAlias.documentElement.doScroll && windowAlias === windowAlias.top) { + (function ready() { + if (!hasLoaded) { + try { + documentAlias.documentElement.doScroll('left'); + } catch (error) { + setTimeout(ready, 0); + + return; + } + loadHandler(); + } + }()); + } + } + + // sniff for older SpiderwebKit versions + if ((new RegExp('SpiderwebKit')).test(navigatorAlias.userAgent)) { + _timer = setInterval(function () { + if (hasLoaded || /loaded|complete/.test(documentAlias.readyState)) { + clearInterval(_timer); + loadHandler(); + } + }, 10); + } + + // fallback + addEventListener(windowAlias, 'load', loadHandler, false); + } + + /* + * Load JavaScript file (asynchronously) + */ + function loadScript(src, onLoad) { + var script = documentAlias.createElement('script'); + + script.type = 'text/javascript'; + script.src = src; + + if (script.readyState) { + script.onreadystatechange = function () { + var state = this.readyState; + + if (state === 'loaded' || state === 'complete') { + script.onreadystatechange = null; + onLoad(); + } + }; + } else { + script.onload = onLoad; + } + + documentAlias.getElementsByTagName('head')[0].appendChild(script); + } + + /* + * Get page referrer + */ + function getReferrer() { + var referrer = ''; + + try { + referrer = windowAlias.top.document.referrer; + } catch (e) { + if (windowAlias.parent) { + try { + referrer = windowAlias.parent.document.referrer; + } catch (e2) { + referrer = ''; + } + } + } + + if (referrer === '') { + referrer = documentAlias.referrer; + } + + return referrer; + } + + /* + * Extract scheme/protocol from URL + */ + function getProtocolScheme(url) { + var e = new RegExp('^([a-z]+):'), + matches = e.exec(url); + + return matches ? matches[1] : null; + } + + /* + * Extract hostname from URL + */ + function getHostName(url) { + // scheme : // [username [: password] @] hostame [: port] [/ [path] [? query] [# fragment]] + var e = new RegExp('^(?:(?:https?|ftp):)/*(?:[^@]+@)?([^:/#]+)'), + matches = e.exec(url); + + return matches ? matches[1] : url; + } + + /* + * Extract parameter from URL + */ + function getParameter(url, name) { + var regexSearch = "[\\?&#]" + name + "=([^&#]*)"; + var regex = new RegExp(regexSearch); + var results = regex.exec(url); + return results ? decodeWrapper(results[1]) : ''; + } + + /* + * UTF-8 encoding + */ + function utf8_encode(argString) { + return unescape(encodeWrapper(argString)); + } + + /************************************************************ + * sha1 + * - based on sha1 from http://phpjs.org/functions/sha1:512 (MIT / GPL v2) + ************************************************************/ + + function sha1(str) { + // + original by: Spiderwebtoolkit.info (http://www.spiderwebtoolkit.info/) + // + namespaced by: Michael White (http://getsprink.com) + // + input by: Brett Zamir (http://brett-zamir.me) + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + jslinted by: Anthon Pang (http://piwik.org) + + var + rotate_left = function (n, s) { + return (n << s) | (n >>> (32 - s)); + }, + + cvt_hex = function (val) { + var strout = '', + i, + v; + + for (i = 7; i >= 0; i--) { + v = (val >>> (i * 4)) & 0x0f; + strout += v.toString(16); + } + + return strout; + }, + + blockstart, + i, + j, + W = [], + H0 = 0x67452301, + H1 = 0xEFCDAB89, + H2 = 0x98BADCFE, + H3 = 0x10325476, + H4 = 0xC3D2E1F0, + A, + B, + C, + D, + E, + temp, + str_len, + word_array = []; + + str = utf8_encode(str); + str_len = str.length; + + for (i = 0; i < str_len - 3; i += 4) { + j = str.charCodeAt(i) << 24 | str.charCodeAt(i + 1) << 16 | + str.charCodeAt(i + 2) << 8 | str.charCodeAt(i + 3); + word_array.push(j); + } + + switch (str_len & 3) { + case 0: + i = 0x080000000; + break; + case 1: + i = str.charCodeAt(str_len - 1) << 24 | 0x0800000; + break; + case 2: + i = str.charCodeAt(str_len - 2) << 24 | str.charCodeAt(str_len - 1) << 16 | 0x08000; + break; + case 3: + i = str.charCodeAt(str_len - 3) << 24 | str.charCodeAt(str_len - 2) << 16 | str.charCodeAt(str_len - 1) << 8 | 0x80; + break; + } + + word_array.push(i); + + while ((word_array.length & 15) !== 14) { + word_array.push(0); + } + + word_array.push(str_len >>> 29); + word_array.push((str_len << 3) & 0x0ffffffff); + + for (blockstart = 0; blockstart < word_array.length; blockstart += 16) { + for (i = 0; i < 16; i++) { + W[i] = word_array[blockstart + i]; + } + + for (i = 16; i <= 79; i++) { + W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + } + + A = H0; + B = H1; + C = H2; + D = H3; + E = H4; + + for (i = 0; i <= 19; i++) { + temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff; + E = D; + D = C; + C = rotate_left(B, 30); + B = A; + A = temp; + } + + for (i = 20; i <= 39; i++) { + temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff; + E = D; + D = C; + C = rotate_left(B, 30); + B = A; + A = temp; + } + + for (i = 40; i <= 59; i++) { + temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff; + E = D; + D = C; + C = rotate_left(B, 30); + B = A; + A = temp; + } + + for (i = 60; i <= 79; i++) { + temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff; + E = D; + D = C; + C = rotate_left(B, 30); + B = A; + A = temp; + } + + H0 = (H0 + A) & 0x0ffffffff; + H1 = (H1 + B) & 0x0ffffffff; + H2 = (H2 + C) & 0x0ffffffff; + H3 = (H3 + D) & 0x0ffffffff; + H4 = (H4 + E) & 0x0ffffffff; + } + + temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4); + + return temp.toLowerCase(); + } + + /************************************************************ + * end sha1 + ************************************************************/ + + /* + * Fix-up URL when page rendered from search engine cache or translated page + */ + function urlFixup(hostName, href, referrer) { + if (!hostName) { + hostName = ''; + } + + if (!href) { + href = ''; + } + + if (hostName === 'translate.googleusercontent.com') { // Google + if (referrer === '') { + referrer = href; + } + + href = getParameter(href, 'u'); + hostName = getHostName(href); + } else if (hostName === 'cc.bingj.com' || // Bing + hostName === 'spiderwebcache.googleusercontent.com' || // Google + hostName.slice(0, 5) === '74.6.') { // Yahoo (via Inktomi 74.6.0.0/16) + href = documentAlias.links[0].href; + hostName = getHostName(href); + } + + return [hostName, href, referrer]; + } + + /* + * Fix-up domain + */ + function domainFixup(domain) { + var dl = domain.length; + + // remove trailing '.' + if (domain.charAt(--dl) === '.') { + domain = domain.slice(0, dl); + } + + // remove leading '*' + if (domain.slice(0, 2) === '*.') { + domain = domain.slice(1); + } + + if (domain.indexOf('/') !== -1) { + domain = domain.substr(0, domain.indexOf('/')); + } + + return domain; + } + + /* + * Title fixup + */ + function titleFixup(title) { + title = title && title.text ? title.text : title; + + if (!isString(title)) { + var tmp = documentAlias.getElementsByTagName('title'); + + if (tmp && isDefined(tmp[0])) { + title = tmp[0].text; + } + } + + return title; + } + + function getChildrenFromNode(node) + { + if (!node) { + return []; + } + + if (!isDefined(node.children) && isDefined(node.childNodes)) { + return node.children; + } + + if (isDefined(node.children)) { + return node.children; + } + + return []; + } + + function containsNodeElement(node, containedNode) + { + if (!node || !containedNode) { + return false; + } + + if (node.contains) { + return node.contains(containedNode); + } + + if (node === containedNode) { + return true; + } + + if (node.compareDocumentPosition) { + return !!(node.compareDocumentPosition(containedNode) & 16); + } + + return false; + } + + // Polyfill for IndexOf for IE6-IE8 + function indexOfArray(theArray, searchElement) + { + if (theArray && theArray.indexOf) { + return theArray.indexOf(searchElement); + } + + // 1. Let O be the result of calling ToObject passing + // the this value as the argument. + if (!isDefined(theArray) || theArray === null) { + return -1; + } + + if (!theArray.length) { + return -1; + } + + var len = theArray.length; + + if (len === 0) { + return -1; + } + + var k = 0; + + // 9. Repeat, while k < len + while (k < len) { + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator + // b. Let kPresent be the result of calling the + // HasProperty internal method of O with argument Pk. + // This step can be combined with c + // c. If kPresent is true, then + // i. Let elementK be the result of calling the Get + // internal method of O with the argument ToString(k). + // ii. Let same be the result of applying the + // Strict Equality Comparison Algorithm to + // searchElement and elementK. + // iii. If same is true, return k. + if (theArray[k] === searchElement) { + return k; + } + k++; + } + return -1; + } + + /************************************************************ + * Element Visiblility + ************************************************************/ + + /** + * Author: Jason Farrell + * Author URI: http://useallfive.com/ + * + * Description: Checks if a DOM element is truly visible. + * Package URL: https://github.com/UseAllFive/true-visibility + * License: MIT (https://github.com/UseAllFive/true-visibility/blob/master/LICENSE.txt) + */ + function isVisible(node) { + + if (!node) { + return false; + } + + //-- Cross browser method to get style properties: + function _getStyle(el, property) { + if (windowAlias.getComputedStyle) { + return documentAlias.defaultView.getComputedStyle(el,null)[property]; + } + if (el.currentStyle) { + return el.currentStyle[property]; + } + } + + function _elementInDocument(element) { + element = element.parentNode; + + while (element) { + if (element === documentAlias) { + return true; + } + element = element.parentNode; + } + return false; + } + + /** + * Checks if a DOM element is visible. Takes into + * consideration its parents and overflow. + * + * @param (el) the DOM element to check if is visible + * + * These params are optional that are sent in recursively, + * you typically won't use these: + * + * @param (t) Top corner position number + * @param (r) Right corner position number + * @param (b) Bottom corner position number + * @param (l) Left corner position number + * @param (w) Element width number + * @param (h) Element height number + */ + function _isVisible(el, t, r, b, l, w, h) { + var p = el.parentNode, + VISIBLE_PADDING = 1; // has to be visible at least one px of the element + + if (!_elementInDocument(el)) { + return false; + } + + //-- Return true for document node + if (9 === p.nodeType) { + return true; + } + + //-- Return false if our element is invisible + if ( + '0' === _getStyle(el, 'opacity') || + 'none' === _getStyle(el, 'display') || + 'hidden' === _getStyle(el, 'visibility') + ) { + return false; + } + + if (!isDefined(t) || + !isDefined(r) || + !isDefined(b) || + !isDefined(l) || + !isDefined(w) || + !isDefined(h)) { + t = el.offsetTop; + l = el.offsetLeft; + b = t + el.offsetHeight; + r = l + el.offsetWidth; + w = el.offsetWidth; + h = el.offsetHeight; + } + + if (node === el && (0 === h || 0 === w) && 'hidden' === _getStyle(el, 'overflow')) { + return false; + } + + //-- If we have a parent, let's continue: + if (p) { + //-- Check if the parent can hide its children. + if (('hidden' === _getStyle(p, 'overflow') || 'scroll' === _getStyle(p, 'overflow'))) { + //-- Only check if the offset is different for the parent + if ( + //-- If the target element is to the right of the parent elm + l + VISIBLE_PADDING > p.offsetWidth + p.scrollLeft || + //-- If the target element is to the left of the parent elm + l + w - VISIBLE_PADDING < p.scrollLeft || + //-- If the target element is under the parent elm + t + VISIBLE_PADDING > p.offsetHeight + p.scrollTop || + //-- If the target element is above the parent elm + t + h - VISIBLE_PADDING < p.scrollTop + ) { + //-- Our target element is out of bounds: + return false; + } + } + //-- Add the offset parent's left/top coords to our element's offset: + if (el.offsetParent === p) { + l += p.offsetLeft; + t += p.offsetTop; + } + //-- Let's recursively check upwards: + return _isVisible(p, t, r, b, l, w, h); + } + return true; + } + + return _isVisible(node); + } + + /************************************************************ + * Query + ************************************************************/ + + var query = { + htmlCollectionToArray: function (foundNodes) + { + var nodes = [], index; + + if (!foundNodes || !foundNodes.length) { + return nodes; + } + + for (index = 0; index < foundNodes.length; index++) { + nodes.push(foundNodes[index]); + } + + return nodes; + }, + find: function (selector) + { + // we use querySelectorAll only on document, not on nodes because of its unexpected behavior. See for + // instance http://stackoverflow.com/questions/11503534/jquery-vs-document-queryselectorall and + // http://jsfiddle.net/QdMc5/ and http://ejohn.org/blog/thoughts-on-queryselectorall + if (!document.querySelectorAll || !selector) { + return []; // we do not support all browsers + } + + var foundNodes = document.querySelectorAll(selector); + + return this.htmlCollectionToArray(foundNodes); + }, + findMultiple: function (selectors) + { + if (!selectors || !selectors.length) { + return []; + } + + var index, foundNodes; + var nodes = []; + for (index = 0; index < selectors.length; index++) { + foundNodes = this.find(selectors[index]); + nodes = nodes.concat(foundNodes); + } + + nodes = this.makeNodesUnique(nodes); + + return nodes; + }, + findNodesByTagName: function (node, tagName) + { + if (!node || !tagName || !node.getElementsByTagName) { + return []; + } + + var foundNodes = node.getElementsByTagName(tagName); + + return this.htmlCollectionToArray(foundNodes); + }, + makeNodesUnique: function (nodes) + { + var copy = [].concat(nodes); + nodes.sort(function(n1, n2){ + if (n1 === n2) { + return 0; + } + + var index1 = indexOfArray(copy, n1); + var index2 = indexOfArray(copy, n2); + + if (index1 === index2) { + return 0; + } + + return index1 > index2 ? -1 : 1; + }); + + if (nodes.length <= 1) { + return nodes; + } + + var index = 0; + var numDuplicates = 0; + var duplicates = []; + var node; + + node = nodes[index++]; + + while (node) { + if (node === nodes[index]) { + numDuplicates = duplicates.push(index); + } + + node = nodes[index++] || null; + } + + while (numDuplicates--) { + nodes.splice(duplicates[numDuplicates], 1); + } + + return nodes; + }, + getAttributeValueFromNode: function (node, attributeName) + { + if (!this.hasNodeAttribute(node, attributeName)) { + return; + } + + if (node && node.getAttribute) { + return node.getAttribute(attributeName); + } + + if (!node || !node.attributes) { + return; + } + + var typeOfAttr = (typeof node.attributes[attributeName]); + if ('undefined' === typeOfAttr) { + return; + } + + if (node.attributes[attributeName].value) { + return node.attributes[attributeName].value; // nodeValue is deprecated ie Chrome + } + + if (node.attributes[attributeName].nodeValue) { + return node.attributes[attributeName].nodeValue; + } + + var index; + var attrs = node.attributes; + + if (!attrs) { + return; + } + + for (index = 0; index < attrs.length; index++) { + if (attrs[index].nodeName === attributeName) { + return attrs[index].nodeValue; + } + } + + return null; + }, + hasNodeAttributeWithValue: function (node, attributeName) + { + var value = this.getAttributeValueFromNode(node, attributeName); + + return !!value; + }, + hasNodeAttribute: function (node, attributeName) + { + if (node && node.hasAttribute) { + return node.hasAttribute(attributeName); + } + + if (node && node.attributes) { + var typeOfAttr = (typeof node.attributes[attributeName]); + return 'undefined' !== typeOfAttr; + } + + return false; + }, + hasNodeCssClass: function (node, klassName) + { + if (node && klassName && node.className) { + var classes = typeof node.className === "string" ? node.className.split(' ') : []; + if (-1 !== indexOfArray(classes, klassName)) { + return true; + } + } + + return false; + }, + findNodesHavingAttribute: function (nodeToSearch, attributeName, nodes) + { + if (!nodes) { + nodes = []; + } + + if (!nodeToSearch || !attributeName) { + return nodes; + } + + var children = getChildrenFromNode(nodeToSearch); + + if (!children || !children.length) { + return nodes; + } + + var index, child; + for (index = 0; index < children.length; index++) { + child = children[index]; + if (this.hasNodeAttribute(child, attributeName)) { + nodes.push(child); + } + + nodes = this.findNodesHavingAttribute(child, attributeName, nodes); + } + + return nodes; + }, + findFirstNodeHavingAttribute: function (node, attributeName) + { + if (!node || !attributeName) { + return; + } + + if (this.hasNodeAttribute(node, attributeName)) { + return node; + } + + var nodes = this.findNodesHavingAttribute(node, attributeName); + + if (nodes && nodes.length) { + return nodes[0]; + } + }, + findFirstNodeHavingAttributeWithValue: function (node, attributeName) + { + if (!node || !attributeName) { + return; + } + + if (this.hasNodeAttributeWithValue(node, attributeName)) { + return node; + } + + var nodes = this.findNodesHavingAttribute(node, attributeName); + + if (!nodes || !nodes.length) { + return; + } + + var index; + for (index = 0; index < nodes.length; index++) { + if (this.getAttributeValueFromNode(nodes[index], attributeName)) { + return nodes[index]; + } + } + }, + findNodesHavingCssClass: function (nodeToSearch, className, nodes) + { + if (!nodes) { + nodes = []; + } + + if (!nodeToSearch || !className) { + return nodes; + } + + if (nodeToSearch.getElementsByClassName) { + var foundNodes = nodeToSearch.getElementsByClassName(className); + return this.htmlCollectionToArray(foundNodes); + } + + var children = getChildrenFromNode(nodeToSearch); + + if (!children || !children.length) { + return []; + } + + var index, child; + for (index = 0; index < children.length; index++) { + child = children[index]; + if (this.hasNodeCssClass(child, className)) { + nodes.push(child); + } + + nodes = this.findNodesHavingCssClass(child, className, nodes); + } + + return nodes; + }, + findFirstNodeHavingClass: function (node, className) + { + if (!node || !className) { + return; + } + + if (this.hasNodeCssClass(node, className)) { + return node; + } + + var nodes = this.findNodesHavingCssClass(node, className); + + if (nodes && nodes.length) { + return nodes[0]; + } + }, + isLinkElement: function (node) + { + if (!node) { + return false; + } + + var elementName = String(node.nodeName).toLowerCase(); + var linkElementNames = ['a', 'area']; + var pos = indexOfArray(linkElementNames, elementName); + + return pos !== -1; + }, + setAnyAttribute: function (node, attrName, attrValue) + { + if (!node || !attrName) { + return; + } + + if (node.setAttribute) { + node.setAttribute(attrName, attrValue); + } else { + node[attrName] = attrValue; + } + } + }; + + /************************************************************ + * Content Tracking + ************************************************************/ + + var content = { + CONTENT_ATTR: 'data-track-content', + CONTENT_CLASS: 'piwikTrackContent', + CONTENT_NAME_ATTR: 'data-content-name', + CONTENT_PIECE_ATTR: 'data-content-piece', + CONTENT_PIECE_CLASS: 'piwikContentPiece', + CONTENT_TARGET_ATTR: 'data-content-target', + CONTENT_TARGET_CLASS: 'piwikContentTarget', + CONTENT_IGNOREINTERACTION_ATTR: 'data-content-ignoreinteraction', + CONTENT_IGNOREINTERACTION_CLASS: 'piwikContentIgnoreInteraction', + location: undefined, + + findContentNodes: function () + { + + var cssSelector = '.' + this.CONTENT_CLASS; + var attrSelector = '[' + this.CONTENT_ATTR + ']'; + var contentNodes = query.findMultiple([cssSelector, attrSelector]); + + return contentNodes; + }, + findContentNodesWithinNode: function (node) + { + if (!node) { + return []; + } + + // NOTE: we do not use query.findMultiple here as querySelectorAll would most likely not deliver the result we want + + var nodes1 = query.findNodesHavingCssClass(node, this.CONTENT_CLASS); + var nodes2 = query.findNodesHavingAttribute(node, this.CONTENT_ATTR); + + if (nodes2 && nodes2.length) { + var index; + for (index = 0; index < nodes2.length; index++) { + nodes1.push(nodes2[index]); + } + } + + if (query.hasNodeAttribute(node, this.CONTENT_ATTR)) { + nodes1.push(node); + } else if (query.hasNodeCssClass(node, this.CONTENT_CLASS)) { + nodes1.push(node); + } + + nodes1 = query.makeNodesUnique(nodes1); + + return nodes1; + }, + findParentContentNode: function (anyNode) + { + if (!anyNode) { + return; + } + + var node = anyNode; + var counter = 0; + + while (node && node !== documentAlias && node.parentNode) { + if (query.hasNodeAttribute(node, this.CONTENT_ATTR)) { + return node; + } + if (query.hasNodeCssClass(node, this.CONTENT_CLASS)) { + return node; + } + + node = node.parentNode; + + if (counter > 1000) { + break; // prevent loop, should not happen anyway but better we do this + } + counter++; + } + }, + findPieceNode: function (node) + { + var contentPiece; + + contentPiece = query.findFirstNodeHavingAttribute(node, this.CONTENT_PIECE_ATTR); + + if (!contentPiece) { + contentPiece = query.findFirstNodeHavingClass(node, this.CONTENT_PIECE_CLASS); + } + + if (contentPiece) { + return contentPiece; + } + + return node; + }, + findTargetNodeNoDefault: function (node) + { + if (!node) { + return; + } + + var target = query.findFirstNodeHavingAttributeWithValue(node, this.CONTENT_TARGET_ATTR); + if (target) { + return target; + } + + target = query.findFirstNodeHavingAttribute(node, this.CONTENT_TARGET_ATTR); + if (target) { + return target; + } + + target = query.findFirstNodeHavingClass(node, this.CONTENT_TARGET_CLASS); + if (target) { + return target; + } + }, + findTargetNode: function (node) + { + var target = this.findTargetNodeNoDefault(node); + if (target) { + return target; + } + + return node; + }, + findContentName: function (node) + { + if (!node) { + return; + } + + var nameNode = query.findFirstNodeHavingAttributeWithValue(node, this.CONTENT_NAME_ATTR); + + if (nameNode) { + return query.getAttributeValueFromNode(nameNode, this.CONTENT_NAME_ATTR); + } + + var contentPiece = this.findContentPiece(node); + if (contentPiece) { + return this.removeDomainIfIsInLink(contentPiece); + } + + if (query.hasNodeAttributeWithValue(node, 'title')) { + return query.getAttributeValueFromNode(node, 'title'); + } + + var clickUrlNode = this.findPieceNode(node); + + if (query.hasNodeAttributeWithValue(clickUrlNode, 'title')) { + return query.getAttributeValueFromNode(clickUrlNode, 'title'); + } + + var targetNode = this.findTargetNode(node); + + if (query.hasNodeAttributeWithValue(targetNode, 'title')) { + return query.getAttributeValueFromNode(targetNode, 'title'); + } + }, + findContentPiece: function (node) + { + if (!node) { + return; + } + + var nameNode = query.findFirstNodeHavingAttributeWithValue(node, this.CONTENT_PIECE_ATTR); + + if (nameNode) { + return query.getAttributeValueFromNode(nameNode, this.CONTENT_PIECE_ATTR); + } + + var contentNode = this.findPieceNode(node); + + var media = this.findMediaUrlInNode(contentNode); + if (media) { + return this.toAbsoluteUrl(media); + } + }, + findContentTarget: function (node) + { + if (!node) { + return; + } + + var targetNode = this.findTargetNode(node); + + if (query.hasNodeAttributeWithValue(targetNode, this.CONTENT_TARGET_ATTR)) { + return query.getAttributeValueFromNode(targetNode, this.CONTENT_TARGET_ATTR); + } + + var href; + if (query.hasNodeAttributeWithValue(targetNode, 'href')) { + href = query.getAttributeValueFromNode(targetNode, 'href'); + return this.toAbsoluteUrl(href); + } + + var contentNode = this.findPieceNode(node); + + if (query.hasNodeAttributeWithValue(contentNode, 'href')) { + href = query.getAttributeValueFromNode(contentNode, 'href'); + return this.toAbsoluteUrl(href); + } + }, + isSameDomain: function (url) + { + if (!url || !url.indexOf) { + return false; + } + + if (0 === url.indexOf(this.getLocation().origin)) { + return true; + } + + var posHost = url.indexOf(this.getLocation().host); + if (8 >= posHost && 0 <= posHost) { + return true; + } + + return false; + }, + removeDomainIfIsInLink: function (text) + { + // we will only remove if domain === location.origin meaning is not an outlink + var regexContainsProtocol = '^https?:\/\/[^\/]+'; + var regexReplaceDomain = '^.*\/\/[^\/]+'; + + if (text && + text.search && + -1 !== text.search(new RegExp(regexContainsProtocol)) + && this.isSameDomain(text)) { + + text = text.replace(new RegExp(regexReplaceDomain), ''); + if (!text) { + text = '/'; + } + } + + return text; + }, + findMediaUrlInNode: function (node) + { + if (!node) { + return; + } + + var mediaElements = ['img', 'embed', 'video', 'audio']; + var elementName = node.nodeName.toLowerCase(); + + if (-1 !== indexOfArray(mediaElements, elementName) && + query.findFirstNodeHavingAttributeWithValue(node, 'src')) { + + var sourceNode = query.findFirstNodeHavingAttributeWithValue(node, 'src'); + + return query.getAttributeValueFromNode(sourceNode, 'src'); + } + + if (elementName === 'object' && + query.hasNodeAttributeWithValue(node, 'data')) { + + return query.getAttributeValueFromNode(node, 'data'); + } + + if (elementName === 'object') { + var params = query.findNodesByTagName(node, 'param'); + if (params && params.length) { + var index; + for (index = 0; index < params.length; index++) { + if ('movie' === query.getAttributeValueFromNode(params[index], 'name') && + query.hasNodeAttributeWithValue(params[index], 'value')) { + + return query.getAttributeValueFromNode(params[index], 'value'); + } + } + } + + var embed = query.findNodesByTagName(node, 'embed'); + if (embed && embed.length) { + return this.findMediaUrlInNode(embed[0]); + } + } + }, + trim: function (text) + { + if (text && String(text) === text) { + return text.replace(/^\s+|\s+$/g, ''); + } + + return text; + }, + isOrWasNodeInViewport: function (node) + { + if (!node || !node.getBoundingClientRect || node.nodeType !== 1) { + return true; + } + + var rect = node.getBoundingClientRect(); + var html = documentAlias.documentElement || {}; + + var wasVisible = rect.top < 0; + if (wasVisible && node.offsetTop) { + wasVisible = (node.offsetTop + rect.height) > 0; + } + + var docWidth = html.clientWidth; // The clientWidth attribute returns the viewport width excluding the size of a rendered scroll bar + + if (windowAlias.innerWidth && docWidth > windowAlias.innerWidth) { + docWidth = windowAlias.innerWidth; // The innerWidth attribute must return the viewport width including the size of a rendered scroll bar + } + + var docHeight = html.clientHeight; // The clientWidth attribute returns the viewport width excluding the size of a rendered scroll bar + + if (windowAlias.innerHeight && docHeight > windowAlias.innerHeight) { + docHeight = windowAlias.innerHeight; // The innerWidth attribute must return the viewport width including the size of a rendered scroll bar + } + + return ( + (rect.bottom > 0 || wasVisible) && + rect.right > 0 && + rect.left < docWidth && + ((rect.top < docHeight) || wasVisible) // rect.top < 0 we assume user has seen all the ones that are above the current viewport + ); + }, + isNodeVisible: function (node) + { + var isItVisible = isVisible(node); + var isInViewport = this.isOrWasNodeInViewport(node); + return isItVisible && isInViewport; + }, + buildInteractionRequestParams: function (interaction, name, piece, target) + { + var params = ''; + + if (interaction) { + params += 'c_i='+ encodeWrapper(interaction); + } + if (name) { + if (params) { + params += '&'; + } + params += 'c_n='+ encodeWrapper(name); + } + if (piece) { + if (params) { + params += '&'; + } + params += 'c_p='+ encodeWrapper(piece); + } + if (target) { + if (params) { + params += '&'; + } + params += 'c_t='+ encodeWrapper(target); + } + + return params; + }, + buildImpressionRequestParams: function (name, piece, target) + { + var params = 'c_n=' + encodeWrapper(name) + + '&c_p=' + encodeWrapper(piece); + + if (target) { + params += '&c_t=' + encodeWrapper(target); + } + + return params; + }, + buildContentBlock: function (node) + { + if (!node) { + return; + } + + var name = this.findContentName(node); + var piece = this.findContentPiece(node); + var target = this.findContentTarget(node); + + name = this.trim(name); + piece = this.trim(piece); + target = this.trim(target); + + return { + name: name || 'Unknown', + piece: piece || 'Unknown', + target: target || '' + }; + }, + collectContent: function (contentNodes) + { + if (!contentNodes || !contentNodes.length) { + return []; + } + + var contents = []; + + var index, contentBlock; + for (index = 0; index < contentNodes.length; index++) { + contentBlock = this.buildContentBlock(contentNodes[index]); + if (isDefined(contentBlock)) { + contents.push(contentBlock); + } + } + + return contents; + }, + setLocation: function (location) + { + this.location = location; + }, + getLocation: function () + { + var locationAlias = this.location || windowAlias.location; + + if (!locationAlias.origin) { + locationAlias.origin = locationAlias.protocol + "//" + locationAlias.hostname + (locationAlias.port ? ':' + locationAlias.port: ''); + } + + return locationAlias; + }, + toAbsoluteUrl: function (url) + { + if ((!url || String(url) !== url) && url !== '') { + // we only handle strings + return url; + } + + if ('' === url) { + return this.getLocation().href; + } + + // Eg //example.com/test.jpg + if (url.search(/^\/\//) !== -1) { + return this.getLocation().protocol + url; + } + + // Eg http://example.com/test.jpg + if (url.search(/:\/\//) !== -1) { + return url; + } + + // Eg #test.jpg + if (0 === url.indexOf('#')) { + return this.getLocation().origin + this.getLocation().pathname + url; + } + + // Eg ?x=5 + if (0 === url.indexOf('?')) { + return this.getLocation().origin + this.getLocation().pathname + url; + } + + // Eg mailto:x@y.z tel:012345, ... market:... sms:..., javasript:... ecmascript: ... and many more + if (0 === url.search('^[a-zA-Z]{2,11}:')) { + return url; + } + + // Eg /test.jpg + if (url.search(/^\//) !== -1) { + return this.getLocation().origin + url; + } + + // Eg test.jpg + var regexMatchDir = '(.*\/)'; + var base = this.getLocation().origin + this.getLocation().pathname.match(new RegExp(regexMatchDir))[0]; + return base + url; + }, + isUrlToCurrentDomain: function (url) { + + var absoluteUrl = this.toAbsoluteUrl(url); + + if (!absoluteUrl) { + return false; + } + + var origin = this.getLocation().origin; + if (origin === absoluteUrl) { + return true; + } + + if (0 === String(absoluteUrl).indexOf(origin)) { + if (':' === String(absoluteUrl).substr(origin.length, 1)) { + return false; // url has port whereas origin has not => different URL + } + + return true; + } + + return false; + }, + setHrefAttribute: function (node, url) + { + if (!node || !url) { + return; + } + + query.setAnyAttribute(node, 'href', url); + }, + shouldIgnoreInteraction: function (targetNode) + { + var hasAttr = query.hasNodeAttribute(targetNode, this.CONTENT_IGNOREINTERACTION_ATTR); + var hasClass = query.hasNodeCssClass(targetNode, this.CONTENT_IGNOREINTERACTION_CLASS); + return hasAttr || hasClass; + } + }; + + /************************************************************ + * Page Overlay + ************************************************************/ + + function getPiwikUrlForOverlay(trackerUrl, apiUrl) { + if (apiUrl) { + return apiUrl; + } + + if (trackerUrl.slice(-9) === 'piwik.php') { + trackerUrl = trackerUrl.slice(0, trackerUrl.length - 9); + } + + return trackerUrl; + } + + /* + * Check whether this is a page overlay session + * + * @return boolean + * + * {@internal side-effect: modifies window.name }} + */ + function isOverlaySession(configTrackerSiteId) { + var windowName = 'Piwik_Overlay'; + + // check whether we were redirected from the piwik overlay plugin + var referrerRegExp = new RegExp('index\\.php\\?module=Overlay&action=startOverlaySession' + + '&idSite=([0-9]+)&period=([^&]+)&date=([^&]+)(&segment=.*)?$'); + + var match = referrerRegExp.exec(documentAlias.referrer); + + if (match) { + // check idsite + var idsite = match[1]; + + if (idsite !== String(configTrackerSiteId)) { + return false; + } + + // store overlay session info in window name + var period = match[2], + date = match[3], + segment = match[4]; + + if (!segment) { + segment = ''; + } else if (segment.indexOf('&segment=') === 0) { + segment = segment.substr('&segment='.length); + } + + windowAlias.name = windowName + '###' + period + '###' + date + '###' + segment; + } + + // retrieve and check data from window name + var windowNameParts = windowAlias.name.split('###'); + + return windowNameParts.length === 4 && windowNameParts[0] === windowName; + } + + /* + * Inject the script needed for page overlay + */ + function injectOverlayScripts(configTrackerUrl, configApiUrl, configTrackerSiteId) { + var windowNameParts = windowAlias.name.split('###'), + period = windowNameParts[1], + date = windowNameParts[2], + segment = windowNameParts[3], + piwikUrl = getPiwikUrlForOverlay(configTrackerUrl, configApiUrl); + + loadScript( + piwikUrl + 'plugins/Overlay/client/client.js?v=1', + function () { + Piwik_Overlay_Client.initialize(piwikUrl, configTrackerSiteId, period, date, segment); + } + ); + } + + /************************************************************ + * End Page Overlay + ************************************************************/ + + /* + * Piwik Tracker class + * + * trackerUrl and trackerSiteId are optional arguments to the constructor + * + * See: Tracker.setTrackerUrl() and Tracker.setSiteId() + */ + function Tracker(trackerUrl, siteId) { + + /************************************************************ + * Private members + ************************************************************/ + + var +/*<DEBUG>*/ + /* + * registered test hooks + */ + registeredHooks = {}, +/*</DEBUG>*/ + + // Current URL and Referrer URL + locationArray = urlFixup(documentAlias.domain, windowAlias.location.href, getReferrer()), + domainAlias = domainFixup(locationArray[0]), + locationHrefAlias = safeDecodeWrapper(locationArray[1]), + configReferrerUrl = safeDecodeWrapper(locationArray[2]), + + enableJSErrorTracking = false, + + defaultRequestMethod = 'GET', + + // Request method (GET or POST) + configRequestMethod = defaultRequestMethod, + + defaultRequestContentType = 'application/x-www-form-urlencoded; charset=UTF-8', + + // Request Content-Type header value; applicable when POST request method is used for submitting tracking events + configRequestContentType = defaultRequestContentType, + + // Tracker URL + configTrackerUrl = trackerUrl || '', + + // API URL (only set if it differs from the Tracker URL) + configApiUrl = '', + + // This string is appended to the Tracker URL Request (eg. to send data that is not handled by the existing setters/getters) + configAppendToTrackingUrl = '', + + // Site ID + configTrackerSiteId = siteId || '', + + // User ID + configUserId = '', + + // Visitor UUID + visitorUUID = '', + + // Document URL + configCustomUrl, + + // Document title + configTitle = documentAlias.title, + + // Extensions to be treated as download links + configDownloadExtensions = ['7z','aac','apk','arc','arj','asf','asx','avi','azw3','bin','csv','deb','dmg','doc','docx','epub','exe','flv','gif','gz','gzip','hqx','ibooks','jar','jpg','jpeg','js','mobi','mp2','mp3','mp4','mpg','mpeg','mov','movie','msi','msp','odb','odf','odg','ods','odt','ogg','ogv','pdf','phps','png','ppt','pptx','qt','qtm','ra','ram','rar','rpm','sea','sit','tar','tbz','tbz2','bz','bz2','tgz','torrent','txt','wav','wma','wmv','wpd','xls','xlsx','xml','z','zip'], + + // Hosts or alias(es) to not treat as outlinks + configHostsAlias = [domainAlias], + + // HTML anchor element classes to not track + configIgnoreClasses = [], + + // HTML anchor element classes to treat as downloads + configDownloadClasses = [], + + // HTML anchor element classes to treat at outlinks + configLinkClasses = [], + + // Maximum delay to wait for spiderweb bug image to be fetched (in milliseconds) + configTrackerPause = 500, + + // Minimum visit time after initial page view (in milliseconds) + configMinimumVisitTime, + + // Recurring heart beat after initial ping (in milliseconds) + configHeartBeatDelay, + + // alias to circumvent circular function dependency (JSLint requires this) + heartBeatPingIfActivityAlias, + + // Disallow hash tags in URL + configDiscardHashTag, + + // Custom data + configCustomData, + + // Campaign names + configCampaignNameParameters = [ 'pk_campaign', 'piwik_campaign', 'utm_campaign', 'utm_source', 'utm_medium' ], + + // Campaign keywords + configCampaignKeywordParameters = [ 'pk_kwd', 'piwik_kwd', 'utm_term' ], + + // First-party cookie name prefix + configCookieNamePrefix = '_pk_', + + // First-party cookie domain + // User agent defaults to origin hostname + configCookieDomain, + + // First-party cookie path + // Default is user agent defined. + configCookiePath, + + // Cookies are disabled + configCookiesDisabled = false, + + // Do Not Track + configDoNotTrack, + + // Count sites which are pre-rendered + configCountPreRendered, + + // Do we attribute the conversion to the first referrer or the most recent referrer? + configConversionAttributionFirstReferrer, + + // Life of the visitor cookie (in milliseconds) + configVisitorCookieTimeout = 33955200000, // 13 months (365 days + 28days) + + // Life of the session cookie (in milliseconds) + configSessionCookieTimeout = 1800000, // 30 minutes + + // Life of the referral cookie (in milliseconds) + configReferralCookieTimeout = 15768000000, // 6 months + + // Is performance tracking enabled + configPerformanceTrackingEnabled = true, + + // Generation time set from the server + configPerformanceGenerationTime = 0, + + // Whether Custom Variables scope "visit" should be stored in a cookie during the time of the visit + configStoreCustomVariablesInCookie = false, + + // Custom Variables read from cookie, scope "visit" + customVariables = false, + + configCustomRequestContentProcessing, + + // Custom Variables, scope "page" + customVariablesPage = {}, + + // Custom Variables, scope "event" + customVariablesEvent = {}, + + // Custom Dimensions (can be any scope) + customDimensions = {}, + + // Custom Variables names and values are each truncated before being sent in the request or recorded in the cookie + customVariableMaximumLength = 200, + + // Ecommerce items + ecommerceItems = {}, + + // Browser features via client-side data collection + browserFeatures = {}, + + // Keeps track of previously tracked content impressions + trackedContentImpressions = [], + isTrackOnlyVisibleContentEnabled = false, + + // Guard to prevent empty visits see #6415. If there is a new visitor and the first 2 (or 3 or 4) + // tracking requests are at nearly same time (eg trackPageView and trackContentImpression) 2 or more + // visits will be created + timeNextTrackingRequestCanBeExecutedImmediately = false, + + // Guard against installing the link tracker more than once per Tracker instance + linkTrackingInstalled = false, + linkTrackingEnabled = false, + + // Guard against installing the activity tracker more than once per Tracker instance + heartBeatSetUp = false, + + // Timestamp of last tracker request sent to Piwik + lastTrackerRequestTime = null, + + // Handle to the current heart beat timeout + heartBeatTimeout, + + // Internal state of the pseudo click handler + lastButton, + lastTarget, + + // Hash function + hash = sha1, + + // Domain hash value + domainHash; + + /* + * Set cookie value + */ + function setCookie(cookieName, value, msToExpire, path, domain, secure) { + if (configCookiesDisabled) { + return; + } + + var expiryDate; + + // relative time to expire in milliseconds + if (msToExpire) { + expiryDate = new Date(); + expiryDate.setTime(expiryDate.getTime() + msToExpire); + } + + documentAlias.cookie = cookieName + '=' + encodeWrapper(value) + + (msToExpire ? ';expires=' + expiryDate.toGMTString() : '') + + ';path=' + (path || '/') + + (domain ? ';domain=' + domain : '') + + (secure ? ';secure' : ''); + } + + /* + * Get cookie value + */ + function getCookie(cookieName) { + if (configCookiesDisabled) { + return 0; + } + + var cookiePattern = new RegExp('(^|;)[ ]*' + cookieName + '=([^;]*)'), + cookieMatch = cookiePattern.exec(documentAlias.cookie); + + return cookieMatch ? decodeWrapper(cookieMatch[2]) : 0; + } + + /* + * Removes hash tag from the URL + * + * URLs are purified before being recorded in the cookie, + * or before being sent as GET parameters + */ + function purify(url) { + var targetPattern; + + if (configDiscardHashTag) { + targetPattern = new RegExp('#.*'); + + return url.replace(targetPattern, ''); + } + + return url; + } + + /* + * Resolve relative reference + * + * Note: not as described in rfc3986 section 5.2 + */ + function resolveRelativeReference(baseUrl, url) { + var protocol = getProtocolScheme(url), + i; + + if (protocol) { + return url; + } + + if (url.slice(0, 1) === '/') { + return getProtocolScheme(baseUrl) + '://' + getHostName(baseUrl) + url; + } + + baseUrl = purify(baseUrl); + + i = baseUrl.indexOf('?'); + if (i >= 0) { + baseUrl = baseUrl.slice(0, i); + } + + i = baseUrl.lastIndexOf('/'); + if (i !== baseUrl.length - 1) { + baseUrl = baseUrl.slice(0, i + 1); + } + + return baseUrl + url; + } + + function isSameHost (hostName, alias) { + var offset; + + hostName = String(hostName).toLowerCase(); + alias = String(alias).toLowerCase(); + + if (hostName === alias) { + return true; + } + + if (alias.slice(0, 1) === '.') { + if (hostName === alias.slice(1)) { + return true; + } + + offset = hostName.length - alias.length; + + if ((offset > 0) && (hostName.slice(offset) === alias)) { + return true; + } + } + + return false; + } + + function stringEndsWith(str, suffix) { + str = String(str); + return str.indexOf(suffix, str.length - suffix.length) !== -1; + } + + function removeCharactersFromEndOfString(str, numCharactersToRemove) { + str = String(str); + return str.substr(0, str.length - numCharactersToRemove); + } + + /* + * Extract pathname from URL. element.pathname is actually supported by pretty much all browsers including + * IE6 apart from some rare very old ones + */ + function getPathName(url) { + var parser = document.createElement('a'); + if (url.indexOf('//') !== 0 && url.indexOf('http') !== 0) { + url = 'http://' + url; + } + + parser.href = content.toAbsoluteUrl(url); + if (parser.pathname) { + return parser.pathname; + } + + return ''; + } + + function isSitePath (path, pathAlias) + { + var matchesAnyPath = (!pathAlias || pathAlias === '/'); + + if (matchesAnyPath) { + return true; + } + + if (path === pathAlias) { + return true; + } + + if (!path) { + return false; + } + + pathAlias = String(pathAlias).toLowerCase(); + path = String(path).toLowerCase(); + + // we need to append slashes so /foobarbaz won't match a site /foobar + if (!stringEndsWith(path, '/')) { + path += '/'; + } + + if (!stringEndsWith(pathAlias, '/')) { + pathAlias += '/'; + } + + return path.indexOf(pathAlias) === 0; + } + + function isSiteHostPath(host, path) + { + var i, + alias, + configAlias, + aliasHost, + aliasPath; + + for (i = 0; i < configHostsAlias.length; i++) { + aliasHost = domainFixup(configHostsAlias[i]); + aliasPath = getPathName(configHostsAlias[i]); + + if (isSameHost(host, aliasHost) && isSitePath(path, aliasPath)) { + return true; + } + } + + return false; + } + + /* + * Is the host local? (i.e., not an outlink) + */ + function isSiteHostName(hostName) { + + var i, + alias, + offset; + + for (i = 0; i < configHostsAlias.length; i++) { + alias = domainFixup(configHostsAlias[i].toLowerCase()); + + if (hostName === alias) { + return true; + } + + if (alias.slice(0, 1) === '.') { + if (hostName === alias.slice(1)) { + return true; + } + + offset = hostName.length - alias.length; + + if ((offset > 0) && (hostName.slice(offset) === alias)) { + return true; + } + } + } + + return false; + } + + /* + * Send image request to Piwik server using GET. + * The infamous spiderweb bug (or beacon) is a transparent, single pixel (1x1) image + */ + function getImage(request, callback) { + var image = new Image(1, 1); + + image.onload = function () { + iterator = 0; // To avoid JSLint warning of empty block + if (typeof callback === 'function') { callback(); } + }; + image.src = configTrackerUrl + (configTrackerUrl.indexOf('?') < 0 ? '?' : '&') + request; + } + + /* + * POST request to Piwik server using XMLHttpRequest. + */ + function sendXmlHttpRequest(request, callback, fallbackToGet) { + if (!isDefined(fallbackToGet) || null === fallbackToGet) { + fallbackToGet = true; + } + + try { + // we use the progid Microsoft.XMLHTTP because + // IE5.5 included MSXML 2.5; the progid MSXML2.XMLHTTP + // is pinned to MSXML2.XMLHTTP.3.0 + var xhr = windowAlias.XMLHttpRequest + ? new windowAlias.XMLHttpRequest() + : windowAlias.ActiveXObject + ? new ActiveXObject('Microsoft.XMLHTTP') + : null; + + xhr.open('POST', configTrackerUrl, true); + + // fallback on error + xhr.onreadystatechange = function () { + if (this.readyState === 4 && !(this.status >= 200 && this.status < 300) && fallbackToGet) { + getImage(request, callback); + } else { + if (typeof callback === 'function') { callback(); } + } + }; + + xhr.setRequestHeader('Content-Type', configRequestContentType); + + xhr.send(request); + } catch (e) { + if (fallbackToGet) { + // fallback + getImage(request, callback); + } + } + } + + function setExpireDateTime(delay) { + + var now = new Date(); + var time = now.getTime() + delay; + + if (!expireDateTime || time > expireDateTime) { + expireDateTime = time; + } + } + + /* + * Sets up the heart beat timeout. + */ + function heartBeatUp(delay) { + if (heartBeatTimeout + || !configHeartBeatDelay + ) { + return; + } + + heartBeatTimeout = setTimeout(function heartBeat() { + heartBeatTimeout = null; + if (heartBeatPingIfActivityAlias()) { + return; + } + + var now = new Date(), + heartBeatDelay = configHeartBeatDelay - (now.getTime() - lastTrackerRequestTime); + // sanity check + heartBeatDelay = Math.min(configHeartBeatDelay, heartBeatDelay); + heartBeatUp(heartBeatDelay); + }, delay || configHeartBeatDelay); + } + + /* + * Removes the heart beat timeout. + */ + function heartBeatDown() { + if (!heartBeatTimeout) { + return; + } + + clearTimeout(heartBeatTimeout); + heartBeatTimeout = null; + } + + function heartBeatOnFocus() { + // since it's possible for a user to come back to a tab after several hours or more, we try to send + // a ping if the page is active. (after the ping is sent, the heart beat timeout will be set) + if (heartBeatPingIfActivityAlias()) { + return; + } + + heartBeatUp(); + } + + function heartBeatOnBlur() { + heartBeatDown(); + } + + /* + * Setup event handlers and timeout for initial heart beat. + */ + function setUpHeartBeat() { + if (heartBeatSetUp + || !configHeartBeatDelay + ) { + return; + } + + heartBeatSetUp = true; + + addEventListener(windowAlias, 'focus', heartBeatOnFocus); + addEventListener(windowAlias, 'blur', heartBeatOnBlur); + + heartBeatUp(); + } + + function makeSureThereIsAGapAfterFirstTrackingRequestToPreventMultipleVisitorCreation(callback) + { + var now = new Date(); + var timeNow = now.getTime(); + + lastTrackerRequestTime = timeNow; + + if (timeNextTrackingRequestCanBeExecutedImmediately && timeNow < timeNextTrackingRequestCanBeExecutedImmediately) { + // we are in the time frame shortly after the first request. we have to delay this request a bit to make sure + // a visitor has been created meanwhile. + + var timeToWait = timeNextTrackingRequestCanBeExecutedImmediately - timeNow; + + setTimeout(callback, timeToWait); + setExpireDateTime(timeToWait + 50); // set timeout is not necessarily executed at timeToWait so delay a bit more + timeNextTrackingRequestCanBeExecutedImmediately += 50; // delay next tracking request by further 50ms to next execute them at same time + + return; + } + + if (timeNextTrackingRequestCanBeExecutedImmediately === false) { + // it is the first request, we want to execute this one directly and delay all the next one(s) within a delay. + // All requests after this delay can be executed as usual again + var delayInMs = 800; + timeNextTrackingRequestCanBeExecutedImmediately = timeNow + delayInMs; + } + + callback(); + } + + /* + * Send request + */ + function sendRequest(request, delay, callback) { + if (!configDoNotTrack && request) { + makeSureThereIsAGapAfterFirstTrackingRequestToPreventMultipleVisitorCreation(function () { + if (configRequestMethod === 'POST') { + sendXmlHttpRequest(request, callback); + } else { + getImage(request, callback); + } + + setExpireDateTime(delay); + }); + } + + if (!heartBeatSetUp) { + setUpHeartBeat(); // setup window events too, but only once + } else { + heartBeatUp(); + } + } + + function canSendBulkRequest(requests) + { + if (configDoNotTrack) { + return false; + } + + return (requests && requests.length); + } + + /* + * Send requests using bulk + */ + function sendBulkRequest(requests, delay) + { + if (!canSendBulkRequest(requests)) { + return; + } + + var bulk = '{"requests":["?' + requests.join('","?') + '"]}'; + + makeSureThereIsAGapAfterFirstTrackingRequestToPreventMultipleVisitorCreation(function () { + sendXmlHttpRequest(bulk, null, false); + setExpireDateTime(delay); + }); + } + + /* + * Get cookie name with prefix and domain hash + */ + function getCookieName(baseName) { + // NOTE: If the cookie name is changed, we must also update the PiwikTracker.php which + // will attempt to discover first party cookies. eg. See the PHP Client method getVisitorId() + return configCookieNamePrefix + baseName + '.' + configTrackerSiteId + '.' + domainHash; + } + + /* + * Does browser have cookies enabled (for this site)? + */ + function hasCookies() { + if (configCookiesDisabled) { + return '0'; + } + + if (!isDefined(navigatorAlias.cookieEnabled)) { + var testCookieName = getCookieName('testcookie'); + setCookie(testCookieName, '1'); + + return getCookie(testCookieName) === '1' ? '1' : '0'; + } + + return navigatorAlias.cookieEnabled ? '1' : '0'; + } + + /* + * Update domain hash + */ + function updateDomainHash() { + domainHash = hash((configCookieDomain || domainAlias) + (configCookiePath || '/')).slice(0, 4); // 4 hexits = 16 bits + } + + /* + * Inits the custom variables object + */ + function getCustomVariablesFromCookie() { + var cookieName = getCookieName('cvar'), + cookie = getCookie(cookieName); + + if (cookie.length) { + cookie = JSON2.parse(cookie); + + if (isObject(cookie)) { + return cookie; + } + } + + return {}; + } + + /* + * Lazy loads the custom variables from the cookie, only once during this page view + */ + function loadCustomVariables() { + if (customVariables === false) { + customVariables = getCustomVariablesFromCookie(); + } + } + + /* + * Generate a pseudo-unique ID to fingerprint this user + * 16 hexits = 64 bits + * note: this isn't a RFC4122-compliant UUID + */ + function generateRandomUuid() { + return hash( + (navigatorAlias.userAgent || '') + + (navigatorAlias.platform || '') + + JSON2.stringify(browserFeatures) + + (new Date()).getTime() + + Math.random() + ).slice(0, 16); + } + + /* + * Load visitor ID cookie + */ + function loadVisitorIdCookie() { + var now = new Date(), + nowTs = Math.round(now.getTime() / 1000), + visitorIdCookieName = getCookieName('id'), + id = getCookie(visitorIdCookieName), + cookieValue, + uuid; + + // Visitor ID cookie found + if (id) { + cookieValue = id.split('.'); + + // returning visitor flag + cookieValue.unshift('0'); + + if(visitorUUID.length) { + cookieValue[1] = visitorUUID; + } + return cookieValue; + } + + if(visitorUUID.length) { + uuid = visitorUUID; + } else if ('0' === hasCookies()){ + uuid = ''; + } else { + uuid = generateRandomUuid(); + } + + // No visitor ID cookie, let's create a new one + cookieValue = [ + // new visitor + '1', + + // uuid + uuid, + + // creation timestamp - seconds since Unix epoch + nowTs, + + // visitCount - 0 = no previous visit + 0, + + // current visit timestamp + nowTs, + + // last visit timestamp - blank = no previous visit + '', + + // last ecommerce order timestamp + '' + ]; + + return cookieValue; + } + + + /** + * Loads the Visitor ID cookie and returns a named array of values + */ + function getValuesFromVisitorIdCookie() { + var cookieVisitorIdValue = loadVisitorIdCookie(), + newVisitor = cookieVisitorIdValue[0], + uuid = cookieVisitorIdValue[1], + createTs = cookieVisitorIdValue[2], + visitCount = cookieVisitorIdValue[3], + currentVisitTs = cookieVisitorIdValue[4], + lastVisitTs = cookieVisitorIdValue[5]; + + // case migrating from pre-1.5 cookies + if (!isDefined(cookieVisitorIdValue[6])) { + cookieVisitorIdValue[6] = ""; + } + + var lastEcommerceOrderTs = cookieVisitorIdValue[6]; + + return { + newVisitor: newVisitor, + uuid: uuid, + createTs: createTs, + visitCount: visitCount, + currentVisitTs: currentVisitTs, + lastVisitTs: lastVisitTs, + lastEcommerceOrderTs: lastEcommerceOrderTs + }; + } + + + function getRemainingVisitorCookieTimeout() { + var now = new Date(), + nowTs = now.getTime(), + cookieCreatedTs = getValuesFromVisitorIdCookie().createTs; + + var createTs = parseInt(cookieCreatedTs, 10); + var originalTimeout = (createTs * 1000) + configVisitorCookieTimeout - nowTs; + return originalTimeout; + } + + /* + * Sets the Visitor ID cookie + */ + function setVisitorIdCookie(visitorIdCookieValues) { + + if(!configTrackerSiteId) { + // when called before Site ID was set + return; + } + + var now = new Date(), + nowTs = Math.round(now.getTime() / 1000); + + if(!isDefined(visitorIdCookieValues)) { + visitorIdCookieValues = getValuesFromVisitorIdCookie(); + } + + var cookieValue = visitorIdCookieValues.uuid + '.' + + visitorIdCookieValues.createTs + '.' + + visitorIdCookieValues.visitCount + '.' + + nowTs + '.' + + visitorIdCookieValues.lastVisitTs + '.' + + visitorIdCookieValues.lastEcommerceOrderTs; + + setCookie(getCookieName('id'), cookieValue, getRemainingVisitorCookieTimeout(), configCookiePath, configCookieDomain); + } + + /* + * Loads the referrer attribution information + * + * @returns array + * 0: campaign name + * 1: campaign keyword + * 2: timestamp + * 3: raw URL + */ + function loadReferrerAttributionCookie() { + // NOTE: if the format of the cookie changes, + // we must also update JS tests, PHP tracker, System tests, + // and notify other tracking clients (eg. Java) of the changes + var cookie = getCookie(getCookieName('ref')); + + if (cookie.length) { + try { + cookie = JSON2.parse(cookie); + if (isObject(cookie)) { + return cookie; + } + } catch (ignore) { + // Pre 1.3, this cookie was not JSON encoded + } + } + + return [ + '', + '', + 0, + '' + ]; + } + + function deleteCookie(cookieName, path, domain) { + setCookie(cookieName, '', -86400, path, domain); + } + + function isPossibleToSetCookieOnDomain(domainToTest) + { + var valueToSet = 'testvalue'; + setCookie('test', valueToSet, 10000, null, domainToTest); + + if (getCookie('test') === valueToSet) { + deleteCookie('test', null, domainToTest); + + return true; + } + + return false; + } + + function deleteCookies() { + var savedConfigCookiesDisabled = configCookiesDisabled; + + // Temporarily allow cookies just to delete the existing ones + configCookiesDisabled = false; + + var cookiesToDelete = ['id', 'ses', 'cvar', 'ref']; + var index, cookieName; + + for (index = 0; index < cookiesToDelete.length; index++) { + cookieName = getCookieName(cookiesToDelete[index]); + if (0 !== getCookie(cookieName)) { + deleteCookie(cookieName, configCookiePath, configCookieDomain); + } + } + + configCookiesDisabled = savedConfigCookiesDisabled; + } + + function setSiteId(siteId) { + configTrackerSiteId = siteId; + setVisitorIdCookie(); + } + + function sortObjectByKeys(value) { + if (!value || !isObject(value)) { + return; + } + + // Object.keys(value) is not supported by all browsers, we get the keys manually + var keys = []; + var key; + + for (key in value) { + if (Object.prototype.hasOwnProperty.call(value, key)) { + keys.push(key); + } + } + + var normalized = {}; + keys.sort(); + var len = keys.length; + var i; + + for (i = 0; i < len; i++) { + normalized[keys[i]] = value[keys[i]]; + } + + return normalized; + } + + /** + * Creates the session cookie + */ + function setSessionCookie() { + setCookie(getCookieName('ses'), '*', configSessionCookieTimeout, configCookiePath, configCookieDomain); + } + + /** + * Returns the URL to call piwik.php, + * with the standard parameters (plugins, resolution, url, referrer, etc.). + * Sends the pageview and browser settings with every request in case of race conditions. + */ + function getRequest(request, customData, pluginMethod, currentEcommerceOrderTs) { + var i, + now = new Date(), + nowTs = Math.round(now.getTime() / 1000), + referralTs, + referralUrl, + referralUrlMaxLength = 1024, + currentReferrerHostName, + originalReferrerHostName, + customVariablesCopy = customVariables, + cookieSessionName = getCookieName('ses'), + cookieReferrerName = getCookieName('ref'), + cookieCustomVariablesName = getCookieName('cvar'), + cookieSessionValue = getCookie(cookieSessionName), + attributionCookie = loadReferrerAttributionCookie(), + currentUrl = configCustomUrl || locationHrefAlias, + campaignNameDetected, + campaignKeywordDetected; + + if (configCookiesDisabled) { + deleteCookies(); + } + + if (configDoNotTrack) { + return ''; + } + + var cookieVisitorIdValues = getValuesFromVisitorIdCookie(); + if (!isDefined(currentEcommerceOrderTs)) { + currentEcommerceOrderTs = ""; + } + + // send charset if document charset is not utf-8. sometimes encoding + // of urls will be the same as this and not utf-8, which will cause problems + // do not send charset if it is utf8 since it's assumed by default in Piwik + var charSet = documentAlias.characterSet || documentAlias.charset; + + if (!charSet || charSet.toLowerCase() === 'utf-8') { + charSet = null; + } + + campaignNameDetected = attributionCookie[0]; + campaignKeywordDetected = attributionCookie[1]; + referralTs = attributionCookie[2]; + referralUrl = attributionCookie[3]; + + if (!cookieSessionValue) { + // cookie 'ses' was not found: we consider this the start of a 'session' + + // here we make sure that if 'ses' cookie is deleted few times within the visit + // and so this code path is triggered many times for one visit, + // we only increase visitCount once per Visit window (default 30min) + var visitDuration = configSessionCookieTimeout / 1000; + if (!cookieVisitorIdValues.lastVisitTs + || (nowTs - cookieVisitorIdValues.lastVisitTs) > visitDuration) { + cookieVisitorIdValues.visitCount++; + cookieVisitorIdValues.lastVisitTs = cookieVisitorIdValues.currentVisitTs; + } + + + // Detect the campaign information from the current URL + // Only if campaign wasn't previously set + // Or if it was set but we must attribute to the most recent one + // Note: we are working on the currentUrl before purify() since we can parse the campaign parameters in the hash tag + if (!configConversionAttributionFirstReferrer + || !campaignNameDetected.length) { + for (i in configCampaignNameParameters) { + if (Object.prototype.hasOwnProperty.call(configCampaignNameParameters, i)) { + campaignNameDetected = getParameter(currentUrl, configCampaignNameParameters[i]); + + if (campaignNameDetected.length) { + break; + } + } + } + + for (i in configCampaignKeywordParameters) { + if (Object.prototype.hasOwnProperty.call(configCampaignKeywordParameters, i)) { + campaignKeywordDetected = getParameter(currentUrl, configCampaignKeywordParameters[i]); + + if (campaignKeywordDetected.length) { + break; + } + } + } + } + + // Store the referrer URL and time in the cookie; + // referral URL depends on the first or last referrer attribution + currentReferrerHostName = getHostName(configReferrerUrl); + originalReferrerHostName = referralUrl.length ? getHostName(referralUrl) : ''; + + if (currentReferrerHostName.length && // there is a referrer + !isSiteHostName(currentReferrerHostName) && // domain is not the current domain + (!configConversionAttributionFirstReferrer || // attribute to last known referrer + !originalReferrerHostName.length || // previously empty + isSiteHostName(originalReferrerHostName))) { // previously set but in current domain + referralUrl = configReferrerUrl; + } + + // Set the referral cookie if we have either a Referrer URL, or detected a Campaign (or both) + if (referralUrl.length + || campaignNameDetected.length) { + referralTs = nowTs; + attributionCookie = [ + campaignNameDetected, + campaignKeywordDetected, + referralTs, + purify(referralUrl.slice(0, referralUrlMaxLength)) + ]; + + setCookie(cookieReferrerName, JSON2.stringify(attributionCookie), configReferralCookieTimeout, configCookiePath, configCookieDomain); + } + } + + // build out the rest of the request + request += '&idsite=' + configTrackerSiteId + + '&rec=1' + + '&r=' + String(Math.random()).slice(2, 8) + // keep the string to a minimum + '&h=' + now.getHours() + '&m=' + now.getMinutes() + '&s=' + now.getSeconds() + + '&url=' + encodeWrapper(purify(currentUrl)) + + (configReferrerUrl.length ? '&urlref=' + encodeWrapper(purify(configReferrerUrl)) : '') + + ((configUserId && configUserId.length) ? '&uid=' + encodeWrapper(configUserId) : '') + + '&_id=' + cookieVisitorIdValues.uuid + '&_idts=' + cookieVisitorIdValues.createTs + '&_idvc=' + cookieVisitorIdValues.visitCount + + '&_idn=' + cookieVisitorIdValues.newVisitor + // currently unused + (campaignNameDetected.length ? '&_rcn=' + encodeWrapper(campaignNameDetected) : '') + + (campaignKeywordDetected.length ? '&_rck=' + encodeWrapper(campaignKeywordDetected) : '') + + '&_refts=' + referralTs + + '&_viewts=' + cookieVisitorIdValues.lastVisitTs + + (String(cookieVisitorIdValues.lastEcommerceOrderTs).length ? '&_ects=' + cookieVisitorIdValues.lastEcommerceOrderTs : '') + + (String(referralUrl).length ? '&_ref=' + encodeWrapper(purify(referralUrl.slice(0, referralUrlMaxLength))) : '') + + (charSet ? '&cs=' + encodeWrapper(charSet) : '') + + '&send_image=0'; + + // browser features + for (i in browserFeatures) { + if (Object.prototype.hasOwnProperty.call(browserFeatures, i)) { + request += '&' + i + '=' + browserFeatures[i]; + } + } + + var customDimensionIdsAlreadyHandled = []; + if (customData) { + for (i in customData) { + if (Object.prototype.hasOwnProperty.call(customData, i) && /^dimension\d+$/.test(i)) { + var index = i.replace('dimension', ''); + customDimensionIdsAlreadyHandled.push(parseInt(index, 10)); + customDimensionIdsAlreadyHandled.push(String(index)); + request += '&' + i + '=' + customData[i]; + delete customData[i]; + } + } + } + + if (customData && isObjectEmpty(customData)) { + customData = null; + // we deleted all keys from custom data + } + + // custom dimensions + for (i in customDimensions) { + if (Object.prototype.hasOwnProperty.call(customDimensions, i)) { + var isNotSetYet = (-1 === customDimensionIdsAlreadyHandled.indexOf(i)); + if (isNotSetYet) { + request += '&dimension' + i + '=' + customDimensions[i]; + } + } + } + + // custom data + if (customData) { + request += '&data=' + encodeWrapper(JSON2.stringify(customData)); + } else if (configCustomData) { + request += '&data=' + encodeWrapper(JSON2.stringify(configCustomData)); + } + + // Custom Variables, scope "page" + function appendCustomVariablesToRequest(customVariables, parameterName) { + var customVariablesStringified = JSON2.stringify(customVariables); + if (customVariablesStringified.length > 2) { + return '&' + parameterName + '=' + encodeWrapper(customVariablesStringified); + } + return ''; + } + + var sortedCustomVarPage = sortObjectByKeys(customVariablesPage); + var sortedCustomVarEvent = sortObjectByKeys(customVariablesEvent); + + request += appendCustomVariablesToRequest(sortedCustomVarPage, 'cvar'); + request += appendCustomVariablesToRequest(sortedCustomVarEvent, 'e_cvar'); + + // Custom Variables, scope "visit" + if (customVariables) { + request += appendCustomVariablesToRequest(customVariables, '_cvar'); + + // Don't save deleted custom variables in the cookie + for (i in customVariablesCopy) { + if (Object.prototype.hasOwnProperty.call(customVariablesCopy, i)) { + if (customVariables[i][0] === '' || customVariables[i][1] === '') { + delete customVariables[i]; + } + } + } + + if (configStoreCustomVariablesInCookie) { + setCookie(cookieCustomVariablesName, JSON2.stringify(customVariables), configSessionCookieTimeout, configCookiePath, configCookieDomain); + } + } + + // performance tracking + if (configPerformanceTrackingEnabled) { + if (configPerformanceGenerationTime) { + request += '>_ms=' + configPerformanceGenerationTime; + } else if (performanceAlias && performanceAlias.timing + && performanceAlias.timing.requestStart && performanceAlias.timing.responseEnd) { + request += '>_ms=' + (performanceAlias.timing.responseEnd - performanceAlias.timing.requestStart); + } + } + + // update cookies + cookieVisitorIdValues.lastEcommerceOrderTs = isDefined(currentEcommerceOrderTs) && String(currentEcommerceOrderTs).length ? currentEcommerceOrderTs : cookieVisitorIdValues.lastEcommerceOrderTs; + setVisitorIdCookie(cookieVisitorIdValues); + setSessionCookie(); + + // tracker plugin hook + request += executePluginMethod(pluginMethod); + + if (configAppendToTrackingUrl.length) { + request += '&' + configAppendToTrackingUrl; + } + + if (isFunction(configCustomRequestContentProcessing)) { + request = configCustomRequestContentProcessing(request); + } + + return request; + } + + /* + * If there was user activity since the last check, and it's been configHeartBeatDelay seconds + * since the last tracker, send a ping request (the heartbeat timeout will be reset by sendRequest). + */ + heartBeatPingIfActivityAlias = function heartBeatPingIfActivity() { + var now = new Date(); + if (lastTrackerRequestTime + configHeartBeatDelay <= now.getTime()) { + var requestPing = getRequest('ping=1', null, 'ping'); + sendRequest(requestPing, configTrackerPause); + + return true; + } + + return false; + }; + + function logEcommerce(orderId, grandTotal, subTotal, tax, shipping, discount) { + var request = 'idgoal=0', + lastEcommerceOrderTs, + now = new Date(), + items = [], + sku; + + if (String(orderId).length) { + request += '&ec_id=' + encodeWrapper(orderId); + // Record date of order in the visitor cookie + lastEcommerceOrderTs = Math.round(now.getTime() / 1000); + } + + request += '&revenue=' + grandTotal; + + if (String(subTotal).length) { + request += '&ec_st=' + subTotal; + } + + if (String(tax).length) { + request += '&ec_tx=' + tax; + } + + if (String(shipping).length) { + request += '&ec_sh=' + shipping; + } + + if (String(discount).length) { + request += '&ec_dt=' + discount; + } + + if (ecommerceItems) { + // Removing the SKU index in the array before JSON encoding + for (sku in ecommerceItems) { + if (Object.prototype.hasOwnProperty.call(ecommerceItems, sku)) { + // Ensure name and category default to healthy value + if (!isDefined(ecommerceItems[sku][1])) { + ecommerceItems[sku][1] = ""; + } + + if (!isDefined(ecommerceItems[sku][2])) { + ecommerceItems[sku][2] = ""; + } + + // Set price to zero + if (!isDefined(ecommerceItems[sku][3]) + || String(ecommerceItems[sku][3]).length === 0) { + ecommerceItems[sku][3] = 0; + } + + // Set quantity to 1 + if (!isDefined(ecommerceItems[sku][4]) + || String(ecommerceItems[sku][4]).length === 0) { + ecommerceItems[sku][4] = 1; + } + + items.push(ecommerceItems[sku]); + } + } + request += '&ec_items=' + encodeWrapper(JSON2.stringify(items)); + } + request = getRequest(request, configCustomData, 'ecommerce', lastEcommerceOrderTs); + sendRequest(request, configTrackerPause); + } + + function logEcommerceOrder(orderId, grandTotal, subTotal, tax, shipping, discount) { + if (String(orderId).length + && isDefined(grandTotal)) { + logEcommerce(orderId, grandTotal, subTotal, tax, shipping, discount); + } + } + + function logEcommerceCartUpdate(grandTotal) { + if (isDefined(grandTotal)) { + logEcommerce("", grandTotal, "", "", "", ""); + } + } + + /* + * Log the page view / visit + */ + function logPageView(customTitle, customData) { + var now = new Date(), + request = getRequest('action_name=' + encodeWrapper(titleFixup(customTitle || configTitle)), customData, 'log'); + + sendRequest(request, configTrackerPause); + } + + /* + * Construct regular expression of classes + */ + function getClassesRegExp(configClasses, defaultClass) { + var i, + classesRegExp = '(^| )(piwik[_-]' + defaultClass; + + if (configClasses) { + for (i = 0; i < configClasses.length; i++) { + classesRegExp += '|' + configClasses[i]; + } + } + + classesRegExp += ')( |$)'; + + return new RegExp(classesRegExp); + } + + function startsUrlWithTrackerUrl(url) { + return (configTrackerUrl && url && 0 === String(url).indexOf(configTrackerUrl)); + } + + /* + * Link or Download? + */ + function getLinkType(className, href, isInLink, hasDownloadAttribute) { + if (startsUrlWithTrackerUrl(href)) { + return 0; + } + + // does class indicate whether it is an (explicit/forced) outlink or a download? + var downloadPattern = getClassesRegExp(configDownloadClasses, 'download'), + linkPattern = getClassesRegExp(configLinkClasses, 'link'), + + // does file extension indicate that it is a download? + downloadExtensionsPattern = new RegExp('\\.(' + configDownloadExtensions.join('|') + ')([?&#]|$)', 'i'); + + if (linkPattern.test(className)) { + return 'link'; + } + + if (hasDownloadAttribute || downloadPattern.test(className) || downloadExtensionsPattern.test(href)) { + return 'download'; + } + + if (isInLink) { + return 0; + } + + return 'link'; + } + + function getSourceElement(sourceElement) + { + var parentElement; + + parentElement = sourceElement.parentNode; + while (parentElement !== null && + /* buggy IE5.5 */ + isDefined(parentElement)) { + + if (query.isLinkElement(sourceElement)) { + break; + } + sourceElement = parentElement; + parentElement = sourceElement.parentNode; + } + + return sourceElement; + } + + function getLinkIfShouldBeProcessed(sourceElement) + { + sourceElement = getSourceElement(sourceElement); + + if (!query.hasNodeAttribute(sourceElement, 'href')) { + return; + } + + if (!isDefined(sourceElement.href)) { + return; + } + + var href = query.getAttributeValueFromNode(sourceElement, 'href'); + + if (startsUrlWithTrackerUrl(href)) { + return; + } + + var originalSourcePath = sourceElement.pathname || getPathName(sourceElement.href); + + // browsers, such as Safari, don't downcase hostname and href + var originalSourceHostName = sourceElement.hostname || getHostName(sourceElement.href); + var sourceHostName = originalSourceHostName.toLowerCase(); + var sourceHref = sourceElement.href.replace(originalSourceHostName, sourceHostName); + + // browsers, such as Safari, don't downcase hostname and href + var scriptProtocol = new RegExp('^(javascript|vbscript|jscript|mocha|livescript|ecmascript|mailto):', 'i'); + + if (!scriptProtocol.test(sourceHref)) { + // track outlinks and all downloads + var linkType = getLinkType(sourceElement.className, sourceHref, isSiteHostPath(sourceHostName, originalSourcePath), query.hasNodeAttribute(sourceElement, 'download')); + + if (linkType) { + return { + type: linkType, + href: sourceHref + }; + } + } + } + + function buildContentInteractionRequest(interaction, name, piece, target) + { + var params = content.buildInteractionRequestParams(interaction, name, piece, target); + + if (!params) { + return; + } + + return getRequest(params, null, 'contentInteraction'); + } + + function buildContentInteractionTrackingRedirectUrl(url, contentInteraction, contentName, contentPiece, contentTarget) + { + if (!isDefined(url)) { + return; + } + + if (startsUrlWithTrackerUrl(url)) { + return url; + } + + var redirectUrl = content.toAbsoluteUrl(url); + var request = 'redirecturl=' + encodeWrapper(redirectUrl) + '&'; + request += buildContentInteractionRequest(contentInteraction, contentName, contentPiece, (contentTarget || url)); + + var separator = '&'; + if (configTrackerUrl.indexOf('?') < 0) { + separator = '?'; + } + + return configTrackerUrl + separator + request; + } + + function isNodeAuthorizedToTriggerInteraction(contentNode, interactedNode) + { + if (!contentNode || !interactedNode) { + return false; + } + + var targetNode = content.findTargetNode(contentNode); + + if (content.shouldIgnoreInteraction(targetNode)) { + // interaction should be ignored + return false; + } + + targetNode = content.findTargetNodeNoDefault(contentNode); + if (targetNode && !containsNodeElement(targetNode, interactedNode)) { + /** + * There is a target node defined but the clicked element is not within the target node. example: + * <div data-track-content><a href="Y" data-content-target>Y</a><img src=""/><a href="Z">Z</a></div> + * + * The user clicked in this case on link Z and not on target Y + */ + return false; + } + + return true; + } + + function getContentInteractionToRequestIfPossible (anyNode, interaction, fallbackTarget) + { + if (!anyNode) { + return; + } + + var contentNode = content.findParentContentNode(anyNode); + + if (!contentNode) { + // we are not within a content block + return; + } + + if (!isNodeAuthorizedToTriggerInteraction(contentNode, anyNode)) { + return; + } + + var contentBlock = content.buildContentBlock(contentNode); + + if (!contentBlock) { + return; + } + + if (!contentBlock.target && fallbackTarget) { + contentBlock.target = fallbackTarget; + } + + return content.buildInteractionRequestParams(interaction, contentBlock.name, contentBlock.piece, contentBlock.target); + } + + function wasContentImpressionAlreadyTracked(contentBlock) + { + if (!trackedContentImpressions || !trackedContentImpressions.length) { + return false; + } + + var index, trackedContent; + + for (index = 0; index < trackedContentImpressions.length; index++) { + trackedContent = trackedContentImpressions[index]; + + if (trackedContent && + trackedContent.name === contentBlock.name && + trackedContent.piece === contentBlock.piece && + trackedContent.target === contentBlock.target) { + return true; + } + } + + return false; + } + + function replaceHrefIfInternalLink(contentBlock) + { + if (!contentBlock) { + return false; + } + + var targetNode = content.findTargetNode(contentBlock); + + if (!targetNode || content.shouldIgnoreInteraction(targetNode)) { + return false; + } + + var link = getLinkIfShouldBeProcessed(targetNode); + if (linkTrackingEnabled && link && link.type) { + + return false; // will be handled via outlink or download. + } + + if (query.isLinkElement(targetNode) && + query.hasNodeAttributeWithValue(targetNode, 'href')) { + var url = String(query.getAttributeValueFromNode(targetNode, 'href')); + + if (0 === url.indexOf('#')) { + return false; + } + + if (startsUrlWithTrackerUrl(url)) { + return true; + } + + if (!content.isUrlToCurrentDomain(url)) { + return false; + } + + var block = content.buildContentBlock(contentBlock); + + if (!block) { + return; + } + + var contentName = block.name; + var contentPiece = block.piece; + var contentTarget = block.target; + + if (!query.hasNodeAttributeWithValue(targetNode, content.CONTENT_TARGET_ATTR) || targetNode.wasContentTargetAttrReplaced) { + // make sure we still track the correct content target when an interaction is happening + targetNode.wasContentTargetAttrReplaced = true; + contentTarget = content.toAbsoluteUrl(url); + query.setAnyAttribute(targetNode, content.CONTENT_TARGET_ATTR, contentTarget); + } + + var targetUrl = buildContentInteractionTrackingRedirectUrl(url, 'click', contentName, contentPiece, contentTarget); + + // location.href does not respect target=_blank so we prefer to use this + content.setHrefAttribute(targetNode, targetUrl); + + return true; + } + + return false; + } + + function replaceHrefsIfInternalLink(contentNodes) + { + if (!contentNodes || !contentNodes.length) { + return; + } + + var index; + for (index = 0; index < contentNodes.length; index++) { + replaceHrefIfInternalLink(contentNodes[index]); + } + } + + function trackContentImpressionClickInteraction (targetNode) + { + return function (event) { + + if (!targetNode) { + return; + } + + var contentBlock = content.findParentContentNode(targetNode); + + var interactedElement; + if (event) { + interactedElement = event.target || event.srcElement; + } + if (!interactedElement) { + interactedElement = targetNode; + } + + if (!isNodeAuthorizedToTriggerInteraction(contentBlock, interactedElement)) { + return; + } + + setExpireDateTime(configTrackerPause); + + if (query.isLinkElement(targetNode) && + query.hasNodeAttributeWithValue(targetNode, 'href') && + query.hasNodeAttributeWithValue(targetNode, content.CONTENT_TARGET_ATTR)) { + // there is a href attribute, the link was replaced with piwik.php but later the href was changed again by the application. + var href = query.getAttributeValueFromNode(targetNode, 'href'); + if (!startsUrlWithTrackerUrl(href) && targetNode.wasContentTargetAttrReplaced) { + query.setAnyAttribute(targetNode, content.CONTENT_TARGET_ATTR, ''); + } + } + + var link = getLinkIfShouldBeProcessed(targetNode); + + if (linkTrackingInstalled && link && link.type) { + // click ignore, will be tracked via processClick, we do not want to track it twice + + return link.type; + } + + if (replaceHrefIfInternalLink(contentBlock)) { + return 'href'; + } + + var block = content.buildContentBlock(contentBlock); + + if (!block) { + return; + } + + var contentName = block.name; + var contentPiece = block.piece; + var contentTarget = block.target; + + // click on any non link element, or on a link element that has not an href attribute or on an anchor + var request = buildContentInteractionRequest('click', contentName, contentPiece, contentTarget); + sendRequest(request, configTrackerPause); + + return request; + }; + } + + function setupInteractionsTracking(contentNodes) + { + if (!contentNodes || !contentNodes.length) { + return; + } + + var index, targetNode; + for (index = 0; index < contentNodes.length; index++) { + targetNode = content.findTargetNode(contentNodes[index]); + + if (targetNode && !targetNode.contentInteractionTrackingSetupDone) { + targetNode.contentInteractionTrackingSetupDone = true; + + addEventListener(targetNode, 'click', trackContentImpressionClickInteraction(targetNode)); + } + } + } + + /* + * Log all content pieces + */ + function buildContentImpressionsRequests(contents, contentNodes) + { + if (!contents || !contents.length) { + return []; + } + + var index, request; + + for (index = 0; index < contents.length; index++) { + + if (wasContentImpressionAlreadyTracked(contents[index])) { + contents.splice(index, 1); + index--; + } else { + trackedContentImpressions.push(contents[index]); + } + } + + if (!contents || !contents.length) { + return []; + } + + replaceHrefsIfInternalLink(contentNodes); + setupInteractionsTracking(contentNodes); + + var requests = []; + + for (index = 0; index < contents.length; index++) { + + request = getRequest( + content.buildImpressionRequestParams(contents[index].name, contents[index].piece, contents[index].target), + undefined, + 'contentImpressions' + ); + + requests.push(request); + } + + return requests; + } + + /* + * Log all content pieces + */ + function getContentImpressionsRequestsFromNodes(contentNodes) + { + var contents = content.collectContent(contentNodes); + + return buildContentImpressionsRequests(contents, contentNodes); + } + + /* + * Log currently visible content pieces + */ + function getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet(contentNodes) + { + if (!contentNodes || !contentNodes.length) { + return []; + } + + var index; + + for (index = 0; index < contentNodes.length; index++) { + if (!content.isNodeVisible(contentNodes[index])) { + contentNodes.splice(index, 1); + index--; + } + } + + if (!contentNodes || !contentNodes.length) { + return []; + } + + return getContentImpressionsRequestsFromNodes(contentNodes); + } + + function buildContentImpressionRequest(contentName, contentPiece, contentTarget) + { + var params = content.buildImpressionRequestParams(contentName, contentPiece, contentTarget); + + return getRequest(params, null, 'contentImpression'); + } + + function buildContentInteractionRequestNode(node, contentInteraction) + { + if (!node) { + return; + } + + var contentNode = content.findParentContentNode(node); + var contentBlock = content.buildContentBlock(contentNode); + + if (!contentBlock) { + return; + } + + if (!contentInteraction) { + contentInteraction = 'Unknown'; + } + + return buildContentInteractionRequest(contentInteraction, contentBlock.name, contentBlock.piece, contentBlock.target); + } + + function buildEventRequest(category, action, name, value) + { + return 'e_c=' + encodeWrapper(category) + + '&e_a=' + encodeWrapper(action) + + (isDefined(name) ? '&e_n=' + encodeWrapper(name) : '') + + (isDefined(value) ? '&e_v=' + encodeWrapper(value) : ''); + } + + /* + * Log the event + */ + function logEvent(category, action, name, value, customData) + { + // Category and Action are required parameters + if (String(category).length === 0 || String(action).length === 0) { + return false; + } + var request = getRequest( + buildEventRequest(category, action, name, value), + customData, + 'event' + ); + + sendRequest(request, configTrackerPause); + } + + /* + * Log the site search request + */ + function logSiteSearch(keyword, category, resultsCount, customData) { + var request = getRequest('search=' + encodeWrapper(keyword) + + (category ? '&search_cat=' + encodeWrapper(category) : '') + + (isDefined(resultsCount) ? '&search_count=' + resultsCount : ''), customData, 'sitesearch'); + + sendRequest(request, configTrackerPause); + } + + /* + * Log the goal with the server + */ + function logGoal(idGoal, customRevenue, customData) { + var request = getRequest('idgoal=' + idGoal + (customRevenue ? '&revenue=' + customRevenue : ''), customData, 'goal'); + + sendRequest(request, configTrackerPause); + } + + /* + * Log the link or click with the server + */ + function logLink(url, linkType, customData, callback, sourceElement) { + + var linkParams = linkType + '=' + encodeWrapper(purify(url)); + + var interaction = getContentInteractionToRequestIfPossible(sourceElement, 'click', url); + + if (interaction) { + linkParams += '&' + interaction; + } + + var request = getRequest(linkParams, customData, 'link'); + + sendRequest(request, (callback ? 0 : configTrackerPause), callback); + } + + /* + * Browser prefix + */ + function prefixPropertyName(prefix, propertyName) { + if (prefix !== '') { + return prefix + propertyName.charAt(0).toUpperCase() + propertyName.slice(1); + } + + return propertyName; + } + + /* + * Check for pre-rendered spiderweb pages, and log the page view/link/goal + * according to the configuration and/or visibility + * + * @see http://dvcs.w3.org/hg/spiderwebperf/raw-file/tip/specs/PageVisibility/Overview.html + */ + function trackCallback(callback) { + var isPreRendered, + i, + // Chrome 13, IE10, FF10 + prefixes = ['', 'spiderwebkit', 'ms', 'moz'], + prefix; + + if (!configCountPreRendered) { + for (i = 0; i < prefixes.length; i++) { + prefix = prefixes[i]; + + // does this browser support the page visibility API? + if (Object.prototype.hasOwnProperty.call(documentAlias, prefixPropertyName(prefix, 'hidden'))) { + // if pre-rendered, then defer callback until page visibility changes + if (documentAlias[prefixPropertyName(prefix, 'visibilityState')] === 'prerender') { + isPreRendered = true; + } + break; + } + } + } + + if (isPreRendered) { + // note: the event name doesn't follow the same naming convention as vendor properties + addEventListener(documentAlias, prefix + 'visibilitychange', function ready() { + documentAlias.removeEventListener(prefix + 'visibilitychange', ready, false); + callback(); + }); + + return; + } + + // configCountPreRendered === true || isPreRendered === false + callback(); + } + + function trackCallbackOnLoad(callback) + { + if (documentAlias.readyState === 'complete') { + callback(); + } else if (windowAlias.addEventListener) { + windowAlias.addEventListener('load', callback); + } else if (windowAlias.attachEvent) { + windowAlias.attachEvent('onLoad', callback); + } + } + + function trackCallbackOnReady(callback) + { + var loaded = false; + + if (documentAlias.attachEvent) { + loaded = documentAlias.readyState === "complete"; + } else { + loaded = documentAlias.readyState !== "loading"; + } + + if (loaded) { + callback(); + } else if (documentAlias.addEventListener) { + documentAlias.addEventListener('DOMContentLoaded', callback); + } else if (documentAlias.attachEvent) { + documentAlias.attachEvent('onreadystatechange', callback); + } + } + + /* + * Process clicks + */ + function processClick(sourceElement) { + var link = getLinkIfShouldBeProcessed(sourceElement); + + if (link && link.type) { + link.href = safeDecodeWrapper(link.href); + logLink(link.href, link.type, undefined, null, sourceElement); + } + } + + function isIE8orOlder() + { + return documentAlias.all && !documentAlias.addEventListener; + } + + function getKeyCodeFromEvent(event) + { + // event.which is deprecated https://developer.mozilla.org/en-US/docs/Spiderweb/API/KeyboardEvent/which + var which = event.which; + + /** + 1 : Left mouse button + 2 : Wheel button or middle button + 3 : Right mouse button + */ + + var typeOfEventButton = (typeof event.button); + + if (!which && typeOfEventButton !== 'undefined' ) { + /** + -1: No button pressed + 0 : Main button pressed, usually the left button + 1 : Auxiliary button pressed, usually the wheel button or themiddle button (if present) + 2 : Secondary button pressed, usually the right button + 3 : Fourth button, typically the Browser Back button + 4 : Fifth button, typically the Browser Forward button + + IE8 and earlier has different values: + 1 : Left mouse button + 2 : Right mouse button + 4 : Wheel button or middle button + + For a left-hand configured mouse, the return values are reversed. We do not take care of that. + */ + + if (isIE8orOlder()) { + if (event.button & 1) { + which = 1; + } else if (event.button & 2) { + which = 3; + } else if (event.button & 4) { + which = 2; + } + } else { + if (event.button === 0 || event.button === '0') { + which = 1; + } else if (event.button & 1) { + which = 2; + } else if (event.button & 2) { + which = 3; + } + } + } + + return which; + } + + function getNameOfClickedButton(event) + { + switch (getKeyCodeFromEvent(event)) { + case 1: + return 'left'; + case 2: + return 'middle'; + case 3: + return 'right'; + } + } + + function getTargetElementFromEvent(event) + { + return event.target || event.srcElement; + } + + /* + * Handle click event + */ + function clickHandler(enable) { + + return function (event) { + + event = event || windowAlias.event; + + var button = getNameOfClickedButton(event); + var target = getTargetElementFromEvent(event); + + if (event.type === 'click') { + + var ignoreClick = false; + if (enable && button === 'middle') { + // if enabled, we track middle clicks via mouseup + // some browsers (eg chrome) trigger click and mousedown/up events when middle is clicked, + // whereas some do not. This way we make "sure" to track them only once, either in click + // (default) or in mouseup (if enable == true) + ignoreClick = true; + } + + if (target && !ignoreClick) { + processClick(target); + } + } else if (event.type === 'mousedown') { + if (button === 'middle' && target) { + lastButton = button; + lastTarget = target; + } else { + lastButton = lastTarget = null; + } + } else if (event.type === 'mouseup') { + if (button === lastButton && target === lastTarget) { + processClick(target); + } + lastButton = lastTarget = null; + } else if (event.type === 'contextmenu') { + processClick(target); + } + }; + } + + /* + * Add click listener to a DOM element + */ + function addClickListener(element, enable) { + addEventListener(element, 'click', clickHandler(enable), false); + + if (enable) { + addEventListener(element, 'mouseup', clickHandler(enable), false); + addEventListener(element, 'mousedown', clickHandler(enable), false); + addEventListener(element, 'contextmenu', clickHandler(enable), false); + } + } + + /* + * Add click handlers to anchor and AREA elements, except those to be ignored + */ + function addClickListeners(enable) { + if (!linkTrackingInstalled) { + linkTrackingInstalled = true; + + // iterate through anchor elements with href and AREA elements + + var i, + ignorePattern = getClassesRegExp(configIgnoreClasses, 'ignore'), + linkElements = documentAlias.links; + + if (linkElements) { + for (i = 0; i < linkElements.length; i++) { + if (!ignorePattern.test(linkElements[i].className)) { + addClickListener(linkElements[i], enable); + } + } + } + } + } + + + function enableTrackOnlyVisibleContent (checkOnSroll, timeIntervalInMs, tracker) { + + if (isTrackOnlyVisibleContentEnabled) { + // already enabled, do not register intervals again + return true; + } + + isTrackOnlyVisibleContentEnabled = true; + + var didScroll = false; + var events, index; + + function setDidScroll() { didScroll = true; } + + trackCallbackOnLoad(function () { + + function checkContent(intervalInMs) { + setTimeout(function () { + if (!isTrackOnlyVisibleContentEnabled) { + return; // the tests stopped tracking only visible content + } + didScroll = false; + tracker.trackVisibleContentImpressions(); + checkContent(intervalInMs); + }, intervalInMs); + } + + function checkContentIfDidScroll(intervalInMs) { + + setTimeout(function () { + if (!isTrackOnlyVisibleContentEnabled) { + return; // the tests stopped tracking only visible content + } + + if (didScroll) { + didScroll = false; + tracker.trackVisibleContentImpressions(); + } + + checkContentIfDidScroll(intervalInMs); + }, intervalInMs); + } + + if (checkOnSroll) { + + // scroll event is executed after each pixel, so we make sure not to + // execute event too often. otherwise FPS goes down a lot! + events = ['scroll', 'resize']; + for (index = 0; index < events.length; index++) { + if (documentAlias.addEventListener) { + documentAlias.addEventListener(events[index], setDidScroll); + } else { + windowAlias.attachEvent('on' + events[index], setDidScroll); + } + } + + checkContentIfDidScroll(100); + } + + if (timeIntervalInMs && timeIntervalInMs > 0) { + timeIntervalInMs = parseInt(timeIntervalInMs, 10); + checkContent(timeIntervalInMs); + } + + }); + } + + /** + * Note: While we check whether the user is on a configHostAlias path we do not check whether the user is + * actually on the configHostAlias domain. This is already done where this method is called and for + * simplicity we do not check this again. + * + * Also we currently assume that all configHostAlias domains start with the same wild card of '*.', '.' or + * none. Eg either all like '*.piwik.org' or '.piwik.org' or 'piwik.org'. Piwik always adds '*.' so it + * should be fine. + */ + function findConfigCookiePathToUse(configHostAlias, currentUrl) + { + var aliasPath = getPathName(configHostAlias); + var currentPath = getPathName(currentUrl); + + if (!aliasPath || aliasPath === '/' || !currentPath || currentPath === '/') { + // no path set that would be useful for cookiePath + return; + } + + var aliasDomain = domainFixup(configHostAlias); + + if (isSiteHostPath(aliasDomain, '/')) { + // there is another configHostsAlias having same domain that allows all paths + // eg this alias is for piwik.org/support but there is another alias allowing + // piwik.org + return; + } + + if (stringEndsWith(aliasPath, '/')) { + aliasPath = removeCharactersFromEndOfString(aliasPath, 1); + } + + // eg if we're in the case of "apache.piwik/foo/bar" we check whether there is maybe + // also a config alias allowing "apache.piwik/foo". In this case we're not allowed to set + // the cookie for "/foo/bar" but "/foo" + var pathAliasParts = aliasPath.split('/'); + var i; + for (i = 2; i < pathAliasParts.length; i++) { + var lessRestrctivePath = pathAliasParts.slice(0, i).join('/'); + if (isSiteHostPath(aliasDomain, lessRestrctivePath)) { + aliasPath = lessRestrctivePath; + break; + } + } + + if (!isSitePath(currentPath, aliasPath)) { + // current path of current URL does not match the alias + // eg user is on piwik.org/demo but configHostAlias is for piwik.org/support + return; + } + + return aliasPath; + } + + /* + * Browser features (plugins, resolution, cookies) + */ + function detectBrowserFeatures() { + var i, + mimeType, + pluginMap = { + // document types + pdf: 'application/pdf', + + // media players + qt: 'video/quicktime', + realp: 'audio/x-pn-realaudio-plugin', + wma: 'application/x-mplayer2', + + // interactive multimedia + dir: 'application/x-director', + fla: 'application/x-shockwave-flash', + + // RIA + java: 'application/x-java-vm', + gears: 'application/x-googlegears', + ag: 'application/x-silverlight' + }, + devicePixelRatio = windowAlias.devicePixelRatio || 1; + + // detect browser features except IE < 11 (IE 11 user agent is no longer MSIE) + if (!((new RegExp('MSIE')).test(navigatorAlias.userAgent))) { + // general plugin detection + if (navigatorAlias.mimeTypes && navigatorAlias.mimeTypes.length) { + for (i in pluginMap) { + if (Object.prototype.hasOwnProperty.call(pluginMap, i)) { + mimeType = navigatorAlias.mimeTypes[pluginMap[i]]; + browserFeatures[i] = (mimeType && mimeType.enabledPlugin) ? '1' : '0'; + } + } + } + + // Safari and Opera + // IE6/IE7 navigator.javaEnabled can't be aliased, so test directly + if (typeof navigator.javaEnabled !== 'unknown' && + isDefined(navigatorAlias.javaEnabled) && + navigatorAlias.javaEnabled()) { + browserFeatures.java = '1'; + } + + // Firefox + if (isFunction(windowAlias.GearsFactory)) { + browserFeatures.gears = '1'; + } + + // other browser features + browserFeatures.cookie = hasCookies(); + } + + var width = parseInt(screenAlias.width, 10) * devicePixelRatio; + var height = parseInt(screenAlias.height, 10) * devicePixelRatio; + browserFeatures.res = parseInt(width, 10) + 'x' + parseInt(height, 10); + } + +/*<DEBUG>*/ + /* + * Register a test hook. Using eval() permits access to otherwise + * privileged members. + */ + function registerHook(hookName, userHook) { + var hookObj = null; + + if (isString(hookName) && !isDefined(registeredHooks[hookName]) && userHook) { + if (isObject(userHook)) { + hookObj = userHook; + } else if (isString(userHook)) { + try { + eval('hookObj =' + userHook); + } catch (ignore) { } + } + + registeredHooks[hookName] = hookObj; + } + + return hookObj; + } +/*</DEBUG>*/ + + /************************************************************ + * Constructor + ************************************************************/ + + /* + * initialize tracker + */ + detectBrowserFeatures(); + updateDomainHash(); + setVisitorIdCookie(); + +/*<DEBUG>*/ + /* + * initialize test plugin + */ + executePluginMethod('run', registerHook); +/*</DEBUG>*/ + + /************************************************************ + * Public data and methods + ************************************************************/ + + return { +/*<DEBUG>*/ + /* + * Test hook accessors + */ + hook: registeredHooks, + getHook: function (hookName) { + return registeredHooks[hookName]; + }, + getQuery: function () { + return query; + }, + getContent: function () { + return content; + }, + + buildContentImpressionRequest: buildContentImpressionRequest, + buildContentInteractionRequest: buildContentInteractionRequest, + buildContentInteractionRequestNode: buildContentInteractionRequestNode, + buildContentInteractionTrackingRedirectUrl: buildContentInteractionTrackingRedirectUrl, + getContentImpressionsRequestsFromNodes: getContentImpressionsRequestsFromNodes, + getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet: getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet, + trackCallbackOnLoad: trackCallbackOnLoad, + trackCallbackOnReady: trackCallbackOnReady, + buildContentImpressionsRequests: buildContentImpressionsRequests, + wasContentImpressionAlreadyTracked: wasContentImpressionAlreadyTracked, + appendContentInteractionToRequestIfPossible: getContentInteractionToRequestIfPossible, + setupInteractionsTracking: setupInteractionsTracking, + trackContentImpressionClickInteraction: trackContentImpressionClickInteraction, + internalIsNodeVisible: isVisible, + isNodeAuthorizedToTriggerInteraction: isNodeAuthorizedToTriggerInteraction, + replaceHrefIfInternalLink: replaceHrefIfInternalLink, + getDomains: function () { + return configHostsAlias; + }, + getConfigCookiePath: function () { + return configCookiePath; + }, + getConfigDownloadExtensions: function () { + return configDownloadExtensions; + }, + enableTrackOnlyVisibleContent: function (checkOnScroll, timeIntervalInMs) { + return enableTrackOnlyVisibleContent(checkOnScroll, timeIntervalInMs, this); + }, + clearTrackedContentImpressions: function () { + trackedContentImpressions = []; + }, + getTrackedContentImpressions: function () { + return trackedContentImpressions; + }, + clearEnableTrackOnlyVisibleContent: function () { + isTrackOnlyVisibleContentEnabled = false; + }, + disableLinkTracking: function () { + linkTrackingInstalled = false; + linkTrackingEnabled = false; + }, + getConfigVisitorCookieTimeout: function () { + return configVisitorCookieTimeout; + }, + getRemainingVisitorCookieTimeout: getRemainingVisitorCookieTimeout, +/*</DEBUG>*/ + + /** + * Get visitor ID (from first party cookie) + * + * @return string Visitor ID in hexits (or empty string, if not yet known) + */ + getVisitorId: function () { + return getValuesFromVisitorIdCookie().uuid; + }, + + /** + * Get the visitor information (from first party cookie) + * + * @return array + */ + getVisitorInfo: function () { + // Note: in a new method, we could return also return getValuesFromVisitorIdCookie() + // which returns named parameters rather than returning integer indexed array + return loadVisitorIdCookie(); + }, + + /** + * Get the Attribution information, which is an array that contains + * the Referrer used to reach the site as well as the campaign name and keyword + * It is useful only when used in conjunction with Tracker API function setAttributionInfo() + * To access specific data point, you should use the other functions getAttributionReferrer* and getAttributionCampaign* + * + * @return array Attribution array, Example use: + * 1) Call JSON2.stringify(piwikTracker.getAttributionInfo()) + * 2) Pass this json encoded string to the Tracking API (php or java client): setAttributionInfo() + */ + getAttributionInfo: function () { + return loadReferrerAttributionCookie(); + }, + + /** + * Get the Campaign name that was parsed from the landing page URL when the visitor + * landed on the site originally + * + * @return string + */ + getAttributionCampaignName: function () { + return loadReferrerAttributionCookie()[0]; + }, + + /** + * Get the Campaign keyword that was parsed from the landing page URL when the visitor + * landed on the site originally + * + * @return string + */ + getAttributionCampaignKeyword: function () { + return loadReferrerAttributionCookie()[1]; + }, + + /** + * Get the time at which the referrer (used for Goal Attribution) was detected + * + * @return int Timestamp or 0 if no referrer currently set + */ + getAttributionReferrerTimestamp: function () { + return loadReferrerAttributionCookie()[2]; + }, + + /** + * Get the full referrer URL that will be used for Goal Attribution + * + * @return string Raw URL, or empty string '' if no referrer currently set + */ + getAttributionReferrerUrl: function () { + return loadReferrerAttributionCookie()[3]; + }, + + /** + * Specify the Piwik server URL + * + * @param string trackerUrl + */ + setTrackerUrl: function (trackerUrl) { + configTrackerUrl = trackerUrl; + }, + + + /** + * Returns the Piwik server URL + * @returns string + */ + getTrackerUrl: function () { + return configTrackerUrl; + }, + + + /** + * Returns the site ID + * + * @returns int + */ + getSiteId: function() { + return configTrackerSiteId; + }, + + /** + * Specify the site ID + * + * @param int|string siteId + */ + setSiteId: function (siteId) { + setSiteId(siteId); + }, + + /** + * Sets a User ID to this user (such as an email address or a username) + * + * @param string User ID + */ + setUserId: function (userId) { + if(!isDefined(userId) || !userId.length) { + return; + } + configUserId = userId; + visitorUUID = hash(configUserId).substr(0, 16); + }, + + /** + * Gets the User ID if set. + * + * @returns string User ID + */ + getUserId: function() { + return configUserId; + }, + + /** + * Pass custom data to the server + * + * Examples: + * tracker.setCustomData(object); + * tracker.setCustomData(key, value); + * + * @param mixed key_or_obj + * @param mixed opt_value + */ + setCustomData: function (key_or_obj, opt_value) { + if (isObject(key_or_obj)) { + configCustomData = key_or_obj; + } else { + if (!configCustomData) { + configCustomData = {}; + } + configCustomData[key_or_obj] = opt_value; + } + }, + + /** + * Get custom data + * + * @return mixed + */ + getCustomData: function () { + return configCustomData; + }, + + /** + * Configure function with custom request content processing logic. + * It gets called after request content in form of query parameters string has been prepared and before request content gets sent. + * + * Examples: + * tracker.setCustomRequestProcessing(function(request){ + * var pairs = request.split('&'); + * var result = {}; + * pairs.forEach(function(pair) { + * pair = pair.split('='); + * result[pair[0]] = decodeURIComponent(pair[1] || ''); + * }); + * return JSON.stringify(result); + * }); + * + * @param function customRequestContentProcessingLogic + */ + setCustomRequestProcessing: function (customRequestContentProcessingLogic) { + configCustomRequestContentProcessing = customRequestContentProcessingLogic; + }, + + /** + * Appends the specified query string to the piwik.php?... Tracking API URL + * + * @param string queryString eg. 'lat=140&long=100' + */ + appendToTrackingUrl: function (queryString) { + configAppendToTrackingUrl = queryString; + }, + + /** + * Returns the query string for the current HTTP Tracking API request. + * Piwik would prepend the hostname and path to Piwik: http://example.org/piwik/piwik.php? + * prior to sending the request. + * + * @param request eg. "param=value¶m2=value2" + */ + getRequest: function (request) { + return getRequest(request); + }, + + /** + * Add plugin defined by a name and a callback function. + * The callback function will be called whenever a tracking request is sent. + * This can be used to append data to the tracking request, or execute other custom logic. + * + * @param string pluginName + * @param Object pluginObj + */ + addPlugin: function (pluginName, pluginObj) { + plugins[pluginName] = pluginObj; + }, + + /** + * Set Custom Dimensions. Any set Custom Dimension will be cleared after a tracked pageview. Make + * sure to set them again if needed. + * + * @param int index A Custom Dimension index + * @param string value + */ + setCustomDimension: function (customDimensionId, value) { + customDimensionId = parseInt(customDimensionId, 10); + if (customDimensionId > 0) { + if (!isDefined(value)) { + value = ''; + } + if (!isString(value)) { + value = String(value); + } + customDimensions[customDimensionId] = value; + } + }, + + /** + * Get a stored value for a specific Custom Dimension index. + * + * @param int index A Custom Dimension index + */ + getCustomDimension: function (customDimensionId) { + customDimensionId = parseInt(customDimensionId, 10); + if (customDimensionId > 0 && Object.prototype.hasOwnProperty.call(customDimensions, customDimensionId)) { + return customDimensions[customDimensionId]; + } + }, + + /** + * Delete a custom dimension. + * + * @param int index Custom dimension Id + */ + deleteCustomDimension: function (customDimensionId) { + customDimensionId = parseInt(customDimensionId, 10); + if (customDimensionId > 0) { + delete customDimensions[customDimensionId]; + } + }, + + /** + * Set custom variable within this visit + * + * @param int index Custom variable slot ID from 1-5 + * @param string name + * @param string value + * @param string scope Scope of Custom Variable: + * - "visit" will store the name/value in the visit and will persist it in the cookie for the duration of the visit, + * - "page" will store the name/value in the next page view tracked. + * - "event" will store the name/value in the next event tracked. + */ + setCustomVariable: function (index, name, value, scope) { + var toRecord; + + if (!isDefined(scope)) { + scope = 'visit'; + } + if (!isDefined(name)) { + return; + } + if (!isDefined(value)) { + value = ""; + } + if (index > 0) { + name = !isString(name) ? String(name) : name; + value = !isString(value) ? String(value) : value; + toRecord = [name.slice(0, customVariableMaximumLength), value.slice(0, customVariableMaximumLength)]; + // numeric scope is there for GA compatibility + if (scope === 'visit' || scope === 2) { + loadCustomVariables(); + customVariables[index] = toRecord; + } else if (scope === 'page' || scope === 3) { + customVariablesPage[index] = toRecord; + } else if (scope === 'event') { /* GA does not have 'event' scope but we do */ + customVariablesEvent[index] = toRecord; + } + } + }, + + /** + * Get custom variable + * + * @param int index Custom variable slot ID from 1-5 + * @param string scope Scope of Custom Variable: "visit" or "page" or "event" + */ + getCustomVariable: function (index, scope) { + var cvar; + + if (!isDefined(scope)) { + scope = "visit"; + } + + if (scope === "page" || scope === 3) { + cvar = customVariablesPage[index]; + } else if (scope === "event") { + cvar = customVariablesEvent[index]; + } else if (scope === "visit" || scope === 2) { + loadCustomVariables(); + cvar = customVariables[index]; + } + + if (!isDefined(cvar) + || (cvar && cvar[0] === '')) { + return false; + } + + return cvar; + }, + + /** + * Delete custom variable + * + * @param int index Custom variable slot ID from 1-5 + * @param string scope + */ + deleteCustomVariable: function (index, scope) { + // Only delete if it was there already + if (this.getCustomVariable(index, scope)) { + this.setCustomVariable(index, '', '', scope); + } + }, + + /** + * When called then the Custom Variables of scope "visit" will be stored (persisted) in a first party cookie + * for the duration of the visit. This is useful if you want to call getCustomVariable later in the visit. + * + * By default, Custom Variables of scope "visit" are not stored on the visitor's computer. + */ + storeCustomVariablesInCookie: function () { + configStoreCustomVariablesInCookie = true; + }, + + /** + * Set delay for link tracking (in milliseconds) + * + * @param int delay + */ + setLinkTrackingTimer: function (delay) { + configTrackerPause = delay; + }, + + /** + * Set list of file extensions to be recognized as downloads + * + * @param string|array extensions + */ + setDownloadExtensions: function (extensions) { + if(isString(extensions)) { + extensions = extensions.split('|'); + } + configDownloadExtensions = extensions; + }, + + /** + * Specify additional file extensions to be recognized as downloads + * + * @param string|array extensions for example 'custom' or ['custom1','custom2','custom3'] + */ + addDownloadExtensions: function (extensions) { + var i; + if(isString(extensions)) { + extensions = extensions.split('|'); + } + for (i=0; i < extensions.length; i++) { + configDownloadExtensions.push(extensions[i]); + } + }, + + /** + * Removes specified file extensions from the list of recognized downloads + * + * @param string|array extensions for example 'custom' or ['custom1','custom2','custom3'] + */ + removeDownloadExtensions: function (extensions) { + var i, newExtensions = []; + if(isString(extensions)) { + extensions = extensions.split('|'); + } + for (i=0; i < configDownloadExtensions.length; i++) { + if (indexOfArray(extensions, configDownloadExtensions[i]) === -1) { + newExtensions.push(configDownloadExtensions[i]); + } + } + configDownloadExtensions = newExtensions; + }, + + /** + * Set array of domains to be treated as local. Also supports path, eg '.piwik.org/subsite1'. In this + * case all links that don't go to '*.piwik.org/subsite1/ *' would be treated as outlinks. + * For example a link to 'piwik.org/' or 'piwik.org/subsite2' both would be treated as outlinks. + * + * We might automatically set a cookieConfigPath to avoid creating several cookies under one domain + * if there is a hostAlias defined with a path. Say a user is visiting 'http://piwik.org/subsite1' + * and '.piwik.org/subsite1' is set as a hostsAlias. Piwik will automatically use '/subsite1' as + * cookieConfigPath. + * + * @param string|array hostsAlias + */ + setDomains: function (hostsAlias) { + configHostsAlias = isString(hostsAlias) ? [hostsAlias] : hostsAlias; + + var hasDomainAliasAlready = false, i; + for (i in configHostsAlias) { + if (Object.prototype.hasOwnProperty.call(configHostsAlias, i) + && isSameHost(domainAlias, domainFixup(String(configHostsAlias[i])))) { + hasDomainAliasAlready = true; + + if (!configCookiePath) { + var path = findConfigCookiePathToUse(configHostsAlias[i], locationHrefAlias); + if (path) { + this.setCookiePath(path); + } + + break; + } + } + } + + if (!hasDomainAliasAlready) { + /** + * eg if domainAlias = 'piwik.org' and someone set hostsAlias = ['piwik.org/foo'] then we should + * not add piwik.org as it would increase the allowed scope. + */ + configHostsAlias.push(domainAlias); + } + }, + + /** + * Set array of classes to be ignored if present in link + * + * @param string|array ignoreClasses + */ + setIgnoreClasses: function (ignoreClasses) { + configIgnoreClasses = isString(ignoreClasses) ? [ignoreClasses] : ignoreClasses; + }, + + /** + * Set request method + * + * @param string method GET or POST; default is GET + */ + setRequestMethod: function (method) { + configRequestMethod = method || defaultRequestMethod; + }, + + /** + * Set request Content-Type header value, applicable when POST request method is used for submitting tracking events. + * See XMLHttpRequest Level 2 spec, section 4.7.2 for invalid headers + * @link http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html + * + * @param string requestContentType; default is 'application/x-www-form-urlencoded; charset=UTF-8' + */ + setRequestContentType: function (requestContentType) { + configRequestContentType = requestContentType || defaultRequestContentType; + }, + + /** + * Override referrer + * + * @param string url + */ + setReferrerUrl: function (url) { + configReferrerUrl = url; + }, + + /** + * Override url + * + * @param string url + */ + setCustomUrl: function (url) { + configCustomUrl = resolveRelativeReference(locationHrefAlias, url); + }, + + /** + * Override document.title + * + * @param string title + */ + setDocumentTitle: function (title) { + configTitle = title; + }, + + /** + * Set the URL of the Piwik API. It is used for Page Overlay. + * This method should only be called when the API URL differs from the tracker URL. + * + * @param string apiUrl + */ + setAPIUrl: function (apiUrl) { + configApiUrl = apiUrl; + }, + + /** + * Set array of classes to be treated as downloads + * + * @param string|array downloadClasses + */ + setDownloadClasses: function (downloadClasses) { + configDownloadClasses = isString(downloadClasses) ? [downloadClasses] : downloadClasses; + }, + + /** + * Set array of classes to be treated as outlinks + * + * @param string|array linkClasses + */ + setLinkClasses: function (linkClasses) { + configLinkClasses = isString(linkClasses) ? [linkClasses] : linkClasses; + }, + + /** + * Set array of campaign name parameters + * + * @see http://piwik.org/faq/how-to/#faq_120 + * @param string|array campaignNames + */ + setCampaignNameKey: function (campaignNames) { + configCampaignNameParameters = isString(campaignNames) ? [campaignNames] : campaignNames; + }, + + /** + * Set array of campaign keyword parameters + * + * @see http://piwik.org/faq/how-to/#faq_120 + * @param string|array campaignKeywords + */ + setCampaignKeywordKey: function (campaignKeywords) { + configCampaignKeywordParameters = isString(campaignKeywords) ? [campaignKeywords] : campaignKeywords; + }, + + /** + * Strip hash tag (or anchor) from URL + * Note: this can be done in the Piwik>Settings>Spiderwebsites on a per-spiderwebsite basis + * + * @deprecated + * @param bool enableFilter + */ + discardHashTag: function (enableFilter) { + configDiscardHashTag = enableFilter; + }, + + /** + * Set first-party cookie name prefix + * + * @param string cookieNamePrefix + */ + setCookieNamePrefix: function (cookieNamePrefix) { + configCookieNamePrefix = cookieNamePrefix; + // Re-init the Custom Variables cookie + customVariables = getCustomVariablesFromCookie(); + }, + + /** + * Set first-party cookie domain + * + * @param string domain + */ + setCookieDomain: function (domain) { + var domainFixed = domainFixup(domain); + + if (isPossibleToSetCookieOnDomain(domainFixed)) { + configCookieDomain = domainFixed; + updateDomainHash(); + } + }, + + /** + * Set first-party cookie path + * + * @param string domain + */ + setCookiePath: function (path) { + configCookiePath = path; + updateDomainHash(); + }, + + /** + * Set visitor cookie timeout (in seconds) + * Defaults to 13 months (timeout=33955200) + * + * @param int timeout + */ + setVisitorCookieTimeout: function (timeout) { + configVisitorCookieTimeout = timeout * 1000; + }, + + /** + * Set session cookie timeout (in seconds). + * Defaults to 30 minutes (timeout=1800000) + * + * @param int timeout + */ + setSessionCookieTimeout: function (timeout) { + configSessionCookieTimeout = timeout * 1000; + }, + + /** + * Set referral cookie timeout (in seconds). + * Defaults to 6 months (15768000000) + * + * @param int timeout + */ + setReferralCookieTimeout: function (timeout) { + configReferralCookieTimeout = timeout * 1000; + }, + + /** + * Set conversion attribution to first referrer and campaign + * + * @param bool if true, use first referrer (and first campaign) + * if false, use the last referrer (or campaign) + */ + setConversionAttributionFirstReferrer: function (enable) { + configConversionAttributionFirstReferrer = enable; + }, + + /** + * Disables all cookies from being set + * + * Existing cookies will be deleted on the next call to track + */ + disableCookies: function () { + configCookiesDisabled = true; + browserFeatures.cookie = '0'; + + if (configTrackerSiteId) { + deleteCookies(); + } + }, + + /** + * One off cookies clearing. Useful to call this when you know for sure a new visitor is using the same browser, + * it maybe helps to "reset" tracking cookies to prevent data reuse for different users. + */ + deleteCookies: function () { + deleteCookies(); + }, + + /** + * Handle do-not-track requests + * + * @param bool enable If true, don't track if user agent sends 'do-not-track' header + */ + setDoNotTrack: function (enable) { + var dnt = navigatorAlias.doNotTrack || navigatorAlias.msDoNotTrack; + configDoNotTrack = enable && (dnt === 'yes' || dnt === '1'); + + // do not track also disables cookies and deletes existing cookies + if (configDoNotTrack) { + this.disableCookies(); + } + }, + + /** + * Add click listener to a specific link element. + * When clicked, Piwik will log the click automatically. + * + * @param DOMElement element + * @param bool enable If true, use pseudo click-handler (middle click + context menu) + */ + addListener: function (element, enable) { + addClickListener(element, enable); + }, + + /** + * Install link tracker + * + * The default behaviour is to use actual click events. However, some browsers + * (e.g., Firefox, Opera, and Konqueror) don't generate click events for the middle mouse button. + * + * To capture more "clicks", the pseudo click-handler uses mousedown + mouseup events. + * This is not industry standard and is vulnerable to false positives (e.g., drag events). + * + * There is a Safari/Chrome/Spiderwebkit bug that prevents tracking requests from being sent + * by either click handler. The workaround is to set a target attribute (which can't + * be "_self", "_top", or "_parent"). + * + * @see https://bugs.spiderwebkit.org/show_bug.cgi?id=54783 + * + * @param bool enable If "true", use pseudo click-handler (treat middle click and open contextmenu as + * left click). A right click (or any click that opens the context menu) on a link + * will be tracked as clicked even if "Open in new tab" is not selected. If + * "false" (default), nothing will be tracked on open context menu or middle click. + * The context menu is usually opened to open a link / download in a new tab + * therefore you can get more accurate results by treat it as a click but it can lead + * to wrong click numbers. + */ + enableLinkTracking: function (enable) { + linkTrackingEnabled = true; + + if (hasLoaded) { + // the load event has already fired, add the click listeners now + addClickListeners(enable); + } else { + // defer until page has loaded + registeredOnLoadHandlers.push(function () { + addClickListeners(enable); + }); + } + }, + + /** + * Enable tracking of uncatched JavaScript errors + * + * If enabled, uncaught JavaScript Errors will be tracked as an event by defining a + * window.onerror handler. If a window.onerror handler is already defined we will make + * sure to call this previously registered error handler after tracking the error. + * + * By default we return false in the window.onerror handler to make sure the error still + * appears in the browser's console etc. Note: Some older browsers might behave differently + * so it could happen that an actual JavaScript error will be suppressed. + * If a window.onerror handler was registered we will return the result of this handler. + * + * Make sure not to overwrite the window.onerror handler after enabling the JS error + * tracking as the error tracking won't work otherwise. To capture all JS errors we + * recommend to include the Piwik JavaScript tracker in the HTML as early as possible. + * If possible directly in <head></head> before loading any other JavaScript. + */ + enableJSErrorTracking: function () { + if (enableJSErrorTracking) { + return; + } + + enableJSErrorTracking = true; + var onError = windowAlias.onerror; + + windowAlias.onerror = function (message, url, linenumber, column, error) { + trackCallback(function () { + var category = 'JavaScript Errors'; + + var action = url + ':' + linenumber; + if (column) { + action += ':' + column; + } + + logEvent(category, action, message); + }); + + if (onError) { + return onError(message, url, linenumber, column, error); + } + + return false; + }; + }, + + /** + * Disable automatic performance tracking + */ + disablePerformanceTracking: function () { + configPerformanceTrackingEnabled = false; + }, + + /** + * Set the server generation time. + * If set, the browser's performance.timing API in not used anymore to determine the time. + * + * @param int generationTime + */ + setGenerationTimeMs: function (generationTime) { + configPerformanceGenerationTime = parseInt(generationTime, 10); + }, + + /** + * Set heartbeat (in seconds) + * + * @param int heartBeatDelayInSeconds Defaults to 15. Cannot be lower than 1. + */ + enableHeartBeatTimer: function (heartBeatDelayInSeconds) { + heartBeatDelayInSeconds = Math.max(heartBeatDelayInSeconds, 1); + configHeartBeatDelay = (heartBeatDelayInSeconds || 15) * 1000; + + // if a tracking request has already been sent, start the heart beat timeout + if (lastTrackerRequestTime !== null) { + setUpHeartBeat(); + } + }, + +/*<DEBUG>*/ + /** + * Clear heartbeat. + */ + disableHeartBeatTimer: function () { + heartBeatDown(); + configHeartBeatDelay = null; + + window.removeEventListener('focus', heartBeatOnFocus); + window.removeEventListener('blur', heartBeatOnBlur); + }, +/*</DEBUG>*/ + + /** + * Frame buster + */ + killFrame: function () { + if (windowAlias.location !== windowAlias.top.location) { + windowAlias.top.location = windowAlias.location; + } + }, + + /** + * Redirect if browsing offline (aka file: buster) + * + * @param string url Redirect to this URL + */ + redirectFile: function (url) { + if (windowAlias.location.protocol === 'file:') { + windowAlias.location = url; + } + }, + + /** + * Count sites in pre-rendered state + * + * @param bool enable If true, track when in pre-rendered state + */ + setCountPreRendered: function (enable) { + configCountPreRendered = enable; + }, + + /** + * Trigger a goal + * + * @param int|string idGoal + * @param int|float customRevenue + * @param mixed customData + */ + trackGoal: function (idGoal, customRevenue, customData) { + trackCallback(function () { + logGoal(idGoal, customRevenue, customData); + }); + }, + + /** + * Manually log a click from your own code + * + * @param string sourceUrl + * @param string linkType + * @param mixed customData + * @param function callback + */ + trackLink: function (sourceUrl, linkType, customData, callback) { + trackCallback(function () { + logLink(sourceUrl, linkType, customData, callback); + }); + }, + + /** + * Log visit to this page + * + * @param string customTitle + * @param mixed customData + */ + trackPageView: function (customTitle, customData) { + trackedContentImpressions = []; + + if (isOverlaySession(configTrackerSiteId)) { + trackCallback(function () { + injectOverlayScripts(configTrackerUrl, configApiUrl, configTrackerSiteId); + }); + } else { + trackCallback(function () { + logPageView(customTitle, customData); + }); + } + }, + + /** + * Scans the entire DOM for all content blocks and tracks all impressions once the DOM ready event has + * been triggered. + * + * If you only want to track visible content impressions have a look at `trackVisibleContentImpressions()`. + * We do not track an impression of the same content block twice if you call this method multiple times + * unless `trackPageView()` is called meanwhile. This is useful for single page applications. + */ + trackAllContentImpressions: function () { + if (isOverlaySession(configTrackerSiteId)) { + return; + } + + trackCallback(function () { + trackCallbackOnReady(function () { + // we have to wait till DOM ready + var contentNodes = content.findContentNodes(); + var requests = getContentImpressionsRequestsFromNodes(contentNodes); + + sendBulkRequest(requests, configTrackerPause); + }); + }); + }, + + /** + * Scans the entire DOM for all content blocks as soon as the page is loaded. It tracks an impression + * only if a content block is actually visible. Meaning it is not hidden and the content is or was at + * some point in the viewport. + * + * If you want to track all content blocks have a look at `trackAllContentImpressions()`. + * We do not track an impression of the same content block twice if you call this method multiple times + * unless `trackPageView()` is called meanwhile. This is useful for single page applications. + * + * Once you have called this method you can no longer change `checkOnScroll` or `timeIntervalInMs`. + * + * If you do want to only track visible content blocks but not want us to perform any automatic checks + * as they can slow down your frames per second you can call `trackVisibleContentImpressions()` or + * `trackContentImpressionsWithinNode()` manually at any time to rescan the entire DOM for newly + * visible content blocks. + * o Call `trackVisibleContentImpressions(false, 0)` to initially track only visible content impressions + * o Call `trackVisibleContentImpressions()` at any time again to rescan the entire DOM for newly visible content blocks or + * o Call `trackContentImpressionsWithinNode(node)` at any time to rescan only a part of the DOM for newly visible content blocks + * + * @param boolean [checkOnScroll=true] Optional, you can disable rescanning the entire DOM automatically + * after each scroll event by passing the value `false`. If enabled, + * we check whether a previously hidden content blocks became visible + * after a scroll and if so track the impression. + * Note: If a content block is placed within a scrollable element + * (`overflow: scroll`), we can currently not detect when this block + * becomes visible. + * @param integer [timeIntervalInMs=750] Optional, you can define an interval to rescan the entire DOM + * for new impressions every X milliseconds by passing + * for instance `timeIntervalInMs=500` (rescan DOM every 500ms). + * Rescanning the entire DOM and detecting the visible state of content + * blocks can take a while depending on the browser and amount of content. + * In case your frames per second goes down you might want to increase + * this value or disable it by passing the value `0`. + */ + trackVisibleContentImpressions: function (checkOnSroll, timeIntervalInMs) { + if (isOverlaySession(configTrackerSiteId)) { + return; + } + + if (!isDefined(checkOnSroll)) { + checkOnSroll = true; + } + + if (!isDefined(timeIntervalInMs)) { + timeIntervalInMs = 750; + } + + enableTrackOnlyVisibleContent(checkOnSroll, timeIntervalInMs, this); + + trackCallback(function () { + trackCallbackOnLoad(function () { + // we have to wait till CSS parsed and applied + var contentNodes = content.findContentNodes(); + var requests = getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet(contentNodes); + + sendBulkRequest(requests, configTrackerPause); + }); + }); + }, + + /** + * Tracks a content impression using the specified values. You should not call this method too often + * as each call causes an XHR tracking request and can slow down your site or your server. + * + * @param string contentName For instance "Ad Sale". + * @param string [contentPiece='Unknown'] For instance a path to an image or the text of a text ad. + * @param string [contentTarget] For instance the URL of a landing page. + */ + trackContentImpression: function (contentName, contentPiece, contentTarget) { + if (isOverlaySession(configTrackerSiteId)) { + return; + } + + if (!contentName) { + return; + } + + contentPiece = contentPiece || 'Unknown'; + + trackCallback(function () { + var request = buildContentImpressionRequest(contentName, contentPiece, contentTarget); + sendRequest(request, configTrackerPause); + }); + }, + + /** + * Scans the given DOM node and its children for content blocks and tracks an impression for them if + * no impression was already tracked for it. If you have called `trackVisibleContentImpressions()` + * upfront only visible content blocks will be tracked. You can use this method if you, for instance, + * dynamically add an element using JavaScript to your DOM after we have tracked the initial impressions. + * + * @param Element domNode + */ + trackContentImpressionsWithinNode: function (domNode) { + if (isOverlaySession(configTrackerSiteId) || !domNode) { + return; + } + + trackCallback(function () { + if (isTrackOnlyVisibleContentEnabled) { + trackCallbackOnLoad(function () { + // we have to wait till CSS parsed and applied + var contentNodes = content.findContentNodesWithinNode(domNode); + + var requests = getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet(contentNodes); + sendBulkRequest(requests, configTrackerPause); + }); + } else { + trackCallbackOnReady(function () { + // we have to wait till DOM ready + var contentNodes = content.findContentNodesWithinNode(domNode); + + var requests = getContentImpressionsRequestsFromNodes(contentNodes); + sendBulkRequest(requests, configTrackerPause); + }); + } + }); + }, + + /** + * Tracks a content interaction using the specified values. You should use this method only in conjunction + * with `trackContentImpression()`. The specified `contentName` and `contentPiece` has to be exactly the + * same as the ones that were used in `trackContentImpression()`. Otherwise the interaction will not count. + * + * @param string contentInteraction The type of interaction that happened. For instance 'click' or 'submit'. + * @param string contentName The name of the content. For instance "Ad Sale". + * @param string [contentPiece='Unknown'] The actual content. For instance a path to an image or the text of a text ad. + * @param string [contentTarget] For instance the URL of a landing page. + */ + trackContentInteraction: function (contentInteraction, contentName, contentPiece, contentTarget) { + if (isOverlaySession(configTrackerSiteId)) { + return; + } + + if (!contentInteraction || !contentName) { + return; + } + + contentPiece = contentPiece || 'Unknown'; + + trackCallback(function () { + var request = buildContentInteractionRequest(contentInteraction, contentName, contentPiece, contentTarget); + sendRequest(request, configTrackerPause); + }); + }, + + /** + * Tracks an interaction with the given DOM node / content block. + * + * By default we track interactions on click but sometimes you might want to track interactions yourself. + * For instance you might want to track an interaction manually on a double click or a form submit. + * Make sure to disable the automatic interaction tracking in this case by specifying either the CSS + * class `piwikContentIgnoreInteraction` or the attribute `data-content-ignoreinteraction`. + * + * @param Element domNode This element itself or any of its parent elements has to be a content block + * element. Meaning one of those has to have a `piwikTrackContent` CSS class or + * a `data-track-content` attribute. + * @param string [contentInteraction='Unknown] The name of the interaction that happened. For instance + * 'click', 'formSubmit', 'DblClick', ... + */ + trackContentInteractionNode: function (domNode, contentInteraction) { + if (isOverlaySession(configTrackerSiteId) || !domNode) { + return; + } + + trackCallback(function () { + var request = buildContentInteractionRequestNode(domNode, contentInteraction); + sendRequest(request, configTrackerPause); + }); + }, + + /** + * Useful to debug content tracking. This method will log all detected content blocks to console + * (if the browser supports the console). It will list the detected name, piece, and target of each + * content block. + */ + logAllContentBlocksOnPage: function () { + var contentNodes = content.findContentNodes(); + var contents = content.collectContent(contentNodes); + + if (console !== undefined && console && console.log) { + console.log(contents); + } + }, + + /** + * Records an event + * + * @param string category The Event Category (Videos, Music, Games...) + * @param string action The Event's Action (Play, Pause, Duration, Add Playlist, Downloaded, Clicked...) + * @param string name (optional) The Event's object Name (a particular Movie name, or Song name, or File name...) + * @param float value (optional) The Event's value + * @param mixed customData + */ + trackEvent: function (category, action, name, value, customData) { + trackCallback(function () { + logEvent(category, action, name, value, customData); + }); + }, + + /** + * Log special pageview: Internal search + * + * @param string keyword + * @param string category + * @param int resultsCount + * @param mixed customData + */ + trackSiteSearch: function (keyword, category, resultsCount, customData) { + trackCallback(function () { + logSiteSearch(keyword, category, resultsCount, customData); + }); + }, + + /** + * Used to record that the current page view is an item (product) page view, or a Ecommerce Category page view. + * This must be called before trackPageView() on the product/category page. + * It will set 3 custom variables of scope "page" with the SKU, Name and Category for this page view. + * Note: Custom Variables of scope "page" slots 3, 4 and 5 will be used. + * + * On a category page, you can set the parameter category, and set the other parameters to empty string or false + * + * Tracking Product/Category page views will allow Piwik to report on Product & Categories + * conversion rates (Conversion rate = Ecommerce orders containing this product or category / Visits to the product or category) + * + * @param string sku Item's SKU code being viewed + * @param string name Item's Name being viewed + * @param string category Category page being viewed. On an Item's page, this is the item's category + * @param float price Item's display price, not use in standard Piwik reports, but output in API product reports. + */ + setEcommerceView: function (sku, name, category, price) { + if (!isDefined(category) || !category.length) { + category = ""; + } else if (category instanceof Array) { + category = JSON2.stringify(category); + } + + customVariablesPage[5] = ['_pkc', category]; + + if (isDefined(price) && String(price).length) { + customVariablesPage[2] = ['_pkp', price]; + } + + // On a category page, do not track Product name not defined + if ((!isDefined(sku) || !sku.length) + && (!isDefined(name) || !name.length)) { + return; + } + + if (isDefined(sku) && sku.length) { + customVariablesPage[3] = ['_pks', sku]; + } + + if (!isDefined(name) || !name.length) { + name = ""; + } + + customVariablesPage[4] = ['_pkn', name]; + }, + + /** + * Adds an item (product) that is in the current Cart or in the Ecommerce order. + * This function is called for every item (product) in the Cart or the Order. + * The only required parameter is sku. + * + * @param string sku (required) Item's SKU Code. This is the unique identifier for the product. + * @param string name (optional) Item's name + * @param string name (optional) Item's category, or array of up to 5 categories + * @param float price (optional) Item's price. If not specified, will default to 0 + * @param float quantity (optional) Item's quantity. If not specified, will default to 1 + */ + addEcommerceItem: function (sku, name, category, price, quantity) { + if (sku.length) { + ecommerceItems[sku] = [ sku, name, category, price, quantity ]; + } + }, + + /** + * Tracks an Ecommerce order. + * If the Ecommerce order contains items (products), you must call first the addEcommerceItem() for each item in the order. + * All revenues (grandTotal, subTotal, tax, shipping, discount) will be individually summed and reported in Piwik reports. + * Parameters orderId and grandTotal are required. For others, you can set to false if you don't need to specify them. + * + * @param string|int orderId (required) Unique Order ID. + * This will be used to count this order only once in the event the order page is reloaded several times. + * orderId must be unique for each transaction, even on different days, or the transaction will not be recorded by Piwik. + * @param float grandTotal (required) Grand Total revenue of the transaction (including tax, shipping, etc.) + * @param float subTotal (optional) Sub total amount, typically the sum of items prices for all items in this order (before Tax and Shipping costs are applied) + * @param float tax (optional) Tax amount for this order + * @param float shipping (optional) Shipping amount for this order + * @param float discount (optional) Discounted amount in this order + */ + trackEcommerceOrder: function (orderId, grandTotal, subTotal, tax, shipping, discount) { + logEcommerceOrder(orderId, grandTotal, subTotal, tax, shipping, discount); + }, + + /** + * Tracks a Cart Update (add item, remove item, update item). + * On every Cart update, you must call addEcommerceItem() for each item (product) in the cart, including the items that haven't been updated since the last cart update. + * Then you can call this function with the Cart grandTotal (typically the sum of all items' prices) + * + * @param float grandTotal (required) Items (products) amount in the Cart + */ + trackEcommerceCartUpdate: function (grandTotal) { + logEcommerceCartUpdate(grandTotal); + } + + }; + } + + /************************************************************ + * Proxy object + * - this allows the caller to continue push()'ing to _paq + * after the Tracker has been initialized and loaded + ************************************************************/ + + function TrackerProxy() { + return { + push: apply + }; + } + + /** + * Applies the given methods in the given order if they are present in paq. + * + * @param {Array} paq + * @param {Array} methodsToApply an array containing method names in the order that they should be applied + * eg ['setSiteId', 'setTrackerUrl'] + * @returns {Array} the modified paq array with the methods that were already applied set to undefined + */ + function applyMethodsInOrder(paq, methodsToApply) + { + var appliedMethods = {}; + var index, iterator; + + for (index = 0; index < methodsToApply.length; index++) { + var methodNameToApply = methodsToApply[index]; + appliedMethods[methodNameToApply] = 1; + + for (iterator = 0; iterator < paq.length; iterator++) { + if (paq[iterator] && paq[iterator][0]) { + var methodName = paq[iterator][0]; + + if (methodNameToApply === methodName) { + apply(paq[iterator]); + delete paq[iterator]; + + if (appliedMethods[methodName] > 1) { + if (console !== undefined && console && console.error) { + console.error('The method ' + methodName + ' is registered more than once in "paq" variable. Only the last call has an effect. Please have a look at the multiple Piwik trackers documentation: http://developer.piwik.org/guides/tracking-javascript-guide#multiple-piwik-trackers'); + } + } + + appliedMethods[methodName]++; + } + } + } + } + + return paq; + } + + /************************************************************ + * Constructor + ************************************************************/ + + // initialize the Piwik singleton + addEventListener(windowAlias, 'beforeunload', beforeUnloadHandler, false); + addReadyListener(); + + Date.prototype.getTimeAlias = Date.prototype.getTime; + + asyncTracker = new Tracker(); + + var applyFirst = ['disableCookies', 'setTrackerUrl', 'setAPIUrl', 'setCookiePath', 'setCookieDomain', 'setDomains', 'setUserId', 'setSiteId', 'enableLinkTracking']; + _paq = applyMethodsInOrder(_paq, applyFirst); + + // apply the queue of actions + for (iterator = 0; iterator < _paq.length; iterator++) { + if (_paq[iterator]) { + apply(_paq[iterator]); + } + } + + // replace initialization array with proxy object + _paq = new TrackerProxy(); + + /************************************************************ + * Public data and methods + ************************************************************/ + + Piwik = { + /** + * Add plugin + * + * @param string pluginName + * @param Object pluginObj + */ + addPlugin: function (pluginName, pluginObj) { + plugins[pluginName] = pluginObj; + }, + + /** + * Get Tracker (factory method) + * + * @param string piwikUrl + * @param int|string siteId + * @return Tracker + */ + getTracker: function (piwikUrl, siteId) { + if(!isDefined(siteId)) { + siteId = this.getAsyncTracker().getSiteId(); + } + if(!isDefined(piwikUrl)) { + piwikUrl = this.getAsyncTracker().getTrackerUrl(); + } + return new Tracker(piwikUrl, siteId); + }, + + /** + * Get internal asynchronous tracker object + * + * @return Tracker + */ + getAsyncTracker: function () { + return asyncTracker; + } + }; + + // Expose Piwik as an AMD module + if (typeof define === 'function' && define.amd) { + define('piwik', [], function () { return Piwik; }); + } + + return Piwik; + }()); +} + +if (window && window.piwikAsyncInit) { + window.piwikAsyncInit(); +} + +/*jslint sloppy: true */ +(function () { + var jsTrackerType = (typeof AnalyticsTracker); + if (jsTrackerType === 'undefined') { + AnalyticsTracker = Piwik; + } +}()); +/*jslint sloppy: false */ + +/************************************************************ + * Deprecated functionality below + * Legacy piwik.js compatibility ftw + ************************************************************/ + +/* + * Piwik globals + * + * var piwik_install_tracker, piwik_tracker_pause, piwik_download_extensions, piwik_hosts_alias, piwik_ignore_classes; + */ +/*global piwik_log:true */ +/*global piwik_track:true */ + +/** + * Track page visit + * + * @param string documentTitle + * @param int|string siteId + * @param string piwikUrl + * @param mixed customData + */ +if (typeof piwik_log !== 'function') { + piwik_log = function (documentTitle, siteId, piwikUrl, customData) { + 'use strict'; + + function getOption(optionName) { + try { + if (window['piwik_' + optionName]) { + return window['piwik_' + optionName]; + } + } catch (ignore) { } + + return; // undefined + } + + // instantiate the tracker + var option, + piwikTracker = Piwik.getTracker(piwikUrl, siteId); + + // initialize tracker + piwikTracker.setDocumentTitle(documentTitle); + piwikTracker.setCustomData(customData); + + // handle Piwik globals + option = getOption('tracker_pause'); + + if (option) { + piwikTracker.setLinkTrackingTimer(option); + } + + option = getOption('download_extensions'); + + if (option) { + piwikTracker.setDownloadExtensions(option); + } + + option = getOption('hosts_alias'); + + if (option) { + piwikTracker.setDomains(option); + } + + option = getOption('ignore_classes'); + + if (option) { + piwikTracker.setIgnoreClasses(option); + } + + // track this page view + piwikTracker.trackPageView(); + + // default is to install the link tracker + if (getOption('install_tracker')) { + + /** + * Track click manually (function is defined below) + * + * @param string sourceUrl + * @param int|string siteId + * @param string piwikUrl + * @param string linkType + */ + piwik_track = function (sourceUrl, siteId, piwikUrl, linkType) { + piwikTracker.setSiteId(siteId); + piwikTracker.setTrackerUrl(piwikUrl); + piwikTracker.trackLink(sourceUrl, linkType); + }; + + // set-up link tracking + piwikTracker.enableLinkTracking(); + } + }; +} + +/*! @license-end */ diff --git a/Server/Plugins/ChatLog b/Server/Plugins/ChatLog -Subproject 983d23ca37baa89f7e4dc11d71502d9c059f637 +Subproject cc04da381b9aa683ee3bbd7013f9d3fd909db03 diff --git a/Server/Plugins/Core b/Server/Plugins/Core -Subproject 0838838a18f49251d62e9b0760215fda6ec319c +Subproject 5df413231a918070adc15dfe36630ffba06e15d diff --git a/Server/Plugins/Debuggers/Debuggers.lua b/Server/Plugins/Debuggers/Debuggers.lua index 0559a4ef8..5b7f26fe6 100644 --- a/Server/Plugins/Debuggers/Debuggers.lua +++ b/Server/Plugins/Debuggers/Debuggers.lua @@ -1459,7 +1459,7 @@ function HandleCompo(a_Split, a_Player) -- Send one composite message to self: local msg = cCompositeChat() msg:AddTextPart("Hello! ", "b@e") -- bold yellow - msg:AddUrlPart("MCServer", "http://mc-server.org") + msg:AddUrlPart("Cuberite", "http://cuberite.org") msg:AddTextPart(" rules! ") msg:AddRunCommandPart("Set morning", "/time set 0") a_Player:SendMessage(msg) @@ -2030,6 +2030,78 @@ end +function HandleConsoleTestUrlParser(a_Split, a_EntireCmd) + LOG("Testing cUrlParser...") + local UrlsToTest = + { + "invalid URL", + "https://github.com", + "ftp://anonymous:user@example.com@ftp.cuberite.org:9921/releases/2015/2015-12-25.zip", + "ftp://anonymous:user:name:with:colons@example.com@ftp.cuberite.org:9921", + "http://google.com/", + "http://google.com/?q=cuberite", + "http://google.com/search?q=cuberite", + "http://google.com/some/search?q=cuberite#results", + "http://google.com/?q=cuberite#results", + "http://google.com/#results", + "ftp://cuberite.org:9921/releases/2015/2015-12-25.zip", + "mailto:support@cuberite.org", + } + for _, u in ipairs(UrlsToTest) do + LOG("URL: " .. u) + local scheme, username, password, host, port, path, query, fragment = cUrlParser:Parse(u) + if not(scheme) then + LOG(" Error: " .. (username or "<nil>")) + else + LOG(" Scheme = " .. scheme) + LOG(" Username = " .. username) + LOG(" Password = " .. password) + LOG(" Host = " .. host) + LOG(" Port = " .. port) + LOG(" Path = " .. path) + LOG(" Query = " .. query) + LOG(" Fragment = " .. fragment) + end + end + LOG("cUrlParser test complete") + return true +end + + + + + +function HandleConsoleUuid(a_Split, a_EntireCmd) + -- Check params: + local playerName = a_Split[2] + if not(playerName) then + return true, "Usage: uuid <PlayerName>" + end + + -- Query with cache: + LOG("Player " .. playerName .. ":") + local cachedUuid = cMojangAPI:GetUUIDFromPlayerName(playerName, true) + if not(cachedUuid) then + LOG(" - not in the UUID cache") + else + LOG(" - in the cache: \"" .. cachedUuid .. "\"") + end + + -- Query online: + local onlineUuid = cMojangAPI:GetUUIDFromPlayerName(playerName, false) + if not(onlineUuid) then + LOG(" - UUID not available online") + else + LOG(" - online: \"" .. onlineUuid .. "\"") + end + + return true +end + + + + + function HandleConsoleBBox(a_Split) local bbox = cBoundingBox(0, 10, 0, 10, 0, 10) local v1 = Vector3d(1, 1, 1) diff --git a/Server/Plugins/Debuggers/Info.lua b/Server/Plugins/Debuggers/Info.lua index f71ee5509..99d3ebe74 100644 --- a/Server/Plugins/Debuggers/Info.lua +++ b/Server/Plugins/Debuggers/Info.lua @@ -253,6 +253,18 @@ g_PluginInfo = Handler = HandleConsoleTestTracer, HelpString = "Tests the cLineBlockTracer", }, + + ["testurlparser"] = + { + Handler = HandleConsoleTestUrlParser, + HelpString = "Tests the cUrlParser", + }, + + ["uuid"] = + { + Handler = HandleConsoleUuid, + HelpString = "Queries the cMojangAPI for a player's UUID", + } }, -- ConsoleCommands } -- g_PluginInfo diff --git a/Server/Plugins/HookNotify/HookNotify.lua b/Server/Plugins/HookNotify/HookNotify.lua index 411dbebbd..33b1a80a8 100644 --- a/Server/Plugins/HookNotify/HookNotify.lua +++ b/Server/Plugins/HookNotify/HookNotify.lua @@ -5,7 +5,7 @@ Implements the entire plugin NOTE: This plugin is not meant for production servers. It is used mainly by developers to verify that things -are working properly when implementing MCServer features. Do not enable this plugin on production servers! +are working properly when implementing Cuberite features. Do not enable this plugin on production servers! This plugin logs a notification for each hook that is being called by the server. The TICK and WORLD_TICK hooks are disabled because they produce too much output. diff --git a/Server/Plugins/NetworkTest/NetworkTest.lua b/Server/Plugins/NetworkTest/NetworkTest.lua index d6849ead6..1bb35d0c6 100644 --- a/Server/Plugins/NetworkTest/NetworkTest.lua +++ b/Server/Plugins/NetworkTest/NetworkTest.lua @@ -107,7 +107,7 @@ local g_Services = -- Send a welcome message to newly accepted connections: OnAccepted = function (a_Link) - a_Link:Send("Hello, " .. a_Link:GetRemoteIP() .. ", welcome to the echo server @ MCServer-Lua\r\n") + a_Link:Send("Hello, " .. a_Link:GetRemoteIP() .. ", welcome to the echo server @ Cuberite-Lua\r\n") end, -- OnAccepted() -- There was an error listening on the port: @@ -140,7 +140,7 @@ local g_Services = -- Send a welcome message and the fortune to newly accepted connections: OnAccepted = function (a_Link) - a_Link:Send("Hello, " .. a_Link:GetRemoteIP() .. ", welcome to the fortune server @ MCServer-Lua\r\n\r\nYour fortune:\r\n") + a_Link:Send("Hello, " .. a_Link:GetRemoteIP() .. ", welcome to the fortune server @ Cuberite-Lua\r\n\r\nYour fortune:\r\n") a_Link:Send(g_Fortunes[math.random(#g_Fortunes)] .. "\r\n") end, -- OnAccepted() diff --git a/Server/Plugins/ProtectionAreas b/Server/Plugins/ProtectionAreas -Subproject ac6ad215295257a9098869d6ec935cbbb900a04 +Subproject d73f95a5000f939a94c372173480282f0fe1e52 diff --git a/Server/Plugins/TestLuaRocks/TestLuaRocks.lua b/Server/Plugins/TestLuaRocks/TestLuaRocks.lua index 4a7cd4e1e..0e4ccb7d5 100644 --- a/Server/Plugins/TestLuaRocks/TestLuaRocks.lua +++ b/Server/Plugins/TestLuaRocks/TestLuaRocks.lua @@ -1,7 +1,7 @@ -- TestLuaRocks.lua --- This is a mockup plugin that does a quick test of LuaRocks capability in MCServer +-- This is a mockup plugin that does a quick test of LuaRocks capability in Cuberite -- "Success" is when the plugin loads, downloads the forum webpage and displays the headers and length and then displays both libs as loaded. -- "Failure" usually manifests as one of the "require" lines failing, although you have the luarock installed. diff --git a/Server/README.txt b/Server/README.txt index 3cddc37d2..f3972e90f 100644 --- a/Server/README.txt +++ b/Server/README.txt @@ -1,20 +1,17 @@ -/============================\ -| Custom Minecraft Server | -| (MCServer) | -| | -| Founder: Kevin Bansberg | -| A.K.A. FakeTruth | -| Lead dev: Mattes D | -| A.K.A. _Xoft(o) | -| A.K.A. xoft | -| Monsters by Alex Sonek | -| A.K.A. Duralex | -|============================| -| Info: www.mc-server.org | -| www.ae-c.net | -| www.rbthinktank.com | -| Mail: faketruth@gmail.com | -\============================/ +/=============================\ +| Custom Minecraft Server | +|(Cuberite, formerly MCServer)| +| | +| Founder: Kevin Bansberg | +| A.K.A. FakeTruth | +| Lead dev: Mattes D | +| A.K.A. _Xoft(o) | +| A.K.A. xoft | +| Monsters by Alex Sonek | +| A.K.A. Duralex | +|=============================| +| Info: www.cuberite.org | +\=============================/ Compatible clients: 1.7.x and 1.8.x Compatible protocol versions: 4, 5, 47 diff --git a/Server/crafting.txt b/Server/crafting.txt index efbb1016a..2a84c5a9f 100644 --- a/Server/crafting.txt +++ b/Server/crafting.txt @@ -123,7 +123,7 @@ BrickSlab, 6 = BrickBlock, 1:1, 2:1, 3:1 StonebrickSlab, 6 = StoneBrick, 1:1, 2:1, 3:1 NetherbrickSlab, 6 = NetherBrick, 1:1, 2:1, 3:1 Quartzslab, 6 = QuartzBlock, 1:1, 2:1, 3:1 -snow, 6 = SnowBlock, 1:1, 2:1, 3:1 +SnowLayer, 6 = SnowBlock, 1:1, 2:1, 3:1 RedSandstoneSlab, 6 = RedSandstone^-1, 1:1, 2:1, 3:1 # Stairs: @@ -1,6 +1,6 @@ #! /bin/bash -# This script runs MCServer under helgrind +# This script runs Cuberite under helgrind # It expects valgrind to be normally installed and available # Note that this is for Linux only and debug-only, since it slows down MCS way too much diff --git a/Server/hg.supp b/Server/hg.supp index bea6ecf3c..7acad9edc 100644 --- a/Server/hg.supp +++ b/Server/hg.supp @@ -1,4 +1,4 @@ -# This is a valgrind suppressions file for running helgrind on MCServer +# This is a valgrind suppressions file for running helgrind on Cuberite # Use by adding "--suppressions=hg.supp" to the helgrind commandline @@ -1,6 +1,6 @@ #! /bin/bash -# This script runs MCServer under valgrind +# This script runs Cuberite under valgrind # It expects valgrind to be normally installed and available # Note that this is for Linux only and debug-only, since it slows down MCS way too much diff --git a/Server/webadmin/files/guest.html b/Server/webadmin/files/guest.html index 4f965b75c..27af93142 100644 --- a/Server/webadmin/files/guest.html +++ b/Server/webadmin/files/guest.html @@ -8,7 +8,7 @@ <body> <p> - Hello! Welcome to the MCServer WebAdmin. + Hello! Welcome to the Cuberite WebAdmin. </p> <p> This is a default message, edit <b>files/guest.html</b> to add your own custom message. diff --git a/Server/webadmin/files/login.css b/Server/webadmin/files/login.css index 5d87da4c5..ad94e5810 100644 --- a/Server/webadmin/files/login.css +++ b/Server/webadmin/files/login.css @@ -1,4 +1,4 @@ -/* Copyright Justin S and MCServer Team, licensed under CC-BY-SA 3.0 */ +/* Copyright Justin S and Cuberite Team, licensed under CC-BY-SA 3.0 */ * { margin: 0; } diff --git a/Server/webadmin/files/style.css b/Server/webadmin/files/style.css index 7c0671970..8cb803a05 100644 --- a/Server/webadmin/files/style.css +++ b/Server/webadmin/files/style.css @@ -1,4 +1,4 @@ -/* Copyright Justin S and MCServer Team, licensed under CC-BY-SA 3.0 */ +/* Copyright Justin S and Cuberite Team, licensed under CC-BY-SA 3.0 */ * { margin: 0; } diff --git a/Server/webadmin/login_template.html b/Server/webadmin/login_template.html index d0ab9b566..30b7d4f82 100644 --- a/Server/webadmin/login_template.html +++ b/Server/webadmin/login_template.html @@ -1,4 +1,4 @@ -<!-- Copyright Justin S and MCServer Team, licensed under CC-BY-SA 3.0 */ --> +<!-- Copyright Justin S and Cuberite Team, licensed under CC-BY-SA 3.0 */ --> <html> <head> <title>Cuberite WebAdmin - Login</title> @@ -32,7 +32,7 @@ <tbody> <tr> <td class="thead rounded_top"> - <div style="float:left!important"><strong>MCServer WebAdmin</strong></div> + <div style="float:left!important"><strong>Cuberite WebAdmin</strong></div> </td> </tr> <tr> diff --git a/Server/webadmin/template.html b/Server/webadmin/template.html index b0864e35d..305c566cd 100644 --- a/Server/webadmin/template.html +++ b/Server/webadmin/template.html @@ -110,9 +110,9 @@ #cssmenu > ul > li > a:after { border-color:#707070; } #cssmenu > ul > li > a:hover { background:#B8B8B8; } </style> - <meta name="msapplication-tooltip" content="MCServer WebAdministrator"/> + <meta name="msapplication-tooltip" content="Cuberite WebAdmin"/> <meta name="msapplication-navbutton-color" content="#B8B8B8" /> - <link rel="shortcut icon" href="http://mc-server.org/favicon.ico" /> + <link rel="shortcut icon" href="http://cuberite.org/favicon.ico" /> </head> <body> <div id="wrapper"> @@ -132,7 +132,7 @@ {CONTENT} </div> <footer> - <p>MCServer is using {MEM}MB of memory, with {NUMCHUNKS} chunks loaded.</p> + <p>Cuberite is using {MEM}MB of memory, with {NUMCHUNKS} chunks loaded.</p> <p>Web Design by <a href="https://github.com/WebFreak001"@WebFreak001</a></p> </footer> </div> diff --git a/Server/webadmin/template.lua b/Server/webadmin/template.lua index 00b2523b7..03ef95088 100644 --- a/Server/webadmin/template.lua +++ b/Server/webadmin/template.lua @@ -81,7 +81,7 @@ function ShowPage(WebAdmin, TemplateRequest) end Output([[ -<!-- Copyright Justin S and MCServer Team, licensed under CC-BY-SA 3.0 --> +<!-- Copyright Justin S and Cuberite Team, licensed under CC-BY-SA 3.0 --> <html> <head> <title>]] .. Title .. [[</title> @@ -94,7 +94,7 @@ function ShowPage(WebAdmin, TemplateRequest) <div class="pagehead"> <div class="row1"> <div class="wrapper"> - <img src="/logo_login.png" alt="MCServer Logo" class="logo"> + <img src="/logo_login.png" alt="Cuberite Logo" class="logo"> </div> </div> <div id="panel"> diff --git a/SetFlags.cmake b/SetFlags.cmake index d3a6aba86..bde3be549 100644 --- a/SetFlags.cmake +++ b/SetFlags.cmake @@ -258,12 +258,13 @@ macro(set_exe_flags) if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") if ("${CLANG_VERSION}" VERSION_LESS 3.0) - message(FATAL_ERROR "MCServer requires clang version 3.0 or higher, version is ${CLANG_VERSION}") + message(FATAL_ERROR "Cuberite requires clang version 3.0 or higher, your version is ${CLANG_VERSION}") endif() # clang does not provide the __extern_always_inline macro and a part of libm depends on this when using fast-math add_flags_cxx("-D__extern_always_inline=inline") add_flags_cxx("-Weverything -Werror -Wno-c++98-compat-pedantic -Wno-string-conversion") add_flags_cxx("-Wno-exit-time-destructors -Wno-padded -Wno-weak-vtables") + add_flags_cxx("-Wno-switch-enum") # This is a pretty useless warning, we've already got -Wswitch which is what we need if ("${CLANG_VERSION}" VERSION_GREATER 3.0) # flags that are not present in 3.0 add_flags_cxx("-Wno-implicit-fallthrough") @@ -288,6 +289,12 @@ macro(set_exe_flags) if ("${CLANG_VERSION}" VERSION_GREATER 3.5) add_flags_cxx("-Wno-error=disabled-macro-expansion") endif() + if ("${CLANG_VERSION}" VERSION_GREATER 3.7) + check_cxx_compiler_flag(-Wno-double-promotion HAS_NO_DOUBLE_PROMOTION) + if (HAS_NO_DOUBLE_PROMOTION) + add_flags_cxx("-Wno-double-promotion") + endif() + endif() add_flags_cxx("-Wno-error=unused-command-line-argument") endif() endif() diff --git a/Tools/BlockZapper/BlockZapper.txt b/Tools/BlockZapper/BlockZapper.txt index 2b52c477e..06687abf6 100644 --- a/Tools/BlockZapper/BlockZapper.txt +++ b/Tools/BlockZapper/BlockZapper.txt @@ -11,7 +11,7 @@ If the specifier line ends with an additional " BE", both blocks and entities ar The tool is aware of extended blocktypes (256 .. 4096). -The source code for this tool is public domain, but note that it depends on a few shared sources in MCServer that may be under other licenses. +The source code for this tool is public domain, but note that it depends on a few shared sources in Cuberite that may be under other licenses. */ diff --git a/Tools/MemDumpAnalysis/MemDumpAnalysis.vcproj b/Tools/MemDumpAnalysis/MemDumpAnalysis.vcproj index 8283fd531..d237e2c36 100644 --- a/Tools/MemDumpAnalysis/MemDumpAnalysis.vcproj +++ b/Tools/MemDumpAnalysis/MemDumpAnalysis.vcproj @@ -62,7 +62,7 @@ /> <Tool Name="VCLinkerTool" - OutputFile="$(ProjectDir)\..\..\MCServer\$(ProjectName)_debug.exe" + OutputFile="$(ProjectDir)\..\..\Server\$(ProjectName)_debug.exe" LinkIncremental="2" GenerateDebugInformation="true" SubSystem="1" @@ -137,7 +137,7 @@ /> <Tool Name="VCLinkerTool" - OutputFile="$(ProjectDir)\..\..\MCServer\$(ProjectName).exe" + OutputFile="$(ProjectDir)\..\..\Server\$(ProjectName).exe" LinkIncremental="1" GenerateDebugInformation="true" SubSystem="1" diff --git a/docs/Generator.html b/docs/Generator.html index 85ebb91ca..3d4e09afe 100644 --- a/docs/Generator.html +++ b/docs/Generator.html @@ -1,12 +1,12 @@ <html> <head> -<title>Generating terrain in MCServer</title> +<title>Generating terrain in Cuberite</title> </head> <body> -<h1>Generating terrain in MCServer</h1> -<p>This article explains the principles behind the terrain generator in MCServer. It is not strictly -specific to MCServer, though, it can be viewed as a generic guide to various terrain-generating algorithms, -with specific implementation notes regarding MCServer.</p> +<h1>Generating terrain in Cuberite</h1> +<p>This article explains the principles behind the terrain generator in Cuberite. It is not strictly +specific to Cuberite, though, it can be viewed as a generic guide to various terrain-generating algorithms, +with specific implementation notes regarding Cuberite.</p> <p>Contents: <ul> @@ -80,7 +80,7 @@ neighboring chunks.</p> <hr /> <a name="composablegen"><h2>The ComposableGenerator pipeline</h2></a> -<p>This leads us directly to the main pipeline that is used for generating terrain in MCServer. For +<p>This leads us directly to the main pipeline that is used for generating terrain in Cuberite. For technical reasons, the terrain composition step is further subdivided into Height generation and Composition generation, and the structures are really called Finishers. For each chunk the generator generates, in this sequence: @@ -131,7 +131,7 @@ generated for any number of dimensions.</p> <a name="biomegen"><h2>Generating biomes</h2></a> <p>The easiest way to generate biomes is to not generate them at all - simply assign a single constant biome to everywhere. And indeed there are times when this kind of "generator" is useful - for the MineCraft's Flat -world type, or for testing purposes, or for tematic maps. In MCServer, this is exactly what the Constant +world type, or for testing purposes, or for tematic maps. In Cuberite, this is exactly what the Constant biome generator does.</p> <p>Of course, there are more interesting test scenarios for which multiple biomes must be generated as easy @@ -175,7 +175,7 @@ gives us the seed's X position. We use another Perlin noise and the same calcula seed.</p> <p>Here's an example of a biome map generated using the Voronoi + jitter grid, as implemented by the Voronoi -biome generator in MCServer:</p> +biome generator in Cuberite:</p> <img src="img/voronoijitterbiomes.png" /> <h3>Distorted Voronoi</h3> @@ -194,7 +194,7 @@ coordinate before sending the coordinates down to the Voronoi generator:</p> DistortedVoronoiBiome(X, Z) := VoronoiBiome(X + PerlinX(X, Z), Z + PerlinZ(X, Z)) </code> -<p>The following image shows the effects of the change, as generated by MCServer's DistortedVoronoi biome +<p>The following image shows the effects of the change, as generated by Cuberite's DistortedVoronoi biome generator. It is actually using the very same Voronoi map as the previous image, the only change has been the addition of the distortion:</p> <img src="img/distortedvoronoibiomes.png" /> @@ -241,7 +241,7 @@ either add them somewhere into the decision diagram, or we can make the generato </ul> </p> -<p>This is the approach implemented in MCServer's MultiStepMap biome generator. It generates biome maps like +<p>This is the approach implemented in Cuberite's MultiStepMap biome generator. It generates biome maps like this:</p> <img src="img/multistepmapbiomes.png" /> @@ -296,10 +296,10 @@ generator uses distortion before querying the small areas.</p> <img src="img/twolevelsmallgrid.jpg" /><br /> <img src="img/twolevelsmallareas.jpg" /><br /> -<p>The following image shows an example output of a TwoLevel biome generator in MCServer:</p> +<p>The following image shows an example output of a TwoLevel biome generator in Cuberite:</p> <img src="img/twolevelbiomes.png" /> -<p>Note that rivers are currently not implemented in this generator in MCServer, but they could be added +<p>Note that rivers are currently not implemented in this generator in Cuberite, but they could be added using the same approach as in MultiStepMap - by using a thresholded 2D Perlin noise.</p> @@ -332,12 +332,12 @@ suddenly become smooth. The following image shows the situation from the previou the averaging process: </p> <img src="img/biomeheightsavg.jpg" /> -<p>The approach used in MCServer's Biomal generator is based on this idea, with two slight modifications. +<p>The approach used in Cuberite's Biomal generator is based on this idea, with two slight modifications. Instead of using a separate generator for each biome, one generator is used with a different set of input parameters for each biomes. These input parameters modify the overall amplitude and frequency of the Perlin noise that the generator produces, thus modifying the final terrain with regards to biomes. Additionally, the averaging process is weighted - columns closer to the queried column get a more powerful weight in the sum -than the columns further away. The following image shows the output of MCServer's Biomal terrain height +than the columns further away. The following image shows the output of Cuberite's Biomal terrain height generator (each block type represents a different biome - ocean in the front (stone), plains and ice plains behind it (lapis, whitewool), extreme hills back right (soulsand), desert hills back left (mossy cobble)):</p> @@ -425,7 +425,7 @@ snow, for example.</p> into an ice block if the biome is cold. This means that any water block that is under any kind of other block, such as under a tree's leaves, will still stay water. Thus an additional improvement could be made by scanning down from the surface block through blocks that we deem as non-surface, such as leaves, torches, -ladders, fences etc. Note that MCServer currently implements only the easy solution.</p> +ladders, fences etc. Note that Cuberite currently implements only the easy solution.</p> <h3>Bottom lava</h3> <p>Most worlds in MineCraft have lava lakes at their bottom. Generating these is pretty straightforward: Use @@ -433,7 +433,7 @@ the user-configured depth and replace all the air blocks below this depth with l that this makes this generator dependent on the order in which the finishers are applied. If the mineshafts generate before bottom lava, the mineshafts that are below the lava level will get filled with lava. On the other hand, if bottom lava is generated before the mineshafts, it is possible for a mineshaft to "drill -through" a lake of lava. MCServer doesn't try to solve this and instead lets the admin choose whichever they +through" a lake of lava. Cuberite doesn't try to solve this and instead lets the admin choose whichever they prefer.</p> <h3>Specific foliage</h3> @@ -500,12 +500,12 @@ anywhere, so it would be rather useless.</p> surface, perhaps a bit more in the mountaineous biomes. There should be quite a few more springs underground, but there should definitely be more water springs than lava springs in the upper levels of the terrain, while there should be more lava springs and almost no water springs near the bottom. To accomodate this, the -MCServer team has made a tool that scanned through MineCraft's terrain and counted the amount of both types +Cuberite team has made a tool that scanned through MineCraft's terrain and counted the amount of both types of springs in relation to their height. Two curves have been found for the distribution of each type of the spring:</p> <img src="http://mc-server.xoft.cz/img/vanilla_springs_huge.png" /> -<p>MCServer uses an approximation of the above curves to choose the height at which to generate the +<p>Cuberite uses an approximation of the above curves to choose the height at which to generate the spring.</p> <!-- diff --git a/docs/_files.txt b/docs/_files.txt index 5147c62c8..85a4253c1 100644 --- a/docs/_files.txt +++ b/docs/_files.txt @@ -11,7 +11,7 @@ Login Sequence.txt - Annotated log of packets exchanged between the client and server for login; 1.6.2 protocol Object ownership.gv - - a GraphViz file to visualise ownership relations in the MCServer code architecture + - a GraphViz file to visualise ownership relations in the Cuberite code architecture SocketThreads states.gv - a GraphViz file documenting the states for individual sockets in cSocketThreads, and transitions between them diff --git a/src/Bindings/CMakeLists.txt b/src/Bindings/CMakeLists.txt index a53e82581..10cda1efb 100644 --- a/src/Bindings/CMakeLists.txt +++ b/src/Bindings/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required (VERSION 2.6) -project (MCServer) +project (Cuberite) include_directories ("${PROJECT_SOURCE_DIR}/../") include_directories (".") @@ -154,5 +154,5 @@ endif() if(NOT MSVC) add_library(Bindings ${SRCS} ${HDRS}) - target_link_libraries(Bindings lua sqlite tolualib mbedtls) + target_link_libraries(Bindings lua sqlite tolualib mbedtls HTTPServer) endif() diff --git a/src/Bindings/ManualBindings.cpp b/src/Bindings/ManualBindings.cpp index 3a595c1d2..42e7e9bd2 100644 --- a/src/Bindings/ManualBindings.cpp +++ b/src/Bindings/ManualBindings.cpp @@ -36,6 +36,7 @@ #include "../StringCompression.h" #include "../CommandOutput.h" #include "../BuildInfo.h" +#include "../HTTPServer/UrlParser.h" @@ -1956,6 +1957,155 @@ static int tolua_get_HTTPRequest_FormData(lua_State* tolua_S) +static int tolua_cUrlParser_GetDefaultPort(lua_State * a_LuaState) +{ + // API function signature: + // cUrlParser:GetDefaultPort("scheme") -> number + + // Check params: + cLuaState L(a_LuaState); + if ( + !L.CheckParamUserTable(1, "cUrlParser") || + !L.CheckParamString(2) || + !L.CheckParamEnd(3) + ) + { + return 0; + } + + // Read params from Lua: + AString scheme; + L.GetStackValue(2, scheme); + + // Execute and push result: + L.Push(cUrlParser::GetDefaultPort(scheme)); + return 1; +} + + + + + +static int tolua_cUrlParser_IsKnownScheme(lua_State * a_LuaState) +{ + // API function signature: + // cUrlParser:IsKnownScheme("scheme") -> bool + + // Check params: + cLuaState L(a_LuaState); + if ( + !L.CheckParamUserTable(1, "cUrlParser") || + !L.CheckParamString(2) || + !L.CheckParamEnd(3) + ) + { + return 0; + } + + // Read params from Lua: + AString scheme; + L.GetStackValue(2, scheme); + + // Execute and push result: + L.Push(cUrlParser::IsKnownScheme(scheme)); + return 1; +} + + + + + +static int tolua_cUrlParser_Parse(lua_State * a_LuaState) +{ + // API function signature: + // cUrlParser:Parse("url") -> "scheme", "user", "password", "host", portnum, "path", "query", "fragment" + // On error, returns nil and error message + + // Check params: + cLuaState L(a_LuaState); + if ( + !L.CheckParamUserTable(1, "cUrlParser") || + !L.CheckParamString(2) || + !L.CheckParamEnd(3) + ) + { + return 0; + } + + // Read params from Lua: + AString url; + L.GetStackValue(2, url); + + // Execute and push result: + AString scheme, username, password, host, path, query, fragment; + UInt16 port; + auto res = cUrlParser::Parse(url, scheme, username, password, host, port, path, query, fragment); + if (!res.first) + { + // Error, return nil and error msg: + L.PushNil(); + L.Push(res.second); + return 2; + } + L.Push(scheme); + L.Push(username); + L.Push(password); + L.Push(host); + L.Push(port); + L.Push(path); + L.Push(query); + L.Push(fragment); + return 8; +} + + + + + +static int tolua_cUrlParser_ParseAuthorityPart(lua_State * a_LuaState) +{ + // API function signature: + // cUrlParser:ParseAuthorityPart("authority") -> "user", "password", "host", portnum + // On error, returns nil and error message + // Parts not specified in the "authority" are left empty / zero + + // Check params: + cLuaState L(a_LuaState); + if ( + !L.CheckParamUserTable(1, "cUrlParser") || + !L.CheckParamString(2) || + !L.CheckParamEnd(3) + ) + { + return 0; + } + + // Read params from Lua: + AString authPart; + L.GetStackValue(2, authPart); + + // Execute and push result: + AString username, password, host; + UInt16 port; + auto res = cUrlParser::ParseAuthorityPart(authPart, username, password, host, port); + if (!res.first) + { + // Error, return nil and error msg: + L.PushNil(); + L.Push(res.second); + return 2; + } + L.Push(username); + L.Push(password); + L.Push(host); + L.Push(port); + return 4; +} + + + + + static int tolua_cWebAdmin_GetPlugins(lua_State * tolua_S) { cWebAdmin * self = reinterpret_cast<cWebAdmin *>(tolua_tousertype(tolua_S, 1, nullptr)); @@ -3224,9 +3374,11 @@ void cManualBindings::Bind(lua_State * tolua_S) tolua_usertype(tolua_S, "cCryptoHash"); tolua_usertype(tolua_S, "cLineBlockTracer"); tolua_usertype(tolua_S, "cStringCompression"); + tolua_usertype(tolua_S, "cUrlParser"); tolua_cclass(tolua_S, "cCryptoHash", "cCryptoHash", "", nullptr); tolua_cclass(tolua_S, "cLineBlockTracer", "cLineBlockTracer", "", nullptr); tolua_cclass(tolua_S, "cStringCompression", "cStringCompression", "", nullptr); + tolua_cclass(tolua_S, "cUrlParser", "cUrlParser", "", nullptr); // Globals: tolua_function(tolua_S, "Clamp", tolua_Clamp); @@ -3390,6 +3542,13 @@ void cManualBindings::Bind(lua_State * tolua_S) tolua_function(tolua_S, "InflateString", tolua_InflateString); tolua_endmodule(tolua_S); + tolua_beginmodule(tolua_S, "cUrlParser"); + tolua_function(tolua_S, "GetDefaultPort", tolua_cUrlParser_GetDefaultPort); + tolua_function(tolua_S, "IsKnownScheme", tolua_cUrlParser_IsKnownScheme); + tolua_function(tolua_S, "Parse", tolua_cUrlParser_Parse); + tolua_function(tolua_S, "ParseAuthorityPart", tolua_cUrlParser_ParseAuthorityPart); + tolua_endmodule(tolua_S); + tolua_beginmodule(tolua_S, "cWebAdmin"); tolua_function(tolua_S, "GetHTMLEscapedString", tolua_AllToLua_cWebAdmin_GetHTMLEscapedString); tolua_function(tolua_S, "GetPlugins", tolua_cWebAdmin_GetPlugins); diff --git a/src/Bindings/ManualBindings_World.cpp b/src/Bindings/ManualBindings_World.cpp index 225e71af5..f40af9778 100644 --- a/src/Bindings/ManualBindings_World.cpp +++ b/src/Bindings/ManualBindings_World.cpp @@ -36,9 +36,9 @@ static int tolua_cWorld_BroadcastParticleEffect(lua_State * tolua_S) AString Name; float PosX, PosY, PosZ, OffX, OffY, OffZ; float ParticleData; - int ParticleAmmount; + int ParticleAmount; cClientHandle * ExcludeClient = nullptr; - L.GetStackValues(1, World, Name, PosX, PosY, PosZ, OffX, OffY, OffZ, ParticleData, ParticleAmmount, ExcludeClient); + L.GetStackValues(1, World, Name, PosX, PosY, PosZ, OffX, OffY, OffZ, ParticleData, ParticleAmount, ExcludeClient); if (World == nullptr) { LOGWARNING("World:BroadcastParticleEffect(): invalid world parameter"); @@ -53,7 +53,7 @@ static int tolua_cWorld_BroadcastParticleEffect(lua_State * tolua_S) L.GetStackValue(11 + i, data[static_cast<size_t>(i)]); } - World->GetBroadcaster().BroadcastParticleEffect(Name, Vector3f(PosX, PosY, PosZ), Vector3f(OffX, OffY, OffZ), ParticleData, ParticleAmmount, ExcludeClient); + World->GetBroadcaster().BroadcastParticleEffect(Name, Vector3f(PosX, PosY, PosZ), Vector3f(OffX, OffY, OffZ), ParticleData, ParticleAmount, ExcludeClient); return 0; } diff --git a/src/BlockEntities/CMakeLists.txt b/src/BlockEntities/CMakeLists.txt index fbf85d2af..6c164c4b4 100644 --- a/src/BlockEntities/CMakeLists.txt +++ b/src/BlockEntities/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required (VERSION 2.6) -project (MCServer) +project (Cuberite) include_directories ("${PROJECT_SOURCE_DIR}/../") diff --git a/src/BlockEntities/MobHeadEntity.cpp b/src/BlockEntities/MobHeadEntity.cpp index 3275bf7f2..542e920ba 100644 --- a/src/BlockEntities/MobHeadEntity.cpp +++ b/src/BlockEntities/MobHeadEntity.cpp @@ -14,8 +14,7 @@ cMobHeadEntity::cMobHeadEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World) : super(E_BLOCK_HEAD, a_BlockX, a_BlockY, a_BlockZ, a_World), m_Type(SKULL_TYPE_SKELETON), - m_Rotation(SKULL_ROTATION_NORTH), - m_Owner("") + m_Rotation(SKULL_ROTATION_NORTH) { } @@ -35,9 +34,9 @@ bool cMobHeadEntity::UsedBy(cPlayer * a_Player) void cMobHeadEntity::SetType(const eMobHeadType & a_Type) { - if ((!m_Owner.empty()) && (a_Type != SKULL_TYPE_PLAYER)) + if ((!m_OwnerName.empty()) && (a_Type != SKULL_TYPE_PLAYER)) { - m_Owner = ""; + m_OwnerName = m_OwnerUUID = m_OwnerTexture = m_OwnerTextureSignature = ""; } m_Type = a_Type; } @@ -55,13 +54,43 @@ void cMobHeadEntity::SetRotation(eMobHeadRotation a_Rotation) -void cMobHeadEntity::SetOwner(const AString & a_Owner) +void cMobHeadEntity::SetOwner(const cPlayer & a_Owner) { - if ((a_Owner.length() > 16) || (m_Type != SKULL_TYPE_PLAYER)) + if (m_Type != SKULL_TYPE_PLAYER) { return; } - m_Owner = a_Owner; + + m_OwnerName = a_Owner.GetName(); + m_OwnerUUID = a_Owner.GetUUID(); + + const Json::Value & Properties = a_Owner.GetClientHandle()->GetProperties(); + for (auto & Node : Properties) + { + if (Node.get("name", "").asString() == "textures") + { + m_OwnerTexture = Node.get("value", "").asString(); + m_OwnerTextureSignature = Node.get("signature", "").asString(); + break; + } + } +} + + + + + +void cMobHeadEntity::SetOwner(const AString & a_OwnerUUID, const AString & a_OwnerName, const AString & a_OwnerTexture, const AString & a_OwnerTextureSignature) +{ + if (m_Type != SKULL_TYPE_PLAYER) + { + return; + } + + m_OwnerUUID = a_OwnerUUID; + m_OwnerName = a_OwnerName; + m_OwnerTexture = a_OwnerTexture; + m_OwnerTextureSignature = a_OwnerTextureSignature; } diff --git a/src/BlockEntities/MobHeadEntity.h b/src/BlockEntities/MobHeadEntity.h index f25cb3a16..2eb932068 100644 --- a/src/BlockEntities/MobHeadEntity.h +++ b/src/BlockEntities/MobHeadEntity.h @@ -39,8 +39,11 @@ public: /** Set the rotation of the mob head */ void SetRotation(eMobHeadRotation a_Rotation); - /** Set the player name for mob heads with player type */ - void SetOwner(const AString & a_Owner); + /** Set the player for mob heads with player type */ + void SetOwner(const cPlayer & a_Owner); + + /** Sets the player components for the mob heads with player type */ + void SetOwner(const AString & a_OwnerUUID, const AString & a_OwnerName, const AString & a_OwnerTexture, const AString & a_OwnerTextureSignature); /** Returns the type of the mob head */ eMobHeadType GetType(void) const { return m_Type; } @@ -49,7 +52,16 @@ public: eMobHeadRotation GetRotation(void) const { return m_Rotation; } /** Returns the player name of the mob head */ - AString GetOwner(void) const { return m_Owner; } + AString GetOwnerName(void) const { return m_OwnerName; } + + /** Returns the player UUID of the mob head */ + AString GetOwnerUUID(void) const { return m_OwnerUUID; } + + /** Returns the texture of the mob head */ + AString GetOwnerTexture(void) const { return m_OwnerTexture; } + + /** Returns the texture signature of the mob head */ + AString GetOwnerTextureSignature(void) const { return m_OwnerTextureSignature; } // tolua_end @@ -60,7 +72,11 @@ private: eMobHeadType m_Type; eMobHeadRotation m_Rotation; - AString m_Owner; + + AString m_OwnerName; + AString m_OwnerUUID; + AString m_OwnerTexture; + AString m_OwnerTextureSignature; } ; // tolua_export diff --git a/src/Blocks/BlockHandler.cpp b/src/Blocks/BlockHandler.cpp index 0ad0e2242..22b70f590 100644 --- a/src/Blocks/BlockHandler.cpp +++ b/src/Blocks/BlockHandler.cpp @@ -453,22 +453,49 @@ void cBlockHandler::DropBlock(cChunkInterface & a_ChunkInterface, cWorldInterfac { switch (m_BlockType) { + case E_BLOCK_ACACIA_DOOR: + case E_BLOCK_ACTIVE_COMPARATOR: + case E_BLOCK_BED: + case E_BLOCK_BIRCH_DOOR: + case E_BLOCK_BREWING_STAND: case E_BLOCK_CAKE: case E_BLOCK_CARROTS: + case E_BLOCK_CAULDRON: case E_BLOCK_COCOA_POD: + case E_BLOCK_CROPS: + case E_BLOCK_DARK_OAK_DOOR: + case E_BLOCK_DOUBLE_RED_SANDSTONE_SLAB: case E_BLOCK_DOUBLE_STONE_SLAB: case E_BLOCK_DOUBLE_WOODEN_SLAB: case E_BLOCK_FIRE: case E_BLOCK_FARMLAND: + case E_BLOCK_FLOWER_POT: + case E_BLOCK_HEAD: + case E_BLOCK_INACTIVE_COMPARATOR: + case E_BLOCK_INVERTED_DAYLIGHT_SENSOR: + case E_BLOCK_IRON_DOOR: + case E_BLOCK_JUNGLE_DOOR: case E_BLOCK_MELON_STEM: case E_BLOCK_MOB_SPAWNER: case E_BLOCK_NETHER_WART: + case E_BLOCK_OAK_DOOR: + case E_BLOCK_PISTON_EXTENSION: case E_BLOCK_POTATOES: case E_BLOCK_PUMPKIN_STEM: + case E_BLOCK_REDSTONE_ORE_GLOWING: + case E_BLOCK_REDSTONE_REPEATER_OFF: + case E_BLOCK_REDSTONE_REPEATER_ON: + case E_BLOCK_REDSTONE_TORCH_OFF: + case E_BLOCK_REDSTONE_WIRE: + case E_BLOCK_SIGN_POST: case E_BLOCK_SNOW: + case E_BLOCK_SPRUCE_DOOR: + case E_BLOCK_STANDING_BANNER: case E_BLOCK_SUGARCANE: case E_BLOCK_TALL_GRASS: - case E_BLOCK_CROPS: + case E_BLOCK_TRIPWIRE: + case E_BLOCK_WALL_BANNER: + case E_BLOCK_WALLSIGN: { // Silktouch can't be used for these blocks ConvertToPickups(Pickups, Meta); diff --git a/src/Blocks/BlockSlab.h b/src/Blocks/BlockSlab.h index 79d440cf6..bc7f79099 100644 --- a/src/Blocks/BlockSlab.h +++ b/src/Blocks/BlockSlab.h @@ -210,7 +210,7 @@ public: { case E_BLOCK_DOUBLE_STONE_SLAB: return E_BLOCK_STONE_SLAB; case E_BLOCK_DOUBLE_WOODEN_SLAB: return E_BLOCK_WOODEN_SLAB; - case E_BLOCK_DOUBLE_RED_SANDSTONE_SLAB: return E_BLOCK_DOUBLE_RED_SANDSTONE_SLAB; + case E_BLOCK_DOUBLE_RED_SANDSTONE_SLAB: return E_BLOCK_RED_SANDSTONE_SLAB; } ASSERT(!"Unhandled double slab type!"); return a_BlockType; diff --git a/src/Blocks/CMakeLists.txt b/src/Blocks/CMakeLists.txt index 1c12d9fbc..e9b3ce386 100644 --- a/src/Blocks/CMakeLists.txt +++ b/src/Blocks/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required (VERSION 2.6) -project (MCServer) +project (Cuberite) include_directories ("${PROJECT_SOURCE_DIR}/../") diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 2478d4af4..3d9e10aa5 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -216,7 +216,7 @@ if (NOT MSVC) # If building a windows version, but not using MSVC, add the resources directly to the makefile: if (WIN32) - list(APPEND SOURCE "Resources/MCServer.rc") + list(APPEND SOURCE "Resources/Cuberite.rc") endif() else () # MSVC-specific handling: Put all files into one project, separate by the folders: @@ -276,7 +276,7 @@ else () SET_SOURCE_FILES_PROPERTIES( "StackWalker.cpp LeakFinder.cpp" PROPERTIES COMPILE_FLAGS "/Yc\"Globals.h\"" ) - list(APPEND SOURCE "Resources/MCServer.rc") + list(APPEND SOURCE "Resources/Cuberite.rc") # Make MSVC generate the PDB files even for the release build: set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /Zi") diff --git a/src/ChunkMap.cpp b/src/ChunkMap.cpp index edf42abe7..cbbf910fb 100644 --- a/src/ChunkMap.cpp +++ b/src/ChunkMap.cpp @@ -1896,10 +1896,10 @@ void cChunkMap::DoExplosionAt(double a_ExplosionSize, double a_BlockX, double a_ public cEntityCallback { public: - cTNTDamageCallback(cBoundingBox & a_bbTNT, Vector3d a_ExplosionPos, int a_ExplosionSize) : - m_bbTNT(a_bbTNT), - m_ExplosionPos(a_ExplosionPos), - m_ExplosionSize(a_ExplosionSize) + cTNTDamageCallback(cBoundingBox & a_CBBBTNT, Vector3d a_CBExplosionPos, int a_CBExplosionSize) : + m_bbTNT(a_CBBBTNT), + m_ExplosionPos(a_CBExplosionPos), + m_ExplosionSize(a_CBExplosionSize) { } @@ -2364,10 +2364,10 @@ bool cChunkMap::GenerateChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * class cPrepareLoadCallback: public cChunkCoordCallback { public: - cPrepareLoadCallback(cWorld & a_World, cChunkMap & a_ChunkMap, cChunkCoordCallback * a_Callback): - m_World(a_World), - m_ChunkMap(a_ChunkMap), - m_Callback(a_Callback) + cPrepareLoadCallback(cWorld & a_CBWorld, cChunkMap & a_CBChunkMap, cChunkCoordCallback * a_CBCallback): + m_World(a_CBWorld), + m_ChunkMap(a_CBChunkMap), + m_Callback(a_CBCallback) { } @@ -2385,7 +2385,7 @@ bool cChunkMap::GenerateChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * } // The chunk failed to load, generate it: - cCSLock Lock(m_ChunkMap.m_CSLayers); + cCSLock CBLock(m_ChunkMap.m_CSLayers); cChunkPtr CBChunk = m_ChunkMap.GetChunkNoLoad(a_CBChunkX, a_CBChunkZ); if (CBChunk == nullptr) diff --git a/src/Cuberite.vcxproj.user b/src/Cuberite.vcxproj.user new file mode 100644 index 000000000..7ebd19d9b --- /dev/null +++ b/src/Cuberite.vcxproj.user @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <LocalDebuggerWorkingDirectory>../Server</LocalDebuggerWorkingDirectory> + <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseProfile|Win32'"> + <LocalDebuggerWorkingDirectory>../Server</LocalDebuggerWorkingDirectory> + <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'"> + <LocalDebuggerWorkingDirectory>../Server</LocalDebuggerWorkingDirectory> + <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='MinSizeRel|Win32'"> + <LocalDebuggerWorkingDirectory>../Server</LocalDebuggerWorkingDirectory> + <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <LocalDebuggerWorkingDirectory>../Server</LocalDebuggerWorkingDirectory> + <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='DebugProfile|Win32'"> + <LocalDebuggerWorkingDirectory>../Server</LocalDebuggerWorkingDirectory> + <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> + </PropertyGroup> +</Project>
\ No newline at end of file diff --git a/src/Defines.h b/src/Defines.h index b0589d8a0..e2f72ed84 100644 --- a/src/Defines.h +++ b/src/Defines.h @@ -481,13 +481,20 @@ inline bool IsBlockFence(BLOCKTYPE a_BlockType) { switch (a_BlockType) { - case E_BLOCK_FENCE: - case E_BLOCK_OAK_FENCE_GATE: - case E_BLOCK_NETHER_BRICK_FENCE: + case E_BLOCK_ACACIA_FENCE: + case E_BLOCK_ACACIA_FENCE_GATE: + case E_BLOCK_BIRCH_FENCE: + case E_BLOCK_BIRCH_FENCE_GATE: case E_BLOCK_COBBLESTONE_WALL: case E_BLOCK_DARK_OAK_FENCE: + case E_BLOCK_DARK_OAK_FENCE_GATE: + case E_BLOCK_FENCE: + case E_BLOCK_JUNGLE_FENCE: + case E_BLOCK_JUNGLE_FENCE_GATE: + case E_BLOCK_NETHER_BRICK_FENCE: + case E_BLOCK_OAK_FENCE_GATE: + case E_BLOCK_SPRUCE_FENCE: case E_BLOCK_SPRUCE_FENCE_GATE: - case E_BLOCK_ACACIA_FENCE: { return true; } diff --git a/src/Entities/CMakeLists.txt b/src/Entities/CMakeLists.txt index 54cca9c90..0416d5338 100644 --- a/src/Entities/CMakeLists.txt +++ b/src/Entities/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required (VERSION 2.6) -project (MCServer) +project (Cuberite) include_directories ("${PROJECT_SOURCE_DIR}/../") @@ -61,10 +61,7 @@ SET (HDRS WitherSkullEntity.h) if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") - set_source_files_properties(Entity.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=sign-conversion -Wno-error=global-constructors -Wno-error=switch-enum ") - set_source_files_properties(EntityEffect.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=switch-enum ") - set_source_files_properties(Floater.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=sign-conversion ") - set_source_files_properties(Player.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=sign-conversion -Wno-error=switch-enum -Wno-error=conversion ") + set_source_files_properties(Entity.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=global-constructors") endif() if(NOT MSVC) diff --git a/src/Entities/Player.cpp b/src/Entities/Player.cpp index 33ded6ab9..80f07cb65 100644 --- a/src/Entities/Player.cpp +++ b/src/Entities/Player.cpp @@ -63,6 +63,7 @@ cPlayer::cPlayer(cClientHandlePtr a_Client, const AString & a_PlayerName) : m_GameMode(eGameMode_NotSet), m_IP(""), m_ClientHandle(a_Client), + m_FreezeCounter(-1), m_NormalMaxSpeed(1.0), m_SprintingMaxSpeed(1.3), m_FlyingMaxSpeed(1.0), @@ -112,6 +113,7 @@ cPlayer::cPlayer(cClientHandlePtr a_Client, const AString & a_PlayerName) : m_LastGroundHeight = static_cast<float>(GetPosY()); m_Stance = GetPosY() + 1.62; + FreezeInternal(GetPosition(), false); // Freeze. Will be unfrozen once the chunk is loaded if (m_GameMode == gmNotSet) { @@ -220,8 +222,35 @@ void cPlayer::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) m_Stats.AddValue(statMinutesPlayed, 1); + // Handle a frozen player + if (m_IsFrozen) + { + m_FreezeCounter += 1; + if (!m_IsManuallyFrozen && a_Chunk.IsValid()) + { + // If the player was automatically frozen, unfreeze if the chunk the player is inside is loaded + Unfreeze(); + } + else + { + // If the player was externally / manually frozen (plugin, etc.) or if the chunk isn't loaded yet: + // 1. Set the location to m_FrozenPosition every tick. + // 2. Zero out the speed every tick. + // 3. Send location updates every 60 ticks. + SetPosition(m_FrozenPosition); + SetSpeed(0, 0, 0); + if (m_FreezeCounter % 60 == 0) + { + BroadcastMovementUpdate(m_ClientHandle.get()); + m_ClientHandle->SendPlayerPosition(); + } + return; + } + } + if (!a_Chunk.IsValid()) { + FreezeInternal(GetPosition(), false); // This may happen if the cPlayer is created before the chunks have the chance of being loaded / generated (#83) return; } @@ -879,7 +908,15 @@ void cPlayer::KilledBy(TakeDamageInfo & a_TDI) case dtEnderPearl: DamageText = "misused an ender pearl"; break; case dtAdmin: DamageText = "was administrator'd"; break; case dtExplosion: DamageText = "blew up"; break; - default: DamageText = "died, somehow; we've no idea how though"; break; + case dtAttack: DamageText = "was attacked by thin air"; break; + #ifndef __clang__ + default: + { + ASSERT(!"Unknown damage type"); + DamageText = "died, somehow; we've no idea how though"; + break; + } + #endif // __clang__ } AString DeathMessage = Printf("%s %s", GetName().c_str(), DamageText.c_str()); PluginManager->CallHookKilled(*this, a_TDI, DeathMessage); @@ -1263,6 +1300,46 @@ void cPlayer::TeleportToCoords(double a_PosX, double a_PosY, double a_PosZ) +void cPlayer::Freeze(const Vector3d & a_Location) +{ + FreezeInternal(a_Location, true); +} + + + + + +bool cPlayer::IsFrozen() +{ + return m_IsFrozen; +} + + + + + +int cPlayer::GetFrozenDuration() +{ + return m_FreezeCounter; +} + + + + + +void cPlayer::Unfreeze() +{ + m_FreezeCounter = -1; + m_IsFrozen = false; + SetPosition(m_FrozenPosition); + BroadcastMovementUpdate(m_ClientHandle.get()); + m_ClientHandle->SendPlayerPosition(); +} + + + + + void cPlayer::SendRotation(double a_YawDegrees, double a_PitchDegrees) { SetYaw(a_YawDegrees); @@ -1533,6 +1610,20 @@ void cPlayer::TossItems(const cItems & a_Items) } + + + +void cPlayer::FreezeInternal(const Vector3d & a_Location, bool a_ManuallyFrozen) +{ + m_IsFrozen = true; + m_FrozenPosition = a_Location; + m_IsManuallyFrozen = a_ManuallyFrozen; +} + + + + + bool cPlayer::DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn, Vector3d a_NewPosition) { ASSERT(a_World != nullptr); diff --git a/src/Entities/Player.h b/src/Entities/Player.h index bff9599f7..10c9106a3 100644 --- a/src/Entities/Player.h +++ b/src/Entities/Player.h @@ -138,6 +138,18 @@ public: // tolua_begin + /** Prevent the player from moving and lock him into a_Location. */ + void Freeze(const Vector3d & a_Location); + + /** Is the player frozen? */ + bool IsFrozen(); + + /** How long has the player been frozen? */ + int GetFrozenDuration(); + + /** Cancels Freeze(...) and allows the player to move naturally. */ + void Unfreeze(); + /** Sends the "look" packet to the player, forcing them to set their rotation to the specified values. a_YawDegrees is clipped to range [-180, +180), a_PitchDegrees is clipped to range [-180, +180) but the client only uses [-90, +90] @@ -240,7 +252,7 @@ public: void SendMessageFatal (const AString & a_Message) { m_ClientHandle->SendChat(a_Message, mtFailure); } void SendMessagePrivateMsg (const AString & a_Message, const AString & a_Sender) { m_ClientHandle->SendChat(a_Message, mtPrivateMessage, a_Sender); } void SendMessage (const cCompositeChat & a_Message) { m_ClientHandle->SendChat(a_Message); } - + void SendSystemMessage (const AString & a_Message) { m_ClientHandle->SendChatSystem(a_Message, mtCustom); } void SendAboveActionBarMessage(const AString & a_Message) { m_ClientHandle->SendChatAboveActionBar(a_Message, mtCustom); } void SendSystemMessage (const cCompositeChat & a_Message) { m_ClientHandle->SendChatSystem(a_Message); } @@ -576,6 +588,18 @@ protected: cSlotNums m_InventoryPaintSlots; + /** if m_IsFrozen is true, we lock m_Location to this position. */ + Vector3d m_FrozenPosition; + + /** If true, we are locking m_Position to m_FrozenPosition. */ + bool m_IsFrozen; + + /** */ + int m_FreezeCounter; + + /** Was the player frozen manually by a plugin or automatically by the server? */ + bool m_IsManuallyFrozen; + /** Max speed, relative to the game default. 1 means regular speed, 2 means twice as fast, 0.5 means half-speed. Default value is 1. */ @@ -661,6 +685,10 @@ protected: /** Tosses a list of items. */ void TossItems(const cItems & a_Items); + /** Pins the player to a_Location until Unfreeze() is called. + If ManuallyFrozen is false, the player will unfreeze when the chunk is loaded. */ + void FreezeInternal(const Vector3d & a_Location, bool a_ManuallyFrozen); + /** Returns the filename for the player data based on the UUID given. This can be used both for online and offline UUIDs. */ AString GetUUIDFileName(const AString & a_UUID); diff --git a/src/Generating/CMakeLists.txt b/src/Generating/CMakeLists.txt index d15d9eba0..dd346b6c4 100644 --- a/src/Generating/CMakeLists.txt +++ b/src/Generating/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required (VERSION 2.6) -project (MCServer) +project (Cuberite) include_directories ("${PROJECT_SOURCE_DIR}/../") diff --git a/src/HTTPServer/CMakeLists.txt b/src/HTTPServer/CMakeLists.txt index 6788d50bf..a08a1fcf8 100644 --- a/src/HTTPServer/CMakeLists.txt +++ b/src/HTTPServer/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required (VERSION 2.6) -project (MCServer) +project (Cuberite) include_directories ("${PROJECT_SOURCE_DIR}/../") @@ -12,7 +12,9 @@ SET (SRCS HTTPServer.cpp MultipartParser.cpp NameValueParser.cpp - SslHTTPConnection.cpp) + SslHTTPConnection.cpp + UrlParser.cpp +) SET (HDRS EnvelopeParser.h @@ -22,7 +24,9 @@ SET (HDRS HTTPServer.h MultipartParser.h NameValueParser.h - SslHTTPConnection.h) + SslHTTPConnection.h + UrlParser.h +) if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") set_source_files_properties(HTTPServer.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=global-constructors ") diff --git a/src/HTTPServer/UrlParser.cpp b/src/HTTPServer/UrlParser.cpp new file mode 100644 index 000000000..05db3e413 --- /dev/null +++ b/src/HTTPServer/UrlParser.cpp @@ -0,0 +1,200 @@ + +// UrlParser.cpp + +// Implements the cUrlParser class that parses string URL into individual parts + +#include "Globals.h" +#include "UrlParser.h" + + + + + +UInt16 cUrlParser::GetDefaultPort(const AString & a_Scheme) +{ + if (a_Scheme == "http") + { + return 80; + } + else if (a_Scheme == "https") + { + return 443; + } + else if (a_Scheme == "ftp") + { + return 21; + } + else if (a_Scheme == "mailto") + { + return 25; + } + return 0; +} + + + + + +std::pair<bool, AString> cUrlParser::ParseAuthorityPart( + const AString & a_AuthorityPart, + AString & a_Username, + AString & a_Password, + AString & a_Host, + UInt16 & a_Port +) +{ + /* + a_AuthorityPart format: + [user:password@]host[:port] + host can be an IPv4, hostname, or an IPv6 enclosed in brackets + Assume only the password can contain an additional at-sign + */ + + // Split the authority on the last at-sign, if present: + auto idxLastAtSign = a_AuthorityPart.find_last_of('@'); + auto credPart = (idxLastAtSign == AString::npos) ? AString() : a_AuthorityPart.substr(0, idxLastAtSign); + auto srvrPart = (idxLastAtSign == AString::npos) ? a_AuthorityPart : a_AuthorityPart.substr(idxLastAtSign + 1); + + // User credentials are completely optional: + auto idxCredColon = credPart.find(':'); + a_Username = credPart.substr(0, idxCredColon); + a_Password = (idxCredColon == AString::npos) ? AString() : credPart.substr(idxCredColon + 1); + + // Host can be a hostname, IPv4 or [IPv6]. If in brackets, search for the closing bracket first + if (srvrPart.empty()) + { + // No host information at all. Bail out with success + a_Host.clear(); + return std::make_pair(true, AString()); + } + if (srvrPart[0] == '[') + { + // [IPv6] host, search for the closing bracket + auto idxClosingBracket = srvrPart.find(']'); + if (idxClosingBracket == AString::npos) + { + return std::make_pair(false, "Invalid IPv6-like address, missing closing bracket"); + } + a_Host = srvrPart.substr(0, idxClosingBracket); + auto portPart = srvrPart.substr(idxClosingBracket + 1); + if (portPart.empty()) + { + // No port was specified, return success + return std::make_pair(true, AString()); + } + if (portPart[0] != ':') + { + return std::make_pair(false, "Invalid port format after IPv6 address, mising colon"); + } + if (!StringToInteger(portPart.substr(2), a_Port)) + { + return std::make_pair(false, "Failed to parse port number after IPv6 address"); + } + return std::make_pair(true, AString()); + } + + // Not an [IPv6] address, split on the last colon: + auto idxLastColon = srvrPart.find_last_of(':'); + a_Host = srvrPart.substr(0, idxLastColon); + if (idxLastColon == AString::npos) + { + // No port was specified, return success + return std::make_pair(true, AString()); + } + auto portPart = srvrPart.substr(idxLastColon + 1); + if (!StringToInteger(portPart, a_Port)) + { + return std::make_pair(false, "Failed to parse port number after hostname"); + } + return std::make_pair(true, AString()); +} + + + + + +std::pair<bool, AString> cUrlParser::Parse( + const AString & a_Url, + AString & a_Scheme, + AString & a_Username, + AString & a_Password, + AString & a_Host, + UInt16 & a_Port, + AString & a_Path, + AString & a_Query, + AString & a_Fragment +) +{ + // Find the scheme - the text before the first colon: + auto idxColon = a_Url.find(':'); + if (idxColon == AString::npos) + { + return std::make_pair(false, "Cannot parse the Scheme part of the URL"); + } + a_Scheme = StrToLower(a_Url.substr(0, idxColon)); + a_Port = GetDefaultPort(a_Scheme); + if (a_Port == 0) + { + return std::make_pair(false, Printf("Unknown URL scheme: \"%s\"", a_Scheme.c_str())); + } + + // If the next two chars are a double-slash, skip them: + auto authStart = idxColon + 1; + if (a_Url.substr(authStart, 2) == "//") + { + authStart += 2; + } + + // The Authority part follows the Scheme, until the first slash: + auto idxFirstSlash = a_Url.find('/', authStart + 1); + if (idxFirstSlash == AString::npos) + { + // No slash, the whole end of the Url is the authority part + idxFirstSlash = a_Url.size(); + } + + // Parse the Authority part into individual components: + auto res = ParseAuthorityPart( + a_Url.substr(authStart, idxFirstSlash - authStart), + a_Username, a_Password, + a_Host, a_Port + ); + if (!res.first) + { + return res; + } + + // Parse the rest into a path, query and fragment: + a_Path.clear(); + a_Query.clear(); + a_Fragment.clear(); + if (idxFirstSlash == a_Url.size()) + { + // No additional data, bail out with success + return std::make_pair(true, AString()); + } + auto idxPathEnd = a_Url.find_first_of("?#", idxFirstSlash + 1); + if (idxPathEnd == AString::npos) + { + a_Path = a_Url.substr(idxFirstSlash); + return std::make_pair(true, AString()); + } + a_Path = a_Url.substr(idxFirstSlash, idxPathEnd - idxFirstSlash); + auto idxHash = a_Url.find('#', idxPathEnd); + if (idxHash == AString::npos) + { + a_Query = a_Url.substr(idxPathEnd + 1); + return std::make_pair(true, AString()); + } + if (idxHash > idxPathEnd) + { + a_Query = a_Url.substr(idxPathEnd + 1, idxHash - idxPathEnd - 1); + } + a_Fragment = a_Url.substr(idxHash + 1); + return std::make_pair(true, AString()); +} + + + + + diff --git a/src/HTTPServer/UrlParser.h b/src/HTTPServer/UrlParser.h new file mode 100644 index 000000000..15a63e05d --- /dev/null +++ b/src/HTTPServer/UrlParser.h @@ -0,0 +1,58 @@ + +// UrlParser.h + +// Declares the cUrlParser class that parses string URL into individual parts + + + + + +#pragma once + + + + + +class cUrlParser +{ +public: + /** Returns true if the specified scheme (http, ftp, mailto, ...) is recognized by the URL parser. + Is case sensitive, known schemes are always lowercase. */ + static bool IsKnownScheme(const AString & a_Scheme) { return (GetDefaultPort(a_Scheme) > 0); } + + /** Returns the default port used by the specified scheme / protocol. + If the scheme is not known, 0 is returned. */ + static UInt16 GetDefaultPort(const AString & a_Scheme); + + /** Parses the given Authority part of an URL into individual components. + Returns true on success, + returns false and error message on failure. */ + static std::pair<bool, AString> ParseAuthorityPart( + const AString & a_AuthorityPart, + AString & a_Username, + AString & a_Password, + AString & a_Host, + UInt16 & a_Port + ); + + /** Parses the given URL into individual components. + Returns true on success, + returns false and error message on failure. + Fails if the scheme (protocol) is not known. + If port is missing, the default port for the specific scheme is applied. */ + static std::pair<bool, AString> Parse( + const AString & a_Url, + AString & a_Scheme, + AString & a_Username, + AString & a_Password, + AString & a_Host, + UInt16 & a_Port, + AString & a_Path, + AString & a_Query, + AString & a_Fragment + ); +}; + + + + diff --git a/src/Items/CMakeLists.txt b/src/Items/CMakeLists.txt index 2e719d1a6..9b3a2d8b5 100644 --- a/src/Items/CMakeLists.txt +++ b/src/Items/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required (VERSION 2.6) -project (MCServer) +project (Cuberite) include_directories ("${PROJECT_SOURCE_DIR}/../") diff --git a/src/MCServer.vcproj.user b/src/MCServer.vcproj.user deleted file mode 100644 index b17909f71..000000000 --- a/src/MCServer.vcproj.user +++ /dev/null @@ -1,167 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<VisualStudioUserFile - ProjectType="Visual C++" - Version="9,00" - ShowAllFiles="false" - > - <Configurations> - <Configuration - Name="Debug|Win32" - > - <DebugSettings - Command="$(TargetPath)" - WorkingDirectory="..\MCServer" - CommandArguments="" - Attach="false" - DebuggerType="3" - RemoteCommand="" - HttpUrl="" - PDBPath="" - SQLDebugging="" - Environment="" - EnvironmentMerge="true" - DebuggerFlavor="0" - MPIRunCommand="" - MPIRunArguments="" - MPIRunWorkingDirectory="" - ApplicationCommand="" - ApplicationArguments="" - ShimCommand="" - MPIAcceptMode="" - MPIAcceptFilter="" - /> - </Configuration> - <Configuration - Name="DebugProfile|Win32" - > - <DebugSettings - Command="$(TargetPath)" - WorkingDirectory="..\MCServer" - CommandArguments="" - Attach="false" - DebuggerType="3" - RemoteCommand="" - HttpUrl="" - PDBPath="" - SQLDebugging="" - Environment="" - EnvironmentMerge="true" - DebuggerFlavor="0" - MPIRunCommand="" - MPIRunArguments="" - MPIRunWorkingDirectory="" - ApplicationCommand="" - ApplicationArguments="" - ShimCommand="" - MPIAcceptMode="" - MPIAcceptFilter="" - /> - </Configuration> - <Configuration - Name="MinSizeRel|Win32" - > - <DebugSettings - Command="$(TargetPath)" - WorkingDirectory="..\MCServer" - CommandArguments="" - Attach="false" - DebuggerType="3" - RemoteCommand="" - HttpUrl="" - PDBPath="" - SQLDebugging="" - Environment="" - EnvironmentMerge="true" - DebuggerFlavor="0" - MPIRunCommand="" - MPIRunArguments="" - MPIRunWorkingDirectory="" - ApplicationCommand="" - ApplicationArguments="" - ShimCommand="" - MPIAcceptMode="" - MPIAcceptFilter="" - /> - </Configuration> - <Configuration - Name="Release|Win32" - > - <DebugSettings - Command="$(TargetPath)" - WorkingDirectory="..\MCServer" - CommandArguments="" - Attach="false" - DebuggerType="3" - RemoteCommand="" - HttpUrl="" - PDBPath="" - SQLDebugging="" - Environment="" - EnvironmentMerge="true" - DebuggerFlavor="0" - MPIRunCommand="" - MPIRunArguments="" - MPIRunWorkingDirectory="" - ApplicationCommand="" - ApplicationArguments="" - ShimCommand="" - MPIAcceptMode="" - MPIAcceptFilter="" - /> - </Configuration> - <Configuration - Name="ReleaseProfile|Win32" - > - <DebugSettings - Command="$(TargetPath)" - WorkingDirectory="..\MCServer" - CommandArguments="" - Attach="false" - DebuggerType="3" - Remote="1" - RemoteMachine="ASAGA" - RemoteCommand="" - HttpUrl="" - PDBPath="" - SQLDebugging="" - Environment="" - EnvironmentMerge="true" - DebuggerFlavor="0" - MPIRunCommand="" - MPIRunArguments="" - MPIRunWorkingDirectory="" - ApplicationCommand="" - ApplicationArguments="" - ShimCommand="" - MPIAcceptMode="" - MPIAcceptFilter="" - /> - </Configuration> - <Configuration - Name="RelWithDebInfo|Win32" - > - <DebugSettings - Command="$(TargetPath)" - WorkingDirectory="..\MCServer" - CommandArguments="" - Attach="false" - DebuggerType="3" - RemoteCommand="" - HttpUrl="" - PDBPath="" - SQLDebugging="" - Environment="" - EnvironmentMerge="true" - DebuggerFlavor="0" - MPIRunCommand="" - MPIRunArguments="" - MPIRunWorkingDirectory="" - ApplicationCommand="" - ApplicationArguments="" - ShimCommand="" - MPIAcceptMode="" - MPIAcceptFilter="" - /> - </Configuration> - </Configurations> -</VisualStudioUserFile> diff --git a/src/Mobs/AggressiveMonster.cpp b/src/Mobs/AggressiveMonster.cpp index 309f6d985..56500309d 100644 --- a/src/Mobs/AggressiveMonster.cpp +++ b/src/Mobs/AggressiveMonster.cpp @@ -22,9 +22,9 @@ cAggressiveMonster::cAggressiveMonster(const AString & a_ConfigName, eMonsterTyp // What to do if in Chasing State -void cAggressiveMonster::InStateChasing(std::chrono::milliseconds a_Dt) +void cAggressiveMonster::InStateChasing(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) { - super::InStateChasing(a_Dt); + super::InStateChasing(a_Dt, a_Chunk); if (m_Target != nullptr) { diff --git a/src/Mobs/AggressiveMonster.h b/src/Mobs/AggressiveMonster.h index 17539d39e..13f59842f 100644 --- a/src/Mobs/AggressiveMonster.h +++ b/src/Mobs/AggressiveMonster.h @@ -11,16 +11,16 @@ class cAggressiveMonster : public cMonster { typedef cMonster super; - + public: cAggressiveMonster(const AString & a_ConfigName, eMonsterType a_MobType, const AString & a_SoundHurt, const AString & a_SoundDeath, double a_Width, double a_Height); virtual void Tick (std::chrono::milliseconds a_Dt, cChunk & a_Chunk) override; - virtual void InStateChasing(std::chrono::milliseconds a_Dt) override; - + virtual void InStateChasing(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) override; + virtual void EventSeePlayer(cEntity *) override; - + /** Try to perform attack returns true if attack was deemed successful (hit player, fired projectile, creeper exploded, etc.) even if it didn't actually do damage return false if e.g. the mob is still in cooldown from a previous attack */ diff --git a/src/Mobs/CMakeLists.txt b/src/Mobs/CMakeLists.txt index 14c7a8ca3..4336af7c3 100644 --- a/src/Mobs/CMakeLists.txt +++ b/src/Mobs/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required (VERSION 2.6) -project (MCServer) +project (Cuberite) include_directories ("${PROJECT_SOURCE_DIR}/../") diff --git a/src/Mobs/Horse.cpp b/src/Mobs/Horse.cpp index f133f9912..01906b7b4 100644 --- a/src/Mobs/Horse.cpp +++ b/src/Mobs/Horse.cpp @@ -72,7 +72,7 @@ void cHorse::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) m_bIsTame = true; } } - + if (m_bIsRearing) { if (m_RearTickCount == 20) @@ -161,12 +161,12 @@ void cHorse::GetDrops(cItems & a_Drops, cEntity * a_Killer) -void cHorse::InStateIdle(std::chrono::milliseconds a_Dt) +void cHorse::InStateIdle(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) { // If horse is tame and someone is sitting on it, don't walk around if ((!m_bIsTame) || (m_Attachee == nullptr)) { - super::InStateIdle(a_Dt); + super::InStateIdle(a_Dt, a_Chunk); } } diff --git a/src/Mobs/Horse.h b/src/Mobs/Horse.h index c87d437c9..7afa5bf29 100644 --- a/src/Mobs/Horse.h +++ b/src/Mobs/Horse.h @@ -11,14 +11,14 @@ class cHorse : public cPassiveMonster { typedef cPassiveMonster super; - + public: cHorse(int Type, int Color, int Style, int TameTimes); CLASS_PROTODEF(cHorse) - + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; - virtual void InStateIdle(std::chrono::milliseconds a_Dt) override; + virtual void InStateIdle(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) override; virtual void HandleSpeedFromAttachee(float a_Forward, float a_Sideways) override; virtual void Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) override; virtual void OnRightClicked(cPlayer & a_Player) override; diff --git a/src/Mobs/Monster.cpp b/src/Mobs/Monster.cpp index fa36285ba..7d8c3de02 100644 --- a/src/Mobs/Monster.cpp +++ b/src/Mobs/Monster.cpp @@ -133,9 +133,8 @@ void cMonster::MoveToWayPoint(cChunk & a_Chunk) { if (DoesPosYRequireJump(FloorC(m_NextWayPointPosition.y))) { - if ( - (IsOnGround() && (GetSpeedX() == 0.0f) && (GetSpeedY() == 0.0f)) // TODO water handling? - ) + if (((IsOnGround()) && (GetSpeed().SqrLength() == 0.0f)) || + (IsSwimming())) { m_bOnGround = false; m_JumpCoolDown = 20; @@ -303,18 +302,18 @@ void cMonster::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) case IDLE: { // If enemy passive we ignore checks for player visibility. - InStateIdle(a_Dt); + InStateIdle(a_Dt, a_Chunk); break; } case CHASING: { // If we do not see a player anymore skip chasing action. - InStateChasing(a_Dt); + InStateChasing(a_Dt, a_Chunk); break; } case ESCAPING: { - InStateEscaping(a_Dt); + InStateEscaping(a_Dt, a_Chunk); break; } case ATTACKING: break; @@ -377,7 +376,7 @@ void cMonster::SetPitchAndYawFromDestination(bool a_IsFollowingPath) double HeadRotation, HeadPitch; HeadDistance.Normalize(); VectorToEuler(HeadDistance.x, HeadDistance.y, HeadDistance.z, HeadRotation, HeadPitch); - if (std::abs(BodyRotation - HeadRotation) < 90) + if ((std::abs(BodyRotation - HeadRotation) < 70) && (std::abs(HeadPitch) < 60)) { SetHeadYaw(HeadRotation); SetPitch(-HeadPitch); @@ -385,7 +384,7 @@ void cMonster::SetPitchAndYawFromDestination(bool a_IsFollowingPath) else { SetHeadYaw(BodyRotation); - SetPitch(-BodyPitch); + SetPitch(0); } } @@ -611,7 +610,7 @@ void cMonster::EventLosePlayer(void) -void cMonster::InStateIdle(std::chrono::milliseconds a_Dt) +void cMonster::InStateIdle(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) { if (m_PathfinderActivated) { @@ -632,9 +631,24 @@ void cMonster::InStateIdle(std::chrono::milliseconds a_Dt) if ((Dist.SqrLength() > 2) && (rem >= 3)) { - Vector3d Destination(GetPosX() + Dist.x, 0, GetPosZ() + Dist.z); - Destination.y = FindFirstNonAirBlockPosition(Destination.x, Destination.z); - MoveToPosition(Destination); + + Vector3d Destination(GetPosX() + Dist.x, GetPosition().y, GetPosZ() + Dist.z); + + cChunk * Chunk = a_Chunk.GetNeighborChunk(static_cast<int>(Destination.x), static_cast<int>(Destination.z)); + if ((Chunk == nullptr) || !Chunk->IsValid()) + { + return; + } + + BLOCKTYPE BlockType; + NIBBLETYPE BlockMeta; + int RelX = static_cast<int>(Destination.x) - Chunk->GetPosX() * cChunkDef::Width; + int RelZ = static_cast<int>(Destination.z) - Chunk->GetPosZ() * cChunkDef::Width; + Chunk->GetBlockTypeMeta(RelX, static_cast<int>(Destination.y) - 1, RelZ, BlockType, BlockMeta); + if (BlockType != E_BLOCK_STATIONARY_WATER) // Idle mobs shouldn't enter water on purpose + { + MoveToPosition(Destination); + } } } } @@ -645,7 +659,7 @@ void cMonster::InStateIdle(std::chrono::milliseconds a_Dt) // What to do if in Chasing State // This state should always be defined in each child class -void cMonster::InStateChasing(std::chrono::milliseconds a_Dt) +void cMonster::InStateChasing(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) { UNUSED(a_Dt); } @@ -655,7 +669,7 @@ void cMonster::InStateChasing(std::chrono::milliseconds a_Dt) // What to do if in Escaping State -void cMonster::InStateEscaping(std::chrono::milliseconds a_Dt) +void cMonster::InStateEscaping(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) { UNUSED(a_Dt); @@ -1084,6 +1098,19 @@ void cMonster::HandleDaylightBurning(cChunk & a_Chunk, bool WouldBurn) bool cMonster::WouldBurnAt(Vector3d a_Location, cChunk & a_Chunk) { + // If the Y coord is out of range, return the most logical result without considering anything else: + int RelY = FloorC(a_Location.y); + if (RelY < 0) + { + // Never burn under the world + return false; + } + if (RelY >= cChunkDef::Height) + { + // Always burn above the world + return true; + } + cChunk * Chunk = a_Chunk.GetNeighborChunk(FloorC(a_Location.x), FloorC(a_Location.z)); if ((Chunk == nullptr) || (!Chunk->IsValid())) { @@ -1091,14 +1118,13 @@ bool cMonster::WouldBurnAt(Vector3d a_Location, cChunk & a_Chunk) } int RelX = FloorC(a_Location.x) - Chunk->GetPosX() * cChunkDef::Width; - int RelY = FloorC(a_Location.y); int RelZ = FloorC(a_Location.z) - Chunk->GetPosZ() * cChunkDef::Width; if ( (Chunk->GetSkyLight(RelX, RelY, RelZ) == 15) && // In the daylight (Chunk->GetBlock(RelX, RelY, RelZ) != E_BLOCK_SOULSAND) && // Not on soulsand - (GetWorld()->GetTimeOfDay() < (12000 + 1000)) && // It is nighttime - GetWorld()->IsWeatherSunnyAt(POSX_TOINT, POSZ_TOINT) // Not raining + (GetWorld()->GetTimeOfDay() < 12000 + 1000) && // Daytime + GetWorld()->IsWeatherSunnyAt(POSX_TOINT, POSZ_TOINT) // Not raining ) { return true; diff --git a/src/Mobs/Monster.h b/src/Mobs/Monster.h index 98b67f343..cc830a058 100644 --- a/src/Mobs/Monster.h +++ b/src/Mobs/Monster.h @@ -79,9 +79,9 @@ public: virtual void EventLosePlayer(void); virtual void CheckEventLostPlayer(void); - virtual void InStateIdle (std::chrono::milliseconds a_Dt); - virtual void InStateChasing (std::chrono::milliseconds a_Dt); - virtual void InStateEscaping(std::chrono::milliseconds a_Dt); + virtual void InStateIdle (std::chrono::milliseconds a_Dt, cChunk & a_Chunk); + virtual void InStateChasing (std::chrono::milliseconds a_Dt, cChunk & a_Chunk); + virtual void InStateEscaping(std::chrono::milliseconds a_Dt, cChunk & a_Chunk); int GetAttackRate() { return static_cast<int>(m_AttackRate); } void SetAttackRate(float a_AttackRate) { m_AttackRate = a_AttackRate; } @@ -193,7 +193,7 @@ protected: /** Returns if a monster can reach a given height by jumping. */ inline bool DoesPosYRequireJump(int a_PosY) { - return ((a_PosY > POSY_TOINT) && (a_PosY == POSY_TOINT + 1)); + return ((a_PosY > POSY_TOINT)); } /** Move in a straight line to the next waypoint in the path, will jump if needed. */ diff --git a/src/Mobs/Path.cpp b/src/Mobs/Path.cpp index 1c8a3657f..03f0ad31a 100644 --- a/src/Mobs/Path.cpp +++ b/src/Mobs/Path.cpp @@ -7,6 +7,8 @@ #include "../Chunk.h" #define JUMP_G_COST 20 +#define NORMAL_G_COST 10 +#define DIAGONAL_G_COST 14 #define DISTANCE_MANHATTAN 0 // 1: More speed, a bit less accuracy 0: Max accuracy, less speed. #define HEURISTICS_ONLY 0 // 1: Much more speed, much less accurate. @@ -30,8 +32,7 @@ bool compareHeuristics::operator()(cPathCell * & a_Cell1, cPathCell * & a_Cell2) cPath::cPath( cChunk & a_Chunk, const Vector3d & a_StartingPoint, const Vector3d & a_EndingPoint, int a_MaxSteps, - double a_BoundingBoxWidth, double a_BoundingBoxHeight, - int a_MaxUp, int a_MaxDown + double a_BoundingBoxWidth, double a_BoundingBoxHeight ) : m_StepsLeft(a_MaxSteps), m_IsValid(true), @@ -39,10 +40,8 @@ cPath::cPath( m_Chunk(&a_Chunk), m_BadChunkFound(false) { - // TODO: if src not walkable OR dest not walkable, then abort. - // Borrow a new "isWalkable" from ProcessIfWalkable, make ProcessIfWalkable also call isWalkable - a_BoundingBoxWidth = 1; // Treat all mobs width as 1 until physics is improved. This would also require changes to stepOnce to work. + a_BoundingBoxWidth = 1; // Treat all mobs width as 1 until physics is improved. m_BoundingBoxWidth = CeilC(a_BoundingBoxWidth); m_BoundingBoxHeight = CeilC(a_BoundingBoxHeight); @@ -57,7 +56,7 @@ cPath::cPath( m_Destination.y = FloorC(a_EndingPoint.y); m_Destination.z = FloorC(a_EndingPoint.z - HalfWidthInt); - if (!IsWalkable(m_Source)) + if (!IsWalkable(m_Source, m_Source)) { m_Status = ePathFinderStatus::PATH_NOT_FOUND; return; @@ -126,51 +125,6 @@ Vector3i cPath::AcceptNearbyPath() -bool cPath::IsSolid(const Vector3i & a_Location) -{ - ASSERT(m_Chunk != nullptr); - - if (!cChunkDef::IsValidHeight(a_Location.y)) - { - return false; - } - auto Chunk = m_Chunk->GetNeighborChunk(a_Location.x, a_Location.z); - if ((Chunk == nullptr) || !Chunk->IsValid()) - { - m_BadChunkFound = true; - return true; - } - m_Chunk = Chunk; - - BLOCKTYPE BlockType; - NIBBLETYPE BlockMeta; - int RelX = a_Location.x - m_Chunk->GetPosX() * cChunkDef::Width; - int RelZ = a_Location.z - m_Chunk->GetPosZ() * cChunkDef::Width; - - m_Chunk->GetBlockTypeMeta(RelX, a_Location.y, RelZ, BlockType, BlockMeta); - if ( - (BlockType == E_BLOCK_FENCE) || - (BlockType == E_BLOCK_OAK_FENCE_GATE) || - (BlockType == E_BLOCK_NETHER_BRICK_FENCE) || - (BlockType == E_BLOCK_COBBLESTONE_WALL) || - ((BlockType >= E_BLOCK_SPRUCE_FENCE_GATE) && (BlockType <= E_BLOCK_ACACIA_FENCE)) - ) - { - // TODO move this out of IsSolid to a proper place. - GetCell(a_Location + Vector3i(0, 1, 0))->m_IsSolid = true; // Mobs will always think that the fence is 2 blocks high and therefore won't jump over. - } - if (BlockType == E_BLOCK_STATIONARY_WATER) - { - GetCell(a_Location + Vector3i(0, -1, 0))->m_IsSolid = true; - } - - return cBlockInfo::IsSolid(BlockType); -} - - - - - bool cPath::StepOnce() { cPathCell * CurrentCell = OpenListPop(); @@ -209,40 +163,47 @@ bool cPath::StepOnce() // Now we start checking adjacent cells. - bool done_east = false, - done_west = false, - done_north = false, - done_south = false; // If true, no need to do more checks in that direction + // If true, no need to do more checks in that direction + bool DoneEast = false, + DoneWest = false, + DoneNorth = false, + DoneSouth = false; + + // If true, we can walk in that direction without changing height + // This is used for deciding if to calculate diagonals + bool WalkableEast = false, + WalkableWest = false, + WalkableNorth = false, + WalkableSouth = false; // If we can jump without hitting the ceiling - if (BodyFitsIn(CurrentCell->m_Location + Vector3i(0, 1, 0))) + if (BodyFitsIn(CurrentCell->m_Location + Vector3i(0, 1, 0), CurrentCell->m_Location)) { + // For ladder climbing + ProcessIfWalkable(CurrentCell->m_Location + Vector3i(0, 1, 0), CurrentCell, JUMP_G_COST); + // Check east-up - if (GetCell(CurrentCell->m_Location + Vector3i(1, 0, 0))->m_IsSolid) + if (ProcessIfWalkable(CurrentCell->m_Location + Vector3i(1, 1, 0), CurrentCell, JUMP_G_COST)) { - ProcessIfWalkable(CurrentCell->m_Location + Vector3i(1, 1, 0), CurrentCell, JUMP_G_COST); - done_east = true; + DoneEast = true; } // Check west-up - if (GetCell(CurrentCell->m_Location + Vector3i(-1, 0, 0))->m_IsSolid) + if (ProcessIfWalkable(CurrentCell->m_Location + Vector3i(-1, 1, 0), CurrentCell, JUMP_G_COST)) { - ProcessIfWalkable(CurrentCell->m_Location + Vector3i(-1, 1, 0), CurrentCell, JUMP_G_COST); - done_west = true; + DoneWest = true; } // Check north-up - if (GetCell(CurrentCell->m_Location + Vector3i(0, 0, -1))->m_IsSolid) + if (ProcessIfWalkable(CurrentCell->m_Location + Vector3i(0, 1, -1), CurrentCell, JUMP_G_COST)) { - ProcessIfWalkable(CurrentCell->m_Location + Vector3i(0, 1, -1), CurrentCell, JUMP_G_COST); - done_north = true; + DoneNorth = true; } // Check south-up - if (GetCell(CurrentCell->m_Location + Vector3i(0, 0, 1))->m_IsSolid) + if (ProcessIfWalkable(CurrentCell->m_Location + Vector3i(0, 1, 1), CurrentCell, JUMP_G_COST)) { - ProcessIfWalkable(CurrentCell->m_Location + Vector3i(0, 1, 1), CurrentCell, JUMP_G_COST); - done_south = true; + DoneSouth = true; } } @@ -251,72 +212,87 @@ bool cPath::StepOnce() // Check North, South, East, West at our own height or below. We are willing to jump up to 3 blocks down. - if (!done_east) + if (!DoneEast) { - for (int i = 0; i >= -3; --i) + for (int y = 0; y >= -3; --y) { - if (ProcessIfWalkable(CurrentCell->m_Location + Vector3i(1, i, 0), CurrentCell, 10)) + if (ProcessIfWalkable(CurrentCell->m_Location + Vector3i(1, y, 0), CurrentCell, NORMAL_G_COST)) { - done_east = true; + DoneEast = true; + if (y == 0) + { + WalkableEast = true; + } break; } } } - if (!done_west) + if (!DoneWest) { - for (int i = 0; i >= -3; --i) + for (int y = 0; y >= -3; --y) { - if (ProcessIfWalkable(CurrentCell->m_Location + Vector3i(-1, i, 0), CurrentCell, 10)) + if (ProcessIfWalkable(CurrentCell->m_Location + Vector3i(-1, y, 0), CurrentCell, NORMAL_G_COST)) { - done_west = true; + DoneWest = true; + if (y == 0) + { + WalkableWest = true; + } break; } } } - if (!done_south) + if (!DoneSouth) { - for (int i = 0; i >= -3; --i) + for (int y = 0; y >= -3; --y) { - if (ProcessIfWalkable(CurrentCell->m_Location + Vector3i(0, i, 1), CurrentCell, 10)) + if (ProcessIfWalkable(CurrentCell->m_Location + Vector3i(0, y, 1), CurrentCell, NORMAL_G_COST)) { - done_west = true; + DoneWest = true; + if (y == 0) + { + WalkableSouth = true; + } break; } } } - if (!done_north) + if (!DoneNorth) { - for (int i = 0; i >= -3; --i) + for (int y = 0; y >= -3; --y) { - if (ProcessIfWalkable(CurrentCell->m_Location + Vector3i(0, i, -1), CurrentCell, 10)) + if (ProcessIfWalkable(CurrentCell->m_Location + Vector3i(0, y, -1), CurrentCell, NORMAL_G_COST)) { - done_north = true; + DoneNorth = true; + if (y == 0) + { + WalkableNorth = true; + } break; } } } - // Check diagonals - - for (int x = -1; x <= 1; x += 2) + if (WalkableNorth && WalkableEast) { - for (int z = -1; z <= 1; z += 2) - { - // This condition prevents diagonal corner cutting. - if (!GetCell(CurrentCell->m_Location + Vector3i(x, 0, 0))->m_IsSolid && !GetCell(CurrentCell->m_Location + Vector3i(0, 0, z))->m_IsSolid) - { - // This prevents falling of "sharp turns" e.g. a 1x1x20 rectangle in the air which breaks in a right angle suddenly. - if (GetCell(CurrentCell->m_Location + Vector3i(x, -1, 0))->m_IsSolid && GetCell(CurrentCell->m_Location + Vector3i(0, -1, z))->m_IsSolid) - { - ProcessIfWalkable(CurrentCell->m_Location + Vector3i(x, 0, z), CurrentCell, 14); // 14 is a good enough approximation of sqrt(10 + 10). - } - } - } + ProcessIfWalkable(CurrentCell->m_Location + Vector3i(1, 0, -1), CurrentCell, DIAGONAL_G_COST); + } + if (WalkableNorth && WalkableWest) + { + ProcessIfWalkable(CurrentCell->m_Location + Vector3i(-1, 0, -1), CurrentCell, DIAGONAL_G_COST); + } + if (WalkableSouth && WalkableEast) + { + ProcessIfWalkable(CurrentCell->m_Location + Vector3i(1, 0, 1), CurrentCell, DIAGONAL_G_COST); + } + if (WalkableSouth && WalkableWest) + { + ProcessIfWalkable(CurrentCell->m_Location + Vector3i(-1, 0, 1), CurrentCell, DIAGONAL_G_COST); } return false; @@ -349,6 +325,12 @@ void cPath::BuildPath() cPathCell * CurrentCell = GetCell(m_Destination); while (CurrentCell->m_Parent != nullptr) { + // Waypoints are cylinders that start at some particular x, y, z and have infinite height. + // Submerging water waypoints allows swimming mobs to be able to touch them. + if (GetCell(CurrentCell->m_Location + Vector3i(0, -1, 0))->m_BlockType == E_BLOCK_STATIONARY_WATER) + { + CurrentCell->m_Location.y -= 30; + } m_PathPoints.push_back(CurrentCell->m_Location); // Populate the cPath with points. All midpoints are added. Destination is added. Source is excluded. CurrentCell = CurrentCell->m_Parent; } @@ -418,7 +400,7 @@ cPathCell * cPath::OpenListPop() // Popping from the open list also means addin bool cPath::ProcessIfWalkable(const Vector3i & a_Location, cPathCell * a_Parent, int a_Cost) { - if (IsWalkable(a_Location)) + if (IsWalkable(a_Location, a_Parent->m_Location)) { ProcessCell(GetCell(a_Location), a_Parent, a_Cost); return true; @@ -486,13 +468,72 @@ void cPath::ProcessCell(cPathCell * a_Cell, cPathCell * a_Caller, int a_GDelta) +void cPath::FillCellAttributes(cPathCell & a_Cell) +{ + const Vector3i & Location = a_Cell.m_Location; + + ASSERT(m_Chunk != nullptr); + + if (!cChunkDef::IsValidHeight(Location.y)) + { + // Players can't build outside the game height, so it must be air + a_Cell.m_IsSolid = false; + a_Cell.m_IsSpecial = false; + a_Cell.m_BlockType = E_BLOCK_AIR; + return; + } + auto Chunk = m_Chunk->GetNeighborChunk(Location.x, Location.z); + if ((Chunk == nullptr) || !Chunk->IsValid()) + { + m_BadChunkFound = true; + a_Cell.m_IsSolid = true; + a_Cell.m_IsSpecial = false; + a_Cell.m_BlockType = E_BLOCK_AIR; // m_BlockType is never used when m_IsSpecial is false, but it may be used if we implement dijkstra + return; + } + m_Chunk = Chunk; + + BLOCKTYPE BlockType; + NIBBLETYPE BlockMeta; + int RelX = Location.x - m_Chunk->GetPosX() * cChunkDef::Width; + int RelZ = Location.z - m_Chunk->GetPosZ() * cChunkDef::Width; + + m_Chunk->GetBlockTypeMeta(RelX, Location.y, RelZ, BlockType, BlockMeta); + a_Cell.m_BlockType = BlockType; + a_Cell.m_BlockMeta = BlockMeta; + + + if (BlockTypeIsSpecial(BlockType)) + { + a_Cell.m_IsSpecial = true; + a_Cell.m_IsSolid = true; // Specials are solids only from a certain direction. But their m_IsSolid is always true + } + else if ((a_Cell.m_BlockType == E_BLOCK_AIR) && IsBlockFence(GetCell(Location + Vector3i(0, -1, 0))->m_BlockType)) + { + // Air blocks with fences below them are consider Special Solids. That is, they sometimes behave as solids. + a_Cell.m_IsSpecial = true; + a_Cell.m_IsSolid = true; + } + else + { + + a_Cell.m_IsSpecial = false; + a_Cell.m_IsSolid = cBlockInfo::IsSolid(BlockType); + } + +} + + + + + cPathCell * cPath::GetCell(const Vector3i & a_Location) { // Create the cell in the hash table if it's not already there. if (m_Map.count(a_Location) == 0) // Case 1: Cell is not on any list. We've never checked this cell before. { m_Map[a_Location].m_Location = a_Location; - m_Map[a_Location].m_IsSolid = IsSolid(a_Location); + FillCellAttributes(m_Map[a_Location]); m_Map[a_Location].m_Status = eCellStatus::NOLIST; #ifdef COMPILING_PATHFIND_DEBUGGER #ifdef COMPILING_PATHFIND_DEBUGGER_MARK_UNCHECKED @@ -511,16 +552,16 @@ cPathCell * cPath::GetCell(const Vector3i & a_Location) -bool cPath::IsWalkable(const Vector3i & a_Location) +bool cPath::IsWalkable(const Vector3i & a_Location, const Vector3i & a_Source) { - return (HasSolidBelow(a_Location) && BodyFitsIn(a_Location)); + return (HasSolidBelow(a_Location) && BodyFitsIn(a_Location, a_Source)); } - -bool cPath::BodyFitsIn(const Vector3i & a_Location) +// We need the source because some special blocks are solid only from a certain direction e.g. doors +bool cPath::BodyFitsIn(const Vector3i & a_Location, const Vector3i & a_Source) { int x, y, z; for (y = 0; y < m_BoundingBoxHeight; ++y) @@ -529,9 +570,20 @@ bool cPath::BodyFitsIn(const Vector3i & a_Location) { for (z = 0; z < m_BoundingBoxWidth; ++z) { - if (GetCell(a_Location + Vector3i(x, y, z))->m_IsSolid) + cPathCell * CurrentCell = GetCell(a_Location + Vector3i(x, y, z)); + if (CurrentCell->m_IsSolid) { - return false; + if (CurrentCell->m_IsSpecial) + { + if (SpecialIsSolidFromThisDirection(CurrentCell->m_BlockType, CurrentCell->m_BlockMeta, a_Location - a_Source)) + { + return false; + } + } + else + { + return false; + } } } } @@ -543,6 +595,71 @@ bool cPath::BodyFitsIn(const Vector3i & a_Location) +bool cPath::BlockTypeIsSpecial(BLOCKTYPE a_Type) +{ + if (IsBlockFence(a_Type)) + { + return true; + } + + switch (a_Type) + { + case E_BLOCK_OAK_DOOR: + case E_BLOCK_DARK_OAK_DOOR: + case E_BLOCK_TRAPDOOR: + case E_BLOCK_WATER: + case E_BLOCK_STATIONARY_WATER: + { + return true; + } + default: + { + return false; + } + } +} + + + + + +bool cPath::SpecialIsSolidFromThisDirection(BLOCKTYPE a_Type, NIBBLETYPE a_Meta, const Vector3i & a_Direction) +{ + if (a_Direction == Vector3i(0, 0, 0)) + { + return false; + } + + + + switch (a_Type) + { + // Air is special only when above a fence + case E_BLOCK_AIR: + { + // Treat the air block as solid if the mob is going upward and trying to climb a fence + if (a_Direction.y > 0) + { + return true; + } + else + { + return false; + } + } + + // TODO Fill this with the other specials after physics is fixed + } + + + + return true; +} + + + + + bool cPath::HasSolidBelow(const Vector3i & a_Location) { int x, z; diff --git a/src/Mobs/Path.h b/src/Mobs/Path.h index ac71968bd..f51b7da77 100644 --- a/src/Mobs/Path.h +++ b/src/Mobs/Path.h @@ -7,6 +7,7 @@ enum class ePathFinderStatus; class cPath; */ + #include "../FastRandom.h" #ifdef COMPILING_PATHFIND_DEBUGGER /* Note: the COMPILING_PATHFIND_DEBUGGER flag is used by Native / WiseOldMan95 to debug @@ -19,22 +20,40 @@ class cPath; //fwd: ../Chunk.h class cChunk; + /* Various little structs and classes */ enum class ePathFinderStatus {CALCULATING, PATH_FOUND, PATH_NOT_FOUND, NEARBY_FOUND}; enum class eCellStatus {OPENLIST, CLOSEDLIST, NOLIST}; +/** The pathfinder has 3 types of cells (cPathCell). +1 - empty. m_IsSolid is false, m_IsSpecial is false. Air cells are always traversable by A*. +2 - occupied / solid. m_IsSolid is true, m_IsSpecial is false. Air cells are never traversable by A*. +3 - Special. m_IsSolid is true, m_IsSpecial is true. These cells are special: They may either behave as empty +or as occupied / solid, depending on the mob's direction of movement. For instance, an airblock above a fence is a special cell, +because when mobs attempt to travel to it by jumping, it acts as a solid. But when mobs fall and land on top of a fence, +it acts as air. Special cells include: Doors, ladders, trapdoors, water, gates. + +The main function which handles special blocks is SpecialIsSolidFromThisDirection. +This function receives a BlockType, a meta, and a direction of travel, +then it uses those 3 parameters to decide whether the special block should behave as a solid or as air in this +particular direction of travel. + +Currently, only fences and water are handled properly. The function always returns "true" (meaning: treat as occuiped/solid) for +the rest of the blocks. This will be fixed once the physics engine issues are fixed. */ struct cPathCell { Vector3i m_Location; // Location of the cell in the world. int m_F, m_G, m_H; // F, G, H as defined in regular A*. eCellStatus m_Status; // Which list is the cell in? Either non, open, or closed. cPathCell * m_Parent; // Cell's parent, as defined in regular A*. - bool m_IsSolid; // Is the cell an air or a solid? Partial solids are currently considered solids. + bool m_IsSolid; // Is the cell an air or a solid? Partial solids are considered solids. If m_IsSpecial is true, this is always true. + bool m_IsSpecial; // The cell is special - it acts as "solid" or "air" depending on direction, e.g. door or top of fence. + BLOCKTYPE m_BlockType; + NIBBLETYPE m_BlockMeta; }; - class compareHeuristics { public: @@ -48,32 +67,22 @@ public: class cPath { public: - /** Creates a pathfinder instance. A Mob will probably need a single pathfinder instance for its entire life. - - Note that if you have a man-sized mob (1x1x2, zombies, etc), you are advised to call this function without parameters - because the declaration might change in later version of the pathFinder, and a parameter-less call always assumes a man-sized mob. + /** Creates a pathfinder instance. + After calling this, you are expected to call CalculationStep() once per tick or once per several ticks + until it returns something other than CALCULATING. - If your mob is not man-sized, you are advised to use cPath(width, height), this would be compatible with future versions, - but please be aware that as of now those parameters will be ignored and your mob will be assumed to be man sized. - - @param a_BoundingBoxWidth the character's boundingbox width in blocks. Currently the parameter is ignored and 1 is assumed. - @param a_BoundingBoxHeight the character's boundingbox width in blocks. Currently the parameter is ignored and 2 is assumed. - @param a_MaxUp the character's max jump height in blocks. Currently the parameter is ignored and 1 is assumed. - @param a_MaxDown How far is the character willing to fall? Currently the parameter is ignored and 1 is assumed. */ - /** Attempts to find a path starting from source to destination. - After calling this, you are expected to call Step() once per tick or once per several ticks until it returns true. You should then call getPath() to obtain the path. - Calling this before a path is found resets the current path and starts another search. @param a_StartingPoint The function expects this position to be the lowest block the mob is in, a rule of thumb: "The block where the Zombie's knees are at". @param a_EndingPoint "The block where the Zombie's knees want to be". - @param a_MaxSteps The maximum steps before giving up. */ + @param a_MaxSteps The maximum steps before giving up. + @param a_BoundingBoxWidth the character's boundingbox width in blocks. Currently the parameter is ignored and 1 is assumed. + @param a_BoundingBoxHeight the character's boundingbox width in blocks. Currently the parameter is ignored and 2 is assumed. */ cPath( cChunk & a_Chunk, const Vector3d & a_StartingPoint, const Vector3d & a_EndingPoint, int a_MaxSteps, - double a_BoundingBoxWidth, double a_BoundingBoxHeight, - int a_MaxUp = 1, int a_MaxDown = 1 + double a_BoundingBoxWidth, double a_BoundingBoxHeight ); - /** Creates a dummy path which does nothing except returning false when isValid is called. */ + /** Creates an invalid path which is not usable. You shouldn't call any method other than isValid on such a path. */ cPath(); /** delete default constructors */ @@ -84,9 +93,11 @@ public: cPath & operator=(cPath && a_other) = delete; /** Performs part of the path calculation and returns the appropriate status. + If PATH_FOUND is returned, the path was found, and you can call query the instance for waypoints via GetNextWayPoint, etc. If NEARBY_FOUND is returned, it means that the destination is not reachable, but a nearby destination is reachable. If the user likes the alternative destination, they can call AcceptNearbyPath to treat the path as found, - and to make consequent calls to step return PATH_FOUND */ + and to make consequent calls to step return PATH_FOUND + If PATH_NOT_FOUND is returned, then no path was found. */ ePathFinderStatus CalculationStep(cChunk & a_Chunk); /** Called after the PathFinder's step returns NEARBY_FOUND. @@ -142,7 +153,6 @@ public: private: /* General */ - bool IsSolid(const Vector3i & a_Location); // Query our hosting world and ask it if there's a solid at a_location. bool StepOnce(); // The public version just calls this version * CALCULATIONS_PER_CALL times. void FinishCalculation(); // Clears the memory used for calculating the path. void FinishCalculation(ePathFinderStatus a_NewStatus); // Clears the memory used for calculating the path and changes the status. @@ -152,7 +162,7 @@ private: /* Openlist and closedlist management */ void OpenListAdd(cPathCell * a_Cell); cPathCell * OpenListPop(); - bool ProcessIfWalkable(const Vector3i &a_Location, cPathCell * a_Parent, int a_Cost); + bool ProcessIfWalkable(const Vector3i & a_Location, cPathCell * a_Source, int a_Cost); /* Map management */ void ProcessCell(cPathCell * a_Cell, cPathCell * a_Caller, int a_GDelta); @@ -179,12 +189,15 @@ private: std::vector<Vector3i> m_PathPoints; /* Interfacing with the world */ + void FillCellAttributes(cPathCell & a_Cell); // Query our hosting world and fill the cell with info cChunk * m_Chunk; // Only valid inside Step()! bool m_BadChunkFound; /* High level world queries */ - bool IsWalkable(const Vector3i & a_Location); - bool BodyFitsIn(const Vector3i & a_Location); + bool IsWalkable(const Vector3i & a_Location, const Vector3i & a_Source); + bool BodyFitsIn(const Vector3i & a_Location, const Vector3i & a_Source); + bool BlockTypeIsSpecial(BLOCKTYPE a_Type); + bool SpecialIsSolidFromThisDirection(BLOCKTYPE a_Type, NIBBLETYPE a_Meta, const Vector3i & a_Direction); bool HasSolidBelow(const Vector3i & a_Location); #ifdef COMPILING_PATHFIND_DEBUGGER #include "../path_irrlicht.cpp" diff --git a/src/Mobs/PathFinder.cpp b/src/Mobs/PathFinder.cpp index bc79e2440..4b6e70bbd 100644 --- a/src/Mobs/PathFinder.cpp +++ b/src/Mobs/PathFinder.cpp @@ -32,12 +32,20 @@ ePathFinderStatus cPathFinder::GetNextWayPoint(cChunk & a_Chunk, const Vector3d } // Tweak the destination. If something is wrong with the destination or the chunk, rest for a while. - if (!EnsureProperDestination(a_Chunk)) + if (!(EnsureProperPoint(m_FinalDestination, a_Chunk) && EnsureProperPoint(m_Source, a_Chunk))) { m_NotFoundCooldown = 20; return ePathFinderStatus::PATH_NOT_FOUND; } + /* printf("%d %d %d -> %d %d %d\n", + static_cast<int>(m_Source.x), + static_cast<int>(m_Source.y), + static_cast<int>(m_Source.z), + static_cast<int>(m_FinalDestination.x), + static_cast<int>(m_FinalDestination.y), + static_cast<int>(m_FinalDestination.z)); */ + // Rest is over. Prepare m_Path by calling ResetPathFinding. if (m_NotFoundCooldown == 0) { @@ -83,7 +91,25 @@ ePathFinderStatus cPathFinder::GetNextWayPoint(cChunk & a_Chunk, const Vector3d { m_GiveUpCounter -= 1; - if ((m_GiveUpCounter == 0) || PathIsTooOld()) + if (m_GiveUpCounter == 0) + { + if (a_DontCare) + { + // We're having trouble reaching the next waypoint but the mob + // Doesn't care where to go, just tell him we got there ;) + m_FinalDestination = m_Source; + *a_Destination = m_FinalDestination; + ResetPathFinding(a_Chunk); + return ePathFinderStatus::CALCULATING; + } + else + { + ResetPathFinding(a_Chunk); + return ePathFinderStatus::CALCULATING; + } + } + + if (PathIsTooOld()) { ResetPathFinding(a_Chunk); return ePathFinderStatus::CALCULATING; @@ -153,9 +179,9 @@ void cPathFinder::ResetPathFinding(cChunk &a_Chunk) -bool cPathFinder::EnsureProperDestination(cChunk & a_Chunk) +bool cPathFinder::EnsureProperPoint(Vector3d & a_Vector, cChunk & a_Chunk) { - cChunk * Chunk = a_Chunk.GetNeighborChunk(FloorC(m_FinalDestination.x), FloorC(m_FinalDestination.z)); + cChunk * Chunk = a_Chunk.GetNeighborChunk(FloorC(a_Vector.x), FloorC(a_Vector.z)); BLOCKTYPE BlockType; NIBBLETYPE BlockMeta; @@ -164,14 +190,14 @@ bool cPathFinder::EnsureProperDestination(cChunk & a_Chunk) return false; } - int RelX = FloorC(m_FinalDestination.x) - Chunk->GetPosX() * cChunkDef::Width; - int RelZ = FloorC(m_FinalDestination.z) - Chunk->GetPosZ() * cChunkDef::Width; + int RelX = FloorC(a_Vector.x) - Chunk->GetPosX() * cChunkDef::Width; + int RelZ = FloorC(a_Vector.z) - Chunk->GetPosZ() * cChunkDef::Width; // If destination in the air, first try to go 1 block north, or east, or west. // This fixes the player leaning issue. // If that failed, we instead go down to the lowest air block. - Chunk->GetBlockTypeMeta(RelX, FloorC(m_FinalDestination.y) - 1, RelZ, BlockType, BlockMeta); - if (!cBlockInfo::IsSolid(BlockType)) + Chunk->GetBlockTypeMeta(RelX, FloorC(a_Vector.y) - 1, RelZ, BlockType, BlockMeta); + if (!(IsWaterOrSolid(BlockType))) { bool InTheAir = true; int x, z; @@ -183,18 +209,18 @@ bool cPathFinder::EnsureProperDestination(cChunk & a_Chunk) { continue; } - Chunk = a_Chunk.GetNeighborChunk(FloorC(m_FinalDestination.x+x), FloorC(m_FinalDestination.z+z)); + Chunk = a_Chunk.GetNeighborChunk(FloorC(a_Vector.x+x), FloorC(a_Vector.z+z)); if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } - RelX = FloorC(m_FinalDestination.x+x) - Chunk->GetPosX() * cChunkDef::Width; - RelZ = FloorC(m_FinalDestination.z+z) - Chunk->GetPosZ() * cChunkDef::Width; - Chunk->GetBlockTypeMeta(RelX, FloorC(m_FinalDestination.y) - 1, RelZ, BlockType, BlockMeta); - if (cBlockInfo::IsSolid(BlockType)) + RelX = FloorC(a_Vector.x+x) - Chunk->GetPosX() * cChunkDef::Width; + RelZ = FloorC(a_Vector.z+z) - Chunk->GetPosZ() * cChunkDef::Width; + Chunk->GetBlockTypeMeta(RelX, FloorC(a_Vector.y) - 1, RelZ, BlockType, BlockMeta); + if (IsWaterOrSolid((BlockType))) { - m_FinalDestination.x += x; - m_FinalDestination.z += z; + a_Vector.x += x; + a_Vector.z += z; InTheAir = false; goto breakBothLoops; } @@ -205,43 +231,28 @@ bool cPathFinder::EnsureProperDestination(cChunk & a_Chunk) // Go down to the lowest air block. if (InTheAir) { - while (m_FinalDestination.y > 0) + while (a_Vector.y > 0) { - Chunk->GetBlockTypeMeta(RelX, FloorC(m_FinalDestination.y) - 1, RelZ, BlockType, BlockMeta); - if (cBlockInfo::IsSolid(BlockType)) + Chunk->GetBlockTypeMeta(RelX, FloorC(a_Vector.y) - 1, RelZ, BlockType, BlockMeta); + if (IsWaterOrSolid(BlockType)) { break; } - m_FinalDestination.y -= 1; + a_Vector.y -= 1; } } } - // If destination in water, go up to the highest water block. - // If destination in solid, go up to first air block. - bool InWater = false; - while (m_FinalDestination.y < cChunkDef::Height) + // If destination in water or solid, go up to the first air block. + while (a_Vector.y < cChunkDef::Height) { - Chunk->GetBlockTypeMeta(RelX, FloorC(m_FinalDestination.y), RelZ, BlockType, BlockMeta); - if (BlockType == E_BLOCK_STATIONARY_WATER) - { - InWater = true; - } - else if (cBlockInfo::IsSolid(BlockType)) - { - InWater = false; - } - else + Chunk->GetBlockTypeMeta(RelX, FloorC(a_Vector.y), RelZ, BlockType, BlockMeta); + if (!IsWaterOrSolid(BlockType)) { break; } - m_FinalDestination.y += 1; + a_Vector.y += 1; } - if (InWater) - { - m_FinalDestination.y -= 1; - } - return true; } @@ -250,6 +261,15 @@ bool cPathFinder::EnsureProperDestination(cChunk & a_Chunk) +bool cPathFinder::IsWaterOrSolid(BLOCKTYPE a_BlockType) +{ + return ((a_BlockType == E_BLOCK_STATIONARY_WATER) || cBlockInfo::IsSolid(a_BlockType)); +} + + + + + bool cPathFinder::PathIsTooOld() const { size_t acceptableDeviation = m_Path->WayPointsLeft() / 2; diff --git a/src/Mobs/PathFinder.h b/src/Mobs/PathFinder.h index 312bb950c..1bdc13a32 100644 --- a/src/Mobs/PathFinder.h +++ b/src/Mobs/PathFinder.h @@ -3,16 +3,11 @@ #include "Path.h" #define WAYPOINT_RADIUS 0.5 -/* -TODO DOXY style -This class wraps cPath. +/** This class wraps cPath. cPath is a "dumb device" - You give it point A and point B, and it returns a full path path. cPathFinder - You give it a constant stream of point A (where you are) and point B (where you want to go), -and it tells you where to go next. It manages path recalculation internally, and is much more efficient that calling cPath every step. - -*/ - +and it tells you where to go next. It manages path recalculation internally, and is much more efficient that calling cPath every step. */ class cPathFinder { @@ -80,17 +75,18 @@ private: /** When a path is not found, this cooldown prevents any recalculations for several ticks. */ int m_NotFoundCooldown; - /** Ensures the destination is not buried underground or under water. Also ensures the destination is not in the air. - Only the Y coordinate of m_FinalDestination might be changed by this call. - 1. If m_FinalDestination is the position of a water block, m_FinalDestination's Y will be modified to point to the heighest water block in the pool in the current column. - 2. If m_FinalDestination is the position of a solid, m_FinalDestination's Y will be modified to point to the first airblock above the solid in the current column. - 3. If m_FinalDestination is the position of an air block, Y will keep decreasing until hitting either a solid or water. - Now either 1 or 2 is performed. */ - bool EnsureProperDestination(cChunk & a_Chunk); + /** Ensures the location is not in the air or under water. + May change the Y coordinate of the given vector. + 1. If a_Vector is the position of water, a_Vector's Y will be modified to point to the first air block above it. + 2. If a_Vector is the position of air, a_Vector's Y will be modified to point to the first airblock below it which has solid or water beneath. */ + bool EnsureProperPoint(Vector3d & a_Vector, cChunk & a_Chunk); /** Resets a pathfinding task, typically because m_FinalDestination has deviated too much from m_DeviationOrigin. */ void ResetPathFinding(cChunk &a_Chunk); + /** Return true the the blocktype is either water or solid */ + bool IsWaterOrSolid(BLOCKTYPE a_BlockType); + /** Is the path too old and should be recalculated? When this is true ResetPathFinding() is called. */ bool PathIsTooOld() const; }; diff --git a/src/Noise/CMakeLists.txt b/src/Noise/CMakeLists.txt index 39f3bc975..4e99347f8 100644 --- a/src/Noise/CMakeLists.txt +++ b/src/Noise/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required (VERSION 2.6) -project (MCServer) +project (Cuberite) include_directories ("${PROJECT_SOURCE_DIR}/../") diff --git a/src/OSSupport/CMakeLists.txt b/src/OSSupport/CMakeLists.txt index ce1d5c530..ee8067c6f 100644 --- a/src/OSSupport/CMakeLists.txt +++ b/src/OSSupport/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required (VERSION 2.6) -project (MCServer) +project (Cuberite) include_directories ("${PROJECT_SOURCE_DIR}/../") diff --git a/src/PolarSSL++/BlockingSslClientSocket.cpp b/src/PolarSSL++/BlockingSslClientSocket.cpp index e789b5374..61aee211d 100644 --- a/src/PolarSSL++/BlockingSslClientSocket.cpp +++ b/src/PolarSSL++/BlockingSslClientSocket.cpp @@ -70,7 +70,9 @@ class cBlockingSslClientSocketLinkCallbacks: { m_Socket.OnDisconnected(); } + public: + cBlockingSslClientSocketLinkCallbacks(cBlockingSslClientSocket & a_Socket): m_Socket(a_Socket) { @@ -143,7 +145,6 @@ bool cBlockingSslClientSocket::Connect(const AString & a_ServerName, UInt16 a_Po return false; } - m_IsConnected = true; return true; } @@ -182,7 +183,11 @@ bool cBlockingSslClientSocket::SetTrustedRootCertsFromString(const AString & a_C bool cBlockingSslClientSocket::Send(const void * a_Data, size_t a_NumBytes) { - ASSERT(m_IsConnected); + if (!m_IsConnected) + { + m_LastErrorText = "Socket is closed"; + return false; + } // Keep sending the data until all of it is sent: const char * Data = reinterpret_cast<const char *>(a_Data); @@ -216,8 +221,7 @@ bool cBlockingSslClientSocket::Send(const void * a_Data, size_t a_NumBytes) int cBlockingSslClientSocket::Receive(void * a_Data, size_t a_MaxBytes) { - ASSERT(m_IsConnected); - + // Even if m_IsConnected is false (socket disconnected), the SSL context may have more data in the queue int res = m_Ssl.ReadPlain(a_Data, a_MaxBytes); if (res < 0) { @@ -239,9 +243,16 @@ void cBlockingSslClientSocket::Disconnect(void) } m_Ssl.NotifyClose(); - m_Socket->Close(); - m_Socket.reset(); m_IsConnected = false; + + // Grab a copy of the socket so that we know it doesn't change under our hands: + auto socket = m_Socket; + if (socket != nullptr) + { + socket->Close(); + } + + m_Socket.reset(); } @@ -293,6 +304,7 @@ int cBlockingSslClientSocket::SendEncrypted(const unsigned char * a_Buffer, size + void cBlockingSslClientSocket::OnConnected(void) { m_IsConnected = true; @@ -305,7 +317,7 @@ void cBlockingSslClientSocket::OnConnected(void) void cBlockingSslClientSocket::OnConnectError(const AString & a_ErrorMsg) { - LOG("Cannot connect to %s: %s", m_ServerName.c_str(), a_ErrorMsg.c_str()); + LOG("Cannot connect to %s: \"%s\"", m_ServerName.c_str(), a_ErrorMsg.c_str()); m_Event.Set(); } @@ -337,8 +349,8 @@ void cBlockingSslClientSocket::SetLink(cTCPLinkPtr a_Link) void cBlockingSslClientSocket::OnDisconnected(void) { - m_Socket.reset(); m_IsConnected = false; + m_Socket.reset(); m_Event.Set(); } diff --git a/src/PolarSSL++/BlockingSslClientSocket.h b/src/PolarSSL++/BlockingSslClientSocket.h index 462ee95a7..3c61f7f89 100644 --- a/src/PolarSSL++/BlockingSslClientSocket.h +++ b/src/PolarSSL++/BlockingSslClientSocket.h @@ -9,6 +9,7 @@ #pragma once +#include <atomic> #include "OSSupport/Network.h" #include "CallbackSslContext.h" @@ -81,7 +82,7 @@ protected: AString m_LastErrorText; /** Set to true if the connection established successfully. */ - bool m_IsConnected; + std::atomic<bool> m_IsConnected; /** Protects m_IncomingData against multithreaded access. */ cCriticalSection m_CSIncomingData; diff --git a/src/PolarSSL++/CMakeLists.txt b/src/PolarSSL++/CMakeLists.txt index fddb37501..3f268ad13 100644 --- a/src/PolarSSL++/CMakeLists.txt +++ b/src/PolarSSL++/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required (VERSION 2.6) -project (MCServer) +project (Cuberite) include_directories ("${PROJECT_SOURCE_DIR}/../") diff --git a/src/Protocol/CMakeLists.txt b/src/Protocol/CMakeLists.txt index 58a69efbf..cd4f33c60 100644 --- a/src/Protocol/CMakeLists.txt +++ b/src/Protocol/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required (VERSION 2.6) -project (MCServer) +project (Cuberite) include_directories ("${PROJECT_SOURCE_DIR}/../") diff --git a/src/Protocol/MojangAPI.cpp b/src/Protocol/MojangAPI.cpp index dfbf9a568..0edb9f33e 100644 --- a/src/Protocol/MojangAPI.cpp +++ b/src/Protocol/MojangAPI.cpp @@ -748,7 +748,7 @@ void cMojangAPI::QueryNamesToUUIDs(AStringVector & a_NamesToQuery) Json::Reader reader; if (!reader.parse(Response, root, false) || !root.isArray()) { - LOGWARNING("%s failed: Cannot parse received data (NameToUUID) to JSON!", __FUNCTION__); + LOGWARNING("%s failed: Cannot parse received data (NameToUUID) to JSON: \"%s\"", __FUNCTION__, reader.getFormattedErrorMessages().c_str()); LOGD("Response body:\n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str()); continue; } @@ -861,7 +861,7 @@ void cMojangAPI::QueryUUIDToProfile(const AString & a_UUID) Json::Value root; if (!reader.parse(Response, root, false) || !root.isObject()) { - LOGWARNING("%s failed: Cannot parse received data (NameToUUID) to JSON!", __FUNCTION__); + LOGWARNING("%s failed: Cannot parse received data (NameToUUID) to JSON: \"%s\"", __FUNCTION__, reader.getFormattedErrorMessages().c_str()); LOGD("Response body:\n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str()); return; } diff --git a/src/Protocol/Protocol17x.cpp b/src/Protocol/Protocol17x.cpp index 010e1a8ba..1c8c81bbd 100644 --- a/src/Protocol/Protocol17x.cpp +++ b/src/Protocol/Protocol17x.cpp @@ -2784,7 +2784,7 @@ void cProtocol172::WriteBlockEntity(cPacketizer & a_Pkt, const cBlockEntity & a_ Writer.AddInt("z", MobHeadEntity.GetPosZ()); Writer.AddByte("SkullType", MobHeadEntity.GetType() & 0xFF); Writer.AddByte("Rot", MobHeadEntity.GetRotation() & 0xFF); - Writer.AddString("ExtraType", MobHeadEntity.GetOwner().c_str()); + Writer.AddString("ExtraType", MobHeadEntity.GetOwnerName()); Writer.AddString("id", "Skull"); // "Tile Entity ID" - MC wiki; vanilla server always seems to send this though break; } diff --git a/src/Protocol/Protocol18x.cpp b/src/Protocol/Protocol18x.cpp index ad2964bed..c80907ed8 100644 --- a/src/Protocol/Protocol18x.cpp +++ b/src/Protocol/Protocol18x.cpp @@ -1834,39 +1834,44 @@ void cProtocol180::AddReceivedData(const char * a_Data, size_t a_Size) } // Check packet for compression: - UInt32 CompressedSize = 0; + UInt32 UncompressedSize = 0; AString UncompressedData; if (m_State == 3) { UInt32 NumBytesRead = static_cast<UInt32>(m_ReceivedData.GetReadableSpace()); - m_ReceivedData.ReadVarInt(CompressedSize); - if (CompressedSize > PacketLen) + + if (!m_ReceivedData.ReadVarInt(UncompressedSize)) { - m_Client->Kick("Bad compression"); + m_Client->Kick("Compression packet incomplete"); return; } - if (CompressedSize > 0) + + NumBytesRead -= static_cast<UInt32>(m_ReceivedData.GetReadableSpace()); // How many bytes has the UncompressedSize taken up? + ASSERT(PacketLen > NumBytesRead); + PacketLen -= NumBytesRead; + + if (UncompressedSize > 0) { // Decompress the data: AString CompressedData; - if (!m_ReceivedData.ReadString(CompressedData, CompressedSize) || (InflateString(CompressedData.data(), CompressedSize, UncompressedData) != Z_OK)) + VERIFY(m_ReceivedData.ReadString(CompressedData, PacketLen)); + if (InflateString(CompressedData.data(), PacketLen, UncompressedData) != Z_OK) { m_Client->Kick("Compression failure"); return; } PacketLen = static_cast<UInt32>(UncompressedData.size()); - } - else - { - NumBytesRead -= static_cast<UInt32>(m_ReceivedData.GetReadableSpace()); // How many bytes has the CompressedSize taken up? - ASSERT(PacketLen > NumBytesRead); - PacketLen -= NumBytesRead; + if (PacketLen != UncompressedSize) + { + m_Client->Kick("Wrong uncompressed packet size given"); + return; + } } } // Move the packet payload to a separate cByteBuffer, bb: cByteBuffer bb(PacketLen + 1); - if (CompressedSize == 0) + if (UncompressedSize == 0) { // No compression was used, move directly VERIFY(m_ReceivedData.ReadToByteBuffer(bb, static_cast<size_t>(PacketLen))); @@ -1916,7 +1921,7 @@ void cProtocol180::AddReceivedData(const char * a_Data, size_t a_Size) bb.ReadAll(Packet); Packet.resize(Packet.size() - 1); // Drop the final NUL pushed there for over-read detection AString Out; - CreateHexDump(Out, Packet.data(), (int)Packet.size(), 24); + CreateHexDump(Out, Packet.data(), Packet.size(), 24); LOGD("Packet contents:\n%s", Out.c_str()); #endif // _DEBUG @@ -2145,7 +2150,7 @@ void cProtocol180::HandlePacketLoginEncryptionResponse(cByteBuffer & a_ByteBuffe // Decrypt EncNonce using privkey cRsaPrivateKey & rsaDecryptor = cRoot::Get()->GetServer()->GetPrivateKey(); - Int32 DecryptedNonce[MAX_ENC_LEN / sizeof(Int32)]; + UInt32 DecryptedNonce[MAX_ENC_LEN / sizeof(Int32)]; int res = rsaDecryptor.Decrypt(reinterpret_cast<const Byte *>(EncNonce.data()), EncNonce.size(), reinterpret_cast<Byte *>(DecryptedNonce), sizeof(DecryptedNonce)); if (res != 4) { @@ -3104,8 +3109,21 @@ void cProtocol180::WriteBlockEntity(cPacketizer & a_Pkt, const cBlockEntity & a_ Writer.AddInt("z", MobHeadEntity.GetPosZ()); Writer.AddByte("SkullType", MobHeadEntity.GetType() & 0xFF); Writer.AddByte("Rot", MobHeadEntity.GetRotation() & 0xFF); - Writer.AddString("ExtraType", MobHeadEntity.GetOwner().c_str()); Writer.AddString("id", "Skull"); // "Tile Entity ID" - MC wiki; vanilla server always seems to send this though + + // The new Block Entity format for a Mob Head. See: http://minecraft.gamepedia.com/Head#Block_entity + Writer.BeginCompound("Owner"); + Writer.AddString("Id", MobHeadEntity.GetOwnerUUID()); + Writer.AddString("Name", MobHeadEntity.GetOwnerName()); + Writer.BeginCompound("Properties"); + Writer.BeginList("textures", TAG_Compound); + Writer.BeginCompound(""); + Writer.AddString("Signature", MobHeadEntity.GetOwnerTextureSignature()); + Writer.AddString("Value", MobHeadEntity.GetOwnerTexture()); + Writer.EndCompound(); + Writer.EndList(); + Writer.EndCompound(); + Writer.EndCompound(); break; } diff --git a/src/RankManager.cpp b/src/RankManager.cpp index cbe9a85aa..922d9768e 100644 --- a/src/RankManager.cpp +++ b/src/RankManager.cpp @@ -2248,6 +2248,7 @@ void cRankManager::CreateDefaults(void) AddGroupToRank("Everything", "Admin"); // Add permissions to groups: + AddPermissionToGroup("core.help", "Default"); AddPermissionToGroup("core.build", "Default"); AddPermissionToGroup("core.teleport", "Teleport"); AddPermissionToGroup("core.kick", "Kick"); diff --git a/src/Resources/MCServer.rc b/src/Resources/Cuberite.rc index e0fbbea5d..779487458 100644 --- a/src/Resources/MCServer.rc +++ b/src/Resources/Cuberite.rc @@ -5,7 +5,7 @@ #include <windows.h> #include <commctrl.h> #include <richedit.h> -#include "resource_MCServer.h" +#include "resource_Cuberite.h" diff --git a/src/Resources/resource_MCServer.h b/src/Resources/resource_Cuberite.h index 42f6c4eaf..42f6c4eaf 100644 --- a/src/Resources/resource_MCServer.h +++ b/src/Resources/resource_Cuberite.h diff --git a/src/Root.cpp b/src/Root.cpp index 36fd067b3..dc00b5c82 100644 --- a/src/Root.cpp +++ b/src/Root.cpp @@ -752,10 +752,10 @@ bool cRoot::FindAndDoWithPlayer(const AString & a_PlayerName, cPlayerListCallbac } public: - cCallback (const AString & a_PlayerName) : + cCallback (const AString & a_CBPlayerName) : m_BestRating(0), - m_NameLength(a_PlayerName.length()), - m_PlayerName(a_PlayerName), + m_NameLength(a_CBPlayerName.length()), + m_PlayerName(a_CBPlayerName), m_BestMatch(), m_NumMatches(0) {} diff --git a/src/Simulator/CMakeLists.txt b/src/Simulator/CMakeLists.txt index a798e4b02..98b4499c7 100644 --- a/src/Simulator/CMakeLists.txt +++ b/src/Simulator/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required (VERSION 2.6) -project (MCServer) +project (Cuberite) include_directories ("${PROJECT_SOURCE_DIR}/../") diff --git a/src/Simulator/IncrementalRedstoneSimulator/CMakeLists.txt b/src/Simulator/IncrementalRedstoneSimulator/CMakeLists.txt index e37f3595c..87052d00a 100644 --- a/src/Simulator/IncrementalRedstoneSimulator/CMakeLists.txt +++ b/src/Simulator/IncrementalRedstoneSimulator/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required (VERSION 2.6) -project (MCServer) +project (Cuberite) include_directories ("${PROJECT_SOURCE_DIR}/../") diff --git a/src/Simulator/IncrementalRedstoneSimulator/IncrementalRedstoneSimulator.cpp b/src/Simulator/IncrementalRedstoneSimulator/IncrementalRedstoneSimulator.cpp index 95329f496..3c79d152b 100644 --- a/src/Simulator/IncrementalRedstoneSimulator/IncrementalRedstoneSimulator.cpp +++ b/src/Simulator/IncrementalRedstoneSimulator/IncrementalRedstoneSimulator.cpp @@ -159,12 +159,5 @@ void cIncrementalRedstoneSimulator::Simulate(float a_dt) { m_Data.GetActiveBlocks().emplace_back(CurrentLocation); } - - #ifdef _DEBUG - for (const auto & UpdateLocation : Updates) - { - LOGD("Queueing block for reupdate (%i %i %i)", UpdateLocation.x, UpdateLocation.y, UpdateLocation.z); - } - #endif } } diff --git a/src/Simulator/IncrementalRedstoneSimulator/RedstoneWireHandler.h b/src/Simulator/IncrementalRedstoneSimulator/RedstoneWireHandler.h index e196f51a1..e9543bb02 100644 --- a/src/Simulator/IncrementalRedstoneSimulator/RedstoneWireHandler.h +++ b/src/Simulator/IncrementalRedstoneSimulator/RedstoneWireHandler.h @@ -35,7 +35,8 @@ public: const cVector3iArray GetTerracingConnectionOffsets(const Vector3i & a_Position) { cVector3iArray RelativePositions; - bool IsYPTerracingBlocked = cBlockInfo::IsSolid(m_World.GetBlock(a_Position + OffsetYP())); + auto YPTerraceBlock = m_World.GetBlock(a_Position + OffsetYP()); + bool IsYPTerracingBlocked = cBlockInfo::IsSolid(YPTerraceBlock) && !cBlockInfo::IsTransparent(YPTerraceBlock); for (const auto & Adjacent : GetRelativeLaterals()) { @@ -46,9 +47,10 @@ public: { RelativePositions.emplace_back(Adjacent + OffsetYP()); } - + auto YMTerraceBlock = m_World.GetBlock(a_Position + Adjacent); if ( - !cBlockInfo::IsSolid(m_World.GetBlock(a_Position + Adjacent)) && // IsYMTerracingBlocked (i.e. check block above lower terracing position, a.k.a. just the plain adjacent) + // IsYMTerracingBlocked (i.e. check block above lower terracing position, a.k.a. just the plain adjacent) + (!cBlockInfo::IsSolid(YMTerraceBlock) || cBlockInfo::IsTransparent(YMTerraceBlock)) && (m_World.GetBlock(a_Position + Adjacent + OffsetYM()) == E_BLOCK_REDSTONE_WIRE) ) { diff --git a/src/UI/CMakeLists.txt b/src/UI/CMakeLists.txt index ad3c00f5f..6753c453e 100644 --- a/src/UI/CMakeLists.txt +++ b/src/UI/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required (VERSION 2.6) -project (MCServer) +project (Cuberite) include_directories ("${PROJECT_SOURCE_DIR}/../") diff --git a/src/World.cpp b/src/World.cpp index 904f5421b..7ac5af972 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -829,7 +829,7 @@ void cWorld::InitialiseGeneratorDefaults(cIniFile & a_IniFile) a_IniFile.GetValueSet("Generator", "HeightGen", "Flat"); a_IniFile.GetValueSet("Generator", "FlatHeight", "128"); a_IniFile.GetValueSet("Generator", "CompositionGen", "Nether"); - a_IniFile.GetValueSet("Generator", "Finishers", "SoulsandRims, WormNestCaves, BottomLava, LavaSprings, NetherClumpFoliage, NetherOreNests, PieceStructures: NetherForts, GlowStone, PreSimulator"); + a_IniFile.GetValueSet("Generator", "Finishers", "SoulsandRims, WormNestCaves, BottomLava, LavaSprings, NetherClumpFoliage, NetherOreNests, PieceStructures: NetherFort, GlowStone, PreSimulator"); a_IniFile.GetValueSet("Generator", "BottomLavaHeight", "30"); break; } diff --git a/src/WorldStorage/CMakeLists.txt b/src/WorldStorage/CMakeLists.txt index 2192564e8..1d8b60140 100644 --- a/src/WorldStorage/CMakeLists.txt +++ b/src/WorldStorage/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required (VERSION 2.6) -project (MCServer) +project (Cuberite) include_directories ("${PROJECT_SOURCE_DIR}/../") diff --git a/src/WorldStorage/NBTChunkSerializer.cpp b/src/WorldStorage/NBTChunkSerializer.cpp index b0451e427..3a0823491 100644 --- a/src/WorldStorage/NBTChunkSerializer.cpp +++ b/src/WorldStorage/NBTChunkSerializer.cpp @@ -358,7 +358,20 @@ void cNBTChunkSerializer::AddMobHeadEntity(cMobHeadEntity * a_MobHead) AddBasicTileEntity(a_MobHead, "Skull"); m_Writer.AddByte ("SkullType", a_MobHead->GetType() & 0xFF); m_Writer.AddByte ("Rot", a_MobHead->GetRotation() & 0xFF); - m_Writer.AddString("ExtraType", a_MobHead->GetOwner()); + + // The new Block Entity format for a Mob Head. See: http://minecraft.gamepedia.com/Head#Block_entity + m_Writer.BeginCompound("Owner"); + m_Writer.AddString("Id", a_MobHead->GetOwnerUUID()); + m_Writer.AddString("Name", a_MobHead->GetOwnerName()); + m_Writer.BeginCompound("Properties"); + m_Writer.BeginList("textures", TAG_Compound); + m_Writer.BeginCompound(""); + m_Writer.AddString("Signature", a_MobHead->GetOwnerTextureSignature()); + m_Writer.AddString("Value", a_MobHead->GetOwnerTexture()); + m_Writer.EndCompound(); + m_Writer.EndList(); + m_Writer.EndCompound(); + m_Writer.EndCompound(); m_Writer.EndCompound(); } diff --git a/src/WorldStorage/WSSAnvil.cpp b/src/WorldStorage/WSSAnvil.cpp index 5138717a7..3d325d354 100755 --- a/src/WorldStorage/WSSAnvil.cpp +++ b/src/WorldStorage/WSSAnvil.cpp @@ -1293,10 +1293,47 @@ cBlockEntity * cWSSAnvil::LoadMobHeadFromNBT(const cParsedNBT & a_NBT, int a_Tag MobHead->SetRotation(static_cast<eMobHeadRotation>(a_NBT.GetByte(currentLine))); } - currentLine = a_NBT.FindChildByName(a_TagIdx, "ExtraType"); - if (currentLine >= 0) + int ownerLine = a_NBT.FindChildByName(a_TagIdx, "Owner"); + if (ownerLine >= 0) { - MobHead->SetOwner(a_NBT.GetString(currentLine)); + AString OwnerName, OwnerUUID, OwnerTexture, OwnerTextureSignature; + + currentLine = a_NBT.FindChildByName(ownerLine, "Id"); + if (currentLine >= 0) + { + OwnerUUID = a_NBT.GetString(currentLine); + } + + currentLine = a_NBT.FindChildByName(ownerLine, "Name"); + if (currentLine >= 0) + { + OwnerName = a_NBT.GetString(currentLine); + } + + int textureLine = a_NBT.GetFirstChild( // The first texture of + a_NBT.FindChildByName( // The texture list of + a_NBT.FindChildByName( // The Properties compound of + ownerLine, // The Owner compound + "Properties" + ), + "textures" + ) + ); + if (textureLine >= 0) + { + currentLine = a_NBT.FindChildByName(textureLine, "Signature"); + if (currentLine >= 0) + { + OwnerTextureSignature = a_NBT.GetString(currentLine); + } + + currentLine = a_NBT.FindChildByName(textureLine, "Value"); + if (currentLine >= 0) + { + OwnerTexture = a_NBT.GetString(currentLine); + } + } + MobHead->SetOwner(OwnerUUID, OwnerName, OwnerTexture, OwnerTextureSignature); } return MobHead.release(); diff --git a/src/main.cpp b/src/main.cpp index aa21d8a31..06f979097 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -20,6 +20,15 @@ + +// Forward declarations to satisfy Clang's -Wmissing-variable-declarations: +extern bool g_ShouldLogCommIn; +extern bool g_ShouldLogCommOut; + + + + + /** If something has told the server to stop; checked periodically in cRoot */ bool cRoot::m_TerminateEventRaised = false; @@ -67,7 +76,8 @@ Synchronize this with Server.cpp to enable the "dumpmem" console command. */ -void NonCtrlHandler(int a_Signal) +#ifndef _DEBUG +static void NonCtrlHandler(int a_Signal) { LOGD("Terminate event raised from std::signal"); cRoot::Get()->QueueExecuteConsoleCommand("stop"); @@ -110,6 +120,7 @@ void NonCtrlHandler(int a_Signal) default: break; } } +#endif // _DEBUG @@ -129,11 +140,11 @@ typedef BOOL (WINAPI *pMiniDumpWriteDump)( PMINIDUMP_CALLBACK_INFORMATION CallbackParam ); -pMiniDumpWriteDump g_WriteMiniDump; // The function in dbghlp DLL that creates dump files +static pMiniDumpWriteDump g_WriteMiniDump; // The function in dbghlp DLL that creates dump files -wchar_t g_DumpFileName[MAX_PATH]; // Filename of the dump file; hes to be created before the dump handler kicks in -char g_ExceptionStack[128 * 1024]; // Substitute stack, just in case the handler kicks in because of "insufficient stack space" -MINIDUMP_TYPE g_DumpFlags = MiniDumpNormal; // By default dump only the stack and some helpers +static wchar_t g_DumpFileName[MAX_PATH]; // Filename of the dump file; hes to be created before the dump handler kicks in +static char g_ExceptionStack[128 * 1024]; // Substitute stack, just in case the handler kicks in because of "insufficient stack space" +static MINIDUMP_TYPE g_DumpFlags = MiniDumpNormal; // By default dump only the stack and some helpers @@ -142,7 +153,7 @@ MINIDUMP_TYPE g_DumpFlags = MiniDumpNormal; // By default dump only the stack a /** This function gets called just before the "program executed an illegal instruction and will be terminated" or similar. Its purpose is to create the crashdump using the dbghlp DLLs */ -LONG WINAPI LastChanceExceptionFilter(__in struct _EXCEPTION_POINTERS * a_ExceptionInfo) +static LONG WINAPI LastChanceExceptionFilter(__in struct _EXCEPTION_POINTERS * a_ExceptionInfo) { char * newStack = &g_ExceptionStack[sizeof(g_ExceptionStack) - 1]; char * oldStack; @@ -185,7 +196,7 @@ LONG WINAPI LastChanceExceptionFilter(__in struct _EXCEPTION_POINTERS * a_Except #ifdef _WIN32 // Handle CTRL events in windows, including console window close -BOOL CtrlHandler(DWORD fdwCtrlType) +static BOOL CtrlHandler(DWORD fdwCtrlType) { cRoot::Get()->QueueExecuteConsoleCommand("stop"); LOGD("Terminate event raised from the Windows CtrlHandler"); @@ -204,7 +215,7 @@ BOOL CtrlHandler(DWORD fdwCtrlType) //////////////////////////////////////////////////////////////////////////////// // UniversalMain - Main startup logic for both standard running and as a service -void UniversalMain(std::unique_ptr<cSettingsRepositoryInterface> a_OverridesRepo) +static void UniversalMain(std::unique_ptr<cSettingsRepositoryInterface> a_OverridesRepo) { // Initialize logging subsystem: cLogger::InitiateMultithreading(); @@ -242,7 +253,7 @@ void UniversalMain(std::unique_ptr<cSettingsRepositoryInterface> a_OverridesRepo //////////////////////////////////////////////////////////////////////////////// // serviceWorkerThread: Keep the service alive -DWORD WINAPI serviceWorkerThread(LPVOID lpParam) +static DWORD WINAPI serviceWorkerThread(LPVOID lpParam) { UNREFERENCED_PARAMETER(lpParam); @@ -262,7 +273,7 @@ DWORD WINAPI serviceWorkerThread(LPVOID lpParam) //////////////////////////////////////////////////////////////////////////////// // serviceSetState: Set the internal status of the service -void serviceSetState(DWORD acceptedControls, DWORD newState, DWORD exitCode) +static void serviceSetState(DWORD acceptedControls, DWORD newState, DWORD exitCode) { SERVICE_STATUS serviceStatus = {}; serviceStatus.dwCheckPoint = 0; @@ -285,7 +296,7 @@ void serviceSetState(DWORD acceptedControls, DWORD newState, DWORD exitCode) //////////////////////////////////////////////////////////////////////////////// // serviceCtrlHandler: Handle stop events from the Service Control Manager -void WINAPI serviceCtrlHandler(DWORD CtrlCode) +static void WINAPI serviceCtrlHandler(DWORD CtrlCode) { switch (CtrlCode) { @@ -308,7 +319,7 @@ void WINAPI serviceCtrlHandler(DWORD CtrlCode) //////////////////////////////////////////////////////////////////////////////// // serviceMain: Startup logic for running as a service -void WINAPI serviceMain(DWORD argc, TCHAR *argv[]) +static void WINAPI serviceMain(DWORD argc, TCHAR *argv[]) { wchar_t applicationFilename[MAX_PATH]; wchar_t applicationDirectory[MAX_PATH]; @@ -353,7 +364,7 @@ void WINAPI serviceMain(DWORD argc, TCHAR *argv[]) -std::unique_ptr<cMemorySettingsRepository> ParseArguments(int argc, char **argv) +static std::unique_ptr<cMemorySettingsRepository> ParseArguments(int argc, char ** argv) { try { @@ -434,7 +445,7 @@ std::unique_ptr<cMemorySettingsRepository> ParseArguments(int argc, char **argv) //////////////////////////////////////////////////////////////////////////////// // main: -int main(int argc, char **argv) +int main(int argc, char ** argv) { #if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER) InitLeakFinder(); diff --git a/tests/LoadablePieces/Stubs.cpp b/tests/LoadablePieces/Stubs.cpp index bd05d5ce7..5fbd7b599 100644 --- a/tests/LoadablePieces/Stubs.cpp +++ b/tests/LoadablePieces/Stubs.cpp @@ -1,8 +1,8 @@ // Stubs.cpp -// Implements stubs of various MCServer methods that are needed for linking but not for runtime -// This is required so that we don't bring in the entire MCServer via dependencies +// Implements stubs of various Cuberite methods that are needed for linking but not for runtime +// This is required so that we don't bring in the entire Cuberite via dependencies #include "Globals.h" #include "BlockInfo.h" diff --git a/tests/NoiseTest/GNUmakefile b/tests/NoiseTest/GNUmakefile index 15617b6ce..0ba473897 100644 --- a/tests/NoiseTest/GNUmakefile +++ b/tests/NoiseTest/GNUmakefile @@ -128,7 +128,7 @@ clean : ################################################### -# Build the parts of MCServer +# Build the parts of Cuberite # # options used: # -x c ... compile as C code |