root/trunk/src/game/World.cpp @ 44

Revision 44, 107.1 kB (checked in by yumileroy, 17 years ago)

[svn] * Merge Temp dev SVN with Assembla.
* Changes include:

  • Implementation of w12x's Outdoor PvP and Game Event Systems.
  • Temporary removal of IRC Chat Bot (until infinite loop when disabled is fixed).
  • All mangos -> trinity (to convert your mangos_string table, please run mangos_string_to_trinity_string.sql).
  • Improved Config cleanup.
  • And many more changes.

Original author: Seline
Date: 2008-10-14 11:57:03-05:00

Line 
1/*
2 * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
3 *
4 * Thanks to the original authors: MaNGOS <http://www.mangosproject.org/>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20
21/** \file
22    \ingroup world
23*/
24
25#include "Common.h"
26//#include "WorldSocket.h"
27#include "Database/DatabaseEnv.h"
28#include "Config/ConfigEnv.h"
29#include "SystemConfig.h"
30#include "Log.h"
31#include "Opcodes.h"
32#include "WorldSession.h"
33#include "WorldPacket.h"
34#include "Weather.h"
35#include "Player.h"
36#include "SkillExtraItems.h"
37#include "SkillDiscovery.h"
38#include "World.h"
39#include "ObjectMgr.h"
40#include "SpellMgr.h"
41#include "Chat.h"
42#include "Database/DBCStores.h"
43#include "LootMgr.h"
44#include "ItemEnchantmentMgr.h"
45#include "MapManager.h"
46#include "ScriptCalls.h"
47#include "CreatureAIRegistry.h"
48#include "Policies/SingletonImp.h"
49#include "BattleGroundMgr.h"
50#include "OutdoorPvPMgr.h"
51#include "TemporarySummon.h"
52#include "WaypointMovementGenerator.h"
53#include "VMapFactory.h"
54#include "GlobalEvents.h"
55#include "GameEvent.h"
56#include "Database/DatabaseImpl.h"
57#include "GridNotifiersImpl.h"
58#include "CellImpl.h"
59#include "InstanceSaveMgr.h"
60#include "WaypointManager.h"
61#include "Util.h"
62#include "Language.h"
63
64INSTANTIATE_SINGLETON_1( World );
65
66volatile bool World::m_stopEvent = false;
67volatile uint32 World::m_worldLoopCounter = 0;
68
69float World::m_MaxVisibleDistanceForCreature  = DEFAULT_VISIBILITY_DISTANCE;
70float World::m_MaxVisibleDistanceForPlayer    = DEFAULT_VISIBILITY_DISTANCE;
71float World::m_MaxVisibleDistanceForObject    = DEFAULT_VISIBILITY_DISTANCE;
72float World::m_MaxVisibleDistanceInFlight     = DEFAULT_VISIBILITY_DISTANCE;
73float World::m_VisibleUnitGreyDistance        = 0;
74float World::m_VisibleObjectGreyDistance      = 0;
75
76// ServerMessages.dbc
77enum ServerMessageType
78{
79    SERVER_MSG_SHUTDOWN_TIME      = 1,
80    SERVER_MSG_RESTART_TIME       = 2,
81    SERVER_MSG_STRING             = 3,
82    SERVER_MSG_SHUTDOWN_CANCELLED = 4,
83    SERVER_MSG_RESTART_CANCELLED  = 5
84};
85
86struct ScriptAction
87{
88    uint64 sourceGUID;
89    uint64 targetGUID;
90    uint64 ownerGUID;                                       // owner of source if source is item
91    ScriptInfo const* script;                               // pointer to static script data
92};
93
94/// World constructor
95World::World()
96{
97    m_playerLimit = 0;
98    m_allowMovement = true;
99    m_ShutdownMask = 0;
100    m_ShutdownTimer = 0;
101    m_gameTime=time(NULL);
102    m_startTime=m_gameTime;
103    m_maxActiveSessionCount = 0;
104    m_maxQueuedSessionCount = 0;
105    m_resultQueue = NULL;
106    m_NextDailyQuestReset = 0;
107
108    m_defaultDbcLocale = LOCALE_enUS;
109    m_availableDbcLocaleMask = 0;
110}
111
112/// World destructor
113World::~World()
114{
115    ///- Empty the kicked session set
116    for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
117        delete *itr;
118
119    m_kicked_sessions.clear();
120
121    ///- Empty the WeatherMap
122    for (WeatherMap::iterator itr = m_weathers.begin(); itr != m_weathers.end(); ++itr)
123        delete itr->second;
124
125    m_weathers.clear();
126
127    VMAP::VMapFactory::clear();
128
129    if(m_resultQueue) delete m_resultQueue;
130   
131    //TODO free addSessQueue
132}
133
134/// Find a player in a specified zone
135Player* World::FindPlayerInZone(uint32 zone)
136{
137    ///- circle through active sessions and return the first player found in the zone
138    SessionMap::iterator itr;
139    for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
140    {
141        if(!itr->second)
142            continue;
143        Player *player = itr->second->GetPlayer();
144        if(!player)
145            continue;
146        if( player->IsInWorld() && player->GetZoneId() == zone )
147        {
148            // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
149            return player;
150        }
151    }
152    return NULL;
153}
154
155/// Find a session by its id
156WorldSession* World::FindSession(uint32 id) const
157{
158    SessionMap::const_iterator itr = m_sessions.find(id);
159
160    if(itr != m_sessions.end())
161        return itr->second;                                 // also can return NULL for kicked session
162    else
163        return NULL;
164}
165
166/// Remove a given session
167bool World::RemoveSession(uint32 id)
168{
169    ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
170    SessionMap::iterator itr = m_sessions.find(id);
171
172    if(itr != m_sessions.end() && itr->second)
173    {
174        if (itr->second->PlayerLoading())
175            return false;
176        itr->second->KickPlayer();
177    }
178
179    return true;
180}
181
182void World::AddSession(WorldSession* s)
183{
184  addSessQueue.add(s);
185}
186
187void
188World::AddSession_ (WorldSession* s)
189{
190  ASSERT (s);
191
192  //NOTE - Still there is race condition in WorldSession* being used in the Sockets
193
194  ///- kick already loaded player with same account (if any) and remove session
195  ///- if player is in loading and want to load again, return
196  if (!RemoveSession (s->GetAccountId ()))
197    {
198      s->KickPlayer ();
199      m_kicked_sessions.insert (s);
200      return;
201    }
202
203  WorldSession* old = m_sessions[s->GetAccountId ()];
204  m_sessions[s->GetAccountId ()] = s;
205
206  // if session already exist, prepare to it deleting at next world update
207  // NOTE - KickPlayer() should be called on "old" in RemoveSession()
208  if (old)
209    m_kicked_sessions.insert (old);
210
211  uint32 Sessions = GetActiveAndQueuedSessionCount ();
212  uint32 pLimit = GetPlayerAmountLimit ();
213  uint32 QueueSize = GetQueueSize (); //number of players in the queue
214  bool inQueue = false;
215  //so we don't count the user trying to
216  //login as a session and queue the socket that we are using
217  --Sessions;
218
219  if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER )
220    {
221      AddQueuedPlayer (s);
222      UpdateMaxSessionCounters ();
223      sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize);
224      return;
225    }
226 
227  WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
228  packet << uint8 (AUTH_OK);
229  packet << uint32 (0); // unknown random value...
230  packet << uint8 (0);
231  packet << uint32 (0);
232  packet << uint8 (s->IsTBC () ? 1 : 0); // 0 - normal, 1 - TBC, must be set in database manually for each account
233  s->SendPacket (&packet);
234
235  UpdateMaxSessionCounters ();
236
237  // Updates the population
238  if (pLimit > 0)
239    {
240      float popu = GetActiveSessionCount (); //updated number of users on the server
241      popu /= pLimit;
242      popu *= 2;
243      loginDatabase.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu, realmID);
244      sLog.outDetail ("Server Population (%f).", popu);
245    }
246}
247
248int32 World::GetQueuePos(WorldSession* sess)
249{
250    uint32 position = 1;
251
252    for(Queue::iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
253        if((*iter) == sess)
254            return position;
255
256    return 0;
257}
258
259void World::AddQueuedPlayer(WorldSession* sess)
260{
261    m_QueuedPlayer.push_back (sess);
262   
263    // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
264    WorldPacket packet (SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
265    packet << uint8 (AUTH_WAIT_QUEUE);
266    packet << uint32 (0); // unknown random value...
267    packet << uint8 (0);
268    packet << uint32 (0);
269    packet << uint8 (sess->IsTBC () ? 1 : 0); // 0 - normal, 1 - TBC, must be set in database manually for each account
270    packet << uint32(GetQueuePos (sess));
271    sess->SendPacket (&packet);
272   
273    //sess->SendAuthWaitQue (GetQueuePos (sess));
274}
275
276void World::RemoveQueuedPlayer(WorldSession* sess)
277{
278    // sessions count including queued to remove (if removed_session set)
279    uint32 sessions = GetActiveSessionCount();
280
281    uint32 position = 1;
282    Queue::iterator iter = m_QueuedPlayer.begin();
283
284    // if session not queued then we need decrease sessions count (Remove socked callet before session removing from session list)
285    bool decrease_session = true;
286
287    // search to remove and count skipped positions
288    for(;iter != m_QueuedPlayer.end(); ++iter, ++position)
289    {
290        if(*iter==sess)
291        {
292            Queue::iterator iter2 = iter;
293            ++iter;
294            m_QueuedPlayer.erase(iter2);
295            decrease_session = false;                       // removing queued session
296            break;
297        }
298    }
299
300    // iter point to next socked after removed or end()
301    // position store position of removed socket and then new position next socket after removed
302
303    // decrease for case session queued for removing
304    if(decrease_session && sessions)
305        --sessions;
306
307    // accept first in queue
308    if( (!m_playerLimit || sessions < m_playerLimit) && !m_QueuedPlayer.empty() )
309    {
310        WorldSession * socket = m_QueuedPlayer.front();
311        socket->SendAuthWaitQue(0);
312        m_QueuedPlayer.pop_front();
313
314        // update iter to point first queued socket or end() if queue is empty now
315        iter = m_QueuedPlayer.begin();
316        position = 1;
317    }
318
319    // update position from iter to end()
320    // iter point to first not updated socket, position store new position
321    for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
322        (*iter)->SendAuthWaitQue(position);
323}
324
325/// Find a Weather object by the given zoneid
326Weather* World::FindWeather(uint32 id) const
327{
328    WeatherMap::const_iterator itr = m_weathers.find(id);
329
330    if(itr != m_weathers.end())
331        return itr->second;
332    else
333        return 0;
334}
335
336/// Remove a Weather object for the given zoneid
337void World::RemoveWeather(uint32 id)
338{
339    // not called at the moment. Kept for completeness
340    WeatherMap::iterator itr = m_weathers.find(id);
341
342    if(itr != m_weathers.end())
343    {
344        delete itr->second;
345        m_weathers.erase(itr);
346    }
347}
348
349/// Add a Weather object to the list
350Weather* World::AddWeather(uint32 zone_id)
351{
352    WeatherZoneChances const* weatherChances = objmgr.GetWeatherChances(zone_id);
353
354    // zone not have weather, ignore
355    if(!weatherChances)
356        return NULL;
357
358    Weather* w = new Weather(zone_id,weatherChances);
359    m_weathers[w->GetZone()] = w;
360    w->ReGenerate();
361    w->UpdateWeather();
362    return w;
363}
364
365/// Initialize config values
366void World::LoadConfigSettings(bool reload)
367{
368    if(reload)
369    {
370        if(!sConfig.Reload())
371        {
372            sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
373            return;
374        }
375        //TODO Check if config is outdated
376    }
377
378    ///- Read the player limit and the Message of the day from the config file
379    SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
380    SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
381
382    ///- Read all rates from the config file
383    rate_values[RATE_HEALTH]      = sConfig.GetFloatDefault("Rate.Health", 1);
384    if(rate_values[RATE_HEALTH] < 0)
385    {
386        sLog.outError("Rate.Health (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
387        rate_values[RATE_HEALTH] = 1;
388    }
389    rate_values[RATE_POWER_MANA]  = sConfig.GetFloatDefault("Rate.Mana", 1);
390    if(rate_values[RATE_POWER_MANA] < 0)
391    {
392        sLog.outError("Rate.Mana (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
393        rate_values[RATE_POWER_MANA] = 1;
394    }
395    rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
396    rate_values[RATE_POWER_RAGE_LOSS]   = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
397    if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
398    {
399        sLog.outError("Rate.Rage.Loss (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
400        rate_values[RATE_POWER_RAGE_LOSS] = 1;
401    }
402    rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
403    rate_values[RATE_LOYALTY]     = sConfig.GetFloatDefault("Rate.Loyalty", 1.0f);
404    rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
405    rate_values[RATE_DROP_ITEM_POOR]       = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
406    rate_values[RATE_DROP_ITEM_NORMAL]     = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
407    rate_values[RATE_DROP_ITEM_UNCOMMON]   = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
408    rate_values[RATE_DROP_ITEM_RARE]       = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
409    rate_values[RATE_DROP_ITEM_EPIC]       = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
410    rate_values[RATE_DROP_ITEM_LEGENDARY]  = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
411    rate_values[RATE_DROP_ITEM_ARTIFACT]   = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
412    rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
413    rate_values[RATE_DROP_MONEY]  = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
414    rate_values[RATE_XP_KILL]     = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
415    rate_values[RATE_XP_QUEST]    = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
416    rate_values[RATE_XP_EXPLORE]  = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
417    rate_values[RATE_XP_PAST_70]  = sConfig.GetFloatDefault("Rate.XP.PastLevel70", 1.0f);
418    rate_values[RATE_REPUTATION_GAIN]  = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
419    rate_values[RATE_CREATURE_NORMAL_DAMAGE]          = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
420    rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE]     = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
421    rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
422    rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
423    rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE]      = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
424    rate_values[RATE_CREATURE_NORMAL_HP]          = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
425    rate_values[RATE_CREATURE_ELITE_ELITE_HP]     = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
426    rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
427    rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
428    rate_values[RATE_CREATURE_ELITE_RARE_HP]      = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
429    rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE]          = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
430    rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE]     = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
431    rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
432    rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
433    rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE]      = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
434    rate_values[RATE_CREATURE_AGGRO]  = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
435    rate_values[RATE_REST_INGAME]                    = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
436    rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
437    rate_values[RATE_REST_OFFLINE_IN_WILDERNESS]     = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
438    rate_values[RATE_DAMAGE_FALL]  = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
439    rate_values[RATE_AUCTION_TIME]  = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
440    rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
441    rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
442    rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
443    rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
444    rate_values[RATE_MINING_NEXT]   = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
445    rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
446    rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
447    if(rate_values[RATE_TALENT] < 0.0f)
448    {
449        sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
450        rate_values[RATE_TALENT] = 1.0f;
451    }
452    rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
453
454    rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
455    if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
456    {
457        sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
458        rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
459    }
460    else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
461    {
462        sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
463        rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
464    }
465
466    rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
467    if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
468    {
469        sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
470        rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
471    }
472    rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
473    if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
474    {
475        sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
476        rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
477    }
478    rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
479    if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
480    {
481        sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
482        rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
483    }
484    rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
485    if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
486    {
487        sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
488        rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
489    }
490
491    ///- Read other configuration items from the config file
492
493    m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
494    if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
495    {
496        sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
497        m_configs[CONFIG_COMPRESSION] = 1;
498    }
499    m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
500    m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
501    m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 900000);
502
503    m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 300000);
504    if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
505    {
506        sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
507        m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
508    }
509    if(reload)
510        MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
511
512    m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
513    if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
514    {
515        sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
516        m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
517    }
518    if(reload)
519        MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
520
521    m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 600000);
522
523    if(reload)
524    {
525        uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
526        if(val!=m_configs[CONFIG_PORT_WORLD])
527            sLog.outError("WorldServerPort option can't be changed at Trinityd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
528    }
529    else
530        m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
531
532    if(reload)
533    {
534        uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
535        if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
536            sLog.outError("SocketSelectTime option can't be changed at Trinityd.conf reload, using current value (%u).",m_configs[DEFAULT_SOCKET_SELECT_TIME]);
537    }
538    else
539        m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
540
541
542    m_configs[CONFIG_TCP_NO_DELAY] = sConfig.GetBoolDefault("TcpNoDelay", false);
543    m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
544    /// \todo Add MonsterSight and GuarderSight (with meaning) in Trinityd.conf or put them as define
545    m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
546    m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
547
548    if(reload)
549    {
550        uint32 val = sConfig.GetIntDefault("GameType", 0);
551        if(val!=m_configs[CONFIG_GAME_TYPE])
552            sLog.outError("GameType option can't be changed at Trinityd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
553    }
554    else
555        m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
556
557    if(reload)
558    {
559        uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
560        if(val!=m_configs[CONFIG_REALM_ZONE])
561            sLog.outError("RealmZone option can't be changed at Trinityd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
562    }
563    else
564        m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
565
566    m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
567    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT]    = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
568    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
569    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP]   = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
570    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD]   = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
571    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION]   = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
572    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL]    = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
573    m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
574    m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
575    m_configs[CONFIG_STRICT_PLAYER_NAMES]  = sConfig.GetIntDefault("StrictPlayerNames",  0);
576    m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault("StrictCharterNames", 0);
577    m_configs[CONFIG_STRICT_PET_NAMES]     = sConfig.GetIntDefault("StrictPetNames",     0);
578
579    m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault("CharactersCreatingDisabled", 0);
580
581    m_configs[CONFIG_MAX_WHO] = sConfig.GetIntDefault("MaxWhoListReturns", 49);
582
583    m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
584    if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
585    {
586        sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
587        m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
588    }
589
590    // must be after CONFIG_CHARACTERS_PER_REALM
591    m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
592    if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
593    {
594        sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
595        m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
596    }
597
598    m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
599    if(m_configs[CONFIG_SKIP_CINEMATICS] < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
600    {
601        sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
602        m_configs[CONFIG_SKIP_CINEMATICS] = 0;
603    }
604
605
606    if(reload)
607    {
608        uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", 60);
609        if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
610            sLog.outError("MaxPlayerLevel option can't be changed at config reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
611    }
612    else
613        m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", 60);
614    if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > 255)
615    {
616        sLog.outError("MaxPlayerLevel (%i) must be in range 1..255. Set to 255.",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
617        m_configs[CONFIG_MAX_PLAYER_LEVEL] = 255;
618    }
619
620    m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
621    if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
622    {
623        sLog.outError("StartPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to 1.",m_configs[CONFIG_START_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
624        m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
625    }
626    else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
627    {
628        sLog.outError("StartPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to %u.",m_configs[CONFIG_START_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
629        m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
630    }
631    m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
632    m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
633
634    m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
635    m_configs[CONFIG_INSTANCE_IGNORE_RAID]  = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
636
637    m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER]              = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
638
639    m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
640    m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR]  = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
641    m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 1800000);
642
643    m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
644    m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
645    if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
646    {
647        sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.",m_configs[CONFIG_MIN_PETITION_SIGNS]);
648        m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
649    }
650
651    m_configs[CONFIG_GM_LOGIN_STATE]       = sConfig.GetIntDefault("GM.LoginState",2);
652    m_configs[CONFIG_GM_ACCEPT_TICKETS]    = sConfig.GetIntDefault("GM.AcceptTickets",2);
653    m_configs[CONFIG_GM_CHAT]              = sConfig.GetIntDefault("GM.Chat",2);
654    m_configs[CONFIG_GM_WISPERING_TO]      = sConfig.GetIntDefault("GM.WhisperingTo",2);
655
656    m_configs[CONFIG_GM_IN_GM_LIST]        = sConfig.GetBoolDefault("GM.InGMList",false);
657    m_configs[CONFIG_GM_IN_WHO_LIST]       = sConfig.GetBoolDefault("GM.InWhoList",false);
658    m_configs[CONFIG_GM_LOG_TRADE]         = sConfig.GetBoolDefault("GM.LogTrade", false);
659
660    m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
661
662    m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
663
664    m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
665    if(m_configs[CONFIG_UPTIME_UPDATE]<=0)
666    {
667        sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
668        m_configs[CONFIG_UPTIME_UPDATE] = 10;
669    }
670    if(reload)
671    {
672        m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
673        m_timers[WUPDATE_UPTIME].Reset();
674    }
675
676    m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
677    m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
678    m_configs[CONFIG_SKILL_CHANCE_GREEN]  = sConfig.GetIntDefault("SkillChance.Green",25);
679    m_configs[CONFIG_SKILL_CHANCE_GREY]   = sConfig.GetIntDefault("SkillChance.Grey",0);
680
681    m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS]  = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
682    m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS]   = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
683
684    m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
685
686    m_configs[CONFIG_SKILL_GAIN_CRAFTING]  = sConfig.GetIntDefault("SkillGain.Crafting", 1);
687    if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
688    {
689        sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
690        m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
691    }
692
693    m_configs[CONFIG_SKILL_GAIN_DEFENSE]  = sConfig.GetIntDefault("SkillGain.Defense", 1);
694    if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
695    {
696        sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
697        m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
698    }
699
700    m_configs[CONFIG_SKILL_GAIN_GATHERING]  = sConfig.GetIntDefault("SkillGain.Gathering", 1);
701    if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
702    {
703        sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
704        m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
705    }
706
707    m_configs[CONFIG_SKILL_GAIN_WEAPON]  = sConfig.GetIntDefault("SkillGain.Weapon", 1);
708    if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
709    {
710        sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
711        m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
712    }
713
714    m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
715    if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
716    {
717        sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
718        m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
719    }
720
721    m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
722    m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
723
724    if(reload)
725    {
726        uint32 val = sConfig.GetIntDefault("Expansion",1);
727        if(val!=m_configs[CONFIG_EXPANSION])
728            sLog.outError("Expansion option can't be changed at Trinityd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
729    }
730    else
731        m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
732
733    m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
734    m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
735    m_configs[CONFIG_CHATFLOOD_MUTE_TIME]     = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
736
737    m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
738
739    m_configs[CONFIG_CREATURE_FAMILY_ASSISTEMCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistenceRadius",10);
740
741    m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
742
743    // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level (255)
744    m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff",4);
745    if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > 255)
746        m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = 255;
747    m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff",7);
748    if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > 255)
749        m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = 255;
750
751    m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
752    m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
753
754    m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
755    m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
756
757    m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
758    m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
759    m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
760    m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
761    m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
762
763    m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault("Death.SicknessLevel", 11);
764    m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
765    m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
766
767    m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
768
769    // always use declined names in the russian client
770    m_configs[CONFIG_DECLINED_NAMES_USED] = 
771        (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
772
773    m_configs[CONFIG_LISTEN_RANGE_SAY]       = sConfig.GetIntDefault("ListenRange.Say", 25);
774    m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
775    m_configs[CONFIG_LISTEN_RANGE_YELL]      = sConfig.GetIntDefault("ListenRange.Yell", 300);
776
777    m_configs[CONFIG_PLAYER_START_GOLD] = sConfig.GetFloatDefault("PlayerStart.Gold", 0);
778    if(m_configs[CONFIG_PLAYER_START_GOLD] < 0)
779        m_configs[CONFIG_PLAYER_START_GOLD] = 0;
780
781    if(m_configs[CONFIG_PLAYER_START_GOLD] > MAX_MONEY_AMOUNT)
782        m_configs[CONFIG_PLAYER_START_GOLD] = MAX_MONEY_AMOUNT;
783
784    m_configs[CONFIG_PLAYER_START_HONOR] = sConfig.GetIntDefault("PlayerStart.HonorPoints", 0);
785    if(m_configs[CONFIG_PLAYER_START_HONOR] < 0)
786        m_configs[CONFIG_PLAYER_START_HONOR] = 0;
787
788    m_configs[CONFIG_PLAYER_START_ARENAPTS] = sConfig.GetIntDefault("PlayerStart.ArenaPoints", 0);
789    if(m_configs[CONFIG_PLAYER_START_ARENAPTS] < 0)
790        m_configs[CONFIG_PLAYER_START_ARENAPTS] = 0;
791
792    m_configs[CONFIG_GM_START_LEVEL] = sConfig.GetIntDefault("GamemasterStartLevel", 70);
793    if(m_configs[CONFIG_GM_START_LEVEL] < 1)
794        m_configs[CONFIG_GM_START_LEVEL] = 1;
795
796    m_configs[CONFIG_INSTANT_LOGOUT] = sConfig.GetBoolDefault("PlayerInstantLogout", false);
797    m_configs[CONFIG_BG_START_MUSIC] = sConfig.GetBoolDefault("MusicInBattleground", false);
798    m_configs[CONFIG_START_ALL_SPELLS] = sConfig.GetBoolDefault("PlayerStart.AllSpells", false);
799    m_configs[CONFIG_HONOR_AFTER_DUEL] = sConfig.GetIntDefault("HonorPointsAfterDuel", 0);
800    if(m_configs[CONFIG_HONOR_AFTER_DUEL] < 0)
801        m_configs[CONFIG_HONOR_AFTER_DUEL]= 0;
802    m_configs[CONFIG_START_ALL_EXPLORED] = sConfig.GetBoolDefault("PlayerStart.MapsExplored", false);
803    m_configs[CONFIG_DISABLE_BREATHING] = sConfig.GetBoolDefault("DisableWaterBreath", false);
804    m_configs[CONFIG_START_ALL_REP] = sConfig.GetBoolDefault("PlayerStart.AllReputation", false);
805    m_configs[CONFIG_ALWAYS_MAXSKILL] = sConfig.GetBoolDefault("AlwaysMaxWeaponSkill", false);
806    m_configs[CONFIG_START_ALL_TAXI] = sConfig.GetBoolDefault("PlayerStart.AllFlightPaths", false);
807    m_configs[CONFIG_PVP_TOKEN_ENABLE] = sConfig.GetBoolDefault("PvPToken.Enable", false);
808    m_configs[CONFIG_PVP_TOKEN_MAP_TYPE] = sConfig.GetIntDefault("PvPToken.MapAllowType", 4);
809    m_configs[CONFIG_PVP_TOKEN_ID] = sConfig.GetIntDefault("PvPToken.ItemID", 29434);
810    m_configs[CONFIG_PVP_TOKEN_COUNT] = sConfig.GetIntDefault("PvPToken.ItemCount", 1);
811    if(m_configs[CONFIG_PVP_TOKEN_COUNT] < 1)
812        m_configs[CONFIG_PVP_TOKEN_COUNT] = 1;
813    m_configs[CONFIG_NO_RESET_TALENT_COST] = sConfig.GetBoolDefault("NoResetTalentsCost", false);
814
815    m_configs[CONFIG_ARENA_MAX_RATING_DIFFERENCE] = sConfig.GetIntDefault("Arena.MaxRatingDifference", 0);
816    m_configs[CONFIG_ARENA_RATING_DISCARD_TIMER] = sConfig.GetIntDefault("Arena.RatingDiscardTimer",300000);
817    m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS] = sConfig.GetBoolDefault("Arena.AutoDistributePoints", false);
818    m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS] = sConfig.GetIntDefault("Arena.AutoDistributeInterval", 7);
819
820    m_configs[CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER] = sConfig.GetIntDefault("BattleGround.PrematureFinishTimer", 0);
821
822    m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
823    if(m_VisibleUnitGreyDistance >  MAX_VISIBILITY_DISTANCE)
824    {
825        sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
826        m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
827    }
828    m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
829    if(m_VisibleObjectGreyDistance >  MAX_VISIBILITY_DISTANCE)
830    {
831        sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
832        m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
833    }
834
835    m_MaxVisibleDistanceForCreature      = sConfig.GetFloatDefault("Visibility.Distance.Creature",     DEFAULT_VISIBILITY_DISTANCE);
836    if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
837    {
838        sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
839        m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
840    }
841    else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance >  MAX_VISIBILITY_DISTANCE)
842    {
843        sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
844        m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
845    }
846    m_MaxVisibleDistanceForPlayer        = sConfig.GetFloatDefault("Visibility.Distance.Player",       DEFAULT_VISIBILITY_DISTANCE);
847    if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
848    {
849        sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
850        m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
851    }
852    else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance >  MAX_VISIBILITY_DISTANCE)
853    {
854        sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
855        m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
856    }
857    m_MaxVisibleDistanceForObject    = sConfig.GetFloatDefault("Visibility.Distance.Gameobject",   DEFAULT_VISIBILITY_DISTANCE);
858    if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
859    {
860        sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
861        m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
862    }
863    else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance >  MAX_VISIBILITY_DISTANCE)
864    {
865        sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
866        m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
867    }
868    m_MaxVisibleDistanceInFlight    = sConfig.GetFloatDefault("Visibility.Distance.InFlight",      DEFAULT_VISIBILITY_DISTANCE);
869    if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
870    {
871        sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
872        m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
873    }
874
875    ///- Read the "Data" directory from the config file
876    std::string dataPath = sConfig.GetStringDefault("DataDir","./");
877    if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
878        dataPath.append("/");
879
880    if(reload)
881    {
882        if(dataPath!=m_dataPath)
883            sLog.outError("DataDir option can't be changed at Trinityd.conf reload, using current value (%s).",m_dataPath.c_str());
884    }
885    else
886    {
887        m_dataPath = dataPath;
888        sLog.outString("Using DataDir %s",m_dataPath.c_str());
889    }
890
891    std::string forbiddenmaps = sConfig.GetStringDefault("ForbiddenMaps", "");
892    char * forbiddenMaps = new char[forbiddenmaps.length() + 1];
893    forbiddenMaps[forbiddenmaps.length()] = 0;
894    strncpy(forbiddenMaps, forbiddenmaps.c_str(), forbiddenmaps.length());
895    const char * delim = ",";
896    char * token = strtok(forbiddenMaps, delim);
897    while(token != NULL)
898    {
899        int32 mapid = strtol(token, NULL, 10);
900        m_forbiddenMapIds.insert(mapid);
901        token = strtok(NULL,delim);
902    }
903    delete[] forbiddenMaps;
904
905    bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
906    bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
907    std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
908    std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
909    VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
910    VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
911    VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
912    VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
913    sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
914    sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
915    sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
916}
917
918/// Initialize the World
919void World::SetInitialWorldSettings()
920{
921    ///- Initialize the random number generator
922    srand((unsigned int)time(NULL));
923
924    ///- Initialize config settings
925    LoadConfigSettings();
926
927    ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
928    objmgr.SetHighestGuids();
929
930    ///- Check the existence of the map files for all races' startup areas.
931    if(   !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
932        ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
933        ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
934        ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
935        ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
936        ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
937        ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
938        ||m_configs[CONFIG_EXPANSION] && (
939        !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
940    {
941        sLog.outError("Correct *.map files not found in path '%smaps' or *.vmap/*vmdir files in '%svmaps'. Please place *.map/*.vmap/*.vmdir files in appropriate directories or correct the DataDir value in the Trinityd.conf file.",m_dataPath.c_str(),m_dataPath.c_str());
942        exit(1);
943    }
944
945    ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
946    sLog.outString( "" );
947    sLog.outString( "Loading Trinity strings..." );
948    if (!objmgr.LoadTrinityStrings())
949        exit(1);                                            // Error message displayed in function already
950
951    ///- Update the realm entry in the database with the realm type from the config file
952    //No SQL injection as values are treated as integers
953
954    // not send custom type REALM_FFA_PVP to realm list
955    uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
956    uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
957    loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
958
959    ///- Remove the bones after a restart
960    CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
961
962    ///- Load the DBC files
963    sLog.outString("Initialize data stores...");
964    LoadDBCStores(m_dataPath);
965    DetectDBCLang();
966
967    sLog.outString( "Loading InstanceTemplate" );
968    objmgr.LoadInstanceTemplate();
969
970    sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
971    spellmgr.LoadSkillLineAbilityMap();
972
973    ///- Clean up and pack instances
974    sLog.outString( "Cleaning up instances..." );
975    sInstanceSaveManager.CleanupInstances();                              // must be called before `creature_respawn`/`gameobject_respawn` tables
976
977    sLog.outString( "Packing instances..." );
978    sInstanceSaveManager.PackInstances();
979
980    sLog.outString( "Loading Localization strings..." );
981    objmgr.LoadCreatureLocales();
982    objmgr.LoadGameObjectLocales();
983    objmgr.LoadItemLocales();
984    objmgr.LoadQuestLocales();
985    objmgr.LoadNpcTextLocales();
986    objmgr.LoadPageTextLocales();
987    objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale());        // Get once for all the locale index of DBC language (console/broadcasts)
988
989    sLog.outString( "Loading Page Texts..." );
990    objmgr.LoadPageTexts();
991
992    sLog.outString( "Loading Game Object Templates..." );   // must be after LoadPageTexts
993    objmgr.LoadGameobjectInfo();
994
995    sLog.outString( "Loading Spell Chain Data..." );
996    spellmgr.LoadSpellChains();
997
998    sLog.outString( "Loading Spell Elixir types..." );
999    spellmgr.LoadSpellElixirs();
1000
1001    sLog.outString( "Loading Spell Learn Skills..." );
1002    spellmgr.LoadSpellLearnSkills();                        // must be after LoadSpellChains
1003
1004    sLog.outString( "Loading Spell Learn Spells..." );
1005    spellmgr.LoadSpellLearnSpells();
1006
1007    sLog.outString( "Loading Spell Proc Event conditions..." );
1008    spellmgr.LoadSpellProcEvents();
1009
1010    sLog.outString( "Loading Aggro Spells Definitions...");
1011    spellmgr.LoadSpellThreats();
1012
1013    sLog.outString( "Loading NPC Texts..." );
1014    objmgr.LoadGossipText();
1015
1016    sLog.outString( "Loading Item Random Enchantments Table..." );
1017    LoadRandomEnchantmentsTable();
1018
1019    sLog.outString( "Loading Items..." );                   // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1020    objmgr.LoadItemPrototypes();
1021
1022    sLog.outString( "Loading Item Texts..." );
1023    objmgr.LoadItemTexts();
1024
1025    sLog.outString( "Loading Creature Model Based Info Data..." );
1026    objmgr.LoadCreatureModelInfo();
1027
1028    sLog.outString( "Loading Equipment templates...");
1029    objmgr.LoadEquipmentTemplates();
1030
1031    sLog.outString( "Loading Creature templates..." );
1032    objmgr.LoadCreatureTemplates();
1033
1034    sLog.outString( "Loading SpellsScriptTarget...");
1035    spellmgr.LoadSpellScriptTarget();                       // must be after LoadCreatureTemplates and LoadGameobjectInfo
1036
1037    sLog.outString( "Loading Creature Reputation OnKill Data..." );
1038    objmgr.LoadReputationOnKill();
1039
1040    sLog.outString( "Loading Pet Create Spells..." );
1041    objmgr.LoadPetCreateSpells();
1042
1043    sLog.outString( "Loading Creature Data..." );
1044    objmgr.LoadCreatures();
1045
1046    sLog.outString( "Loading Creature Addon Data..." );
1047    objmgr.LoadCreatureAddons();                            // must be after LoadCreatureTemplates() and LoadCreatures()
1048
1049    sLog.outString( "Loading Creature Respawn Data..." );   // must be after PackInstances()
1050    objmgr.LoadCreatureRespawnTimes();
1051
1052    sLog.outString( "Loading Gameobject Data..." );
1053    objmgr.LoadGameobjects();
1054
1055    sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1056    objmgr.LoadGameobjectRespawnTimes();
1057
1058    sLog.outString( "Loading Game Event Data...");
1059    gameeventmgr.LoadFromDB();
1060
1061    sLog.outString( "Loading Weather Data..." );
1062    objmgr.LoadWeatherZoneChances();
1063
1064    sLog.outString( "Loading Quests..." );
1065    objmgr.LoadQuests();                                    // must be loaded after DBCs, creature_template, item_template, gameobject tables
1066
1067    sLog.outString( "Loading Quests Relations..." );
1068    objmgr.LoadQuestRelations();                            // must be after quest load
1069
1070    sLog.outString( "Loading AreaTrigger definitions..." );
1071    objmgr.LoadAreaTriggerTeleports();                      // must be after item template load
1072
1073    sLog.outString( "Loading Quest Area Triggers..." );
1074    objmgr.LoadQuestAreaTriggers();                         // must be after LoadQuests
1075
1076    sLog.outString( "Loading Tavern Area Triggers..." );
1077    objmgr.LoadTavernAreaTriggers();
1078   
1079    sLog.outString( "Loading AreaTrigger script names..." );
1080    objmgr.LoadAreaTriggerScripts();
1081
1082
1083    sLog.outString( "Loading Graveyard-zone links...");
1084    objmgr.LoadGraveyardZones();
1085
1086    sLog.outString( "Loading Spell target coordinates..." );
1087    spellmgr.LoadSpellTargetPositions();
1088
1089    sLog.outString( "Loading SpellAffect definitions..." );
1090    spellmgr.LoadSpellAffects();
1091
1092    sLog.outString( "Loading spell pet auras..." );
1093    spellmgr.LoadSpellPetAuras();
1094
1095    sLog.outString( "Loading player Create Info & Level Stats..." );
1096    objmgr.LoadPlayerInfo();
1097
1098    sLog.outString( "Loading Exploration BaseXP Data..." );
1099    objmgr.LoadExplorationBaseXP();
1100
1101    sLog.outString( "Loading Pet Name Parts..." );
1102    objmgr.LoadPetNames();
1103
1104    sLog.outString( "Loading the max pet number..." );
1105    objmgr.LoadPetNumber();
1106
1107    sLog.outString( "Loading pet level stats..." );
1108    objmgr.LoadPetLevelInfo();
1109
1110    sLog.outString( "Loading Player Corpses..." );
1111    objmgr.LoadCorpses();
1112
1113    sLog.outString( "Loading Loot Tables..." );
1114    LoadLootTables();
1115
1116    sLog.outString( "Loading Skill Discovery Table..." );
1117    LoadSkillDiscoveryTable();
1118
1119    sLog.outString( "Loading Skill Extra Item Table..." );
1120    LoadSkillExtraItemTable();
1121
1122    sLog.outString( "Loading Skill Fishing base level requirements..." );
1123    objmgr.LoadFishingBaseSkillLevel();
1124
1125    ///- Load dynamic data tables from the database
1126    sLog.outString( "Loading Auctions..." );
1127    objmgr.LoadAuctionItems();
1128    objmgr.LoadAuctions();
1129
1130    sLog.outString( "Loading Guilds..." );
1131    objmgr.LoadGuilds();
1132
1133    sLog.outString( "Loading ArenaTeams..." );
1134    objmgr.LoadArenaTeams();
1135
1136    sLog.outString( "Loading Groups..." );
1137    objmgr.LoadGroups();
1138
1139    sLog.outString( "Loading ReservedNames..." );
1140    objmgr.LoadReservedPlayersNames();
1141
1142    sLog.outString( "Loading GameObject for quests..." );
1143    objmgr.LoadGameObjectForQuests();
1144
1145    sLog.outString( "Loading BattleMasters..." );
1146    objmgr.LoadBattleMastersEntry();
1147
1148    sLog.outString( "Loading GameTeleports..." );
1149    objmgr.LoadGameTele();
1150
1151    sLog.outString( "Loading Npc Text Id..." );
1152    objmgr.LoadNpcTextId();                                 // must be after load Creature and NpcText
1153
1154    sLog.outString( "Loading vendors..." );
1155    objmgr.LoadVendors();                                   // must be after load CreatureTemplate and ItemTemplate
1156
1157    sLog.outString( "Loading trainers..." );
1158    objmgr.LoadTrainerSpell();                              // must be after load CreatureTemplate
1159
1160    sLog.outString( "Loading Waypoints..." );
1161    WaypointMgr.Load();
1162
1163    ///- Handle outdated emails (delete/return)
1164    sLog.outString( "Returning old mails..." );
1165    objmgr.ReturnOrDeleteOldMails(false);
1166
1167    ///- Load and initialize scripts
1168    sLog.outString( "Loading Scripts..." );
1169    objmgr.LoadQuestStartScripts();                         // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1170    objmgr.LoadQuestEndScripts();                           // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1171    objmgr.LoadSpellScripts();                              // must be after load Creature/Gameobject(Template/Data)
1172    objmgr.LoadGameObjectScripts();                         // must be after load Creature/Gameobject(Template/Data)
1173    objmgr.LoadEventScripts();                              // must be after load Creature/Gameobject(Template/Data)
1174
1175    sLog.outString( "Initializing Scripts..." );
1176    if(!LoadScriptingModule())
1177        exit(1);
1178
1179    ///- Initialize game time and timers
1180    sLog.outString( "DEBUG:: Initialize game time and timers" );
1181    m_gameTime = time(NULL);
1182    m_startTime=m_gameTime;
1183
1184    tm local;
1185    time_t curr;
1186    time(&curr);
1187    local=*(localtime(&curr));                              // dereference and assign
1188    char isoDate[128];
1189    sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1190        local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1191
1192    WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', %ld, 0)", isoDate, m_startTime );
1193
1194    m_timers[WUPDATE_OBJECTS].SetInterval(0);
1195    m_timers[WUPDATE_SESSIONS].SetInterval(0);
1196    m_timers[WUPDATE_WEATHERS].SetInterval(1000);
1197    m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*1000);    //set auction update interval to 1 minute
1198    m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
1199                                                            //Update "uptime" table based on configuration entry in minutes.
1200    m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*1000);  //erase corpses every 20 minutes
1201
1202    //to set mailtimer to return mails every day between 4 and 5 am
1203    //mailtimer is increased when updating auctions
1204    //one second is 1000 -(tested on win system)
1205    mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * 1000) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1206                                                            //1440
1207    mail_timer_expires = ( (DAY * 1000) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1208    sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1209
1210    ///- Initilize static helper structures
1211    AIRegistry::Initialize();
1212    WaypointMovementGenerator<Creature>::Initialize();
1213    Player::InitVisibleBits();
1214
1215    ///- Initialize MapManager
1216    sLog.outString( "Starting Map System" );
1217    MapManager::Instance().Initialize();
1218
1219    ///- Initialize Battlegrounds
1220    sLog.outString( "Starting BattleGround System" );
1221    sBattleGroundMgr.CreateInitialBattleGrounds();
1222    sBattleGroundMgr.InitAutomaticArenaPointDistribution();
1223
1224    ///- Initialize outdoor pvp
1225    sLog.outString( "Starting Outdoor PvP System" );
1226    sOutdoorPvPMgr.InitOutdoorPvP();
1227
1228    //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1229    sLog.outString( "Loading Transports..." );
1230    MapManager::Instance().LoadTransports();
1231
1232    sLog.outString("Deleting expired bans..." );
1233    loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1234
1235    sLog.outString("Calculate next daily quest reset time..." );
1236    InitDailyQuestResetTime();
1237
1238    sLog.outString("Starting Game Event system..." );
1239    uint32 nextGameEvent = gameeventmgr.Initialize();
1240    m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);    //depend on next event
1241
1242    sLog.outString( "WORLD: World initialized" );
1243}
1244void World::DetectDBCLang()
1245{
1246    uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1247
1248    if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1249    {
1250        sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1251        m_lang_confid = LOCALE_enUS;
1252    }
1253
1254    ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1255
1256    std::string availableLocalsStr;
1257
1258    int default_locale = MAX_LOCALE;
1259    for (int i = MAX_LOCALE-1; i >= 0; --i)
1260    {
1261        if ( strlen(race->name[i]) > 0)                     // check by race names
1262        {
1263            default_locale = i;
1264            m_availableDbcLocaleMask |= (1 << i);
1265            availableLocalsStr += localeNames[i];
1266            availableLocalsStr += " ";
1267        }
1268    }
1269
1270    if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1271        (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1272    {
1273        default_locale = m_lang_confid;
1274    }
1275
1276    if(default_locale >= MAX_LOCALE)
1277    {
1278        sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1279        exit(1);
1280    }
1281
1282    m_defaultDbcLocale = LocaleConstant(default_locale);
1283
1284    sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1285}
1286
1287/// Update the World !
1288void World::Update(time_t diff)
1289{
1290    ///- Update the different timers
1291    for(int i = 0; i < WUPDATE_COUNT; i++)
1292        if(m_timers[i].GetCurrent()>=0)
1293            m_timers[i].Update(diff);
1294    else m_timers[i].SetCurrent(0);
1295
1296    ///- Update the game time and check for shutdown time
1297    _UpdateGameTime();
1298
1299    /// Handle daily quests reset time
1300    if(m_gameTime > m_NextDailyQuestReset)
1301    {
1302        ResetDailyQuests();
1303        m_NextDailyQuestReset += DAY;
1304    }
1305
1306    /// <ul><li> Handle auctions when the timer has passed
1307    if (m_timers[WUPDATE_AUCTIONS].Passed())
1308    {
1309        m_timers[WUPDATE_AUCTIONS].Reset();
1310
1311        ///- Update mails (return old mails with item, or delete them)
1312        //(tested... works on win)
1313        if (++mail_timer > mail_timer_expires)
1314        {
1315            mail_timer = 0;
1316            objmgr.ReturnOrDeleteOldMails(true);
1317        }
1318
1319        AuctionHouseObject* AuctionMap;
1320        for (int i = 0; i < 3; i++)
1321        {
1322            switch (i)
1323            {
1324                case 0:
1325                    AuctionMap = objmgr.GetAuctionsMap( 6 );//horde
1326                    break;
1327                case 1:
1328                    AuctionMap = objmgr.GetAuctionsMap( 2 );//alliance
1329                    break;
1330                case 2:
1331                    AuctionMap = objmgr.GetAuctionsMap( 7 );//neutral
1332                    break;
1333            }
1334
1335            ///- Handle expired auctions
1336            AuctionHouseObject::AuctionEntryMap::iterator itr,next;
1337            for (itr = AuctionMap->GetAuctionsBegin(); itr != AuctionMap->GetAuctionsEnd();itr = next)
1338            {
1339                next = itr;
1340                ++next;
1341                if (m_gameTime > (itr->second->time))
1342                {
1343                    ///- Either cancel the auction if there was no bidder
1344                    if (itr->second->bidder == 0)
1345                    {
1346                        objmgr.SendAuctionExpiredMail( itr->second );
1347                    }
1348                    ///- Or perform the transaction
1349                    else
1350                    {
1351                        //we should send an "item sold" message if the seller is online
1352                        //we send the item to the winner
1353                        //we send the money to the seller
1354                        objmgr.SendAuctionSuccessfulMail( itr->second );
1355                        objmgr.SendAuctionWonMail( itr->second );
1356                    }
1357
1358                    ///- In any case clear the auction
1359                    //No SQL injection (Id is integer)
1360                    CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",itr->second->Id);
1361                    objmgr.RemoveAItem(itr->second->item_guidlow);
1362                    delete itr->second;
1363                    AuctionMap->RemoveAuction(itr->first);
1364                }
1365            }
1366        }
1367    }
1368
1369    /// <li> Handle session updates when the timer has passed
1370    if (m_timers[WUPDATE_SESSIONS].Passed())
1371    {
1372        m_timers[WUPDATE_SESSIONS].Reset();
1373
1374        UpdateSessions(diff);
1375    }
1376
1377    /// <li> Handle weather updates when the timer has passed
1378    if (m_timers[WUPDATE_WEATHERS].Passed())
1379    {
1380        m_timers[WUPDATE_WEATHERS].Reset();
1381
1382        ///- Send an update signal to Weather objects
1383        WeatherMap::iterator itr, next;
1384        for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1385        {
1386            next = itr;
1387            ++next;
1388
1389            ///- and remove Weather objects for zones with no player
1390                                                            //As interval > WorldTick
1391            if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1392            {
1393                delete itr->second;
1394                m_weathers.erase(itr);
1395            }
1396        }
1397    }
1398    /// <li> Update uptime table
1399    if (m_timers[WUPDATE_UPTIME].Passed())
1400    {
1401        uint32 tmpDiff = (m_gameTime - m_startTime);
1402        uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1403
1404        m_timers[WUPDATE_UPTIME].Reset();
1405        WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1406    }
1407
1408    /// <li> Handle all other objects
1409    if (m_timers[WUPDATE_OBJECTS].Passed())
1410    {
1411        m_timers[WUPDATE_OBJECTS].Reset();
1412        ///- Update objects when the timer has passed (maps, transport, creatures,...)
1413        MapManager::Instance().Update(diff);                // As interval = 0
1414
1415        ///- Process necessary scripts
1416        if (!m_scriptSchedule.empty())
1417            ScriptsProcess();
1418
1419        sBattleGroundMgr.Update(diff);
1420
1421        sOutdoorPvPMgr.Update(diff);
1422    }
1423
1424    // execute callbacks from sql queries that were queued recently
1425    UpdateResultQueue();
1426
1427    ///- Erase corpses once every 20 minutes
1428    if (m_timers[WUPDATE_CORPSES].Passed())
1429    {
1430        m_timers[WUPDATE_CORPSES].Reset();
1431
1432        CorpsesErase();
1433    }
1434
1435    ///- Process Game events when necessary
1436    if (m_timers[WUPDATE_EVENTS].Passed())
1437    {
1438        m_timers[WUPDATE_EVENTS].Reset();                   // to give time for Update() to be processed
1439        uint32 nextGameEvent = gameeventmgr.Update();
1440        m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1441        m_timers[WUPDATE_EVENTS].Reset();
1442    }
1443
1444    MapManager::Instance().DoDelayedMovesAndRemoves(); ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1445
1446    // update the instance reset times
1447    sInstanceSaveManager.Update();
1448
1449    // And last, but not least handle the issued cli commands
1450    ProcessCliCommands();
1451}
1452
1453void World::ForceGameEventUpdate()
1454{
1455    m_timers[WUPDATE_EVENTS].Reset();                   // to give time for Update() to be processed
1456    uint32 nextGameEvent = gameeventmgr.Update();
1457    m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1458    m_timers[WUPDATE_EVENTS].Reset();
1459}
1460
1461/// Put scripts in the execution queue
1462void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1463{
1464    ///- Find the script map
1465    ScriptMapMap::const_iterator s = scripts.find(id);
1466    if (s == scripts.end())
1467        return;
1468
1469    // prepare static data
1470    uint64 sourceGUID = source->GetGUID();
1471    uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1472    uint64 ownerGUID  = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1473
1474    ///- Schedule script execution for all scripts in the script map
1475    ScriptMap const *s2 = &(s->second);
1476    bool immedScript = false;
1477    for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1478    {
1479        ScriptAction sa;
1480        sa.sourceGUID = sourceGUID;
1481        sa.targetGUID = targetGUID;
1482        sa.ownerGUID  = ownerGUID;
1483
1484        sa.script = &iter->second;
1485        m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1486        if (iter->first == 0)
1487            immedScript = true;
1488    }
1489    ///- If one of the effects should be immediate, launch the script execution
1490    if (immedScript)
1491        ScriptsProcess();
1492}
1493
1494void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1495{
1496    // NOTE: script record _must_ exist until command executed
1497
1498    // prepare static data
1499    uint64 sourceGUID = source->GetGUID();
1500    uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1501    uint64 ownerGUID  = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1502
1503    ScriptAction sa;
1504    sa.sourceGUID = sourceGUID;
1505    sa.targetGUID = targetGUID;
1506    sa.ownerGUID  = ownerGUID;
1507
1508    sa.script = &script;
1509    m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1510
1511    ///- If effects should be immediate, launch the script execution
1512    if(delay == 0)
1513        ScriptsProcess();
1514}
1515
1516/// Process queued scripts
1517void World::ScriptsProcess()
1518{
1519    if (m_scriptSchedule.empty())
1520        return;
1521
1522    ///- Process overdue queued scripts
1523    std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1524                                                            // ok as multimap is a *sorted* associative container
1525    while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1526    {
1527        ScriptAction const& step = iter->second;
1528
1529        Object* source = NULL;
1530
1531        if(step.sourceGUID)
1532        {
1533            switch(GUID_HIPART(step.sourceGUID))
1534            {
1535                case HIGHGUID_ITEM:
1536                    // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1537                    {
1538                        Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1539                        if(player)
1540                            source = player->GetItemByGuid(step.sourceGUID);
1541                        break;
1542                    }
1543                case HIGHGUID_UNIT:
1544                    source = HashMapHolder<Creature>::Find(step.sourceGUID);
1545                    break;
1546                case HIGHGUID_PET:
1547                    source = HashMapHolder<Pet>::Find(step.sourceGUID);
1548                    break;
1549                case HIGHGUID_PLAYER:
1550                    source = HashMapHolder<Player>::Find(step.sourceGUID);
1551                    break;
1552                case HIGHGUID_GAMEOBJECT:
1553                    source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1554                    break;
1555                case HIGHGUID_CORPSE:
1556                    source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1557                    break;
1558                default:
1559                    sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1560                    break;
1561            }
1562        }
1563
1564        Object* target = NULL;
1565
1566        if(step.targetGUID)
1567        {
1568            switch(GUID_HIPART(step.targetGUID))
1569            {
1570                case HIGHGUID_UNIT:
1571                    target = HashMapHolder<Creature>::Find(step.targetGUID);
1572                    break;
1573                case HIGHGUID_PET:
1574                    target = HashMapHolder<Pet>::Find(step.targetGUID);
1575                    break;
1576                case HIGHGUID_PLAYER:                       // empty GUID case also
1577                    target = HashMapHolder<Player>::Find(step.targetGUID);
1578                    break;
1579                case HIGHGUID_GAMEOBJECT:
1580                    target = HashMapHolder<GameObject>::Find(step.targetGUID);
1581                    break;
1582                case HIGHGUID_CORPSE:
1583                    target = HashMapHolder<Corpse>::Find(step.targetGUID);
1584                    break;
1585                default:
1586                    sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1587                    break;
1588            }
1589        }
1590
1591        switch (step.script->command)
1592        {
1593            case SCRIPT_COMMAND_TALK:
1594            {
1595                if(!source)
1596                {
1597                    sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1598                    break;
1599                }
1600
1601                if(source->GetTypeId()!=TYPEID_UNIT)
1602                {
1603                    sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1604                    break;
1605                }
1606                if(step.script->datalong > 3)
1607                {
1608                    sLog.outError("SCRIPT_COMMAND_TALK invalid chat type (%u), skipping.",step.script->datalong);
1609                    break;
1610                }
1611
1612                uint64 unit_target = target ? target->GetGUID() : 0;
1613
1614                //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1615                switch(step.script->datalong)
1616                {
1617                    case 0:                                 // Say
1618                        ((Creature *)source)->Say(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1619                        break;
1620                    case 1:                                 // Whisper
1621                        if(!unit_target)
1622                        {
1623                            sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1624                            break;
1625                        }
1626                        ((Creature *)source)->Whisper(step.script->datatext.c_str(),unit_target);
1627                        break;
1628                    case 2:                                 // Yell
1629                        ((Creature *)source)->Yell(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1630                        break;
1631                    case 3:                                 // Emote text
1632                        ((Creature *)source)->TextEmote(step.script->datatext.c_str(), unit_target);
1633                        break;
1634                    default:
1635                        break;                              // must be already checked at load
1636                }
1637                break;
1638            }
1639
1640            case SCRIPT_COMMAND_EMOTE:
1641                if(!source)
1642                {
1643                    sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1644                    break;
1645                }
1646
1647                if(source->GetTypeId()!=TYPEID_UNIT)
1648                {
1649                    sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1650                    break;
1651                }
1652
1653                ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1654                break;
1655            case SCRIPT_COMMAND_FIELD_SET:
1656                if(!source)
1657                {
1658                    sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1659                    break;
1660                }
1661                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1662                {
1663                    sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1664                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1665                    break;
1666                }
1667
1668                source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1669                break;
1670            case SCRIPT_COMMAND_MOVE_TO:
1671                if(!source)
1672                {
1673                    sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1674                    break;
1675                }
1676
1677                if(source->GetTypeId()!=TYPEID_UNIT)
1678                {
1679                    sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1680                    break;
1681                }
1682                ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
1683                MapManager::Instance().GetMap(((Unit *)source)->GetMapId(), ((Unit *)source))->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1684                break;
1685            case SCRIPT_COMMAND_FLAG_SET:
1686                if(!source)
1687                {
1688                    sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1689                    break;
1690                }
1691                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1692                {
1693                    sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1694                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1695                    break;
1696                }
1697
1698                source->SetFlag(step.script->datalong, step.script->datalong2);
1699                break;
1700            case SCRIPT_COMMAND_FLAG_REMOVE:
1701                if(!source)
1702                {
1703                    sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1704                    break;
1705                }
1706                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1707                {
1708                    sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1709                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1710                    break;
1711                }
1712
1713                source->RemoveFlag(step.script->datalong, step.script->datalong2);
1714                break;
1715
1716            case SCRIPT_COMMAND_TELEPORT_TO:
1717            {
1718                // accept player in any one from target/source arg
1719                if (!target && !source)
1720                {
1721                    sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1722                    break;
1723                }
1724
1725                                                            // must be only Player
1726                if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1727                {
1728                    sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1729                    break;
1730                }
1731
1732                Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1733
1734                pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1735                break;
1736            }
1737
1738            case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1739            {
1740                if(!step.script->datalong)                  // creature not specified
1741                {
1742                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1743                    break;
1744                }
1745
1746                if(!source)
1747                {
1748                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1749                    break;
1750                }
1751
1752                WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1753
1754                if(!summoner)
1755                {
1756                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1757                    break;
1758                }
1759
1760                float x = step.script->x;
1761                float y = step.script->y;
1762                float z = step.script->z;
1763                float o = step.script->o;
1764
1765                Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1766                if (!pCreature)
1767                {
1768                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1769                    break;
1770                }
1771
1772                break;
1773            }
1774
1775            case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1776            {
1777                if(!step.script->datalong)                  // gameobject not specified
1778                {
1779                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1780                    break;
1781                }
1782
1783                if(!source)
1784                {
1785                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1786                    break;
1787                }
1788
1789                WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1790
1791                if(!summoner)
1792                {
1793                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1794                    break;
1795                }
1796
1797                GameObject *go = NULL;
1798                int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1799
1800                CellPair p(Trinity::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1801                Cell cell(p);
1802                cell.data.Part.reserved = ALL_DISTRICT;
1803
1804                Trinity::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1805                Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck> checker(go,go_check);
1806
1807                TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1808                CellLock<GridReadGuard> cell_lock(cell, p);
1809                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(summoner->GetMapId(), summoner));
1810
1811                if ( !go )
1812                {
1813                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1814                    break;
1815                }
1816
1817                if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1818                    go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1819                    go->GetGoType()==GAMEOBJECT_TYPE_DOOR        ||
1820                    go->GetGoType()==GAMEOBJECT_TYPE_BUTTON      ||
1821                    go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1822                {
1823                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1824                    break;
1825                }
1826
1827                if( go->isSpawned() )
1828                    break;                                  //gameobject already spawned
1829
1830                go->SetLootState(GO_READY);
1831                go->SetRespawnTime(time_to_despawn);        //despawn object in ? seconds
1832
1833                MapManager::Instance().GetMap(go->GetMapId(), go)->Add(go);
1834                break;
1835            }
1836            case SCRIPT_COMMAND_OPEN_DOOR:
1837            {
1838                if(!step.script->datalong)                  // door not specified
1839                {
1840                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1841                    break;
1842                }
1843
1844                if(!source)
1845                {
1846                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1847                    break;
1848                }
1849
1850                if(!source->isType(TYPEMASK_UNIT))          // must be any Unit (creature or player)
1851                {
1852                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1853                    break;
1854                }
1855
1856                Unit* caster = (Unit*)source;
1857
1858                GameObject *door = NULL;
1859                int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1860
1861                CellPair p(Trinity::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1862                Cell cell(p);
1863                cell.data.Part.reserved = ALL_DISTRICT;
1864
1865                Trinity::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1866                Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck> checker(door,go_check);
1867
1868                TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1869                CellLock<GridReadGuard> cell_lock(cell, p);
1870                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1871
1872                if ( !door )
1873                {
1874                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1875                    break;
1876                }
1877                if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1878                {
1879                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1880                    break;
1881                }
1882
1883                if( !door->GetGoState() )
1884                    break;                                  //door already  open
1885
1886                door->UseDoorOrButton(time_to_close);
1887
1888                if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1889                    ((GameObject*)target)->UseDoorOrButton(time_to_close);
1890                break;
1891            }
1892            case SCRIPT_COMMAND_CLOSE_DOOR:
1893            {
1894                if(!step.script->datalong)                  // guid for door not specified
1895                {
1896                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
1897                    break;
1898                }
1899
1900                if(!source)
1901                {
1902                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
1903                    break;
1904                }
1905
1906                if(!source->isType(TYPEMASK_UNIT))          // must be any Unit (creature or player)
1907                {
1908                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1909                    break;
1910                }
1911
1912                Unit* caster = (Unit*)source;
1913
1914                GameObject *door = NULL;
1915                int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1916
1917                CellPair p(Trinity::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1918                Cell cell(p);
1919                cell.data.Part.reserved = ALL_DISTRICT;
1920
1921                Trinity::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1922                Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck> checker(door,go_check);
1923
1924                TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1925                CellLock<GridReadGuard> cell_lock(cell, p);
1926                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1927
1928                if ( !door )
1929                {
1930                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1931                    break;
1932                }
1933                if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1934                {
1935                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1936                    break;
1937                }
1938
1939                if( door->GetGoState() )
1940                    break;                                  //door already closed
1941
1942                door->UseDoorOrButton(time_to_open);
1943
1944                if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1945                    ((GameObject*)target)->UseDoorOrButton(time_to_open);
1946
1947                break;
1948            }
1949            case SCRIPT_COMMAND_QUEST_EXPLORED:
1950            {
1951                if(!source)
1952                {
1953                    sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
1954                    break;
1955                }
1956
1957                if(!target)
1958                {
1959                    sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
1960                    break;
1961                }
1962
1963                // when script called for item spell casting then target == (unit or GO) and source is player
1964                WorldObject* worldObject;
1965                Player* player;
1966
1967                if(target->GetTypeId()==TYPEID_PLAYER)
1968                {
1969                    if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
1970                    {
1971                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
1972                        break;
1973                    }
1974
1975                    worldObject = (WorldObject*)source;
1976                    player = (Player*)target;
1977                }
1978                else
1979                {
1980                    if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
1981                    {
1982                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1983                        break;
1984                    }
1985
1986                    if(source->GetTypeId()!=TYPEID_PLAYER)
1987                    {
1988                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
1989                        break;
1990                    }
1991
1992                    worldObject = (WorldObject*)target;
1993                    player = (Player*)source;
1994                }
1995
1996                // quest id and flags checked at script loading
1997                if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
1998                    (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
1999                    player->AreaExploredOrEventHappens(step.script->datalong);
2000                else
2001                    player->FailQuest(step.script->datalong);
2002
2003                break;
2004            }
2005
2006            case SCRIPT_COMMAND_ACTIVATE_OBJECT:
2007            {
2008                if(!source)
2009                {
2010                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
2011                    break;
2012                }
2013
2014                if(!source->isType(TYPEMASK_UNIT))
2015                {
2016                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2017                    break;
2018                }
2019
2020                if(!target)
2021                {
2022                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
2023                    break;
2024                }
2025
2026                if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
2027                {
2028                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2029                    break;
2030                }
2031
2032                Unit* caster = (Unit*)source;
2033
2034                GameObject *go = (GameObject*)target;
2035
2036                go->Use(caster);
2037                break;
2038            }
2039
2040            case SCRIPT_COMMAND_REMOVE_AURA:
2041            {
2042                Object* cmdTarget = step.script->datalong2 ? source : target;
2043
2044                if(!cmdTarget)
2045                {
2046                    sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
2047                    break;
2048                }
2049
2050                if(!cmdTarget->isType(TYPEMASK_UNIT))
2051                {
2052                    sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2053                    break;
2054                }
2055
2056                ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
2057                break;
2058            }
2059
2060            case SCRIPT_COMMAND_CAST_SPELL:
2061            {
2062                if(!source)
2063                {
2064                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2065                    break;
2066                }
2067
2068                if(!source->isType(TYPEMASK_UNIT))
2069                {
2070                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2071                    break;
2072                }
2073
2074                Object* cmdTarget = step.script->datalong2 ? source : target;
2075
2076                if(!cmdTarget)
2077                {
2078                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 ? "source" : "target");
2079                    break;
2080                }
2081
2082                if(!cmdTarget->isType(TYPEMASK_UNIT))
2083                {
2084                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2085                    break;
2086                }
2087
2088                Unit* spellTarget = (Unit*)cmdTarget;
2089
2090                //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2091                ((Unit*)source)->CastSpell(spellTarget,step.script->datalong,false);
2092
2093                break;
2094            }
2095
2096            default:
2097                sLog.outError("Unknown script command %u called.",step.script->command);
2098                break;
2099        }
2100
2101        m_scriptSchedule.erase(iter);
2102
2103        iter = m_scriptSchedule.begin();
2104    }
2105    return;
2106}
2107
2108/// Send a packet to all players (except self if mentioned)
2109void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2110{
2111    SessionMap::iterator itr;
2112    for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2113    {
2114        if (itr->second &&
2115            itr->second->GetPlayer() &&
2116            itr->second->GetPlayer()->IsInWorld() &&
2117            itr->second != self &&
2118            (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2119        {
2120            itr->second->SendPacket(packet);
2121        }
2122    }
2123}
2124
2125/// Send a System Message to all players (except self if mentioned)
2126void World::SendWorldText(int32 string_id, ...)
2127{
2128    std::vector<std::vector<WorldPacket*> > data_cache;     // 0 = default, i => i-1 locale index
2129
2130    for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2131    {
2132        if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2133            continue;
2134
2135        uint32 loc_idx = itr->second->GetSessionDbLocaleIndex();
2136        uint32 cache_idx = loc_idx+1;
2137
2138        std::vector<WorldPacket*>* data_list;
2139
2140        // create if not cached yet
2141        if(data_cache.size() < cache_idx+1 || data_cache[cache_idx].empty())
2142        {
2143            if(data_cache.size() < cache_idx+1)
2144                data_cache.resize(cache_idx+1);
2145
2146            data_list = &data_cache[cache_idx];
2147
2148            char const* text = objmgr.GetTrinityString(string_id,loc_idx);
2149
2150            char buf[1000];
2151
2152            va_list argptr;
2153            va_start( argptr, string_id );
2154            vsnprintf( buf,1000, text, argptr );
2155            va_end( argptr );
2156
2157            char* pos = &buf[0];
2158
2159            while(char* line = ChatHandler::LineFromMessage(pos))
2160            {
2161                WorldPacket* data = new WorldPacket();
2162                ChatHandler::FillMessageData(data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2163                data_list->push_back(data);
2164            }
2165        }
2166        else
2167            data_list = &data_cache[cache_idx];
2168
2169        for(int i = 0; i < data_list->size(); ++i)
2170            itr->second->SendPacket((*data_list)[i]);
2171    }
2172
2173    // free memory
2174    for(int i = 0; i < data_cache.size(); ++i)
2175        for(int j = 0; j < data_cache[i].size(); ++j)
2176            delete data_cache[i][j];
2177}
2178
2179/// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2180void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2181{
2182    SessionMap::iterator itr;
2183    for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2184    {
2185        if (itr->second &&
2186            itr->second->GetPlayer() &&
2187            itr->second->GetPlayer()->IsInWorld() &&
2188            itr->second->GetPlayer()->GetZoneId() == zone &&
2189            itr->second != self &&
2190            (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2191        {
2192            itr->second->SendPacket(packet);
2193        }
2194    }
2195}
2196
2197/// Send a System Message to all players in the zone (except self if mentioned)
2198void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2199{
2200    WorldPacket data;
2201    ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2202    SendZoneMessage(zone, &data, self,team);
2203}
2204
2205/// Kick (and save) all players
2206void World::KickAll()
2207{
2208    // session not removed at kick and will removed in next update tick
2209    for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2210        itr->second->KickPlayer();
2211}
2212
2213/// Kick (and save) all players with security level less `sec`
2214void World::KickAllLess(AccountTypes sec)
2215{
2216    // session not removed at kick and will removed in next update tick
2217    for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2218        if(itr->second->GetSecurity() < sec)
2219            itr->second->KickPlayer();
2220}
2221
2222/// Kick all queued players
2223void World::KickAllQueued()
2224{
2225    // session not removed at kick and will removed in next update tick
2226  //TODO here
2227//    for (Queue::iterator itr = m_QueuedPlayer.begin(); itr != m_QueuedPlayer.end(); ++itr)
2228//        if(WorldSession* session = (*itr)->GetSession())
2229//            session->KickPlayer();
2230
2231    m_QueuedPlayer.empty();
2232}
2233
2234/// Kick (and save) the designated player
2235bool World::KickPlayer(std::string playerName)
2236{
2237    SessionMap::iterator itr;
2238
2239    // session not removed at kick and will removed in next update tick
2240    for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2241    {
2242        if(!itr->second)
2243            continue;
2244        Player *player = itr->second->GetPlayer();
2245        if(!player)
2246            continue;
2247        if( player->IsInWorld() )
2248        {
2249            if (playerName == player->GetName())
2250            {
2251                itr->second->KickPlayer();
2252                return true;
2253            }
2254        }
2255    }
2256    return false;
2257}
2258
2259/// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2260uint8 World::BanAccount(std::string type, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2261{
2262    loginDatabase.escape_string(nameOrIP);
2263    loginDatabase.escape_string(reason);
2264    std::string safe_author=author;
2265    loginDatabase.escape_string(safe_author);
2266
2267    if(type != "ip" && !normalizePlayerName(nameOrIP))
2268        return BAN_NOTFOUND;                                // Nobody to ban
2269
2270    uint32 duration_secs = TimeStringToSecs(duration);
2271    QueryResult *resultAccounts = NULL;                     //used for kicking
2272
2273    ///- Update the database with ban information
2274
2275    if(type=="ip")
2276    {
2277        //No SQL injection as strings are escaped
2278        resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2279        loginDatabase.PExecute("INSERT INTO ip_banned VALUES ('%s',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()+%u,'%s','%s')",nameOrIP.c_str(),duration_secs,safe_author.c_str(),reason.c_str());
2280    }
2281    else if(type=="account")
2282    {
2283        //No SQL injection as string is escaped
2284        resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2285    }
2286    else if(type=="character")
2287    {
2288        //No SQL injection as string is escaped
2289        resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2290    }
2291    else
2292        return BAN_SYNTAX_ERROR;                            //Syntax problem
2293
2294    if(!resultAccounts)
2295        if(type=="ip")
2296            return BAN_SUCCESS;                             // ip correctly banned but nobody affected (yet)
2297    else
2298        return BAN_NOTFOUND;                                // Nobody to ban
2299
2300    ///- Disconnect all affected players (for IP it can be several)
2301    do
2302    {
2303        Field* fieldsAccount = resultAccounts->Fetch();
2304        uint32 account = fieldsAccount->GetUInt32();
2305
2306        if(type != "ip")
2307            //No SQL injection as strings are escaped
2308            loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2309                account,duration_secs,safe_author.c_str(),reason.c_str());
2310
2311        WorldSession* sess = FindSession(account);
2312        if( sess )
2313            if(std::string(sess->GetPlayerName()) != author)
2314                sess->KickPlayer();
2315    }
2316    while( resultAccounts->NextRow() );
2317
2318    delete resultAccounts;
2319    return BAN_SUCCESS;
2320}
2321
2322/// Remove a ban from an account or IP address
2323bool World::RemoveBanAccount(std::string type, std::string nameOrIP)
2324{
2325    if(type == "ip")
2326    {
2327        loginDatabase.escape_string(nameOrIP);
2328        loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2329    }
2330    else
2331    {
2332        uint32 account=0;
2333        if(type == "account")
2334        {
2335            //NO SQL injection as name is escaped
2336            loginDatabase.escape_string(nameOrIP);
2337            QueryResult *resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2338            if(!resultAccounts)
2339                return false;
2340            Field* fieldsAccount = resultAccounts->Fetch();
2341            account = fieldsAccount->GetUInt32();
2342
2343            delete resultAccounts;
2344        }
2345        else if(type == "character")
2346        {
2347            if(!normalizePlayerName(nameOrIP))
2348                return false;
2349
2350            //NO SQL injection as name is escaped
2351            loginDatabase.escape_string(nameOrIP);
2352            QueryResult *resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2353            if(!resultAccounts)
2354                return false;
2355            Field* fieldsAccount = resultAccounts->Fetch();
2356            account = fieldsAccount->GetUInt32();
2357
2358            delete resultAccounts;
2359        }
2360        if(!account)
2361            return false;
2362        //NO SQL injection as account is uint32
2363        loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2364    }
2365    return true;
2366}
2367
2368/// Update the game time
2369void World::_UpdateGameTime()
2370{
2371    ///- update the time
2372    time_t thisTime = time(NULL);
2373    uint32 elapsed = uint32(thisTime - m_gameTime);
2374    m_gameTime = thisTime;
2375
2376    ///- if there is a shutdown timer
2377    if(m_ShutdownTimer > 0 && elapsed > 0)
2378    {
2379        ///- ... and it is overdue, stop the world (set m_stopEvent)
2380        if( m_ShutdownTimer <= elapsed )
2381        {
2382            if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2383                m_stopEvent = true;
2384            else
2385                m_ShutdownTimer = 1;                        // minimum timer value to wait idle state
2386        }
2387        ///- ... else decrease it and if necessary display a shutdown countdown to the users
2388        else
2389        {
2390            m_ShutdownTimer -= elapsed;
2391
2392            ShutdownMsg();
2393        }
2394    }
2395}
2396
2397/// Shutdown the server
2398void World::ShutdownServ(uint32 time, uint32 options)
2399{
2400    m_ShutdownMask = options;
2401
2402    ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2403    if(time==0)
2404    {
2405        if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2406            m_stopEvent = true;
2407        else
2408            m_ShutdownTimer = 1;                            //So that the session count is re-evaluated at next world tick
2409    }
2410    ///- Else set the shutdown timer and warn users
2411    else
2412    {
2413        m_ShutdownTimer = time;
2414        ShutdownMsg(true);
2415    }
2416}
2417
2418/// Display a shutdown message to the user(s)
2419void World::ShutdownMsg(bool show, Player* player)
2420{
2421    // not show messages for idle shutdown mode
2422    if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2423        return;
2424
2425    ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2426    if ( show ||
2427        (m_ShutdownTimer < 10) ||
2428                                                            // < 30 sec; every 5 sec
2429        (m_ShutdownTimer<30        && (m_ShutdownTimer % 5         )==0) ||
2430                                                            // < 5 min ; every 1 min
2431        (m_ShutdownTimer<5*MINUTE  && (m_ShutdownTimer % MINUTE    )==0) ||
2432                                                            // < 30 min ; every 5 min
2433        (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2434                                                            // < 12 h ; every 1 h
2435        (m_ShutdownTimer<12*HOUR   && (m_ShutdownTimer % HOUR      )==0) ||
2436                                                            // > 12 h ; every 12 h
2437        (m_ShutdownTimer>12*HOUR   && (m_ShutdownTimer % (12*HOUR) )==0))
2438    {
2439        std::string str = secsToTimeString(m_ShutdownTimer);
2440
2441        uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2442
2443        SendServerMessage(msgid,str.c_str(),player);
2444        outstring_log("Server will %s in %s", (m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shutdown"), str.c_str());
2445    }
2446}
2447
2448/// Cancel a planned server shutdown
2449void World::ShutdownCancel()
2450{
2451    if(!m_ShutdownTimer)
2452        return;
2453
2454    uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2455
2456    m_ShutdownMask = 0;
2457    m_ShutdownTimer = 0;
2458    SendServerMessage(msgid);
2459
2460    DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2461}
2462
2463/// Send a server message to the user(s)
2464void World::SendServerMessage(uint32 type, const char *text, Player* player)
2465{
2466    WorldPacket data(SMSG_SERVER_MESSAGE, 50);              // guess size
2467    data << uint32(type);
2468    if(type <= SERVER_MSG_STRING)
2469        data << text;
2470
2471    if(player)
2472        player->GetSession()->SendPacket(&data);
2473    else
2474        SendGlobalMessage( &data );
2475}
2476
2477void World::UpdateSessions( time_t diff )
2478{
2479    while(!addSessQueue.empty())
2480    {
2481      WorldSession* sess = addSessQueue.next ();
2482      AddSession_ (sess);
2483    }
2484       
2485    ///- Delete kicked sessions at add new session
2486    for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
2487        delete *itr;
2488    m_kicked_sessions.clear();
2489
2490    ///- Then send an update signal to remaining ones
2491    for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2492    {
2493        next = itr;
2494        ++next;
2495
2496        if(!itr->second)
2497            continue;
2498
2499        ///- and remove not active sessions from the list
2500        if(!itr->second->Update(diff))                      // As interval = 0
2501        {
2502            delete itr->second;
2503            m_sessions.erase(itr);
2504        }
2505    }
2506}
2507
2508// This handles the issued and queued CLI commands
2509void World::ProcessCliCommands()
2510{
2511    if (cliCmdQueue.empty()) return;
2512
2513    CliCommandHolder *command;
2514    pPrintf p_zprintf;
2515    while (!cliCmdQueue.empty())
2516    {
2517        sLog.outDebug("CLI command under processing...");
2518        command = cliCmdQueue.next();
2519        command->Execute();
2520        p_zprintf=command->GetOutputMethod();
2521        delete command;
2522    }
2523    // print the console message here so it looks right
2524    p_zprintf("TC> ");
2525}
2526
2527void World::InitResultQueue()
2528{
2529    m_resultQueue = new SqlResultQueue;
2530    CharacterDatabase.SetResultQueue(m_resultQueue);
2531}
2532
2533void World::UpdateResultQueue()
2534{
2535    m_resultQueue->Update();
2536}
2537
2538void World::UpdateRealmCharCount(uint32 accountId)
2539{
2540    CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2541        "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2542}
2543
2544void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2545{
2546    if (resultCharCount)
2547    {
2548        Field *fields = resultCharCount->Fetch();
2549        uint32 charCount = fields[0].GetUInt32();
2550        delete resultCharCount;
2551        loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2552        loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2553    }
2554}
2555
2556void World::InitDailyQuestResetTime()
2557{
2558    time_t mostRecentQuestTime;
2559
2560    QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2561    if(result)
2562    {
2563        Field *fields = result->Fetch();
2564
2565        mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2566        delete result;
2567    }
2568    else
2569        mostRecentQuestTime = 0;
2570
2571    // client built-in time for reset is 6:00 AM
2572    // FIX ME: client not show day start time
2573    time_t curTime = time(NULL);
2574    tm localTm = *localtime(&curTime);
2575    localTm.tm_hour = 6;
2576    localTm.tm_min  = 0;
2577    localTm.tm_sec  = 0;
2578
2579    // current day reset time
2580    time_t curDayResetTime = mktime(&localTm);
2581
2582    // last reset time before current moment
2583    time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2584
2585    // need reset (if we have quest time before last reset time (not processed by some reason)
2586    if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2587        m_NextDailyQuestReset = mostRecentQuestTime;
2588    else
2589    {
2590        // plan next reset time
2591        m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2592    }
2593}
2594
2595void World::ResetDailyQuests()
2596{
2597    sLog.outDetail("Daily quests reset for all characters.");
2598    CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2599    for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2600        if(itr->second->GetPlayer())
2601            itr->second->GetPlayer()->ResetDailyQuestStatus();
2602}
2603
2604void World::SetPlayerLimit( int32 limit, bool needUpdate )
2605{
2606    if(limit < -SEC_ADMINISTRATOR)
2607        limit = -SEC_ADMINISTRATOR;
2608
2609    // lock update need
2610    bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2611
2612    m_playerLimit = limit;
2613
2614    if(db_update_need)
2615        loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2616}
2617
2618void World::UpdateMaxSessionCounters()
2619{
2620    m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2621    m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2622}
Note: See TracBrowser for help on using the browser.